From f4c4f6bac7a15ebc33fcdcdaf4b786339f2ac68f Mon Sep 17 00:00:00 2001 From: andpavlenko Date: Fri, 1 Apr 2022 09:32:55 +0000 Subject: [PATCH] Mirgate to PSR12 and other small fixes --- .gitignore | 7 +- src/.editorconfig | 82 + src/.php-cs-fixer.dist.php | 26 + src/bb-config-sample.php | 141 +- src/bb-cron.php | 28 +- src/bb-di.php | 241 +- src/bb-ipn.php | 45 +- src/bb-load.php | 187 +- src/bb-modules/Activity/Api/Admin.php | 74 +- src/bb-modules/Activity/Controller/Admin.php | 38 +- src/bb-modules/Activity/Service.php | 121 +- src/bb-modules/Api/Controller/Client.php | 135 +- src/bb-modules/Api/Service.php | 45 +- src/bb-modules/Branding/Service.php | 6 +- src/bb-modules/Cart/Api/Admin.php | 34 +- src/bb-modules/Cart/Api/Client.php | 12 +- src/bb-modules/Cart/Api/Guest.php | 48 +- src/bb-modules/Cart/Controller/Client.php | 7 +- src/bb-modules/Cart/Service.php | 401 ++- src/bb-modules/Client/Api/Admin.php | 359 +-- src/bb-modules/Client/Api/Client.php | 154 +- src/bb-modules/Client/Api/Guest.php | 199 +- src/bb-modules/Client/Controller/Admin.php | 83 +- src/bb-modules/Client/Controller/Client.php | 30 +- src/bb-modules/Client/Service.php | 387 +-- src/bb-modules/Client/ServiceBalance.php | 70 +- src/bb-modules/Cookieconsent/Api/Guest.php | 10 +- .../Cookieconsent/Controller/Admin.php | 30 +- src/bb-modules/Cookieconsent/Service.php | 5 +- src/bb-modules/Cron/Api/Admin.php | 14 +- src/bb-modules/Cron/Api/Guest.php | 12 +- src/bb-modules/Cron/Service.php | 32 +- src/bb-modules/Currency/Api/Admin.php | 152 +- src/bb-modules/Currency/Api/Guest.php | 47 +- src/bb-modules/Currency/Controller/Admin.php | 12 +- src/bb-modules/Currency/Service.php | 209 +- src/bb-modules/Custompages/Api/Admin.php | 52 +- .../Custompages/Controller/Admin.php | 36 +- .../Custompages/Controller/Client.php | 19 +- src/bb-modules/Custompages/Service.php | 44 +- .../Dashboard/Controller/Client.php | 8 +- src/bb-modules/Email/Api/Admin.php | 206 +- src/bb-modules/Email/Api/Client.php | 69 +- src/bb-modules/Email/Controller/Admin.php | 50 +- src/bb-modules/Email/Controller/Client.php | 17 +- src/bb-modules/Email/Service.php | 324 +-- src/bb-modules/Embed/Controller/Admin.php | 29 +- src/bb-modules/Embed/Controller/Client.php | 9 +- src/bb-modules/Example/Api/Admin.php | 20 +- src/bb-modules/Example/Api/Client.php | 28 +- src/bb-modules/Example/Api/Guest.php | 23 +- src/bb-modules/Example/Controller/Admin.php | 66 +- src/bb-modules/Example/Controller/Client.php | 15 +- src/bb-modules/Example/Service.php | 103 +- src/bb-modules/Extension/Api/Admin.php | 222 +- src/bb-modules/Extension/Api/Guest.php | 36 +- src/bb-modules/Extension/Controller/Admin.php | 54 +- src/bb-modules/Extension/Service.php | 258 +- src/bb-modules/Formbuilder/Api/Admin.php | 111 +- src/bb-modules/Formbuilder/Api/Guest.php | 22 +- .../Formbuilder/Controller/Client.php | 9 +- src/bb-modules/Formbuilder/Service.php | 174 +- src/bb-modules/Forum/Api/Admin.php | 402 +-- src/bb-modules/Forum/Api/Client.php | 228 +- src/bb-modules/Forum/Api/Guest.php | 65 +- src/bb-modules/Forum/Controller/Admin.php | 53 +- src/bb-modules/Forum/Controller/Client.php | 46 +- src/bb-modules/Forum/Service.php | 191 +- src/bb-modules/Hook/Api/Admin.php | 42 +- src/bb-modules/Hook/Service.php | 111 +- src/bb-modules/Index/Controller/Admin.php | 15 +- src/bb-modules/Invoice/Api/Admin.php | 530 ++-- src/bb-modules/Invoice/Api/Client.php | 120 +- src/bb-modules/Invoice/Api/Guest.php | 43 +- src/bb-modules/Invoice/Controller/Admin.php | 152 +- src/bb-modules/Invoice/Controller/Client.php | 71 +- src/bb-modules/Invoice/Service.php | 973 +++---- src/bb-modules/Invoice/ServiceInvoiceItem.php | 224 +- src/bb-modules/Invoice/ServicePayGateway.php | 206 +- .../Invoice/ServiceSubscription.php | 121 +- src/bb-modules/Invoice/ServiceTax.php | 54 +- src/bb-modules/Invoice/ServiceTransaction.php | 378 +-- src/bb-modules/Kb/Api/Admin.php | 111 +- src/bb-modules/Kb/Api/Guest.php | 45 +- src/bb-modules/Kb/Controller/Admin.php | 49 +- src/bb-modules/Kb/Controller/Client.php | 21 +- src/bb-modules/Kb/Service.php | 152 +- src/bb-modules/Massmailer/Api/Admin.php | 110 +- .../Massmailer/Controller/Admin.php | 37 +- src/bb-modules/Massmailer/Service.php | 155 +- src/bb-modules/News/Api/Admin.php | 78 +- src/bb-modules/News/Api/Guest.php | 27 +- src/bb-modules/News/Controller/Admin.php | 43 +- src/bb-modules/News/Controller/Client.php | 15 +- src/bb-modules/News/Service.php | 70 +- src/bb-modules/Notification/Api/Admin.php | 39 +- .../Notification/Controller/Admin.php | 8 +- src/bb-modules/Notification/Service.php | 21 +- src/bb-modules/Order/Api/Admin.php | 137 +- src/bb-modules/Order/Api/Client.php | 47 +- src/bb-modules/Order/Controller/Admin.php | 77 +- src/bb-modules/Order/Controller/Client.php | 49 +- src/bb-modules/Order/Service.php | 718 ++--- .../Orderbutton/Controller/Client.php | 12 +- src/bb-modules/Page/Api/Admin.php | 9 +- src/bb-modules/Page/Service.php | 21 +- src/bb-modules/Paidsupport/Service.php | 38 +- src/bb-modules/Product/Api/Admin.php | 367 +-- src/bb-modules/Product/Api/Guest.php | 93 +- src/bb-modules/Product/Controller/Admin.php | 92 +- src/bb-modules/Product/Service.php | 532 ++-- src/bb-modules/Profile/Api/Admin.php | 56 +- src/bb-modules/Profile/Api/Client.php | 42 +- src/bb-modules/Profile/Service.php | 137 +- src/bb-modules/Queue/Api/Admin.php | 241 +- src/bb-modules/Queue/Service.php | 86 +- src/bb-modules/Redirect/Api/Admin.php | 108 +- src/bb-modules/Redirect/Controller/Client.php | 36 +- src/bb-modules/Redirect/Service.php | 14 +- src/bb-modules/Seo/Service.php | 44 +- .../Servicecentovacast/Api/Admin.php | 203 +- .../Servicecentovacast/Api/Client.php | 163 +- src/bb-modules/Servicecentovacast/Service.php | 334 +-- .../Servicecentovacast/ccapiclient.php | 584 ++-- .../class_HTTPRetriever.php | 2382 +++++++++-------- src/bb-modules/Servicecustom/Api/Admin.php | 14 +- src/bb-modules/Servicecustom/Api/Client.php | 8 +- src/bb-modules/Servicecustom/Service.php | 106 +- src/bb-modules/Servicedomain/Api/Admin.php | 163 +- src/bb-modules/Servicedomain/Api/Client.php | 27 +- src/bb-modules/Servicedomain/Api/Guest.php | 47 +- .../Servicedomain/Controller/Admin.php | 41 +- src/bb-modules/Servicedomain/Service.php | 585 ++-- src/bb-modules/Servicedomain/ServiceTld.php | 6 +- .../Servicedownloadable/Api/Admin.php | 27 +- .../Servicedownloadable/Api/Client.php | 19 +- .../Servicedownloadable/Controller/Client.php | 12 +- .../Servicedownloadable/Service.php | 96 +- src/bb-modules/Servicehosting/Api/Admin.php | 319 ++- src/bb-modules/Servicehosting/Api/Client.php | 65 +- src/bb-modules/Servicehosting/Api/Guest.php | 20 +- .../Servicehosting/Controller/Admin.php | 42 +- src/bb-modules/Servicehosting/Service.php | 492 ++-- src/bb-modules/Servicelicense/Api/Admin.php | 54 +- src/bb-modules/Servicelicense/Api/Client.php | 27 +- src/bb-modules/Servicelicense/Api/Guest.php | 15 +- .../Servicelicense/Plugin/Simple.php | 27 +- src/bb-modules/Servicelicense/Server.php | 52 +- src/bb-modules/Servicelicense/Service.php | 270 +- src/bb-modules/Servicemembership/Service.php | 38 +- src/bb-modules/Servicesolusvm/Api/Admin.php | 529 ++-- src/bb-modules/Servicesolusvm/Api/Client.php | 120 +- src/bb-modules/Servicesolusvm/Api/Guest.php | 21 +- .../Servicesolusvm/Controller/Admin.php | 14 +- src/bb-modules/Servicesolusvm/Service.php | 293 +- src/bb-modules/Servicesolusvm/SolusVM.php | 709 ++--- src/bb-modules/Spamchecker/Api/Guest.php | 23 +- src/bb-modules/Spamchecker/Service.php | 96 +- .../Spamchecker/akismet.curl.class.php | 367 ++- src/bb-modules/Staff/Api/Admin.php | 366 +-- src/bb-modules/Staff/Api/Guest.php | 64 +- src/bb-modules/Staff/Controller/Admin.php | 61 +- src/bb-modules/Staff/Service.php | 380 +-- src/bb-modules/Stats/Api/Admin.php | 50 +- src/bb-modules/Stats/Service.php | 100 +- src/bb-modules/Support/Api/Admin.php | 347 +-- src/bb-modules/Support/Api/Client.php | 66 +- src/bb-modules/Support/Api/Guest.php | 47 +- src/bb-modules/Support/Controller/Admin.php | 152 +- src/bb-modules/Support/Controller/Client.php | 33 +- src/bb-modules/Support/Service.php | 791 +++--- src/bb-modules/System/Api/Admin.php | 86 +- src/bb-modules/System/Api/Guest.php | 103 +- src/bb-modules/System/Controller/Admin.php | 49 +- src/bb-modules/System/Service.php | 1119 ++++---- src/bb-modules/Theme/Api/Admin.php | 78 +- src/bb-modules/Theme/Controller/Admin.php | 62 +- src/bb-modules/Theme/Model/Theme.php | 102 +- src/bb-modules/Theme/Service.php | 167 +- src/bb-update.php | 488 ++-- src/composer.json | 19 +- src/composer.lock | 2256 +++++++++++++--- src/csrfp-config.php | 40 +- src/index.php | 13 +- 184 files changed, 15781 insertions(+), 13117 deletions(-) create mode 100644 src/.editorconfig create mode 100644 src/.php-cs-fixer.dist.php diff --git a/.gitignore b/.gitignore index 4981f25a5..dbd3b9a15 100644 --- a/.gitignore +++ b/.gitignore @@ -18,9 +18,14 @@ composer.phar public report/* data/db + +### phpunit/phpunit ### .phpunit.result.cache -### node_moduels ### +### node_modules ### node_modules npm-debug.log .history/ + +### friendsofphp/php-cs-fixer ### +src/.php-cs-fixer.cache diff --git a/src/.editorconfig b/src/.editorconfig new file mode 100644 index 000000000..b5f72a57e --- /dev/null +++ b/src/.editorconfig @@ -0,0 +1,82 @@ +# EditorConfig helps developers define and maintain consistent +# coding styles between different editors and IDEs +# editorconfig.org + +root = true + +[*] +# Change these settings to your own preference +indent_style = space +indent_size = 4 + +# We recommend you to keep these unchanged +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.feature] +indent_style = space +indent_size = 4 + +[*.js] +indent_style = space +indent_size = 2 + +[*.json] +indent_style = space +indent_size = 2 + +[*.md] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = false + +[*.neon] +indent_style = space +indent_size = 4 + +[*.php] +indent_style = space +indent_size = 4 + +[*.sh] +indent_style = space +indent_size = 4 + +[*.{yaml,yml}] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = false + +[.babelrc] +indent_style = space +indent_size = 2 + +[.gitmodules] +indent_style = tab +indent_size = 4 + +[.php_cs{,.dist}] +indent_style = space +indent_size = 4 + +[composer.json] +indent_style = space +indent_size = 4 + +[package.json] +indent_style = space +indent_size = 2 + +[phpspec.yml{,.dist}] +indent_style = space +indent_size = 4 + +[phpstan.neon] +indent_style = space +indent_size = 4 + +[phpunit.xml{,.dist}] +indent_style = space +indent_size = 4 diff --git a/src/.php-cs-fixer.dist.php b/src/.php-cs-fixer.dist.php new file mode 100644 index 000000000..47366a954 --- /dev/null +++ b/src/.php-cs-fixer.dist.php @@ -0,0 +1,26 @@ +setRules([ + '@PHP71Migration' => true, + '@Symfony' => true, + 'protected_to_private' => false, + 'nullable_type_declaration_for_default_null_value' => ['use_nullable_type_declaration' => false], + 'phpdoc_to_comment' => false, + ]) + ->setRiskyAllowed(false) + ->setFinder( + (new PhpCsFixer\Finder()) + ->in(__DIR__) + ->exclude([ + 'bb-data', + 'bb-library', + 'bb-locale', + 'bb-themes', + 'bb-vendor', + 'install', + 'bb-modules/Wysiwyg' + ]) + ->notPath('rb.php') + ) +; diff --git a/src/bb-config-sample.php b/src/bb-config-sample.php index f0856dce1..1cfa8a120 100755 --- a/src/bb-config-sample.php +++ b/src/bb-config-sample.php @@ -1,6 +1,6 @@ '', +return [ + 'salt' => '', /** - * Full URL where BoxBilling is installed with trailing slash + * Full URL where BoxBilling is installed with trailing slash. */ - 'url' => 'http://localhost/', + 'url' => 'http://localhost/', /** - * The URL prefix to access the BB admin area. Ex: '/bb-admin' for https://example.com/bb-admin + * The URL prefix to access the BB admin area. Ex: '/bb-admin' for https://example.com/bb-admin. */ - 'admin_area_prefix' => '/bb-admin', + 'admin_area_prefix' => '/bb-admin', /** * Enable or disable displaying advanced debugging messages. * You should keep this disabled unless you're making tests as it can reveal some information about your server. */ - 'debug' => false, + 'debug' => false, - 'maintenance_mode' => array( + 'maintenance_mode' => [ /** * Enable or disable the system maintenance mode. * Enabling this will block public access to your website, and API endpoints except the allowed ones won't work * However, this will not block access to the administrator area. - * + * * @since 4.22.0 */ - 'enabled' => false, + 'enabled' => false, /** * Don't block these URLs when the maintenance is going on. - * Supports wildcard (e.g. '/api/guest/staff/*') + * Supports wildcard (e.g. '/api/guest/staff/*'). * * @since 4.22.0 */ - 'allowed_urls' => array(), + 'allowed_urls' => [], /** * Don't block these IP/Subnet addresses when the maintenance is going on. - * Supported formats: 127.0.0.1、127.0.0.1/32 + * Supported formats: 127.0.0.1、127.0.0.1/32. * * @since 4.22.0 */ - 'allowed_ips' => array(), - ), - + 'allowed_ips' => [], + ], + /** * Enable or disable search engine friendly URLs. * Configure .htaccess file before enabling this feature - * Set to TRUE if using nginx + * Set to TRUE if using nginx. */ - 'sef_urls' => true, + 'sef_urls' => true, /** - * System timezone + * System timezone. */ - 'timezone' => 'UTC', + 'timezone' => 'UTC', /** - * BoxBilling locale + * BoxBilling locale. */ - 'locale' => 'en_US', + 'locale' => 'en_US', /** - * Set default date format for localized strings + * Set default date format for localized strings. + * * @see http://php.net/manual/en/function.strftime.php */ - 'locale_date_format' => '%A, %d %B %G', + 'locale_date_format' => '%A, %d %B %G', /** - * Set default time format for localized strings + * Set default time format for localized strings. + * * @see http://php.net/manual/en/function.strftime.php */ - 'locale_time_format' => ' %T', + 'locale_time_format' => ' %T', /** - * Set location to store sensitive data + * Set location to store sensitive data. */ - 'path_data' => dirname(__FILE__) . '/bb-data', + 'path_data' => dirname(__FILE__).'/bb-data', - 'path_logs' => dirname(__FILE__) . '/bb-data/log/application.log', + 'path_logs' => dirname(__FILE__).'/bb-data/log/application.log', - 'log_to_db' => true, + 'log_to_db' => true, - 'db' => array( + 'db' => [ /** * Database type. Don't change this if in doubt. */ - 'type' => 'mysql', + 'type' => 'mysql', /** * Database hostname. Don't change this if in doubt. */ - 'host' => getenv('DB_HOST') ?: '127.0.0.1', + 'host' => getenv('DB_HOST') ?: '127.0.0.1', /** - * The name of the database for BoxBilling + * The name of the database for BoxBilling. */ - 'name' => getenv('DB_NAME') ?: 'boxbilling', + 'name' => getenv('DB_NAME') ?: 'boxbilling', /** - * Database username + * Database username. */ - 'user' => getenv('DB_USER') ?: 'foo', + 'user' => getenv('DB_USER') ?: 'foo', /** - * Database password + * Database password. */ - 'password' => getenv('DB_PASS') ?: 'foo', + 'password' => getenv('DB_PASS') ?: 'foo', /** - * Database Port + * Database Port. */ - 'port' => getenv('DB_PORT') ?: '3306', - ), + 'port' => getenv('DB_PORT') ?: '3306', + ], - 'twig' => array( - 'debug' => false, - 'auto_reload' => false, - 'cache' => dirname(__FILE__) . '/bb-data/cache', - ), + 'twig' => [ + 'debug' => false, + 'auto_reload' => false, + 'cache' => dirname(__FILE__).'/bb-data/cache', + ], - 'api' => array( + 'api' => [ // All requests made to the API must have referrer request header with the same URL as the BoxBilling installation - 'require_referrer_header' => false, + 'require_referrer_header' => false, // Empty array will allow all IPs to access the API - 'allowed_ips' => array(), + 'allowed_ips' => [], // Time span for limit in seconds - 'rate_span' => 60 * 60, + 'rate_span' => 60 * 60, // How many requests allowed per time span - 'rate_limit' => 1000, + 'rate_limit' => 1000, /** * Note about rate-limiting login attempts: - * When the limit is reached, a default delay of 2 seconds is added to the request. + * When the limit is reached, a default delay of 2 seconds is added to the request. * This makes brute-forcing a password useless while not outright blocking legitimate traffic. * When calculating, ensure the rate-limited traffic can still make enough requests to stay rate limited - * Ex: One request every 2 seconds is more than 20 times in 1 minute, so the IP will remain throttled + * Ex: One request every 2 seconds is more than 20 times in 1 minute, so the IP will remain throttled. * * @since 4.22.0 */ // Throttling delay - 'throttle_delay' => 2, + 'throttle_delay' => 2, // Time span login for limit in seconds - 'rate_span_login' => 60, + 'rate_span_login' => 60, // How many login requests allowed per time span - 'rate_limit_login' => 20, - ), + 'rate_limit_login' => 20, + ], - 'guzzle' => array( + 'guzzle' => [ /** - * The user agent to be used when making requests to external services + * The user agent to be used when making requests to external services. * * @since 4.22.0 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent */ - 'user_agent' => 'Mozilla/5.0 (RedHatEnterpriseLinux; Linux x86_64; BoxBilling; +http://boxbilling.org) Gecko/20100101 Firefox/93.0', + 'user_agent' => 'Mozilla/5.0 (RedHatEnterpriseLinux; Linux x86_64; BoxBilling; +http://boxbilling.org) Gecko/20100101 Firefox/93.0', /** * Default request timeout - * Setting 0 will disable this limitation + * Setting 0 will disable this limitation. * * @since 4.22.0 * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/timeout */ - 'timeout' => 0, + 'timeout' => 0, /** * The HTTP Upgrade-Insecure-Requests header sends a signal to the server * expressing the client’s preference for an encrypted response. - * + * * 0: don't ask for an encrypted response * 1: ask for an encrypted response - * + * * @since 4.22.0 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Upgrade-Insecure-Requests */ - 'upgrade_insecure_requests' => 0 - ), -); \ No newline at end of file + 'upgrade_insecure_requests' => 0, + ], +]; diff --git a/src/bb-cron.php b/src/bb-cron.php index 5c385a34f..ad73a0280 100644 --- a/src/bb-cron.php +++ b/src/bb-cron.php @@ -1,6 +1,6 @@ getLastExecutionTime() . ".\e[0m"); + if ('cli' == php_sapi_name()) { + echo "\e[34mLast executed: ".$service->getLastExecutionTime().".\e[0m"; } $service->runCrons($interval); - } catch (Exception $exception) { +} catch (Exception $exception) { throw new Exception($exception); - } finally { - if (php_sapi_name() == 'cli') { - print ("\e[32mSuccessfully ran the cron jobs.\e[0m"); +} finally { + if ('cli' == php_sapi_name()) { + echo "\e[32mSuccessfully ran the cron jobs.\e[0m"; } else { $login_url = $di['url']->link('bb-admin'); unset($service, $interval, $di); header("Location: $login_url"); } - } +} diff --git a/src/bb-di.php b/src/bb-di.php index 7ba839136..06bc541cf 100644 --- a/src/bb-di.php +++ b/src/bb-di.php @@ -1,6 +1,6 @@ setDi($di); $log_to_db = isset($di['config']['log_to_db']) && $di['config']['log_to_db']; if ($log_to_db) { $activity_service = $di['mod_service']('activity'); - $writer2 = new Box_LogDb($activity_service); - if ($di['auth']->isAdminLoggedIn()){ - $admin = $di['loggedin_admin']; - $log->setEventItem('admin_id', $admin->id); - } - elseif ($di['auth']->isClientLoggedIn()) { + $writer2 = new Box_LogDb($activity_service); + if ($di['auth']->isAdminLoggedIn()) { + $admin = $di['loggedin_admin']; + $log->setEventItem('admin_id', $admin->id); + } elseif ($di['auth']->isClientLoggedIn()) { $client = $di['loggedin_client']; $log->setEventItem('client_id', $client->id); } $log->addWriter($writer2); } else { $logFile = $di['config']['path_logs']; - $writer = new Box_LogStream($logFile); + $writer = new Box_LogStream($logFile); $log->addWriter($writer); } return $log; }; -$di['crypt'] = function() use ($di) { - $crypt = new Box_Crypt(); +$di['crypt'] = function () use ($di) { + $crypt = new Box_Crypt(); $crypt->setDi($di); + return $crypt; }; -$di['pdo'] = function() use ($di) { +$di['pdo'] = function () use ($di) { $c = $di['config']['db']; $pdo = new PDO($c['type'].':host='.$c['host'].';port='.$c['port'].';dbname='.$c['name'], $c['user'], $c['password'], - array( - PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, - PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, - ) + [ + PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ] ); - if(isset($c['debug']) && $c['debug']) { - $pdo->setAttribute(PDO::ATTR_STATEMENT_CLASS, array ('Box_DbLoggedPDOStatement')); + if (isset($c['debug']) && $c['debug']) { + $pdo->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['Box_DbLoggedPDOStatement']); } - if($c['type'] == 'mysql') { - $pdo->exec( 'SET NAMES "utf8"' ); - $pdo->exec( 'SET CHARACTER SET utf8' ); - $pdo->exec( 'SET CHARACTER_SET_CONNECTION = utf8' ); - $pdo->exec( 'SET character_set_results = utf8' ); - $pdo->exec( 'SET character_set_server = utf8' ); - $pdo->exec( 'SET SESSION interactive_timeout = 28800' ); - $pdo->exec( 'SET SESSION wait_timeout = 28800' ); + if ('mysql' == $c['type']) { + $pdo->exec('SET NAMES "utf8"'); + $pdo->exec('SET CHARACTER SET utf8'); + $pdo->exec('SET CHARACTER_SET_CONNECTION = utf8'); + $pdo->exec('SET character_set_results = utf8'); + $pdo->exec('SET character_set_server = utf8'); + $pdo->exec('SET SESSION interactive_timeout = 28800'); + $pdo->exec('SET SESSION wait_timeout = 28800'); } return $pdo; }; -$di['db'] = function() use ($di) { - - require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'rb.php'; +$di['db'] = function () use ($di) { + require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'rb.php'; R::setup($di['pdo']); - \RedBeanPHP\Util\DispenseHelper::setEnforceNamingPolicy( false ); + \RedBeanPHP\Util\DispenseHelper::setEnforceNamingPolicy(false); $helper = new Box_BeanHelper(); $helper->setDi($di); $mapper = new \RedBeanPHP\Facade(); $mapper->getRedBean()->setBeanHelper($helper); - $freeze = isset($di['config']['db']['freeze']) ? (bool)$di['config']['db']['freeze'] : true; + $freeze = isset($di['config']['db']['freeze']) ? (bool) $di['config']['db']['freeze'] : true; $mapper->freeze($freeze); $db = new Box_Database(); $db->setDi($di); $db->setDataMapper($mapper); + return $db; }; -$di['pager'] = function() use($di) { +$di['pager'] = function () use ($di) { $service = new Box_Pagination(); $service->setDi($di); + return $service; }; -$di['url'] = function() use ($di) { - $url = new Box_Url(); +$di['url'] = function () use ($di) { + $url = new Box_Url(); $url->setDi($di); $url->setBaseUri(BB_URL); + return $url; }; -$di['mod'] = $di->protect(function ($name) use($di) { +$di['mod'] = $di->protect(function ($name) use ($di) { $mod = new Box_Mod($name); $mod->setDi($di); + return $mod; }); -$di['mod_service'] = $di->protect(function ($mod, $sub = '') use($di) { +$di['mod_service'] = $di->protect(function ($mod, $sub = '') use ($di) { return $di['mod']($mod)->getService($sub); }); -$di['mod_config'] = $di->protect(function ($name) use($di) { +$di['mod_config'] = $di->protect(function ($name) use ($di) { return $di['mod']($name)->getConfig(); }); -$di['events_manager'] = function() use ($di) { +$di['events_manager'] = function () use ($di) { $service = new Box_EventManager(); $service->setDi($di); + return $service; }; $di['session'] = function () use ($di) { $handler = new PdoSessionHandler($di['pdo']); + return new Box_Session($handler); }; $di['cookie'] = function () use ($di) { $service = new Box_Cookie(); $service->setDi($di); + return $service; }; $di['request'] = function () use ($di) { $service = new Box_Request(); $service->setDi($di); + return $service; }; -$di['cache'] = function () use ($di) { return new FileCache();}; -$di['auth'] = function () use ($di) { return new Box_Authorization($di);}; +$di['cache'] = function () { return new FileCache(); }; +$di['auth'] = function () use ($di) { return new Box_Authorization($di); }; $di['twig'] = $di->factory(function () use ($di) { $config = $di['config']; $options = $config['twig']; @@ -147,18 +153,17 @@ $di['twig'] = $di->factory(function () use ($di) { $box_extensions = new Box_TwigExtensions(); $box_extensions->setDi($di); - //$twig->addExtension(new Twig\Extension\OptimizerExtension()); - $twig->addExtension(new \Twig\Extension\StringLoaderExtension()); - $twig->addExtension(new Twig\Extension\DebugExtension()); - $twig->addExtension(new Twig\Extensions\I18nExtension()); + // $twig->addExtension(new Twig\Extension\OptimizerExtension()); + $twig->addExtension(new \Twig\Extension\StringLoaderExtension()); + $twig->addExtension(new Twig\Extension\DebugExtension()); + $twig->addExtension(new Twig\Extensions\I18nExtension()); $twig->addExtension($box_extensions); - $twig->getExtension(Twig\Extension\CoreExtension::class)->setDateFormat($config['locale_date_format']); - $twig->getExtension(Twig\Extension\CoreExtension::class)->setTimezone($config['timezone']); - + $twig->getExtension(Twig\Extension\CoreExtension::class)->setDateFormat($config['locale_date_format']); + $twig->getExtension(Twig\Extension\CoreExtension::class)->setTimezone($config['timezone']); // add globals - if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { - $_GET['ajax'] = TRUE; + if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']) { + $_GET['ajax'] = true; } $twig->addGlobal('request', $_GET); @@ -167,58 +172,58 @@ $di['twig'] = $di->factory(function () use ($di) { return $twig; }); -$di['is_client_logged'] = function() use($di) { - if(!$di['auth']->isClientLoggedIn()) { +$di['is_client_logged'] = function () use ($di) { + if (!$di['auth']->isClientLoggedIn()) { $api_str = '/api/'; $url = $di['request']->getQuery('_url'); - if (strncasecmp($url, $api_str , strlen($api_str)) === 0) { - //Throw Exception if api request + if (0 === strncasecmp($url, $api_str, strlen($api_str))) { + // Throw Exception if api request throw new Exception('Client is not logged in'); - } - else { - //Redirect to login page if browser request + } else { + // Redirect to login page if browser request $login_url = $di['url']->link('login'); header("Location: $login_url"); } - } + return true; }; -$di['is_admin_logged'] = function() use($di) { - - if(!$di['auth']->isAdminLoggedIn()) { - $api_str = '/api/'; - $url = $di['request']->getQuery('_url'); - if (strncasecmp($url, $api_str , strlen($api_str)) === 0) { - //Throw Exception if api request - throw new Exception('Admin is not logged in'); - } - else { - //Redirect to login page if browser request - $login_url = $di['url']->adminLink('staff/login'); - header("Location: $login_url"); +$di['is_admin_logged'] = function () use ($di) { + if (!$di['auth']->isAdminLoggedIn()) { + $api_str = '/api/'; + $url = $di['request']->getQuery('_url'); + if (0 === strncasecmp($url, $api_str, strlen($api_str))) { + // Throw Exception if api request + throw new Exception('Admin is not logged in'); + } else { + // Redirect to login page if browser request + $login_url = $di['url']->adminLink('staff/login'); + header("Location: $login_url"); } } + return true; }; -$di['loggedin_client'] = function() use ($di) { +$di['loggedin_client'] = function () use ($di) { $di['is_client_logged']; $client_id = $di['session']->get('client_id'); + return $di['db']->getExistingModelById('Client', $client_id); }; -$di['loggedin_admin'] = function() use ($di) { - if(php_sapi_name() == 'cli' || substr(php_sapi_name(), 0, 3) == 'cgi') { +$di['loggedin_admin'] = function () use ($di) { + if ('cli' == php_sapi_name() || 'cgi' == substr(php_sapi_name(), 0, 3)) { return $di['mod_service']('staff')->getCronAdmin(); } $di['is_admin_logged']; $admin = $di['session']->get('admin'); + return $di['db']->getExistingModelById('Admin', $admin['id']); }; -$di['api'] = $di->protect(function($role) use($di) { +$di['api'] = $di->protect(function ($role) use ($di) { switch ($role) { case 'guest': $identity = new \Model_Guest(); @@ -241,31 +246,34 @@ $di['api'] = $di->protect(function($role) use($di) { } $api = new Api_Handler($identity); $api->setDi($di); + return $api; }); -$di['api_guest'] = function() use ($di) { return $di['api']('guest'); }; -$di['api_client'] = function() use ($di) { return $di['api']('client');}; -$di['api_admin'] = function() use ($di) { return $di['api']('admin'); }; -$di['api_system'] = function() use ($di) { return $di['api']('system'); }; +$di['api_guest'] = function () use ($di) { return $di['api']('guest'); }; +$di['api_client'] = function () use ($di) { return $di['api']('client'); }; +$di['api_admin'] = function () use ($di) { return $di['api']('admin'); }; +$di['api_system'] = function () use ($di) { return $di['api']('system'); }; -$di['tools'] = function () use ($di){ +$di['tools'] = function () use ($di) { $service = new Box_Tools(); $service->setDi($di); + return $service; }; -$di['validator'] = function () use ($di){ +$di['validator'] = function () use ($di) { $validator = new Box_Validate(); $validator->setDi($di); + return $validator; }; -$di['guzzle_client'] = function () use($di) { +$di['guzzle_client'] = function () use ($di) { return new GuzzleHttp\Client([ 'headers' => [ 'User-Agent' => $di['config']['guzzle']['user_agent'], - 'Upgrade-Insecure-Requests' => $di['config']['guzzle']['upgrade_insecure_requests'] + 'Upgrade-Insecure-Requests' => $di['config']['guzzle']['upgrade_insecure_requests'], ], - 'timeout' => $di['config']['guzzle']['timeout'] + 'timeout' => $di['config']['guzzle']['timeout'], ]); }; $di['mail'] = function () { @@ -274,97 +282,110 @@ $di['mail'] = function () { $di['extension'] = function () use ($di) { $extension = new \Box_Extension(); $extension->setDi($di); + return $extension; }; $di['updater'] = function () use ($di) { $updater = new \Box_Update(); $updater->setDi($di); + return $updater; }; $di['curl'] = function ($url) use ($di) { $curl = new \Box_Curl($url); $curl->setDi($di); + return $curl; - }; -$di['zip_archive'] = function () use ($di) {return new ZipArchive();}; +$di['zip_archive'] = function () {return new ZipArchive(); }; -$di['server_package'] = function () use ($di) {return new Server_Package();}; -$di['server_client'] = function () use ($di) {return new Server_Client();}; -$di['server_account'] = function () use ($di) {return new Server_Account();}; +$di['server_package'] = function () {return new Server_Package(); }; +$di['server_client'] = function () {return new Server_Client(); }; +$di['server_account'] = function () {return new Server_Account(); }; -$di['server_manager'] = $di->protect(function ($manager, $config) use($di) { +$di['server_manager'] = $di->protect(function ($manager, $config) { $class = sprintf('Server_Manager_%s', ucfirst($manager)); + return new $class($config); }); $di['requirements'] = function () use ($di) { $r = new Box_Requirements(); $r->setDi($di); + return $r; }; -$di['period'] = $di->protect(function($code) use($di){ return new \Box_Period($code); }); +$di['period'] = $di->protect(function ($code) { return new \Box_Period($code); }); -$di['theme'] = function() use($di) { +$di['theme'] = function () use ($di) { $service = $di['mod_service']('theme'); + return $service->getCurrentClientAreaTheme(); }; -$di['cart'] = function() use($di) { +$di['cart'] = function () use ($di) { $service = $di['mod_service']('cart'); + return $service->getSessionCart(); }; -$di['table'] = $di->protect(function ($name) use($di) { +$di['table'] = $di->protect(function ($name) use ($di) { $tools = new Box_Tools(); $tools->setDi($di); - $table = $tools->getTable($name); + $table = $tools->getTable($name); $table->setDi($di); + return $table; }); $di['license_server'] = function () use ($di) { $server = new \Box\Mod\Servicelicense\Server($di['logger']); $server->setDi($di); + return $server; }; -$di['solusvm'] = $di->protect(function ($config) use($di) { +$di['solusvm'] = $di->protect(function ($config) use ($di) { $solusVM = new \Box\Mod\Servicesolusvm\SolusVM(); $solusVM->setDi($di); $solusVM->setConfig($config); + return $solusVM; }); -$di['service_boxbilling'] = $di->protect(function ($config) use($di) { +$di['service_boxbilling'] = $di->protect(function ($config) { $service = new \Box\Mod\Serviceboxbillinglicense\ServiceBoxbilling($config); + return $service; }); -$di['ftp'] = $di->protect(function($params) use($di){ return new \Box_Ftp($params); }); +$di['ftp'] = $di->protect(function ($params) { return new \Box_Ftp($params); }); $di['pdf'] = function () use ($di) { - include BB_PATH_LIBRARY . '/PDF_ImageAlpha.php'; + include BB_PATH_LIBRARY.'/PDF_ImageAlpha.php'; + return new \PDF_ImageAlpha(); }; -$di['geoip'] = function () use ($di) { return new \GeoIp2\Database\Reader(BB_PATH_LIBRARY . '/GeoLite2-Country.mmdb'); }; +$di['geoip'] = function () { return new \GeoIp2\Database\Reader(BB_PATH_LIBRARY.'/GeoLite2-Country.mmdb'); }; -$di['password'] = function() use ($di) { return new Box_Password();}; -$di['translate'] = $di->protect(function($textDomain = '') use ($di) { +$di['password'] = function () { return new Box_Password(); }; +$di['translate'] = $di->protect(function ($textDomain = '') use ($di) { $tr = new Box_Translate(); - if (!empty($textDomain)){ + if (!empty($textDomain)) { $tr->setDomain($textDomain); } $cookieBBlang = $di['cookie']->get('BBLANG'); - $locale = !empty($cookieBBlang) ? $cookieBBlang : $di['config']['locale']; + $locale = !empty($cookieBBlang) ? $cookieBBlang : $di['config']['locale']; $tr->setDi($di); $tr->setLocale($locale); $tr->setup(); + return $tr; }); -$di['array_get'] = $di->protect(function (array $array, $key, $default = null) use ($di) { - return array_key_exists($key, $array) ? $array[$key] : $default; +$di['array_get'] = $di->protect(function (array $array, $key, $default = null) { + return array_key_exists($key, $array) ? $array[$key] : $default; }); + return $di; diff --git a/src/bb-ipn.php b/src/bb-ipn.php index 4e9399f22..362a0b25f 100644 --- a/src/bb-ipn.php +++ b/src/bb-ipn.php @@ -1,6 +1,6 @@ true, - 'bb_invoice_id' => $bb_invoice_id, - 'bb_gateway_id' => $bb_gateway_id, - 'get' => $_GET, - 'post' => $_POST, - 'server' => $_SERVER, - 'http_raw_post_data' => file_get_contents("php://input"), -); +$ipn = [ + 'skip_validation' => true, + 'bb_invoice_id' => $bb_invoice_id, + 'bb_gateway_id' => $bb_gateway_id, + 'get' => $_GET, + 'post' => $_POST, + 'server' => $_SERVER, + 'http_raw_post_data' => file_get_contents('php://input'), +]; try { $service = $di['mod_service']('invoice', 'transaction'); $output = $service->createAndProcess($ipn); - $res = array('result'=>$output, 'error'=>null); -} catch(Exception $e) { - $res = array('result'=>null, 'error'=> array('message' => $e->getMessage())); + $res = ['result' => $output, 'error' => null]; +} catch (Exception $e) { + $res = ['result' => null, 'error' => ['message' => $e->getMessage()]]; $output = false; } // redirect to invoice if gateways requires -if(isset($_GET['bb_redirect']) && isset($_GET['bb_invoice_hash'])) { +if (isset($_GET['bb_redirect']) && isset($_GET['bb_invoice_hash'])) { $url = $di['url']->link('invoice/'.$_GET['bb_invoice_hash']); header("Location: $url"); exit; @@ -58,6 +57,6 @@ if(isset($_GET['bb_redirect']) && isset($_GET['bb_invoice_hash'])) { header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json; charset=utf-8'); - print json_encode($res); + echo json_encode($res); exit; -} \ No newline at end of file +} diff --git a/src/bb-load.php b/src/bb-load.php index 60d9f68b5..feaa815b9 100644 --- a/src/bb-load.php +++ b/src/bb-load.php @@ -1,6 +1,6 @@ getCode() ."] occurred in [". $e->getFile() ."] at line [". $e->getLine() ."]: [". trim(strip_tags($e->getMessage())) ."]"; - } else { - if(APPLICATION_ENV == 'testing') { - print $e->getMessage() . PHP_EOL; - return ; - } - error_log($e->getMessage()); - - if(defined('BB_MODE_API')) { - $code = $e->getCode() ? $e->getCode() : 9998; - $result = array('result'=>NULL, 'error'=>array('message'=>$e->getMessage(), 'code'=>$code)); - print json_encode($result); - return false; - } - - if(defined('BB_DEBUG') && BB_DEBUG && file_exists(BB_PATH_VENDOR)) { - /** - * If advanced debugging is enabled, print Whoops instead of our error page. - * flip/whoops documentation: https://github.com/filp/whoops/blob/master/docs/API%20Documentation.md - */ - $whoops = new \Whoops\Run; - $prettyPage = new \Whoops\Handler\PrettyPageHandler; - $prettyPage->setPageTitle("An error ocurred"); - $prettyPage->addDataTable('BoxBilling environment', [ - 'PHP Version' => phpversion(), - 'Error code' => $e->getCode() - ]); - $whoops->pushHandler($prettyPage); - $whoops->allowQuit(false); - $whoops->writeToOutput(false); - - print($whoops->handleException($e)); + if (isCLI) { + echo 'Error #['.$e->getCode().'] occurred in ['.$e->getFile().'] at line ['.$e->getLine().']: ['.trim(strip_tags($e->getMessage())).']'; } else { - $page = " + if (APPLICATION_ENV == 'testing') { + echo $e->getMessage().PHP_EOL; + + return; + } + error_log($e->getMessage()); + + if (defined('BB_MODE_API')) { + $code = $e->getCode() ? $e->getCode() : 9998; + $result = ['result' => null, 'error' => ['message' => $e->getMessage(), 'code' => $code]]; + echo json_encode($result); + + return false; + } + + if (defined('BB_DEBUG') && BB_DEBUG && file_exists(BB_PATH_VENDOR)) { + /** + * If advanced debugging is enabled, print Whoops instead of our error page. + * flip/whoops documentation: https://github.com/filp/whoops/blob/master/docs/API%20Documentation.md. + */ + $whoops = new \Whoops\Run(); + $prettyPage = new \Whoops\Handler\PrettyPageHandler(); + $prettyPage->setPageTitle('An error ocurred'); + $prettyPage->addDataTable('BoxBilling environment', [ + 'PHP Version' => phpversion(), + 'Error code' => $e->getCode(), + ]); + $whoops->pushHandler($prettyPage); + $whoops->allowQuit(false); + $whoops->writeToOutput(false); + + echo $whoops->handleException($e); + } else { + $page = " @@ -205,57 +207,56 @@ function handler_exception($e)

Error

"; - $page = str_replace(PHP_EOL, "", $page); - print $page; - if($e->getCode()) { - print sprintf('

Error code: %s

', $e->getCode()); - } - print sprintf('

%s

', $e->getMessage()); - - print sprintf('

Look for detailed error explanation

', urlencode($e->getMessage())); - print('

Powered by BoxBilling

+ $page = str_replace(PHP_EOL, '', $page); + echo $page; + if ($e->getCode()) { + echo sprintf('

Error code: %s

', $e->getCode()); + } + echo sprintf('

%s

', $e->getMessage()); + + echo sprintf('

Look for detailed error explanation

', urlencode($e->getMessage())); + echo '

Powered by BoxBilling

- '); + '; + } } - } } -set_exception_handler("handler_exception"); +set_exception_handler('handler_exception'); set_error_handler('handler_error'); // Check for Composer packages -if(!file_exists(BB_PATH_VENDOR)) { - throw new Exception("It seems like Composer packages are missing. You have to run \"composer install\" in order to install them. For detailed instruction, you can see Composer's getting started guide.

If you have downloaded BoxBilling from GitHub releases, this shouldn't happen.", 110); +if (!file_exists(BB_PATH_VENDOR)) { + throw new Exception("It seems like Composer packages are missing. You have to run \"composer install\" in order to install them. For detailed instruction, you can see Composer's getting started guide.

If you have downloaded BoxBilling from GitHub releases, this shouldn't happen.", 110); } // Multisite support. Load new configuration depending on the current hostname // If being run from CLI, first parameter must be the hostname $configPath = BB_PATH_ROOT.'/bb-config.php'; -if((isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST']) || (php_sapi_name() == 'cli' && isset($argv[1]) ) ) { - if(php_sapi_name() == 'cli') { +if ((isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST']) || ('cli' == php_sapi_name() && isset($argv[1]))) { + if ('cli' == php_sapi_name()) { $host = $argv[1]; } else { $host = $_SERVER['HTTP_HOST']; } - + $predictConfigPath = BB_PATH_ROOT.'/bb-config-'.$host.'.php'; - if(file_exists($predictConfigPath)) { + if (file_exists($predictConfigPath)) { $configPath = $predictConfigPath; } } // Try to check if configuration is available -if(!file_exists($configPath) || 0 == filesize($configPath)) { - +if (!file_exists($configPath) || 0 == filesize($configPath)) { // Try to create an empty configuration file @file_put_contents($configPath, ''); - - $base_url = "http".(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ? 's' : '')."://".$_SERVER['HTTP_HOST']; - $base_url .= preg_replace('@/+$@','',dirname($_SERVER['SCRIPT_NAME'])); - $url = $base_url . '/install/index.php'; - if(file_exists(BB_PATH_ROOT.'/install/index.php')){ + $base_url = 'http'.(isset($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'] || 1 == $_SERVER['HTTPS']) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 'https' == $_SERVER['HTTP_X_FORWARDED_PROTO'] ? 's' : '').'://'.$_SERVER['HTTP_HOST']; + $base_url .= preg_replace('@/+$@', '', dirname($_SERVER['SCRIPT_NAME'])); + $url = $base_url.'/install/index.php'; + + if (file_exists(BB_PATH_ROOT.'/install/index.php')) { header("Location: $url"); } @@ -265,34 +266,34 @@ if(!file_exists($configPath) || 0 == filesize($configPath)) { } // Try to check if /install directory still exists, even after the installation was completed -if(file_exists($configPath) && 0 !== filesize($configPath) && file_exists(BB_PATH_ROOT.'/install/index.php')) { - throw new Exception("For safety reasons, you have to delete the /install directory to start using BoxBilling.

Please delete the /install directory from your web server.", 102); +if (file_exists($configPath) && 0 !== filesize($configPath) && file_exists(BB_PATH_ROOT.'/install/index.php')) { + throw new Exception('For safety reasons, you have to delete the /install directory to start using BoxBilling.

Please delete the /install directory from your web server.', 102); } $config = require_once $configPath; -require BB_PATH_VENDOR . '/autoload.php'; +require BB_PATH_VENDOR.'/autoload.php'; date_default_timezone_set($config['timezone']); -define('BB_DEBUG', $config['debug']); -define('BB_URL', $config['url']); -define('BB_SEF_URLS', $config['sef_urls']); -define('BB_PATH_CACHE', $config['path_data'] . '/cache'); -define('BB_PATH_LOG', $config['path_data'] . '/log'); -define('BB_SSL', (substr($config['url'], 0, 5) === 'https')); +define('BB_DEBUG', $config['debug']); +define('BB_URL', $config['url']); +define('BB_SEF_URLS', $config['sef_urls']); +define('BB_PATH_CACHE', $config['path_data'].'/cache'); +define('BB_PATH_LOG', $config['path_data'].'/log'); +define('BB_SSL', ('https' === substr($config['url'], 0, 5))); -if($config['sef_urls']) { - define('BB_URL_API', $config['url'] . 'api/'); +if ($config['sef_urls']) { + define('BB_URL_API', $config['url'].'api/'); } else { - define('BB_URL_API', $config['url'] . 'index.php?_url=/api/'); + define('BB_URL_API', $config['url'].'index.php?_url=/api/'); } -include_once BB_PATH_LIBRARY .'/Security/CSRF-Protector-PHP/libs/csrf/csrfprotector.php'; +include_once BB_PATH_LIBRARY.'/Security/CSRF-Protector-PHP/libs/csrf/csrfprotector.php'; // Initialize CSRFProtector library csrfProtector::init(); -if($config['debug']) { +if ($config['debug']) { error_reporting(E_ALL); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); @@ -303,5 +304,5 @@ if($config['debug']) { } ini_set('log_errors', '1'); -ini_set('html_errors', FALSE); -ini_set('error_log', BB_PATH_LOG . '/php_error.log'); +ini_set('html_errors', false); +ini_set('error_log', BB_PATH_LOG.'/php_error.log'); diff --git a/src/bb-modules/Activity/Api/Admin.php b/src/bb-modules/Activity/Api/Admin.php index a6e009dde..1b4db8616 100644 --- a/src/bb-modules/Activity/Api/Admin.php +++ b/src/bb-modules/Activity/Api/Admin.php @@ -1,6 +1,6 @@ di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - list($sql, $params) = $this->getService()->getSearchQuery($data); + $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + [$sql, $params] = $this->getService()->getSearchQuery($data); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { if (isset($item['staff_id'])) { - $pager['list'][$key]['staff']['id'] = $item['staff_id']; - $pager['list'][$key]['staff']['name'] = $item['staff_name']; + $pager['list'][$key]['staff']['id'] = $item['staff_id']; + $pager['list'][$key]['staff']['name'] = $item['staff_name']; $pager['list'][$key]['staff']['email'] = $item['staff_email']; } if (isset($item['client_id'])) { - $pager['list'][$key]['client']['id'] = $item['client_id']; - $pager['list'][$key]['client']['name'] = $item['client_name']; + $pager['list'][$key]['client']['id'] = $item['client_id']; + $pager['list'][$key]['client']['name'] = $item['client_name']; $pager['list'][$key]['client']['email'] = $item['client_email']; } } @@ -45,38 +45,38 @@ class Admin extends \Api_Abstract } /** - * Add message to log + * Add message to log. * * @param string $m - Message text * @optional int $admin_id - admin id * @optional int $client_id - client id * @optional string $priority - log priority - * + * * @return bool */ public function log($data) { - if(!isset($data['m'])) { + if (!isset($data['m'])) { return false; } - + $priority = $this->di['array_get']($data, 'priority', 6); $entry = $this->di['db']->dispense('ActivitySystem'); - $entry->client_id = $this->di['array_get']($data, 'client_id', NULL); - $entry->admin_id = $this->di['array_get']($data, 'admin_id', NULL); - $entry->priority = $priority; - $entry->message = $data['m']; - $entry->created_at = date('Y-m-d H:i:s'); - $entry->updated_at = date('Y-m-d H:i:s'); - $entry->ip = $this->di['request']->getClientAddress(); + $entry->client_id = $this->di['array_get']($data, 'client_id', null); + $entry->admin_id = $this->di['array_get']($data, 'admin_id', null); + $entry->priority = $priority; + $entry->message = $data['m']; + $entry->created_at = date('Y-m-d H:i:s'); + $entry->updated_at = date('Y-m-d H:i:s'); + $entry->ip = $this->di['request']->getClientAddress(); $this->di['db']->store($entry); - + return true; } - + /** - * Add email to log + * Add email to log. * * @return bool */ @@ -84,39 +84,41 @@ class Admin extends \Api_Abstract { if (!isset($data['subject'])) { error_log('Email was not logged. Subject not passed'); + return false; } - $client_id = $this->di['array_get']($data, 'client_id', NULL); - $sender = $this->di['array_get']($data, 'sender', NULL); - $recipients = $this->di['array_get']($data, 'recipients', NULL); - $subject = $data['subject']; - $content_html = $this->di['array_get']($data, 'content_html', NULL); - $content_text = $this->di['array_get']($data, 'content_text', NULL); + $client_id = $this->di['array_get']($data, 'client_id', null); + $sender = $this->di['array_get']($data, 'sender', null); + $recipients = $this->di['array_get']($data, 'recipients', null); + $subject = $data['subject']; + $content_html = $this->di['array_get']($data, 'content_html', null); + $content_text = $this->di['array_get']($data, 'content_text', null); return $this->getService()->logEmail($subject, $client_id, $sender, $recipients, $content_html, $content_text); } /** - * Remove activity message + * Remove activity message. * * @param int $id - Message ID */ public function log_delete($data) { - $required = array( + $required = [ 'id' => 'ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ActivitySystem', $data['id'], 'Event not found'); $this->di['db']->trash($model); + return true; } /** - * Deletes logs with given IDs + * Deletes logs with given IDs. * * @param array $ids - IDs for deletion * @@ -124,13 +126,13 @@ class Admin extends \Api_Abstract */ public function batch_delete($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->log_delete(array('id' => $id)); + $this->log_delete(['id' => $id]); } return true; diff --git a/src/bb-modules/Activity/Controller/Admin.php b/src/bb-modules/Activity/Controller/Admin.php index c92d456f2..420eb518b 100644 --- a/src/bb-modules/Activity/Controller/Admin.php +++ b/src/bb-modules/Activity/Controller/Admin.php @@ -1,6 +1,6 @@ array( - 'index' => 700, - 'location' => 'activity', + return [ + 'group' => [ + 'index' => 700, + 'location' => 'activity', 'label' => 'Activity', - 'class' => 'graphs', + 'class' => 'graphs', 'sprite_class' => 'dark-sprite-icon sprite-graph', - ), - 'subpages'=> array( - array( - 'location' => 'activity', + ], + 'subpages' => [ + [ + 'location' => 'activity', 'label' => 'Events history', - 'index' => 100, + 'index' => 100, 'uri' => $this->di['url']->adminLink('activity'), - 'class' => '', - ), - ), - ); + 'class' => '', + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/activity', 'get_index', array(), get_class($this)); + $app->get('/activity', 'get_index', [], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_activity_index'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Activity/Service.php b/src/bb-modules/Activity/Service.php index e883b1d24..f969ffff7 100644 --- a/src/bb-modules/Activity/Service.php +++ b/src/bb-modules/Activity/Service.php @@ -1,6 +1,6 @@ di['db']->dispense('ActivitySystem'); - $entry->client_id = $this->di['array_get']($data, 'client_id', NULL); - $entry->admin_id = $this->di['array_get']($data, 'admin_id', NULL); - $entry->priority = $this->di['array_get']($data, 'priority', NULL); - $entry->message = $data['message']; - $entry->created_at = date('Y-m-d H:i:s'); - $entry->updated_at = date('Y-m-d H:i:s'); - $entry->ip = $this->di['request']->getClientAddress(); + $entry->client_id = $this->di['array_get']($data, 'client_id', null); + $entry->admin_id = $this->di['array_get']($data, 'admin_id', null); + $entry->priority = $this->di['array_get']($data, 'priority', null); + $entry->message = $data['message']; + $entry->created_at = date('Y-m-d H:i:s'); + $entry->updated_at = date('Y-m-d H:i:s'); + $entry->ip = $this->di['request']->getClientAddress(); $this->di['db']->store($entry); } /** EVENTS **/ - public static function onAfterClientLogin(\Box_Event $event) { $params = $event->getParameters(); $di = $event->getDi(); $log = $di['db']->dispense('ActivityClientHistory'); - $log->client_id = $params['id']; - $log->ip = $params['ip']; - $log->created_at = date('Y-m-d H:i:s'); - $log->updated_at = date('Y-m-d H:i:s'); + $log->client_id = $params['id']; + $log->ip = $params['ip']; + $log->created_at = date('Y-m-d H:i:s'); + $log->updated_at = date('Y-m-d H:i:s'); $di['db']->store($log); } - + public static function onAfterAdminLogin(\Box_Event $event) { $params = $event->getParameters(); $di = $event->getDi(); - - $log= $di['db']->dispense('ActivityAdminHistory'); - $log->admin_id = $params['id']; - $log->ip = $params['ip']; - $log->created_at = date('Y-m-d H:i:s'); - $log->updated_at = date('Y-m-d H:i:s'); + + $log = $di['db']->dispense('ActivityAdminHistory'); + $log->admin_id = $params['id']; + $log->ip = $params['ip']; + $log->created_at = date('Y-m-d H:i:s'); + $log->updated_at = date('Y-m-d H:i:s'); $di['db']->store($log); } public function getSearchQuery($data) { - $sql = 'SELECT m.*, a.id as staff_id, a.email as staff_email, a.name as staff_name, c.id as client_id, CONCAT(c.first_name, " ", c.last_name) as client_name, c.email as client_email FROM activity_system as m left join admin as a on a.id = m.admin_id left join client as c on c.id = m.client_id'; - $params = array(); - $search = $this->di['array_get']($data, 'search', NULL); - $priority = $this->di['array_get']($data, 'priority', NULL); - $only_staff = $this->di['array_get']($data, 'only_staff', NULL); - $admin_id = $this->di['array_get']($data, 'admin_id', NULL); - $only_clients = $this->di['array_get']($data, 'only_clients', NULL); - $no_info = $this->di['array_get']($data, 'no_info', NULL); - $no_debug = $this->di['array_get']($data, 'no_debug', NULL); - $where = array (); - if($priority) { + $params = []; + $search = $this->di['array_get']($data, 'search', null); + $priority = $this->di['array_get']($data, 'priority', null); + $only_staff = $this->di['array_get']($data, 'only_staff', null); + $admin_id = $this->di['array_get']($data, 'admin_id', null); + $only_clients = $this->di['array_get']($data, 'only_clients', null); + $no_info = $this->di['array_get']($data, 'no_info', null); + $no_debug = $this->di['array_get']($data, 'no_debug', null); + $where = []; + if ($priority) { $where[] = 'm.priority = :priority'; $params[':priority'] = $priority; } - if($no_info) { + if ($no_info) { $where[] = 'm.priority < :priority'; $params[':priority'] = \Box_Log::INFO; } - if($no_debug) { + if ($no_debug) { $where[] = 'm.priority < :priority'; $params[':priority'] = \Box_Log::DEBUG; } - if($only_staff) { + if ($only_staff) { $where[] = 'm.admin_id IS NOT NULL'; } - if($admin_id) { + if ($admin_id) { $where[] = 'm.admin_id = :admin_id'; $params[':admin_id'] = $admin_id; } - if($only_clients) { + if ($only_clients) { $where[] = 'm.client_id IS NOT NULL'; } - if($search) { + if ($search) { $where[] = 'm.message LIKE :search OR m.ip LIKE :search2'; $params[':search'] = $search; $params[':search2'] = $search; } - if (!empty($where)){ + if (!empty($where)) { $whereStatment = implode(' and ', $where); $sql .= ' WHERE '.$whereStatment; } $sql .= ' ORDER by m.id desc'; - return array($sql, $params); + + return [$sql, $params]; } public function logEmail($subject, $clientId = null, $sender = null, $recipients = null, $content_html = null, $content_text = null) { $entry = $this->di['db']->dispense('ActivityClientEmail'); - $entry->client_id = $clientId; - $entry->sender = $sender; - $entry->recipients = $recipients; - $entry->subject = $subject; + $entry->client_id = $clientId; + $entry->sender = $sender; + $entry->recipients = $recipients; + $entry->subject = $subject; $entry->content_html = $content_html; $entry->content_text = $content_text; - $entry->created_at = date('Y-m-d H:i:s'); - $entry->updated_at = date('Y-m-d H:i:s'); + $entry->created_at = date('Y-m-d H:i:s'); + $entry->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($entry); @@ -151,24 +151,25 @@ class Service implements InjectionAwareInterface public function toApiArray(\Model_ActivityClientHistory $model) { $client = $this->di['db']->getExistingModelById('Client', $model->client_id, 'Client not found'); - return array( - 'id' => $model->id, - 'ip' => $model->ip, - 'created_at' => $model->created_at, - 'client' => array( - 'id' => $client->id, - 'first_name' => $client->first_name, - 'last_name' => $client->last_name, - 'email' => $client->email, - ) - ); + + return [ + 'id' => $model->id, + 'ip' => $model->ip, + 'created_at' => $model->created_at, + 'client' => [ + 'id' => $client->id, + 'first_name' => $client->first_name, + 'last_name' => $client->last_name, + 'email' => $client->email, + ], + ]; } public function rmByClient(\Model_Client $client) { - $models = $this->di['db']->find('ActivitySystem', 'client_id = ?', array($client->id)); - foreach($models as $model){ + $models = $this->di['db']->find('ActivitySystem', 'client_id = ?', [$client->id]); + foreach ($models as $model) { $this->di['db']->trash($model); } } -} \ No newline at end of file +} diff --git a/src/bb-modules/Api/Controller/Client.php b/src/bb-modules/Api/Controller/Client.php index 47dace2b0..3ecc92573 100644 --- a/src/bb-modules/Api/Controller/Client.php +++ b/src/bb-modules/Api/Controller/Client.php @@ -1,6 +1,6 @@ post('/api/:role/:class/:method', 'post_method', array('role', 'class', 'method'), get_class($this)); - $app->get('/api/:role/:class/:method', 'get_method', array('role', 'class', 'method'), get_class($this)); - - //all other requests are error requests - $app->get('/api/:page', 'show_error', array('page' => '(.?)+'), get_class($this)); - $app->post('/api/:page', 'show_error', array('page' => '(.?)+'), get_class($this)); + $app->post('/api/:role/:class/:method', 'post_method', ['role', 'class', 'method'], get_class($this)); + $app->get('/api/:role/:class/:method', 'get_method', ['role', 'class', 'method'], get_class($this)); + + // all other requests are error requests + $app->get('/api/:page', 'show_error', ['page' => '(.?)+'], get_class($this)); + $app->post('/api/:page', 'show_error', ['page' => '(.?)+'], get_class($this)); } - + public function show_error(\Box_App $app, $page) { - $exc = new \Box_Exception('Unknown API call :call', array(':call'=>$page), 879); + $exc = new \Box_Exception('Unknown API call :call', [':call' => $page], 879); + return $this->renderJson(null, $exc); } - + public function get_method(\Box_App $app, $role, $class, $method) { $call = $class.'_'.$method; + return $this->tryCall($role, $call, $_GET); } public function post_method(\Box_App $app, $role, $class, $method) { $p = $_POST; - + // adding support for raw post input with json string - $input = file_get_contents("php://input"); - if(empty($p) && !empty($input)) { + $input = file_get_contents('php://input'); + if (empty($p) && !empty($input)) { $p = @json_decode($input, 1); } - + $call = $class.'_'.$method; + return $this->tryCall($role, $call, $p); } @@ -87,23 +90,23 @@ class Client implements InjectionAwareInterface $this->renderJson(null, $exc); } } - + private function _loadConfig() { - if(is_null($this->_api_config)) { + if (is_null($this->_api_config)) { $this->_api_config = $this->di['config']['api']; } } - private function checkRateLimit($method=null) + private function checkRateLimit($method = null) { $isLoginMethod = false; - if($method == 'staff_login' || $method == 'client_login'){ - $rate_span = $this->_api_config['rate_span_login']; + if ('staff_login' == $method || 'client_login' == $method) { + $rate_span = $this->_api_config['rate_span_login']; $rate_limit = $this->_api_config['rate_limit_login']; $isLoginMethod = true; } else { - $rate_span = $this->_api_config['rate_span']; + $rate_span = $this->_api_config['rate_span']; $rate_limit = $this->_api_config['rate_limit']; } @@ -114,41 +117,44 @@ class Client implements InjectionAwareInterface if ($requests_left < 0) { sleep($this->_api_config['throttle_delay']); } + return true; } private function checkHttpReferer() { // snake oil: check request is from the same domain as BoxBilling is installed if present - $check_referer_header = isset($this->_api_config['require_referrer_header']) ? (bool)$this->_api_config['require_referrer_header'] : false; - if($check_referer_header) { + $check_referer_header = isset($this->_api_config['require_referrer_header']) ? (bool) $this->_api_config['require_referrer_header'] : false; + if ($check_referer_header) { $url = strtolower(BB_URL); - $referer = isset($_SERVER['HTTP_REFERER']) ? strtolower($_SERVER['HTTP_REFERER']) : null ; - if(!$referer || $url != substr($referer, 0, strlen($url))) { - throw new \Box_Exception('Invalid request. Make sure request origin is :from', array(':from'=>BB_URL), 1004); + $referer = isset($_SERVER['HTTP_REFERER']) ? strtolower($_SERVER['HTTP_REFERER']) : null; + if (!$referer || $url != substr($referer, 0, strlen($url))) { + throw new \Box_Exception('Invalid request. Make sure request origin is :from', [':from' => BB_URL], 1004); } } + return true; } private function checkAllowedIps() { $ips = $this->_api_config['allowed_ips']; - if(!empty($ips) && !in_array($this->_getIp(), $ips)) { + if (!empty($ips) && !in_array($this->_getIp(), $ips)) { throw new \Box_Exception('Unauthorized IP', null, 1002); } + return true; } private function isRoleLoggedIn($role) { - if ($role == 'client'){ + if ('client' == $role) { $this->di['is_client_logged']; - } - if ($role == 'admin'){ + if ('admin' == $role) { $this->di['is_admin_logged']; } + return true; } @@ -163,65 +169,66 @@ class Client implements InjectionAwareInterface $this->checkHttpReferer(); $this->isRoleAllowed($role); - try{ + try { $this->isRoleLoggedIn($role); - }catch (\Exception $e){ + } catch (\Exception $e) { $this->_tryTokenLogin(); } $api = $this->di['api']($role); $result = $api->$method($params); + return $this->renderJson($result); } private function getAuth() { - if(isset($_SERVER['HTTP_AUTHORIZATION'])) { - $auth_params = explode(":" , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); + if (isset($_SERVER['HTTP_AUTHORIZATION'])) { + $auth_params = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); $_SERVER['PHP_AUTH_USER'] = $auth_params[0]; unset($auth_params[0]); - $_SERVER['PHP_AUTH_PW'] = implode('',$auth_params); + $_SERVER['PHP_AUTH_PW'] = implode('', $auth_params); } - if(!isset($_SERVER['PHP_AUTH_USER'])) { + if (!isset($_SERVER['PHP_AUTH_USER'])) { throw new \Box_Exception('Authentication Failed', null, 201); } - if(!isset($_SERVER['PHP_AUTH_PW'])) { + if (!isset($_SERVER['PHP_AUTH_PW'])) { throw new \Box_Exception('Authentication Failed', null, 202); } - if(empty($_SERVER['PHP_AUTH_PW'])) { + if (empty($_SERVER['PHP_AUTH_PW'])) { throw new \Box_Exception('Authentication Failed', null, 206); } - return array($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); + return [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']]; } private function _tryTokenLogin() { - list($username, $password) = $this->getAuth(); + [$username, $password] = $this->getAuth(); switch ($username) { case 'client': - $model = $this->di['db']->findOne('Client', 'api_token = ?', array($password)); - if(!$model instanceof \Model_Client) { + $model = $this->di['db']->findOne('Client', 'api_token = ?', [$password]); + if (!$model instanceof \Model_Client) { throw new \Box_Exception('Authentication Failed', null, 204); } $this->di['session']->set('client_id', $model->id); break; case 'admin': - $model = $this->di['db']->findOne('Admin', 'api_token = ?', array($password)); - if(!$model instanceof \Model_Admin) { + $model = $this->di['db']->findOne('Admin', 'api_token = ?', [$password]); + if (!$model instanceof \Model_Admin) { throw new \Box_Exception('Authentication Failed', null, 205); } - $sessionAdminArray = array( - 'id' => $model->id, - 'email' => $model->email, - 'name' => $model->name, - 'role' => $model->role, - ); + $sessionAdminArray = [ + 'id' => $model->id, + 'email' => $model->email, + 'name' => $model->name, + 'role' => $model->role, + ]; $this->di['session']->set('admin', $sessionAdminArray); break; @@ -233,26 +240,28 @@ class Client implements InjectionAwareInterface /** * @param string $role + * * @throws \Box_Exception */ private function isRoleAllowed($role) { - $allowed = array('guest', 'client', 'admin'); - if (!in_array($role, $allowed)){ + $allowed = ['guest', 'client', 'admin']; + if (!in_array($role, $allowed)) { throw new \Box_Exception('Unknow API call', null, 701); } + return true; } - public function renderJson($data = NULL, \Exception $e = NULL) + public function renderJson($data = null, \Exception $e = null) { // do not emit response if headers already sent if (headers_sent()) { - return ; + return; } - + $this->_loadConfig(); - + header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json; charset=utf-8'); @@ -260,14 +269,14 @@ class Client implements InjectionAwareInterface header('X-RateLimit-Span: '.$this->_api_config['rate_span']); header('X-RateLimit-Limit: '.$this->_api_config['rate_limit']); header('X-RateLimit-Remaining: '.$this->_requests_left); - if(NULL !== $e) { + if (null !== $e) { error_log($e->getMessage().' '.$e->getCode()); $code = $e->getCode() ? $e->getCode() : 9999; - $result = array('result'=>NULL, 'error'=>array('message'=>$e->getMessage(), 'code'=>$code)); + $result = ['result' => null, 'error' => ['message' => $e->getMessage(), 'code' => $code]]; } else { - $result = array('result'=>$data, 'error'=> NULL); + $result = ['result' => $data, 'error' => null]; } - print json_encode($result); + echo json_encode($result); exit; } @@ -275,4 +284,4 @@ class Client implements InjectionAwareInterface { return $this->di['request']->getClientAddress(); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Api/Service.php b/src/bb-modules/Api/Service.php index 9ac60a23e..6c03198c7 100644 --- a/src/bb-modules/Api/Service.php +++ b/src/bb-modules/Api/Service.php @@ -1,6 +1,6 @@ di['request']; - $sql=" + $sql = ' INSERT INTO api_request (ip, request, created_at) VALUES(:ip, :request, NOW()) - "; - $values = array( - 'ip' => $request->getClientAddress(), - 'request' => $request->getURI(), - ); + '; + $values = [ + 'ip' => $request->getClientAddress(), + 'request' => $request->getURI(), + ]; + return $this->di['db']->exec($sql, $values); } /** - * @param int $since - timestamp + * @param int $since - timestamp * @param string|null $ip + * * @return int */ public function getRequestCount($since, $ip = null, $isLoginMethod = false) { - if (!is_numeric($since)){ + if (!is_numeric($since)) { $since = strtotime($since); } $sinceIso = date('Y-m-d H:i:s', $since); - $values = array( - 'since' => $sinceIso, - ); - if($isLoginMethod){ - $sql=" + $values = [ + 'since' => $sinceIso, + ]; + if ($isLoginMethod) { + $sql = ' SELECT COUNT(id) as cclogin FROM api_request WHERE created_at > :since - "; + '; } else { - $sql=" + $sql = ' SELECT COUNT(id) as cc FROM api_request WHERE created_at > :since - "; + '; } - if(null != $ip) { - $sql .= " AND ip = :ip"; + if (null != $ip) { + $sql .= ' AND ip = :ip'; $values['ip'] = $ip; } - return (int)$this->di['db']->getCell($sql, $values); + return (int) $this->di['db']->getCell($sql, $values); } /** @@ -93,7 +95,6 @@ class Service implements \Box\InjectionAwareInterface return $this->di['api_guest']; } - /** * @deprecated use DI */ @@ -109,4 +110,4 @@ class Service implements \Box\InjectionAwareInterface { return $this->di['api_admin']; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Branding/Service.php b/src/bb-modules/Branding/Service.php index afb0565fa..1688eb312 100644 --- a/src/bb-modules/Branding/Service.php +++ b/src/bb-modules/Branding/Service.php @@ -1,6 +1,6 @@ getService()->getSearchQuery($data); + [$sql, $params] = $this->getService()->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); + $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); - foreach ($pager['list'] as $key => $cartArr){ - $cart = $this->di['db']->getExistingModelById('Cart', $cartArr['id'], 'Cart not found'); + foreach ($pager['list'] as $key => $cartArr) { + $cart = $this->di['db']->getExistingModelById('Cart', $cartArr['id'], 'Cart not found'); $pager['list'][$key] = $this->getService()->toApiArray($cart); } @@ -37,15 +36,17 @@ class Admin extends \Api_Abstract } /** - * Get shopping cart contents by id + * Get shopping cart contents by id. + * * @param int $id - shopping cart id + * * @return array - shopping cart contents */ public function get($data) { - $required = array( + $required = [ 'id' => 'Shopping cart id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $cart = $this->di['db']->getExistingModelById('Cart', $data['id'], 'Shopping cart not found'); @@ -54,25 +55,26 @@ class Admin extends \Api_Abstract } /** - * Remove shopping carts that are older than a week and was not ordered + * Remove shopping carts that are older than a week and was not ordered. * * @BOXBILLING_CRON + * * @return bool */ public function batch_expire($data) { $this->di['logger']->info('Executed action to clear expired shopping carts from database'); - $query = "SELECT id, created_at FROM `cart` WHERE DATEDIFF(CURDATE(), created_at) > 7;"; - $list = $this->di['db']->getAssoc($query); + $query = 'SELECT id, created_at FROM `cart` WHERE DATEDIFF(CURDATE(), created_at) > 7;'; + $list = $this->di['db']->getAssoc($query); if ($list) { foreach ($list as $id => $created_at) { - $this->di['db']->exec('DELETE FROM `cart_product` WHERE cart_id = :id', array(':id' => $id)); - $this->di['db']->exec('DELETE FROM `cart` WHERE id = :id', array(':id' => $id)); + $this->di['db']->exec('DELETE FROM `cart_product` WHERE cart_id = :id', [':id' => $id]); + $this->di['db']->exec('DELETE FROM `cart` WHERE id = :id', [':id' => $id]); } $this->di['logger']->info('Removed %s expired shopping carts', count($list)); } return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cart/Api/Client.php b/src/bb-modules/Cart/Api/Client.php index 3337bf0a5..c810a12a2 100644 --- a/src/bb-modules/Cart/Api/Client.php +++ b/src/bb-modules/Cart/Api/Client.php @@ -1,6 +1,6 @@ di['array_get']($data, 'gateway_id'); + $gateway_id = $this->di['array_get']($data, 'gateway_id'); $cart = $this->getService()->getSessionCart(); $client = $this->getIdentity(); + return $this->getService()->checkoutCart($cart, $client, $gateway_id); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cart/Api/Guest.php b/src/bb-modules/Cart/Api/Guest.php index 522de1dcb..5a96d4469 100644 --- a/src/bb-modules/Cart/Api/Guest.php +++ b/src/bb-modules/Cart/Api/Guest.php @@ -1,6 +1,6 @@ 'Currency code not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $currencyService = $this->di['mod_service']('currency'); - $currency = $currencyService->getByCode($data['currency']); + $currency = $currencyService->getByCode($data['currency']); if (!$currency instanceof \Model_Currency) { throw new \Box_Exception('Currency not found'); } @@ -67,7 +66,7 @@ class Guest extends \Api_Abstract } /** - * Retrieve information about currently selected shopping cart currency + * Retrieve information about currently selected shopping cart currency. * * @return array - Currency details */ @@ -76,7 +75,7 @@ class Guest extends \Api_Abstract $cart = $this->getService()->getSessionCart(); $currencyService = $this->di['mod_service']('currency'); - $currency = $this->di['db']->load('Currency', $cart->currency_id); + $currency = $this->di['db']->load('Currency', $cart->currency_id); if (!$currency instanceof \Model_Currency) { $currency = $currencyService->getDefault(); } @@ -85,7 +84,7 @@ class Guest extends \Api_Abstract } /** - * Apply Promo code to shopping cart + * Apply Promo code to shopping cart. * * @param string $promocode - Promo code string * @@ -93,18 +92,17 @@ class Guest extends \Api_Abstract */ public function apply_promo($data) { - $required = array( + $required = [ 'promocode' => 'Promo code not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $promo = $this->getService()->findActivePromoByCode($data['promocode']); if (!$promo instanceof \Model_Promo) { throw new \Box_Exception('Promo code is expired or does not exist'); } - if (!$this->getService()->isPromoAvailableForClientGroup($promo)){ + if (!$this->getService()->isPromoAvailableForClientGroup($promo)) { throw new \Box_Exception('Promo can not be applied to your account'); } @@ -118,7 +116,7 @@ class Guest extends \Api_Abstract } /** - * Removes promo from shopping cart and resets discounted prices if any + * Removes promo from shopping cart and resets discounted prices if any. * * @return bool */ @@ -130,7 +128,7 @@ class Guest extends \Api_Abstract } /** - * Removes product from shopping cart + * Removes product from shopping cart. * * @param int $id - Shopping cart item id * @@ -138,9 +136,9 @@ class Guest extends \Api_Abstract */ public function remove_item($data) { - $required = array( + $required = [ 'id' => 'Cart item id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $cart = $this->getService()->getSessionCart(); @@ -149,7 +147,7 @@ class Guest extends \Api_Abstract } /** - * Adds product to shopping cart + * Adds product to shopping cart. * * @param int $id - Product ID * @@ -163,20 +161,20 @@ class Guest extends \Api_Abstract */ public function add_item($data) { - $required = array( + $required = [ 'id' => 'Product id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $cart = $this->getService()->getSessionCart(); $product = $this->di['db']->getExistingModelById('Product', $data['id'], 'Product not found'); - //reset cart by default + // reset cart by default if (!isset($data['multiple']) || !$data['multiple']) { $this->reset(); } return $this->getService()->addItem($cart, $product, $data); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cart/Controller/Client.php b/src/bb-modules/Cart/Controller/Client.php index 36d64ae79..52968a734 100644 --- a/src/bb-modules/Cart/Controller/Client.php +++ b/src/bb-modules/Cart/Controller/Client.php @@ -1,6 +1,6 @@ get('/cart', 'get_cart', array(), get_class($this)); + $app->get('/cart', 'get_cart', [], get_class($this)); } public function get_cart(\Box_App $app) { return $app->render('mod_cart_index'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cart/Service.php b/src/bb-modules/Cart/Service.php index e7c606000..a2c3e8ca9 100644 --- a/src/bb-modules/Cart/Service.php +++ b/src/bb-modules/Cart/Service.php @@ -1,6 +1,6 @@ $this->di['session']->getId()); - $cart = $this->di['db']->findOne('Cart', 'session_id = :session_id', $sqlBindings); + $sqlBindings = [':session_id' => $this->di['session']->getId()]; + $cart = $this->di['db']->findOne('Cart', 'session_id = :session_id', $sqlBindings); if ($cart instanceof \Model_Cart) { return $cart; @@ -55,16 +54,16 @@ class Service implements InjectionAwareInterface if ($this->di['session']->get('client_id')) { $client_id = $this->di['session']->get('client_id'); - $currency = $cc->getCurrencyByClientId($client_id); + $currency = $cc->getCurrencyByClientId($client_id); } else { $currency = $cc->getDefault(); } - $cart = $this->di['db']->dispense('Cart'); - $cart->session_id = $this->di['session']->getId(); + $cart = $this->di['db']->dispense('Cart'); + $cart->session_id = $this->di['session']->getId(); $cart->currency_id = $currency->id; - $cart->created_at = date('Y-m-d H:i:s'); - $cart->updated_at = date('Y-m-d H:i:s'); + $cart->created_at = date('Y-m-d H:i:s'); + $cart->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($cart); return $cart; @@ -72,15 +71,15 @@ class Service implements InjectionAwareInterface public function addItem(\Model_Cart $cart, \Model_Product $product, array $data) { - $event_params = array_merge($data, array('cart_id' => $cart->id, 'product_id' => $product->id)); - $this->di['events_manager']->fire(array('event' => 'onBeforeProductAddedToCart', 'params' => $event_params)); + $event_params = array_merge($data, ['cart_id' => $cart->id, 'product_id' => $product->id]); + $this->di['events_manager']->fire(['event' => 'onBeforeProductAddedToCart', 'params' => $event_params]); $productService = $product->getService(); if ($this->isRecurrentPricing($product)) { - $required = array( + $required = [ 'period' => 'Period parameter not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); if (!$this->isPeriodEnabledForProduct($product, $data['period'])) { @@ -88,23 +87,23 @@ class Service implements InjectionAwareInterface } } - $qty = $this->di['array_get']($data, 'quantity', 1); + $qty = $this->di['array_get']($data, 'quantity', 1); // check stock if (!$this->isStockAvailable($product, $qty)) { throw new \Box_Exception("I'm afraid we are out of stock."); } - $addons = $this->di['array_get']($data, 'addons', array()); + $addons = $this->di['array_get']($data, 'addons', []); unset($data['id']); unset($data['addons']); - $list = array(); - $list[] = array( + $list = []; + $list[] = [ 'product' => $product, - 'config' => $data, - ); + 'config' => $data, + ]; - //check for required domain product + // check for required domain product if (method_exists($productService, 'getDomainProductFromConfig')) { $dc = $productService->getDomainProductFromConfig($product, $data); if (isset($dc['config']) && $dc['product'] && $dc['product'] instanceof \Model_Product) { @@ -114,14 +113,13 @@ class Service implements InjectionAwareInterface $productService = $this->di['mod_service']('Product'); foreach ($addons as $id => $ac) { - if (isset($ac['selected']) && (bool)$ac['selected']) { + if (isset($ac['selected']) && (bool) $ac['selected']) { $addon = $productService->getAddonById($id); if ($addon instanceof \Model_Product) { if ($this->isRecurrentPricing($addon)) { - - $required = array( + $required = [ 'period' => 'Addon period parameter not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $ac); if (!$this->isPeriodEnabledForProduct($addon, $ac['period'])) { @@ -130,12 +128,12 @@ class Service implements InjectionAwareInterface } $ac['parent_id'] = $product->id; - $list[] = array( + $list[] = [ 'product' => $addon, - 'config' => $ac, - ); + 'config' => $ac, + ]; } else { - error_log('Addon not found by id ' . $id); + error_log('Addon not found by id '.$id); } } } @@ -146,14 +144,14 @@ class Service implements InjectionAwareInterface $productServiceFromList = $productFromList->getService(); - //@deprecated logic + // @deprecated logic if (method_exists($productServiceFromList, 'prependOrderConfig')) { $productFromListConfig = $productServiceFromList->prependOrderConfig($productFromList, $productFromListConfig); } if (method_exists($productServiceFromList, 'attachOrderConfig')) { $model = $this->di['db']->load('Product', $productFromList->id); - $productFromListConfig = $productServiceFromList->attachOrderConfig($model, $productFromListConfig); + $productFromListConfig = $productServiceFromList->attachOrderConfig($model, $productFromListConfig); } if (method_exists($productServiceFromList, 'validateOrderData')) { $productServiceFromList->validateOrderData($productFromListConfig); @@ -166,7 +164,7 @@ class Service implements InjectionAwareInterface $this->di['logger']->info('Added "%s" to shopping cart', $product->title); - $this->di['events_manager']->fire(array('event' => 'onAfterProductAddedToCart', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onAfterProductAddedToCart', 'params' => $event_params]); return true; } @@ -174,25 +172,26 @@ class Service implements InjectionAwareInterface public function isStockAvailable(\Model_Product $product, $qty) { if ($product->stock_control) { - return ($product->quantity_in_stock >= $qty); + return $product->quantity_in_stock >= $qty; } - return TRUE; + return true; } public function isRecurrentPricing(\Model_Product $model) { $productTable = $model->getTable(); - $pricing = $productTable->getPricingArray($model); - return (isset($pricing['type']) && $pricing['type'] == \Model_ProductPayment::RECURRENT); + $pricing = $productTable->getPricingArray($model); + + return isset($pricing['type']) && \Model_ProductPayment::RECURRENT == $pricing['type']; } public function isPeriodEnabledForProduct(\Model_Product $model, $period) { $productTable = $model->getTable(); - $pricing = $productTable->getPricingArray($model); - if ($pricing['type'] == \Model_ProductPayment::RECURRENT) { - return (bool)$pricing['recurrent'][$period]['enabled']; + $pricing = $productTable->getPricingArray($model); + if (\Model_ProductPayment::RECURRENT == $pricing['type']) { + return (bool) $pricing['recurrent'][$period]['enabled']; } return true; @@ -200,10 +199,10 @@ class Service implements InjectionAwareInterface protected function addProduct(\Model_Cart $cart, \Model_Product $product, array $data) { - $item = $this->di['db']->dispense('CartProduct'); - $item->cart_id = $cart->id; + $item = $this->di['db']->dispense('CartProduct'); + $item->cart_id = $cart->id; $item->product_id = $product->id; - $item->config = json_encode($data); + $item->config = json_encode($data); $this->di['db']->store($item); return true; @@ -211,10 +210,10 @@ class Service implements InjectionAwareInterface public function removeProduct(\Model_Cart $cart, $id, $removeAddons = true) { - $bindings = array( + $bindings = [ ':cart_id' => $cart->id, - ':id' => $id - ); + ':id' => $id, + ]; $cartProduct = $this->di['db']->findOne('CartProduct', 'id = :id AND cart_id = :cart_id', $bindings); if (!$cartProduct instanceof \Model_CartProduct) { @@ -222,8 +221,8 @@ class Service implements InjectionAwareInterface } if ($removeAddons) { - $allCartProducts = $this->di['db']->find('CartProduct', 'cart_id = :cart_id', array(':cart_id' => $cart->id)); - foreach ((array)$allCartProducts as $cProduct) { + $allCartProducts = $this->di['db']->find('CartProduct', 'cart_id = :cart_id', [':cart_id' => $cart->id]); + foreach ((array) $allCartProducts as $cProduct) { $config = json_decode($cProduct->config, true); if (isset($config['parent_id']) && $config['parent_id'] == $cartProduct->product_id) { $this->di['db']->trash($cProduct); @@ -251,11 +250,11 @@ class Service implements InjectionAwareInterface public function resetCart(\Model_Cart $cart) { - $cartProducts = $this->di['db']->find('CartProduct', 'cart_id = :cart_id', array(':cart_id' => $cart->id)); + $cartProducts = $this->di['db']->find('CartProduct', 'cart_id = :cart_id', [':cart_id' => $cart->id]); foreach ($cartProducts as $cartProduct) { $this->di['db']->trash($cartProduct); } - $cart->promo_id = NULL; + $cart->promo_id = null; $cart->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($cart); @@ -264,7 +263,7 @@ class Service implements InjectionAwareInterface public function removePromo(\Model_Cart $cart) { - $cart->promo_id = NULL; + $cart->promo_id = null; $cart->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($cart); @@ -293,14 +292,14 @@ class Service implements InjectionAwareInterface protected function isEmptyCart(\Model_Cart $cart) { - $cartProducts = $this->di['db']->find('CartProduct', 'cart_id = :cart_id', array(':cart_id' => $cart->id)); + $cartProducts = $this->di['db']->find('CartProduct', 'cart_id = :cart_id', [':cart_id' => $cart->id]); - return (count($cartProducts) == 0); + return 0 == count($cartProducts); } public function rm(\Model_Cart $cart) { - $cartProducts = $this->di['db']->find('CartProduct', 'cart_id = :cart_id', array(':cart_id' => $cart->id)); + $cartProducts = $this->di['db']->find('CartProduct', 'cart_id = :cart_id', [':cart_id' => $cart->id]); foreach ($cartProducts as $cartProduct) { $this->di['db']->trash($cartProduct); @@ -317,9 +316,9 @@ class Service implements InjectionAwareInterface $currency = $this->di['db']->getExistingModelById('Currency', $model->currency_id); - $items = array(); - $total = 0; - $cart_discount = 0; + $items = []; + $total = 0; + $cart_discount = 0; $items_discount = 0; foreach ($products as $product) { $p = $this->cartProductToApiArray($product); @@ -332,18 +331,18 @@ class Service implements InjectionAwareInterface $promo = $this->di['db']->getExistingModelById('Promo', $model->promo_id, 'Promo not found'); $promocode = $promo->code; } else { - $promocode = NULL; + $promocode = null; } $currencyService = $this->di['mod_service']('currency'); - $result = array( + $result = [ 'promocode' => $promocode, - 'discount' => $items_discount, - 'subtotal' => $total, - 'total' => $total - $items_discount, - 'items' => $items, - 'currency' => $currencyService->toApiArray($currency), - ); + 'discount' => $items_discount, + 'subtotal' => $total, + 'total' => $total - $items_discount, + 'items' => $items, + 'currency' => $currencyService->toApiArray($currency), + ]; return $result; } @@ -396,7 +395,7 @@ class Service implements InjectionAwareInterface $client = null; } - if (is_null($client)){ + if (is_null($client)) { return false; } @@ -409,15 +408,15 @@ class Service implements InjectionAwareInterface protected function clientHadUsedPromo(\Model_Client $client, \Model_Promo $promo) { - $sql = "SELECT id FROM client_order WHERE promo_id = :promo AND client_id = :cid LIMIT 1"; - $promoId = $this->di['db']->getCell($sql, array(':promo' => $promo->id, ':cid' => $client->id)); + $sql = 'SELECT id FROM client_order WHERE promo_id = :promo AND client_id = :cid LIMIT 1'; + $promoId = $this->di['db']->getCell($sql, [':promo' => $promo->id, ':cid' => $client->id]); - return ($promoId !== null); + return null !== $promoId; } public function getCartProducts(\Model_Cart $model) { - return $this->di['db']->find('CartProduct', 'cart_id = :cart_id ORDER BY id ASC', array(':cart_id' => $model->id)); + return $this->di['db']->find('CartProduct', 'cart_id = :cart_id ORDER BY id ASC', [':cart_id' => $model->id]); } public function checkoutCart(\Model_Cart $cart, \Model_Client $client, $gateway_id = null) @@ -430,41 +429,41 @@ class Service implements InjectionAwareInterface } $this->di['events_manager']->fire( - array( - 'event' => 'onBeforeClientCheckout', - 'params' => array( - 'ip' => $this->di['request']->getClientAddress(), + [ + 'event' => 'onBeforeClientCheckout', + 'params' => [ + 'ip' => $this->di['request']->getClientAddress(), 'client_id' => $client->id, - 'cart_id' => $cart->id) - ) + 'cart_id' => $cart->id, ], + ] ); - list($order, $invoice, $orders) = $this->createFromCart($client, $gateway_id); + [$order, $invoice, $orders] = $this->createFromCart($client, $gateway_id); $this->rm($cart); $this->di['logger']->info('Checked out shopping cart'); $this->di['events_manager']->fire( - array( - 'event' => 'onAfterClientOrderCreate', - 'params' => array( - 'ip' => $this->di['request']->getClientAddress(), + [ + 'event' => 'onAfterClientOrderCreate', + 'params' => [ + 'ip' => $this->di['request']->getClientAddress(), 'client_id' => $client->id, - 'id' => $order->id - ) - ) + 'id' => $order->id, + ], + ] ); - $result = array( - 'gateway_id' => $gateway_id, + $result = [ + 'gateway_id' => $gateway_id, 'invoice_hash' => null, - 'order_id' => $order->id, - 'orders' => $orders, - ); + 'order_id' => $order->id, + 'orders' => $orders, + ]; // invoice may not be created if total is 0 - if ($invoice instanceof \Model_Invoice && $invoice->status == \Model_Invoice::STATUS_UNPAID) { + if ($invoice instanceof \Model_Invoice && \Model_Invoice::STATUS_UNPAID == $invoice->status) { $result['invoice_hash'] = $invoice->hash; } @@ -475,31 +474,29 @@ class Service implements InjectionAwareInterface { $cart = $this->getSessionCart(); $ca = $this->toApiArray($cart); - if (count($ca['items']) == 0) { + if (0 == count($ca['items'])) { throw new \Box_Exception('Can not checkout empty cart.'); } - $currency = $this->di['db']->getExistingModelById('Currency', $cart->currency_id, 'Currency not found.'); - //set default client currency + // set default client currency if (!$client->currency) { $client->currency = $currency->code; $this->di['db']->store($client); } if ($client->currency != $currency->code) { - throw new \Box_Exception('Selected currency :selected does not match your profile currency :code. Please change cart currency to continue.', - array(':selected' => $currency->code, ':code' => $client->currency)); + throw new \Box_Exception('Selected currency :selected does not match your profile currency :code. Please change cart currency to continue.', [':selected' => $currency->code, ':code' => $client->currency]); } $clientService = $this->di['mod_service']('client'); - $taxed = $clientService->isClientTaxable($client); + $taxed = $clientService->isClientTaxable($client); - $orders = array(); - $invoice_items = array(); - $master_order = null; - $i = 0; + $orders = []; + $invoice_items = []; + $master_order = null; + $i = 0; foreach ($this->getCartProducts($cart) as $p) { $item = $this->cartProductToApiArray($p); @@ -517,28 +514,28 @@ class Service implements InjectionAwareInterface $item['domain']['register_sld'] = strtolower($item['domain']['register_sld']); $item['domain']['transfer_sld'] = strtolower($item['domain']['transfer_sld']); - $order = $this->di['db']->dispense('ClientOrder'); - $order->client_id = $client->id; - $order->promo_id = $cart->promo_id; + $order = $this->di['db']->dispense('ClientOrder'); + $order->client_id = $client->id; + $order->promo_id = $cart->promo_id; $order->product_id = $item['product_id']; - $order->form_id = $item['form_id']; + $order->form_id = $item['form_id']; - $order->group_id = $cart->id; - $order->group_master = ($i == 0); + $order->group_id = $cart->id; + $order->group_master = (0 == $i); $order->invoice_option = 'issue-invoice'; - $order->title = $item['title']; - $order->currency = $currency->code; - $order->service_type = $item['type']; - $order->unit = $this->di['array_get']($item, 'unit', NULL); - $order->period = $this->di['array_get']($item, 'period', NULL); - $order->quantity = $this->di['array_get']($item, 'quantity', NULL); - $order->price = $item['price'] * $currency->conversion_rate; - $order->discount = $item['discount_price'] * $currency->conversion_rate; - $order->status = \Model_ClientOrder::STATUS_PENDING_SETUP; - $order->notes = $this->di['array_get']($item, 'notes', NULL); - $order->config = json_encode($item); - $order->created_at = date('Y-m-d H:i:s'); - $order->updated_at = date('Y-m-d H:i:s'); + $order->title = $item['title']; + $order->currency = $currency->code; + $order->service_type = $item['type']; + $order->unit = $this->di['array_get']($item, 'unit', null); + $order->period = $this->di['array_get']($item, 'period', null); + $order->quantity = $this->di['array_get']($item, 'quantity', null); + $order->price = $item['price'] * $currency->conversion_rate; + $order->discount = $item['discount_price'] * $currency->conversion_rate; + $order->status = \Model_ClientOrder::STATUS_PENDING_SETUP; + $order->notes = $this->di['array_get']($item, 'notes', null); + $order->config = json_encode($item); + $order->created_at = date('Y-m-d H:i:s'); + $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); $orders[] = $order; @@ -548,69 +545,68 @@ class Service implements InjectionAwareInterface $promo = $this->di['db']->getExistingModelById('Promo', $cart->promo_id, 'Promo not found.'); $this->usePromo($promo); - //set promo info for later use + // set promo info for later use $order->promo_recurring = $promo->recurring; - $order->promo_used = 1; + $order->promo_used = 1; $this->di['db']->store($order); } $orderService = $this->di['mod_service']('order'); $orderService->saveStatusChange($order, 'Order created'); - $invoice_items[] = array( - 'title' => $order->title, - 'price' => $order->price, + $invoice_items[] = [ + 'title' => $order->title, + 'price' => $order->price, 'quantity' => $order->quantity, - 'unit' => $order->unit, - 'period' => $order->period, - 'taxed' => $taxed, - 'type' => \Model_InvoiceItem::TYPE_ORDER, - 'rel_id' => $order->id, - 'task' => \Model_InvoiceItem::TASK_ACTIVATE, - ); + 'unit' => $order->unit, + 'period' => $order->period, + 'taxed' => $taxed, + 'type' => \Model_InvoiceItem::TYPE_ORDER, + 'rel_id' => $order->id, + 'task' => \Model_InvoiceItem::TASK_ACTIVATE, + ]; - if($order->discount > 0){ - $invoice_items[] = array( - 'title' => __('Discount: :product', array(':product' => $order->title)), - 'price' => $order->discount * -1, + if ($order->discount > 0) { + $invoice_items[] = [ + 'title' => __('Discount: :product', [':product' => $order->title]), + 'price' => $order->discount * -1, 'quantity' => 1, - 'unit' => 'discount', - 'rel_id' => $order->id, - 'taxed' => $taxed, - ); + 'unit' => 'discount', + 'rel_id' => $order->id, + 'taxed' => $taxed, + ]; } if ($item['setup_price'] > 0) { - $setup_price = ($item['setup_price'] * $currency->conversion_rate) - ($item['discount_setup'] * $currency->conversion_rate); - $invoice_items[] = array( - 'title' => __(':product setup', array(':product' => $order->title)), - 'price' => $setup_price, + $setup_price = ($item['setup_price'] * $currency->conversion_rate) - ($item['discount_setup'] * $currency->conversion_rate); + $invoice_items[] = [ + 'title' => __(':product setup', [':product' => $order->title]), + 'price' => $setup_price, 'quantity' => 1, - 'unit' => 'service', - 'taxed' => $taxed, - ); + 'unit' => 'service', + 'taxed' => $taxed, + ]; } - //define master order to be returned + // define master order to be returned if (null === $master_order) { $master_order = $order; } - $i++; + ++$i; } - if ($ca['total'] > 0) { //crete invoice if order total > 0 - - $invoiceService = $this->di['mod_service']('Invoice'); - $invoiceModel = $invoiceService->prepareInvoice($client, array('client_id' => $client->id, 'items' => $invoice_items, 'gateway_id' => $gateway_id)); + if ($ca['total'] > 0) { // crete invoice if order total > 0 + $invoiceService = $this->di['mod_service']('Invoice'); + $invoiceModel = $invoiceService->prepareInvoice($client, ['client_id' => $client->id, 'items' => $invoice_items, 'gateway_id' => $gateway_id]); $clientBalanceService = $this->di['mod_service']('Client', 'Balance'); $balanceAmount = $clientBalanceService->getClientBalance($client); $useCredits = $balanceAmount >= $ca['total']; - $invoiceService->approveInvoice($invoiceModel, array('id' => $invoiceModel->id, 'use_credits' => $useCredits)); + $invoiceService->approveInvoice($invoiceModel, ['id' => $invoiceModel->id, 'use_credits' => $useCredits]); - if ($invoiceModel->status == \Model_Invoice::STATUS_UNPAID) { + if (\Model_Invoice::STATUS_UNPAID == $invoiceModel->status) { foreach ($orders as $order) { $order->unpaid_invoice_id = $invoiceModel->id; $this->di['db']->store($order); @@ -618,51 +614,50 @@ class Service implements InjectionAwareInterface } } - //activate orders if product is setup to be activated after order place or order total is $0 + // activate orders if product is setup to be activated after order place or order total is $0 $orderService = $this->di['mod_service']('Order'); - $ids = array(); + $ids = []; foreach ($orders as $order) { $ids[] = $order->id; - $oa = $orderService->toApiArray($order, false, $client); + $oa = $orderService->toApiArray($order, false, $client); $product = $this->di['db']->getExistingModelById('Product', $oa['product_id']); try { - if ($product->setup == \Model_ProductTable::SETUP_AFTER_ORDER){ + if (\Model_ProductTable::SETUP_AFTER_ORDER == $product->setup) { $orderService->activateOrder($order); } - if ($ca['total'] <= 0 && $product->setup == \Model_ProductTable::SETUP_AFTER_PAYMENT && $oa['total'] - $oa['discount'] <= 0){ + if ($ca['total'] <= 0 && \Model_ProductTable::SETUP_AFTER_PAYMENT == $product->setup && $oa['total'] - $oa['discount'] <= 0) { $orderService->activateOrder($order); } - if ($ca['total'] > 0 && $product->setup == \Model_ProductTable::SETUP_AFTER_PAYMENT && $invoiceModel->status == \Model_Invoice::STATUS_PAID ){ + if ($ca['total'] > 0 && \Model_ProductTable::SETUP_AFTER_PAYMENT == $product->setup && \Model_Invoice::STATUS_PAID == $invoiceModel->status) { $orderService->activateOrder($order); } - } - catch (\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); $status = 'error'; - $notes = 'Order could not be activated after checkout due to error: ' . $e->getMessage(); + $notes = 'Order could not be activated after checkout due to error: '.$e->getMessage(); $orderService->orderStatusAdd($order, $status, $notes); } } - return array( + return [ $master_order, - isset($invoiceModel) ? $invoiceModel : null, + $invoiceModel ?? null, $ids, - ); + ]; } public function usePromo(\Model_Promo $promo) { - $promo->used++; + ++$promo->used; $promo->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($promo); } public function findActivePromoByCode($code) { - return $this->di['db']->findOne('Promo', 'code = :code AND active = 1 ORDER BY id ASC', array(':code' => $code)); + return $this->di['db']->findOne('Promo', 'code = :code AND active = 1 ORDER BY id ASC', [':code' => $code]); } private function getItemPrice(\Model_CartProduct $model) @@ -670,6 +665,7 @@ class Service implements InjectionAwareInterface $product = $this->di['db']->load('Product', $model->product_id); $config = $this->getItemConfig($model); $repo = $product->getTable(); + return $repo->getProductPrice($product, $config); } @@ -678,15 +674,14 @@ class Service implements InjectionAwareInterface $product = $this->di['db']->load('Product', $model->product_id); $config = $this->getItemConfig($model); $repo = $product->getTable(); + return $repo->getProductSetupPrice($product, $config); } /** * Function checks if product is related to other products in cart - * If relation exists then count discount for this + * If relation exists then count discount for this. * - * @param \Model_Cart $cart - * @param \Model_CartProduct $model * @return number */ protected function getRelatedItemsDiscount(\Model_Cart $cart, \Model_CartProduct $model) @@ -696,16 +691,17 @@ class Service implements InjectionAwareInterface $config = $this->getItemConfig($model); $discount = 0; - if(method_exists($repo, 'getRelatedDiscount')) { - $list = array(); + if (method_exists($repo, 'getRelatedDiscount')) { + $list = []; $products = $this->getCartProducts($cart); - foreach($products as $p) { + foreach ($products as $p) { $item = $this->di['db']->toArray($p); $item['config'] = $this->getItemConfig($p); $list[] = $item; } $discount = $repo->getRelatedDiscount($list, $product, $config); } + return $discount; } @@ -714,10 +710,10 @@ class Service implements InjectionAwareInterface $product = $this->di['db']->load('Product', $model->product_id); $config = $this->getItemConfig($model); $service = $product->getService(); - if(method_exists($service, 'getCartProductTitle')) { + if (method_exists($service, 'getCartProductTitle')) { return $service->getCartProductTitle($product, $config); } else { - return __(':product_title', array(':product_title'=>$product->title)); + return __(':product_title', [':product_title' => $product->title]); } } @@ -726,6 +722,7 @@ class Service implements InjectionAwareInterface $product = $this->di['db']->load('Product', $model->product_id); $repo = $this->di['mod_service']('product'); $config = $this->getItemConfig($model); + return $repo->getProductDiscount($product, $promo, $config); } @@ -741,33 +738,34 @@ class Service implements InjectionAwareInterface $config = $this->getItemConfig($model); $setup = $repo->getProductSetupPrice($product, $config); $price = $repo->getProductPrice($product, $config); - $qty = $this->di['array_get']($config, 'quantity', 1) ; + $qty = $this->di['array_get']($config, 'quantity', 1); - list ($discount_price, $discount_setup) = $this->getProductDiscount($model, $setup); + [$discount_price, $discount_setup] = $this->getProductDiscount($model, $setup); $discount_total = $discount_price + $discount_setup; - $subtotal = ($price * $qty); - if(abs($discount_total) > ($subtotal + $setup) ) { + $subtotal = ($price * $qty); + if (abs($discount_total) > ($subtotal + $setup)) { $discount_total = $subtotal; $discount_price = $subtotal; } - $data = array_merge($config, array( - 'id' => $model->id, - 'product_id' => $product->id, - 'form_id' => $product->form_id, - 'title' => $this->getItemTitle($model), - 'type' => $product->type, - 'quantity' => $qty, - 'unit' => $repo->getUnit($product), - 'price' => $price, - 'setup_price' => $setup, - 'discount' => $discount_total, - 'discount_price'=> $discount_price, - 'discount_setup'=> $discount_setup, - 'total' => $subtotal, - )); + $data = array_merge($config, [ + 'id' => $model->id, + 'product_id' => $product->id, + 'form_id' => $product->form_id, + 'title' => $this->getItemTitle($model), + 'type' => $product->type, + 'quantity' => $qty, + 'unit' => $repo->getUnit($product), + 'price' => $price, + 'setup_price' => $setup, + 'discount' => $discount_total, + 'discount_price' => $discount_price, + 'discount_setup' => $discount_setup, + 'total' => $subtotal, + ]); + return $data; } @@ -776,15 +774,16 @@ class Service implements InjectionAwareInterface $cart = $this->di['db']->load('Cart', $cartProduct->cart_id); $discount_price = $this->getRelatedItemsDiscount($cart, $cartProduct); $discount_setup = 0; // discount for setup price - if($cart->promo_id) { + if ($cart->promo_id) { $promo = $this->di['db']->getExistingModelById('Promo', $cart->promo_id, 'Promo not found'); - //Promo discount should override related item discount + // Promo discount should override related item discount $discount_price = $this->getItemPromoDiscount($cartProduct, $promo); - if($promo->freesetup) { + if ($promo->freesetup) { $discount_setup = $setup; } } - return array($discount_price, $discount_setup); + + return [$discount_price, $discount_setup]; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Client/Api/Admin.php b/src/bb-modules/Client/Api/Admin.php index 3b7802280..27a7dc31f 100644 --- a/src/bb-modules/Client/Api/Admin.php +++ b/src/bb-modules/Client/Api/Admin.php @@ -1,6 +1,6 @@ di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - list($sql, $params) = $this->getService()->getSearchQuery($data); + [$sql, $params] = $this->getService()->getSearchQuery($data); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); - foreach($pager['list'] as $key => $clientArr){ + foreach ($pager['list'] as $key => $clientArr) { $client = $this->di['db']->getExistingModelById('Client', $clientArr['id'], 'Client not found'); $pager['list'][$key] = $this->getService()->toApiArray($client, true, $this->getIdentity()); } @@ -40,34 +40,36 @@ class Admin extends \Api_Abstract } /** - * Get clients index + * Get clients index. * * @return array - list of clients in id => full name pair */ public function get_pairs($data) { $service = $this->di['mod_service']('client'); + return $service->getPairs($data); } /** - * Get client by id or email. Email is also unique in database + * Get client by id or email. Email is also unique in database. * * @param int $id - client ID - * + * * @optional string $email - client email - * + * * @return array - client details */ public function get($data) { $service = $this->getService(); $client = $service->get($data); + return $service->toApiArray($client, true, $this->getIdentity()); } /** - * Login to clients area with client id + * Login to clients area with client id. * * @param int $id - client ID * @@ -75,9 +77,9 @@ class Admin extends \Api_Abstract */ public function login($data) { - $required = array( + $required = [ 'id' => 'ID required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $client = $this->di['db']->getExistingModelById('Client', $data['id'], 'Client not found'); @@ -88,15 +90,16 @@ class Admin extends \Api_Abstract $session = $this->di['session']; $session->set('client_id', $client->id); $this->di['logger']->info('Logged in as client #%s', $client->id); + return $result; } /** - * Creates new client + * Creates new client. * - * @param string $email - client email, must not be registered on system + * @param string $email - client email, must not be registered on system * @param string $first_name - client first name - * + * * @optional string $password - client password * @optional string $auth_type - client authorization type. Default null * @optional string $last_name - client last name @@ -134,22 +137,22 @@ class Admin extends \Api_Abstract * @optional string $custom_8 - Custom field 8 * @optional string $custom_9 - Custom field 9 * @optional string $custom_10 - Custom field 10 - * + * * @return int - client id */ public function create($data) { - $required = array( - 'email' => 'Email required', + $required = [ + 'email' => 'Email required', 'first_name' => 'First name is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $validator = $this->di['validator']; $validator->isEmailValid($data['email']); $service = $this->getService(); - if($service->emailAreadyRegistered($data['email'])) { + if ($service->emailAreadyRegistered($data['email'])) { throw new \Box_Exception('Email is already registered.'); } @@ -157,7 +160,7 @@ class Admin extends \Api_Abstract } /** - * Deletes client from system + * Deletes client from system. * * @param string $id - client ID * @@ -165,28 +168,29 @@ class Admin extends \Api_Abstract */ public function delete($data) { - $required = array( + $required = [ 'id' => 'Client id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Client', $data['id'], 'Client not found'); - - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminClientDelete', 'params'=>array('id'=>$model->id))); + + $this->di['events_manager']->fire(['event' => 'onBeforeAdminClientDelete', 'params' => ['id' => $model->id]]); $id = $model->id; $this->getService()->remove($model); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminClientDelete', 'params'=>array('id'=>$id))); - + $this->di['events_manager']->fire(['event' => 'onAfterAdminClientDelete', 'params' => ['id' => $id]]); + $this->di['logger']->info('Removed client #%s', $id); + return true; } /** - * Update client profile + * Update client profile. * * @param string $id - client ID - * + * * @optional string $email - client email * @optional string $first_name - client first_name * @optional string $last_name - client last_name @@ -221,72 +225,72 @@ class Admin extends \Api_Abstract * @optional string $custom_8 - Custom field 8 * @optional string $custom_9 - Custom field 9 * @optional string $custom_10 - Custom field 10 - * + * * @return bool */ - public function update($data = array()) + public function update($data = []) { - $required = array('id' => 'Id required'); + $required = ['id' => 'Id required']; $this->di['validator']->checkRequiredParamsForArray($required, $data); $client = $this->di['db']->getExistingModelById('Client', $this->di['array_get']($data, 'id'), 'Client not found'); $service = $this->di['mod_service']('client'); - if(!is_null($this->di['array_get']($data, 'email'))) { - $email = $this->di['array_get']($data, 'email'); + if (!is_null($this->di['array_get']($data, 'email'))) { + $email = $this->di['array_get']($data, 'email'); $this->di['validator']->isEmailValid($email); - if($service->emailAreadyRegistered($email, $client)) { + if ($service->emailAreadyRegistered($email, $client)) { throw new \Box_Exception('Can not change email. It is already registered.'); } } $this->di['validator']->isBirthdayValid($this->di['array_get']($data, 'birthday')); - if($this->di['array_get']($data, 'currency') && $service->canChangeCurrency($client, $this->di['array_get']($data, 'currency'))) { + if ($this->di['array_get']($data, 'currency') && $service->canChangeCurrency($client, $this->di['array_get']($data, 'currency'))) { $client->currency = $this->di['array_get']($data, 'currency', $client->currency); } - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminClientUpdate', 'params'=>$data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminClientUpdate', 'params' => $data]); $phoneCC = $this->di['array_get']($data, 'phone_cc', $client->phone_cc); - if(!empty($phoneCC)){ + if (!empty($phoneCC)) { $client->phone_cc = intval($phoneCC); } - $client->email = $this->di['array_get']($data, 'email', $client->email); - $client->first_name = $this->di['array_get']($data, 'first_name', $client->first_name); - $client->last_name = $this->di['array_get']($data, 'last_name', $client->last_name); - $client->aid = $this->di['array_get']($data, 'aid', $client->aid); - $client->gender = $this->di['array_get']($data, 'gender', $client->gender); - $client->birthday = $this->di['array_get']($data, 'birthday', $client->birthday); - $client->company = $this->di['array_get']($data, 'company', $client->company); - $client->company_vat = $this->di['array_get']($data, 'company_vat', $client->company_vat); - $client->address_1 = $this->di['array_get']($data, 'address_1', $client->address_1); - $client->address_2 = $this->di['array_get']($data, 'address_2', $client->address_2); - $client->phone = $this->di['array_get']($data, 'phone', $client->phone); - $client->document_type = $this->di['array_get']($data, 'document_type', $client->document_type); - $client->document_nr = $this->di['array_get']($data, 'document_nr', $client->document_nr); - $client->notes = $this->di['array_get']($data, 'notes', $client->notes); - $client->country = $this->di['array_get']($data, 'country', $client->country); - $client->postcode = $this->di['array_get']($data, 'postcode', $client->postcode); - $client->state = $this->di['array_get']($data, 'state', $client->state); - $client->city = $this->di['array_get']($data, 'city', $client->city); + $client->email = $this->di['array_get']($data, 'email', $client->email); + $client->first_name = $this->di['array_get']($data, 'first_name', $client->first_name); + $client->last_name = $this->di['array_get']($data, 'last_name', $client->last_name); + $client->aid = $this->di['array_get']($data, 'aid', $client->aid); + $client->gender = $this->di['array_get']($data, 'gender', $client->gender); + $client->birthday = $this->di['array_get']($data, 'birthday', $client->birthday); + $client->company = $this->di['array_get']($data, 'company', $client->company); + $client->company_vat = $this->di['array_get']($data, 'company_vat', $client->company_vat); + $client->address_1 = $this->di['array_get']($data, 'address_1', $client->address_1); + $client->address_2 = $this->di['array_get']($data, 'address_2', $client->address_2); + $client->phone = $this->di['array_get']($data, 'phone', $client->phone); + $client->document_type = $this->di['array_get']($data, 'document_type', $client->document_type); + $client->document_nr = $this->di['array_get']($data, 'document_nr', $client->document_nr); + $client->notes = $this->di['array_get']($data, 'notes', $client->notes); + $client->country = $this->di['array_get']($data, 'country', $client->country); + $client->postcode = $this->di['array_get']($data, 'postcode', $client->postcode); + $client->state = $this->di['array_get']($data, 'state', $client->state); + $client->city = $this->di['array_get']($data, 'city', $client->city); - $client->status = $this->di['array_get']($data, 'status', $client->status); + $client->status = $this->di['array_get']($data, 'status', $client->status); $client->email_approved = $this->di['array_get']($data, 'email_approved', $client->email_approved); - $client->tax_exempt = $this->di['array_get']($data, 'tax_exempt', $client->tax_exempt); - $client->created_at = $this->di['array_get']($data, 'created_at', $client->created_at); + $client->tax_exempt = $this->di['array_get']($data, 'tax_exempt', $client->tax_exempt); + $client->created_at = $this->di['array_get']($data, 'created_at', $client->created_at); - $client->custom_1 = $this->di['array_get']($data, 'custom_1', $client->custom_1); - $client->custom_2 = $this->di['array_get']($data, 'custom_2', $client->custom_2); - $client->custom_3 = $this->di['array_get']($data, 'custom_3', $client->custom_3); - $client->custom_4 = $this->di['array_get']($data, 'custom_4', $client->custom_4); - $client->custom_5 = $this->di['array_get']($data, 'custom_5', $client->custom_5); - $client->custom_6 = $this->di['array_get']($data, 'custom_6', $client->custom_6); - $client->custom_7 = $this->di['array_get']($data, 'custom_7', $client->custom_7); - $client->custom_8 = $this->di['array_get']($data, 'custom_8', $client->custom_8); - $client->custom_9 = $this->di['array_get']($data, 'custom_9', $client->custom_9); - $client->custom_10 = $this->di['array_get']($data, 'custom_10', $client->custom_10); + $client->custom_1 = $this->di['array_get']($data, 'custom_1', $client->custom_1); + $client->custom_2 = $this->di['array_get']($data, 'custom_2', $client->custom_2); + $client->custom_3 = $this->di['array_get']($data, 'custom_3', $client->custom_3); + $client->custom_4 = $this->di['array_get']($data, 'custom_4', $client->custom_4); + $client->custom_5 = $this->di['array_get']($data, 'custom_5', $client->custom_5); + $client->custom_6 = $this->di['array_get']($data, 'custom_6', $client->custom_6); + $client->custom_7 = $this->di['array_get']($data, 'custom_7', $client->custom_7); + $client->custom_8 = $this->di['array_get']($data, 'custom_8', $client->custom_8); + $client->custom_9 = $this->di['array_get']($data, 'custom_9', $client->custom_9); + $client->custom_10 = $this->di['array_get']($data, 'custom_10', $client->custom_10); $client->client_group_id = $this->di['array_get']($data, 'group_id', $client->client_group_id); $client->company_number = $this->di['array_get']($data, 'company_number', $client->company_number); @@ -295,75 +299,77 @@ class Admin extends \Api_Abstract $client->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($client); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminClientUpdate', 'params'=>array('id'=>$client->id))); - + $this->di['events_manager']->fire(['event' => 'onAfterAdminClientUpdate', 'params' => ['id' => $client->id]]); + $this->di['logger']->info('Updated client #%s profile', $client->id); + return true; } /** - * Change client password + * Change client password. * - * @param int $id - Client ID - * @param string $password - new client password + * @param int $id - Client ID + * @param string $password - new client password * @param string $password_confirm - repeat same new client password * * @return bool */ public function change_password($data) { - $required = array( - 'id' => 'ID required', - 'password' => 'Password required', + $required = [ + 'id' => 'ID required', + 'password' => 'Password required', 'password_confirm' => 'Password confirmation required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - if($data['password'] != $data['password_confirm']) { + if ($data['password'] != $data['password_confirm']) { throw new \Box_Exception('Passwords do not match'); } $client = $this->di['db']->getExistingModelById('Client', $data['id'], 'Client not found'); - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminClientPasswordChange', 'params'=>$data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminClientPasswordChange', 'params' => $data]); $client->pass = $this->di['password']->hashIt($data['password']); $client->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($client); - - $this->di['events_manager']->fire(array('event'=>'onAfterAdminClientPasswordChange', 'params'=>array('id'=>$client->id, 'password'=>$data['password']))); - + + $this->di['events_manager']->fire(['event' => 'onAfterAdminClientPasswordChange', 'params' => ['id' => $client->id, 'password' => $data['password']]]); + $this->di['logger']->info('Changed client #%s password', $client->id); + return true; } /** - * Returns list of client payments + * Returns list of client payments. * * @return array */ public function balance_get_list($data) { $service = $this->di['mod_service']('Client', 'Balance'); - list($q, $params) = $service->getSearchQuery($data); + [$q, $params] = $service->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - $pager = $this->di['pager']->getSimpleResultSet($q, $params, $per_page); + $pager = $this->di['pager']->getSimpleResultSet($q, $params, $per_page); - foreach($pager['list'] as $key => $item){ - $pager['list'][$key] = array( - 'id' => $item['id'], - 'description' => $item['description'], - 'amount' => $item['amount'], - 'currency' => $item['currency'], - 'created_at' => $item['created_at'], - ); + foreach ($pager['list'] as $key => $item) { + $pager['list'][$key] = [ + 'id' => $item['id'], + 'description' => $item['description'], + 'amount' => $item['amount'], + 'currency' => $item['currency'], + 'created_at' => $item['created_at'], + ]; } return $pager; } /** - * Remove row from clients balance + * Remove row from clients balance. * * @param int $id - Balance line id * @@ -371,13 +377,13 @@ class Admin extends \Api_Abstract */ public function balance_delete($data) { - $required = array( + $required = [ 'id' => 'Client ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ClientBalance', $data['id'], 'Balance line not found'); - + $id = $model->id; $client_id = $model->client_id; $amount = $model->amount; @@ -385,16 +391,17 @@ class Admin extends \Api_Abstract $this->di['db']->trash($model); $this->di['logger']->info('Removed line %s from client #%s balance for %s', $id, $client_id, $amount); + return true; } - + /** - * Adds funds to clients balance + * Adds funds to clients balance. * - * @param int $id - Client ID - * @param int $amount - Amount of clients currency to added to balance + * @param int $id - Client ID + * @param int $amount - Amount of clients currency to added to balance * @param int $description - Description of this transaction - * + * * @optional string $type - Related item type * @optional string $rel_id - Related item id * @@ -402,22 +409,23 @@ class Admin extends \Api_Abstract */ public function balance_add_funds($data) { - $required = array( - 'id' => 'Client ID required', - 'amount' => 'Amount is required', + $required = [ + 'id' => 'Client ID required', + 'amount' => 'Amount is required', 'description' => 'Description is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $client = $this->di['db']->getExistingModelById('Client', $data['id'], 'Client not found'); $service = $this->di['mod_service']('client'); $service->addFunds($client, $data['amount'], $data['description'], $data); + return true; } /** - * Remove password reminders which were not confirmed in 2 hours + * Remove password reminders which were not confirmed in 2 hours. * * @return bool */ @@ -425,171 +433,179 @@ class Admin extends \Api_Abstract { $service = $this->di['mod_service']('client'); $expired = $service->getExpiredPasswordReminders(); - foreach($expired as $model) { + foreach ($expired as $model) { $this->di['db']->trash($model); } - + $this->di['logger']->info('Executed action to delete expired clients password reminders'); - return TRUE; + + return true; } /** - * Get list of clients logins history + * Get list of clients logins history. * * @optional int $client_id - filter by client - * + * * @return array */ public function login_history_get_list($data) { - list($q, $params) = $this->getService()->getHistorySearchQuery($data); + [$q, $params] = $this->getService()->getHistorySearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - $pager = $this->di['pager']->getSimpleResultSet($q, $params, $per_page); + $pager = $this->di['pager']->getSimpleResultSet($q, $params, $per_page); - foreach($pager['list'] as $key => $item){ - $pager['list'][$key] = array( - 'id' => $item['id'], - 'ip' => $item['ip'], - 'created_at' => $item['created_at'], - 'client' => array( - 'id' => $item['client_id'], - 'first_name' => $item['first_name'], - 'last_name' => $item['last_name'], - 'email' => $item['email'], - ) - ); + foreach ($pager['list'] as $key => $item) { + $pager['list'][$key] = [ + 'id' => $item['id'], + 'ip' => $item['ip'], + 'created_at' => $item['created_at'], + 'client' => [ + 'id' => $item['client_id'], + 'first_name' => $item['first_name'], + 'last_name' => $item['last_name'], + 'email' => $item['email'], + ], + ]; } return $pager; } /** - * Remove log entry form clients logins history - * + * Remove log entry form clients logins history. + * * @param int $id - Log entry ID - * + * * @return bool */ public function login_history_delete($data) { - - $required = array( + $required = [ 'id' => 'Id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ActivityClientHistory', $data['id']); - if(!$model instanceof \Model_ActivityClientHistory) { + if (!$model instanceof \Model_ActivityClientHistory) { throw new \Box_Exception('Event not found'); } $this->di['db']->trash($model); + return true; } /** * Return client statuses with counter. - * + * * @return array */ public function get_statuses($data) { $service = $this->di['mod_service']('client'); + return $service->counter(); } /** - * Return client groups. Id and title pairs - * + * Return client groups. Id and title pairs. + * * @return array */ public function group_get_pairs($data) { $service = $this->di['mod_service']('client'); + return $service->getGroupPairs(); } /** - * Create new clients group - * + * Create new clients group. + * * @param string $title - New group title - * + * * @return int $id - newly created group id */ public function group_create($data) { - $required = array( + $required = [ 'title' => 'Group title is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->createGroup($data); } /** - * Update client group - * + * Update client group. + * * @param int $id - client group ID * @optional string $title - new group title - * + * * @return bool - * @throws ErrorException + * + * @throws ErrorException */ public function group_update($data) { - $required = array( + $required = [ 'id' => 'Group id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ClientGroup', $data['id'], 'Group not found'); - + $model->title = $this->di['array_get']($data, 'title', $model->title); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return true; } /** - * Delete client group - * + * Delete client group. + * * @param int $id - client group ID - * + * * @return bool - * @throws ErrorException + * + * @throws ErrorException */ public function group_delete($data) { - $required = array( + $required = [ 'id' => 'Group id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ClientGroup', $data['id'], 'Group not found'); + return $this->getService()->deleteGroup($model); } /** - * Get client group details - * + * Get client group details. + * * @param int $id - client group ID - * + * * @return array - * @throws ErrorException + * + * @throws ErrorException */ public function group_get($data) { - $required = array( + $required = [ 'id' => 'Group id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ClientGroup', $data['id'], 'Group not found'); - + return $this->di['db']->toArray($model); } /** - * Deletes clients with given IDs + * Deletes clients with given IDs. * * @param array $ids - IDs for deletion * @@ -597,21 +613,20 @@ class Admin extends \Api_Abstract */ public function batch_delete($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->delete(array('id' => $id)); + $this->delete(['id' => $id]); } return true; } - /** - * Deletes client login logs with given IDs + * Deletes client login logs with given IDs. * * @param array $ids - IDs for deletion * @@ -619,15 +634,15 @@ class Admin extends \Api_Abstract */ public function batch_delete_log($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->login_history_delete(array('id' => $id)); + $this->login_history_delete(['id' => $id]); } return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Client/Api/Client.php b/src/bb-modules/Client/Api/Client.php index 41c64b61d..9fc2a29e7 100644 --- a/src/bb-modules/Client/Api/Client.php +++ b/src/bb-modules/Client/Api/Client.php @@ -1,6 +1,6 @@ getIdentity(); - $event_params = $data; + $event_params = $data; $event_params['id'] = $client->id; - $this->di['events_manager']->fire(array('event'=>'onBeforeClientProfileUpdate', 'params'=>$event_params)); + $this->di['events_manager']->fire(['event' => 'onBeforeClientProfileUpdate', 'params' => $event_params]); $email = $this->di['array_get']($data, 'email', ''); - if(!empty($email)) { + if (!empty($email)) { $this->di['validator']->isEmailValid($email); $this->getService()->canChangeEmail($client, $email); - if($this->getService()->emailAreadyRegistered($email, $client)) { + if ($this->getService()->emailAreadyRegistered($email, $client)) { throw new \Box_Exception('Can not change email. It is already registered.'); } $client->email = strtolower(trim($email)); } $phoneCC = $this->di['array_get']($data, 'phone_cc', $client->phone_cc); - if(!empty($phoneCC)){ + if (!empty($phoneCC)) { $client->phone_cc = intval($phoneCC); } - $client->first_name = $this->di['array_get']($data, 'first_name', $client->first_name); - $client->last_name = $this->di['array_get']($data, 'last_name', $client->last_name); - $client->gender = $this->di['array_get']($data, 'gender', $client->gender); - $client->birthday = $this->di['array_get']($data, 'birthday', $client->birthday); - $client->company = $this->di['array_get']($data, 'company', $client->company); - $client->company_vat = $this->di['array_get']($data, 'company_vat', $client->company_vat); + $client->first_name = $this->di['array_get']($data, 'first_name', $client->first_name); + $client->last_name = $this->di['array_get']($data, 'last_name', $client->last_name); + $client->gender = $this->di['array_get']($data, 'gender', $client->gender); + $client->birthday = $this->di['array_get']($data, 'birthday', $client->birthday); + $client->company = $this->di['array_get']($data, 'company', $client->company); + $client->company_vat = $this->di['array_get']($data, 'company_vat', $client->company_vat); $client->company_number = $this->di['array_get']($data, 'company_number', $client->company_number); - $client->type = $this->di['array_get']($data, 'type', $client->type); - $client->address_1 = $this->di['array_get']($data, 'address_1', $client->address_1); - $client->address_2 = $this->di['array_get']($data, 'address_2', $client->address_2); - $client->phone = $this->di['array_get']($data, 'phone', $client->phone); - $client->country = $this->di['array_get']($data, 'country', $client->country); - $client->postcode = $this->di['array_get']($data, 'postcode', $client->postcode); - $client->city = $this->di['array_get']($data, 'city', $client->city); - $client->state = $this->di['array_get']($data, 'state', $client->state); - $client->document_type = $this->di['array_get']($data, 'document_type', 'passport'); - $client->document_nr = $this->di['array_get']($data, 'document_nr', ''); - $client->notes = $this->di['array_get']($data, 'notes', $client->notes); + $client->type = $this->di['array_get']($data, 'type', $client->type); + $client->address_1 = $this->di['array_get']($data, 'address_1', $client->address_1); + $client->address_2 = $this->di['array_get']($data, 'address_2', $client->address_2); + $client->phone = $this->di['array_get']($data, 'phone', $client->phone); + $client->country = $this->di['array_get']($data, 'country', $client->country); + $client->postcode = $this->di['array_get']($data, 'postcode', $client->postcode); + $client->city = $this->di['array_get']($data, 'city', $client->city); + $client->state = $this->di['array_get']($data, 'state', $client->state); + $client->document_type = $this->di['array_get']($data, 'document_type', 'passport'); + $client->document_nr = $this->di['array_get']($data, 'document_nr', ''); + $client->notes = $this->di['array_get']($data, 'notes', $client->notes); - $client->custom_1 = $this->di['array_get']($data, 'custom_1', $client->custom_1); - $client->custom_2 = $this->di['array_get']($data, 'custom_2', $client->custom_2); - $client->custom_3 = $this->di['array_get']($data, 'custom_3', $client->custom_3); - $client->custom_4 = $this->di['array_get']($data, 'custom_4', $client->custom_4); - $client->custom_5 = $this->di['array_get']($data, 'custom_5', $client->custom_5); - $client->custom_6 = $this->di['array_get']($data, 'custom_6', $client->custom_6); - $client->custom_7 = $this->di['array_get']($data, 'custom_7', $client->custom_7); - $client->custom_8 = $this->di['array_get']($data, 'custom_8', $client->custom_8); - $client->custom_9 = $this->di['array_get']($data, 'custom_9', $client->custom_9); + $client->custom_1 = $this->di['array_get']($data, 'custom_1', $client->custom_1); + $client->custom_2 = $this->di['array_get']($data, 'custom_2', $client->custom_2); + $client->custom_3 = $this->di['array_get']($data, 'custom_3', $client->custom_3); + $client->custom_4 = $this->di['array_get']($data, 'custom_4', $client->custom_4); + $client->custom_5 = $this->di['array_get']($data, 'custom_5', $client->custom_5); + $client->custom_6 = $this->di['array_get']($data, 'custom_6', $client->custom_6); + $client->custom_7 = $this->di['array_get']($data, 'custom_7', $client->custom_7); + $client->custom_8 = $this->di['array_get']($data, 'custom_8', $client->custom_8); + $client->custom_9 = $this->di['array_get']($data, 'custom_9', $client->custom_9); $client->custom_10 = $this->di['array_get']($data, 'custom_10', $client->custom_10); $client->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($client); - $this->di['events_manager']->fire(array('event'=>'onAfterClientProfileUpdate', 'params'=>array('id'=>$client->id))); + $this->di['events_manager']->fire(['event' => 'onAfterClientProfileUpdate', 'params' => ['id' => $client->id]]); $this->di['logger']->info('Updated profile'); + return true; } - + /** - * Retrieve current API key + * Retrieve current API key. + * * @deprecated moved to profile module */ public function api_key_get($data) { $client = $this->getIdentity(); + return $client->api_token; } - + /** - * Generate new API key + * Generate new API key. + * * @deprecated moved to profile module */ public function api_key_reset($data) { $client = $this->getIdentity(); - + $client->api_token = $this->di['tools']->generatePassword(32); $client->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($client); $this->di['logger']->info('Generated new API key'); + return $client->api_token; } - + /** - * Change client area password + * Change client area password. + * * @deprecated moved to profile module */ public function change_password($data) { - $required = array( - 'password' => 'Password required', + $required = [ + 'password' => 'Password required', 'password_confirm' => 'Password confirmation required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - if($data['password'] != $data['password_confirm']) { + if ($data['password'] != $data['password_confirm']) { throw new \Box_Exception('Passwords do not match.'); } $event_params = $data; $event_params['id'] = $this->getIdentity()->id; - $this->di['events_manager']->fire(array('event'=>'onBeforeClientProfilePasswordChange', 'params'=>$event_params)); - + $this->di['events_manager']->fire(['event' => 'onBeforeClientProfilePasswordChange', 'params' => $event_params]); + $this->di['validator']->isPasswordStrong($data['password']); $client = $this->getIdentity(); $client->pass = $this->di['password']->hashIt($data['password']); $this->di['db']->store($client); - $this->di['events_manager']->fire(array('event'=>'onAfterClientProfilePasswordChange', 'params'=>array('id'=>$client->id))); - + $this->di['events_manager']->fire(['event' => 'onAfterClientProfilePasswordChange', 'params' => ['id' => $client->id]]); + $this->di['logger']->info('Changed profile password'); - + return true; } /** - * Clear session and logout - * @return boolean + * Clear session and logout. + * + * @return bool + * * @deprecated moved to profile module */ public function logout() { - if($_COOKIE) { // testing env fix - $this->di['cookie']->set('BOXCLR', "", time() - 3600, '/'); + if ($_COOKIE) { // testing env fix + $this->di['cookie']->set('BOXCLR', '', time() - 3600, '/'); } $this->di['session']->delete('client'); $this->di['session']->delete('client_id'); $this->di['logger']->info('Logged out'); + return true; } - + /** - * Get payments information - * @return array + * Get payments information. + * + * @return array */ public function balance_get_list($data) { - $service = $this->di['mod_service']('Client', 'Balance'); + $service = $this->di['mod_service']('Client', 'Balance'); $data['client_id'] = $this->identity->id; - list($q, $params) = $service->getSearchQuery($data); + [$q, $params] = $service->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($q, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $balance = $this->di['db']->getExistingModelById('ClientBalance', $item['id'], 'Balance not found'); + $balance = $this->di['db']->getExistingModelById('ClientBalance', $item['id'], 'Balance not found'); $pager['list'][$key] = $service->toApiArray($balance); } @@ -226,12 +239,14 @@ class Client extends \Api_Abstract } /** - * Get client balance + * Get client balance. + * * @return float */ public function balance_get_total() { $service = $this->di['mod_service']('Client', 'Balance'); + return $service->getClientBalance($this->identity); } @@ -239,5 +254,4 @@ class Client extends \Api_Abstract { return $this->getService()->isClientTaxable($this->identity); } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Client/Api/Guest.php b/src/bb-modules/Client/Api/Guest.php index ea7b21843..f7674ddb2 100644 --- a/src/bb-modules/Client/Api/Guest.php +++ b/src/bb-modules/Client/Api/Guest.php @@ -1,6 +1,6 @@ di['mod_config']('client'); - if(isset($config['allow_signup']) && !$config['allow_signup']) { + if (isset($config['allow_signup']) && !$config['allow_signup']) { throw new \Box_Exception('New registrations are temporary disabled'); } - $required = array( + $required = [ 'email' => 'Email required', 'first_name' => 'First name required', 'password' => 'Password required', 'password_confirm' => 'Password confirmation required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - if($data['password'] != $data['password_confirm']) { + if ($data['password'] != $data['password_confirm']) { throw new \Box_Exception('Passwords do not match.'); } @@ -87,20 +87,20 @@ class Guest extends \Api_Abstract $email = $this->di['array_get']($data, 'email'); $this->di['validator']->isEmailValid($email); $email = strtolower(trim($email)); - if($service->clientAlreadyExists($email)) { + if ($service->clientAlreadyExists($email)) { throw new \Box_Exception('Email is already registered. You may want to login instead of registering.'); } $client = $service->guestCreateClient($data); - if (isset($config['require_email_confirmation']) && (int)$config['require_email_confirmation'] && !$client->email_approved) { - throw new \Box_Exception('Account has been created. Please check your mailbox and confirm email address.', null, 7777); + if (isset($config['require_email_confirmation']) && (int) $config['require_email_confirmation'] && !$client->email_approved) { + throw new \Box_Exception('Account has been created. Please check your mailbox and confirm email address.', null, 7777); } - if($this->di['array_get']($data, 'auto_login', 0)) { + if ($this->di['array_get']($data, 'auto_login', 0)) { try { - $this->login(array('email'=>$client->email, 'password' => $this->di['array_get']($data, 'password'))); - } catch(\Exception $e) { + $this->login(['email' => $client->email, 'password' => $this->di['array_get']($data, 'password')]); + } catch (\Exception $e) { error_log($e->getMessage()); } } @@ -109,172 +109,181 @@ class Guest extends \Api_Abstract } /** - * Client login action - * - * @param string $email - client email + * Client login action. + * + * @param string $email - client email * @param string $password - client password - * + * * @return array - session data - * @throws Box_Exception + * + * @throws Box_Exception */ public function login($data) { - $required = array( - 'email' => 'Email required', + $required = [ + 'email' => 'Email required', 'password' => 'Password required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $event_params = $data; $event_params['ip'] = $this->ip; - $this->di['events_manager']->fire(array('event'=>'onBeforeClientLogin', 'params'=>$event_params)); + $this->di['events_manager']->fire(['event' => 'onBeforeClientLogin', 'params' => $event_params]); $service = $this->getService(); $client = $service->authorizeClient($data['email'], $data['password']); - if(!$client instanceof \Model_Client ) { - - $this->di['events_manager']->fire(array('event'=>'onEventClientLoginFailed', 'params'=>$event_params)); - - throw new \Box_Exception('Please check your login details', array(), 403); + if (!$client instanceof \Model_Client) { + $this->di['events_manager']->fire(['event' => 'onEventClientLoginFailed', 'params' => $event_params]); + + throw new \Box_Exception('Please check your login details', [], 403); } - - if(isset($data['remember'])) { + + if (isset($data['remember'])) { $email = $data['email']; $cookie_time = (3600 * 24 * 30); // 30 days $this->di['cookie']->set('BOXCLR', 'e='.base64_encode($email).'&p='.base64_encode($client->pass), time() + $cookie_time, '/'); } - - $this->di['events_manager']->fire(array('event'=>'onAfterClientLogin', 'params'=>array('id'=>$client->id, 'ip'=>$this->ip))); - + + $this->di['events_manager']->fire(['event' => 'onAfterClientLogin', 'params' => ['id' => $client->id, 'ip' => $this->ip]]); + $result = $service->toSessionArray($client); $this->di['session']->set('client_id', $client->id); $this->di['logger']->info('Client #%s logged in', $client->id); + return $result; } /** * Password reset confirmation email will be sent to email. - * + * * @param string $email - client email - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function reset_password($data) { - $required = array( - 'email' => 'Email required', - ); + $required = [ + 'email' => 'Email required', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - - $this->di['events_manager']->fire(array('event'=>'onBeforeGuestPasswordResetRequest', 'params'=>$data)); - $c = $this->di['db']->findOne('Client', 'email = ?', array($data['email'])); - if(!$c instanceof \Model_Client ) { + $this->di['events_manager']->fire(['event' => 'onBeforeGuestPasswordResetRequest', 'params' => $data]); + + $c = $this->di['db']->findOne('Client', 'email = ?', [$data['email']]); + if (!$c instanceof \Model_Client) { throw new \Box_Exception('Email not found in our database'); } - $hash = sha1(time() . uniqid()); - + $hash = sha1(time().uniqid()); + $reset = $this->di['db']->dispense('ClientPasswordReset'); - $reset->client_id = $c->id; - $reset->ip = $this->ip; - $reset->hash = $hash; - $reset->created_at = date('Y-m-d H:i:s'); - $reset->updated_at = date('Y-m-d H:i:s'); + $reset->client_id = $c->id; + $reset->ip = $this->ip; + $reset->hash = $hash; + $reset->created_at = date('Y-m-d H:i:s'); + $reset->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($reset); - //send email - $email = array(); + // send email + $email = []; $email['to_client'] = $c->id; - $email['code'] = 'mod_client_password_reset_request'; - $email['hash'] = $hash; + $email['code'] = 'mod_client_password_reset_request'; + $email['hash'] = $hash; $emailSerivce = $this->di['mod_service']('email'); $emailSerivce->sendTemplate($email); - + $this->di['logger']->info('Client requested password reset. Sent to email %s', $c->email); + return true; } /** - * Confirm password reset action - * + * Confirm password reset action. + * * @param string $hash - hash received in email - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function confirm_reset($data) { - $required = array( - 'hash' => 'Hash required', - ); + $required = [ + 'hash' => 'Hash required', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $reset = $this->di['db']->findOne('ClientPasswordReset', 'hash = ?', array($data['hash'])); - if(!$reset instanceof \Model_ClientPasswordReset) { + $reset = $this->di['db']->findOne('ClientPasswordReset', 'hash = ?', [$data['hash']]); + if (!$reset instanceof \Model_ClientPasswordReset) { throw new \Box_Exception('The link have expired or you have already confirmed password reset.'); } - $new_pass = substr(md5(time() . uniqid()), 0, 10); - + $new_pass = substr(md5(time().uniqid()), 0, 10); + $c = $this->di['db']->getExistingModelById('Client', $reset->client_id, 'Client not found'); $c->pass = $this->di['password']->hashIt($new_pass); $this->di['db']->store($c); - - //send email - $email = array(); + + // send email + $email = []; $email['to_client'] = $reset->client_id; - $email['code'] = 'mod_client_password_reset_approve'; - $email['password'] = $new_pass; + $email['code'] = 'mod_client_password_reset_approve'; + $email['password'] = $new_pass; $emailService = $this->di['mod_service']('email'); $emailService->sendTemplate($email); $this->di['db']->trash($reset); $this->di['logger']->info('Client password reset request was approved'); + return true; } - + /** * Check if given vat number is valid EU country VAT number - * This method uses http://isvat.appspot.com/ method to validate VAT - * - * @param string $country - Country CODE: FR - France etc. - * @param string $vat - VAT number - * + * This method uses http://isvat.appspot.com/ method to validate VAT. + * + * @param string $country - Country CODE: FR - France etc + * @param string $vat - VAT number + * * @return bool- true if VAT is valid, false if not */ public function is_vat($data) { - $required = array( + $required = [ 'country' => 'Country code', - 'vat' => 'Country VAT is required', - ); + 'vat' => 'Country VAT is required', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $cc = $data['country']; + $cc = $data['country']; $vatnum = $data['vat']; - //@todo add new service provider https://vatlayer.com/ check + // @todo add new service provider https://vatlayer.com/ check // $url = 'http://isvat.appspot.com/' . rawurlencode($cc) . '/' . rawurlencode($vatnum) . '/'; // $result = $this->di['guzzle_client']->get($url); return true; } - + /** - * List of required fields for client registration + * List of required fields for client registration. */ public function required() { $config = $this->di['mod_config']('client'); - return isset($config['required']) ? $config['required'] : array(); + + return $config['required'] ?? []; } /** - * Array of custom fields for client registration + * Array of custom fields for client registration. */ public function custom_fields() { $config = $this->di['mod_config']('client'); - return isset($config['custom_fields']) ? $config['custom_fields'] : array(); + + return $config['custom_fields'] ?? []; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Client/Controller/Admin.php b/src/bb-modules/Client/Controller/Admin.php index a1ddaeed8..2122010f2 100644 --- a/src/bb-modules/Client/Controller/Admin.php +++ b/src/bb-modules/Client/Controller/Admin.php @@ -1,6 +1,6 @@ array( + return [ + 'group' => [ 'index' => 200, 'location' => 'client', 'label' => 'Clients', 'uri' => $this->di['url']->adminLink('client'), - 'class' => 'contacts', + 'class' => 'contacts', 'sprite_class' => 'dark-sprite-icon sprite-users', - ), - 'subpages' => array( - array( + ], + 'subpages' => [ + [ 'location' => 'client', 'label' => 'Overview', 'uri' => $this->di['url']->adminLink('client'), 'index' => 100, - 'class' => '', - ), - array( + 'class' => '', + ], + [ 'location' => 'client', 'label' => 'Advanced search', - 'uri' => $this->di['url']->adminLink('client', array('show_filter' => 1)), + 'uri' => $this->di['url']->adminLink('client', ['show_filter' => 1]), 'index' => 200, - 'class' => '', - ), - array( + 'class' => '', + ], + [ 'location' => 'activity', - 'index' => 900, + 'index' => 900, 'label' => 'Client logins history', 'uri' => $this->di['url']->adminLink('client/logins'), - 'class' => '', - ), - ), - ); + 'class' => '', + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/client', 'get_index', array(), get_class($this)); - $app->get('/client/', 'get_index', array(), get_class($this)); - $app->get('/client/index', 'get_index', array(), get_class($this)); - $app->get('/client/login/:id', 'get_login', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/client/manage/:id', 'get_manage', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/client/group/:id', 'get_group', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/client/create', 'get_create', array(), get_class($this)); - $app->get('/client/logins', 'get_history', array(), get_class($this)); + $app->get('/client', 'get_index', [], get_class($this)); + $app->get('/client/', 'get_index', [], get_class($this)); + $app->get('/client/index', 'get_index', [], get_class($this)); + $app->get('/client/login/:id', 'get_login', ['id' => '[0-9]+'], get_class($this)); + $app->get('/client/manage/:id', 'get_manage', ['id' => '[0-9]+'], get_class($this)); + $app->get('/client/group/:id', 'get_group', ['id' => '[0-9]+'], get_class($this)); + $app->get('/client/create', 'get_create', [], get_class($this)); + $app->get('/client/logins', 'get_history', [], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_client_index'); } public function get_manage(\Box_App $app, $id) { $api = $this->di['api_admin']; - $client = $api->client_get(array('id'=>$id)); - return $app->render('mod_client_manage', array('client'=>$client)); + $client = $api->client_get(['id' => $id]); + + return $app->render('mod_client_manage', ['client' => $client]); } public function get_group(\Box_App $app, $id) { $api = $this->di['api_admin']; - $model = $api->client_group_get(array('id'=>$id)); - return $app->render('mod_client_group', array('group'=>$model)); + $model = $api->client_group_get(['id' => $id]); + + return $app->render('mod_client_group', ['group' => $model]); } - + public function get_history(\Box_App $app) { $api = $this->di['api_admin']; + return $app->render('mod_client_login_history'); } public function get_login(\Box_App $app, $id) { $api = $this->di['api_admin']; - $api->client_login(array('id'=>$id)); + $api->client_login(['id' => $id]); $redirect_to = '/'; if ($this->di['request']->getQuery('r')) { - $r = $this->di['request']->getQuery('r'); - $redirect_to = '/' . trim($r, '/'); + $r = $this->di['request']->getQuery('r'); + $redirect_to = '/'.trim($r, '/'); } - Header( "HTTP/1.1 301 Moved Permanently" ); - Header( "Location: ".$this->di['tools']->url($redirect_to) ); + header('HTTP/1.1 301 Moved Permanently'); + header('Location: '.$this->di['tools']->url($redirect_to)); exit; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Client/Controller/Client.php b/src/bb-modules/Client/Controller/Client.php index a72724c5c..950d50d24 100644 --- a/src/bb-modules/Client/Controller/Client.php +++ b/src/bb-modules/Client/Controller/Client.php @@ -1,6 +1,6 @@ get('/client/me', 'get_profile', array(), get_class($this)); + // @deprecated + $app->get('/client/me', 'get_profile', [], get_class($this)); - $app->get('/client/reset-password-confirm/:hash', 'get_reset_password_confirm', array('hash'=>'[a-z0-9]+'), get_class($this)); - $app->get('/client', 'get_client_index', array(), get_class($this)); - $app->get('/client/logout', 'get_client_logout', array(), get_class($this)); - $app->get('/client/:page', 'get_client_page', array('page'=>'[a-z0-9-]+'), get_class($this)); - $app->get('/client/confirm-email/:hash', 'get_client_confirmation', array('page'=>'[a-z0-9-]+'), get_class($this)); + $app->get('/client/reset-password-confirm/:hash', 'get_reset_password_confirm', ['hash' => '[a-z0-9]+'], get_class($this)); + $app->get('/client', 'get_client_index', [], get_class($this)); + $app->get('/client/logout', 'get_client_logout', [], get_class($this)); + $app->get('/client/:page', 'get_client_page', ['page' => '[a-z0-9-]+'], get_class($this)); + $app->get('/client/confirm-email/:hash', 'get_client_confirmation', ['page' => '[a-z0-9-]+'], get_class($this)); } /** * @param Box_App $app + * * @deprecated */ public function get_profile(\Box_App $app) @@ -56,6 +56,7 @@ class Client implements \Box\InjectionAwareInterface /** * @param Box_App $app + * * @deprecated */ public function get_balance(\Box_App $app) @@ -66,6 +67,7 @@ class Client implements \Box\InjectionAwareInterface public function get_client_index(\Box_App $app) { $this->di['is_client_logged']; + return $app->render('mod_client_index'); } @@ -89,17 +91,17 @@ class Client implements \Box\InjectionAwareInterface { $this->di['is_client_logged']; $template = 'mod_client_'.$page; + return $app->render($template); } public function get_reset_password_confirm(\Box_App $app, $hash) { $api = $this->di['api_guest']; - $data = array( - 'hash' => $hash, - ); + $data = [ + 'hash' => $hash, + ]; $api->client_confirm_reset($data); $app->redirect('/login'); } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Client/Service.php b/src/bb-modules/Client/Service.php index 081fa3093..33498d3e8 100644 --- a/src/bb-modules/Client/Service.php +++ b/src/bb-modules/Client/Service.php @@ -1,6 +1,6 @@ di['db']; - $result = $db->getRow('SELECT id, client_id FROM extension_meta WHERE extension = "mod_client" AND meta_key = "confirm_email" AND meta_value = :hash', array(':hash'=>$hash)); - if(!$result) { + $result = $db->getRow('SELECT id, client_id FROM extension_meta WHERE extension = "mod_client" AND meta_key = "confirm_email" AND meta_value = :hash', [':hash' => $hash]); + if (!$result) { throw new \Box_Exception('Invalid email confirmation link'); } - $db->exec('UPDATE client SET email_approved = 1 WHERE id = :id', array('id'=>$result['client_id'])); - $db->exec('DELETE FROM extension_meta WHERE id = :id', array('id'=>$result['id'])); + $db->exec('UPDATE client SET email_approved = 1 WHERE id = :id', ['id' => $result['client_id']]); + $db->exec('DELETE FROM extension_meta WHERE id = :id', ['id' => $result['id']]); + return true; } - + public function generateEmailConfirmationLink($client_id) { $hash = strtolower($this->di['tools']->generatePassword(50)); $db = $this->di['db']; $meta = $db->dispense('ExtensionMeta'); - $meta->extension = 'mod_client'; - $meta->client_id = $client_id; - $meta->meta_key = 'confirm_email'; - $meta->meta_value = $hash; - $meta->created_at = date('Y-m-d H:i:s'); - $meta->updated_at = date('Y-m-d H:i:s'); + $meta->extension = 'mod_client'; + $meta->client_id = $client_id; + $meta->meta_key = 'confirm_email'; + $meta->meta_value = $hash; + $meta->created_at = date('Y-m-d H:i:s'); + $meta->updated_at = date('Y-m-d H:i:s'); $db->store($meta); return $this->di['tools']->url('/client/confirm-email/'.$hash); } - + public static function onAfterClientSignUp(\Box_Event $event) { $di = $event->getDi(); @@ -71,22 +71,22 @@ class Service implements InjectionAwareInterface $config = $di['mod_config']('client'); $emailService = $di['mod_service']('email'); try { - $email = array(); + $email = []; $email['to_client'] = $params['id']; - $email['code'] = 'mod_client_signup'; - $email['password'] = $params['password']; - $email['require_email_confirmation'] = false; - if(isset($config['require_email_confirmation']) && $config['require_email_confirmation']) { + $email['code'] = 'mod_client_signup'; + $email['password'] = $params['password']; + $email['require_email_confirmation'] = false; + if (isset($config['require_email_confirmation']) && $config['require_email_confirmation']) { $clientService = $di['mod_service']('client'); - $email['require_email_confirmation'] = true; + $email['require_email_confirmation'] = true; $email['email_confirmation_link'] = $clientService->generateEmailConfirmationLink($params['id']); } $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } - + return true; } @@ -95,77 +95,77 @@ class Service implements InjectionAwareInterface $sql = $selectStmt; $sql .= ' FROM client as c left join client_group as cg on c.client_group_id = cg.id'; - $search = (isset($data['search']) && !empty($data['search'])) ? $data['search'] : NULL; - $client_id = (isset($data['client_id']) && !empty($data['client_id'])) ? $data['client_id'] : NULL; - $group_id = (isset($data['group_id']) && !empty($data['group_id'])) ? $data['group_id'] : NULL; - $id = (isset($data['id']) && !empty($data['id'])) ? $data['id'] : NULL; - $status = (isset($data['status']) && !empty($data['status'])) ? $data['status'] : NULL; - $name = (isset($data['name']) && !empty($data['name'])) ? $data['name'] : NULL; - $company = (isset($data['company']) && !empty($data['company'])) ? $data['company'] : NULL; - $email = (isset($data['email']) && !empty($data['email'])) ? $data['email'] : NULL; - $created_at = (isset($data['created_at']) && !empty($data['created_at'])) ? $data['created_at'] : NULL; - $date_from = (isset($data['date_from']) && !empty($data['date_from'])) ? $data['date_from'] : NULL; - $date_to = (isset($data['date_to']) && !empty($data['date_to'])) ? $data['date_to'] : NULL; + $search = (isset($data['search']) && !empty($data['search'])) ? $data['search'] : null; + $client_id = (isset($data['client_id']) && !empty($data['client_id'])) ? $data['client_id'] : null; + $group_id = (isset($data['group_id']) && !empty($data['group_id'])) ? $data['group_id'] : null; + $id = (isset($data['id']) && !empty($data['id'])) ? $data['id'] : null; + $status = (isset($data['status']) && !empty($data['status'])) ? $data['status'] : null; + $name = (isset($data['name']) && !empty($data['name'])) ? $data['name'] : null; + $company = (isset($data['company']) && !empty($data['company'])) ? $data['company'] : null; + $email = (isset($data['email']) && !empty($data['email'])) ? $data['email'] : null; + $created_at = (isset($data['created_at']) && !empty($data['created_at'])) ? $data['created_at'] : null; + $date_from = (isset($data['date_from']) && !empty($data['date_from'])) ? $data['date_from'] : null; + $date_to = (isset($data['date_to']) && !empty($data['date_to'])) ? $data['date_to'] : null; - $where = array(); - $params = array(); - if($id) { + $where = []; + $params = []; + if ($id) { $where[] = 'c.id = :client_id or c.aid = :alt_client_id'; $params[':client_id'] = $id; $params[':alt_client_id'] = $id; } - if($name) { + if ($name) { $where[] = '(c.first_name LIKE :first_name or c.last_name LIKE :last_name )'; - $name = "%" . $name . "%"; + $name = '%'.$name.'%'; $params[':first_name'] = $name; $params[':last_name'] = $name; } - if($email) { + if ($email) { $where[] = 'c.email LIKE :email'; - $params[':email'] = "%" . $email . "%"; + $params[':email'] = '%'.$email.'%'; } - if($company) { + if ($company) { $where[] = 'c.company LIKE :company'; - $params[':company'] = "%" . $company . "%"; + $params[':company'] = '%'.$company.'%'; } - if($status) { + if ($status) { $where[] = 'c.status = :status'; $params[':status'] = $status; } - if($group_id) { + if ($group_id) { $where[] = 'c.client_group_id = :group_id'; $params[':group_id'] = $group_id; } - if($created_at) { + if ($created_at) { $where[] = "DATE_FORMAT(c.created_at, '%Y-%m-%d') = :created_at"; - $params[':created_at'] = date('Y-m-d', strtotime($created_at)) ; + $params[':created_at'] = date('Y-m-d', strtotime($created_at)); } - if($date_from) { + if ($date_from) { $where[] = 'UNIX_TIMESTAMP(c.created_at) >= :date_from'; $params[':date_from'] = strtotime($date_from); } - if($date_to) { + if ($date_to) { $where[] = 'UNIX_TIMESTAMP(c.created_at) <= :date_from'; $params[':date_to'] = strtotime($date_to); } - //smartSearch - if($search) { - if(is_numeric($search)) { + // smartSearch + if ($search) { + if (is_numeric($search)) { $where[] = 'c.id = :cid or c.aid = :caid'; $params[':cid'] = $search; $params[':caid'] = $search; } else { $where[] = "c.company LIKE :s_company OR c.first_name LIKE :s_first_time OR c.last_name LIKE :s_last_name OR c.email LIKE :s_email OR CONCAT(c.first_name, ' ', c.last_name ) LIKE :full_name"; - $search = "%" . $search . "%"; + $search = '%'.$search.'%'; $params[':s_company'] = $search; $params[':s_first_time'] = $search; $params[':s_last_name'] = $search; @@ -174,39 +174,40 @@ class Service implements InjectionAwareInterface } } - if (!empty($where)){ + if (!empty($where)) { $sql .= ' WHERE '.implode(' AND ', $where); } $sql = $sql.' ORDER BY c.created_at desc'; - return array($sql, $params); + return [$sql, $params]; } public function getPairs($data) { - $limit = $this->di['array_get']($data, 'per_page', 30); - list($sql, $params) = $this->getSearchQuery($data, "SELECT c.id, CONCAT(c.first_name, ' ', c.last_name) as full_name"); + $limit = $this->di['array_get']($data, 'per_page', 30); + [$sql, $params] = $this->getSearchQuery($data, "SELECT c.id, CONCAT(c.first_name, ' ', c.last_name) as full_name"); $sql = $sql.' LIMIT '.$limit; + return $this->di['db']->getAssoc($sql, $params); } public function toSessionArray(\Model_Client $model) { - return array( - 'id' => $model->id, - 'email' => $model->email, - 'name' => $model->getFullName(), - 'role' => $model->role, - ); + return [ + 'id' => $model->id, + 'email' => $model->email, + 'name' => $model->getFullName(), + 'role' => $model->role, + ]; } public function emailAreadyRegistered($new_email, \Model_Client $model = null) { - if($model && $model->email == $new_email) { + if ($model && $model->email == $new_email) { return false; } - $result = $this->di['db']->findOne('Client', 'email = ?', array($new_email)); + $result = $this->di['db']->findOne('Client', 'email = ?', [$new_email]); return ($result) ? true : false; } @@ -221,12 +222,12 @@ class Service implements InjectionAwareInterface return false; } - $invoice = $this->di['db']->findOne('Invoice', 'client_id = :client_id', array(':client_id' => $model->id)); + $invoice = $this->di['db']->findOne('Invoice', 'client_id = :client_id', [':client_id' => $model->id]); if ($invoice instanceof \Model_Invoice) { throw new \Box_Exception('Currency can not be changed. Client already have invoices issued.'); } - $order = $this->di['db']->findOne('ClientOrder', 'client_id = :client_id', array(':client_id' => $model->id)); + $order = $this->di['db']->findOne('ClientOrder', 'client_id = :client_id', [':client_id' => $model->id]); if ($order instanceof \Model_ClientOrder) { throw new \Box_Exception('Currency can not be changed. Client already have orders.'); } @@ -234,38 +235,40 @@ class Service implements InjectionAwareInterface return true; } - public function addFunds(\Model_Client $client, $amount, $description, array $data = array()) + public function addFunds(\Model_Client $client, $amount, $description, array $data = []) { - if(!$client->currency) { + if (!$client->currency) { throw new \Box_Exception('Define clients currency before adding funds.'); } - if(!is_numeric($amount)) { + if (!is_numeric($amount)) { throw new \Box_Exception('Funds amount is not valid'); } - if(empty($description)) { + if (empty($description)) { throw new \Box_Exception('Funds description is not valid'); } $credit = $this->di['db']->dispense('ClientBalance'); $credit->client_id = $client->id; - $credit->type = $this->di['array_get']($data, 'type', 'gift'); - $credit->rel_id = $this->di['array_get']($data, 'rel_id'); + $credit->type = $this->di['array_get']($data, 'type', 'gift'); + $credit->rel_id = $this->di['array_get']($data, 'rel_id'); $credit->description = $description; $credit->amount = $amount; $credit->created_at = date('Y-m-d H:i:s'); $credit->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($credit); + return true; } public function getExpiredPasswordReminders() { $expire_after_hours = 2; - $expired = $this->di['db']->find('ClientPasswordReset', 'UNIX_TIMESTAMP() - ? > UNIX_TIMESTAMP(created_at)', array($expire_after_hours * 60 * 60)); + $expired = $this->di['db']->find('ClientPasswordReset', 'UNIX_TIMESTAMP() - ? > UNIX_TIMESTAMP(created_at)', [$expire_after_hours * 60 * 60]); + return $expired; } @@ -275,30 +278,30 @@ class Service implements InjectionAwareInterface FROM activity_client_history as ach LEFT JOIN client as c on ach.client_id = c.id '; - $search = $this->di['array_get']($data, 'search'); - $client_id = $this->di['array_get']($data, 'client_id'); + $search = $this->di['array_get']($data, 'search'); + $client_id = $this->di['array_get']($data, 'client_id'); - $where = array(); - $params = array(); - if($search) { + $where = []; + $params = []; + if ($search) { $where[] = 'c.first_name LIKE :first_name OR c.last_name LIKE :last_name OR c.id LIKE :id'; - $params[':first_name'] = "%".$search."%"; - $params[':last_name'] = "%".$search."%"; + $params[':first_name'] = '%'.$search.'%'; + $params[':last_name'] = '%'.$search.'%'; $params[':id'] = $search; } - if($client_id) { + if ($client_id) { $where[] = 'ach.client_id = :client_id'; $params[':client_id'] = $client_id; } - if (!empty($where)){ + if (!empty($where)) { $q .= ' WHERE '.implode(' AND ', $where); } $q .= ' ORDER BY ach.id desc'; - return array($q, $params); + return [$q, $params]; } public function counter() @@ -307,84 +310,87 @@ class Service implements InjectionAwareInterface FROM client group by status'; $data = $this->di['db']->getAssoc($sql); - return array( - 'total' => array_sum($data), - \Model_Client::ACTIVE => isset($data[\Model_Client::ACTIVE]) ? $data[\Model_Client::ACTIVE] : 0, - \Model_Client::SUSPENDED => isset($data[\Model_Client::SUSPENDED]) ? $data[\Model_Client::SUSPENDED] : 0, - \Model_Client::CANCELED => isset($data[\Model_Client::CANCELED]) ? $data[\Model_Client::CANCELED] : 0, - ); + + return [ + 'total' => array_sum($data), + \Model_Client::ACTIVE => $data[\Model_Client::ACTIVE] ?? 0, + \Model_Client::SUSPENDED => $data[\Model_Client::SUSPENDED] ?? 0, + \Model_Client::CANCELED => $data[\Model_Client::CANCELED] ?? 0, + ]; } public function getGroupPairs() { $sql = 'SELECT id, title FROM client_group'; + return $this->di['db']->getAssoc($sql); } public function clientAlreadyExists($email) { - $client = $this->di['db']->findOne('Client', 'email = :email ', array(':email' => $email)); + $client = $this->di['db']->findOne('Client', 'email = :email ', [':email' => $email]); - return ($client instanceof \Model_Client); + return $client instanceof \Model_Client; } public function getByLoginDetails($email, $password) { - $client = $this->di['db']->findOne('Client', 'email = ? and pass = ? and status = ?', array($email, $password, \Model_Client::ACTIVE)); + $client = $this->di['db']->findOne('Client', 'email = ? and pass = ? and status = ?', [$email, $password, \Model_Client::ACTIVE]); + return $client; } public function toApiArray(\Model_Client $model, $deep = false, $identity = null) { - $details = array( - 'id' => $model->id, - 'aid' => $model->aid, - 'email' => $model->email, - 'type' => $model->type, + $details = [ + 'id' => $model->id, + 'aid' => $model->aid, + 'email' => $model->email, + 'type' => $model->type, 'group_id' => $model->client_group_id, - 'company' => $model->company, - 'company_vat' => $model->company_vat, - 'company_number' => $model->company_number, - 'first_name' => $model->first_name, - 'last_name' => $model->last_name, - 'gender' => $model->gender, - 'birthday' => $model->birthday, - 'phone_cc' => $model->phone_cc, - 'phone' => $model->phone, - 'address_1' => $model->address_1, - 'address_2' => $model->address_2, - 'city' => $model->city, - 'state' => $model->state, - 'postcode' => $model->postcode, - 'country' => $model->country, - 'currency' => $model->currency, - 'notes' => $model->notes, - 'created_at' => $model->created_at, + 'company' => $model->company, + 'company_vat' => $model->company_vat, + 'company_number' => $model->company_number, + 'first_name' => $model->first_name, + 'last_name' => $model->last_name, + 'gender' => $model->gender, + 'birthday' => $model->birthday, + 'phone_cc' => $model->phone_cc, + 'phone' => $model->phone, + 'address_1' => $model->address_1, + 'address_2' => $model->address_2, + 'city' => $model->city, + 'state' => $model->state, + 'postcode' => $model->postcode, + 'country' => $model->country, + 'currency' => $model->currency, + 'notes' => $model->notes, + 'created_at' => $model->created_at, 'document_nr' => $model->document_nr, - ); + ]; - if($deep) { + if ($deep) { $details['balance'] = $this->getClientBalance($model); } $m = $this->di['db']->toArray($model); - for ($i = 1; $i < 11; $i++) { + for ($i = 1; $i < 11; ++$i) { $k = 'custom_'.$i; - if(isset($m[$k]) && !empty($m[$k])) { + if (isset($m[$k]) && !empty($m[$k])) { $details[$k] = $m[$k]; } } $clientGroup = $this->di['db']->load('ClientGroup', $model->client_group_id); - if($identity instanceof \Model_Admin) { + if ($identity instanceof \Model_Admin) { $details['auth_type'] = $model->auth_type; $details['api_token'] = $model->api_token; $details['ip'] = $model->ip; $details['status'] = $model->status; $details['tax_exempt'] = $model->tax_exempt; - $details['group'] = ($clientGroup) ? $clientGroup->title : NULL; + $details['group'] = ($clientGroup) ? $clientGroup->title : null; $details['updated_at'] = $model->updated_at; $details['email_approved'] = $model->email_approved; } @@ -399,30 +405,31 @@ class Service implements InjectionAwareInterface WHERE client_id = ? GROUP BY client_id'; - $balance = $this->di['db']->getCell($sql, array($c->id)); + $balance = $this->di['db']->getCell($sql, [$c->id]); return $balance; } public function get($data) { - if(!isset($data['id']) && !isset($data['email'])) { + if (!isset($data['id']) && !isset($data['email'])) { throw new \Box_Exception('Client ID or email is required'); } $db = $this->di['db']; $client = null; - if(isset($data['id'])) { - $client = $db->findOne('Client', 'id = ?', array($data['id'])); + if (isset($data['id'])) { + $client = $db->findOne('Client', 'id = ?', [$data['id']]); } - if(!$client && isset($data['email'])) { - $client = $db->findOne('Client', 'email = ?', array($data['email'])); + if (!$client && isset($data['email'])) { + $client = $db->findOne('Client', 'email = ?', [$data['email']]); } - if(!$client instanceof \Model_Client ) { + if (!$client instanceof \Model_Client) { throw new \Box_Exception('Client not found'); } + return $client; } @@ -455,18 +462,20 @@ class Service implements InjectionAwareInterface $group_id = $this->di['db']->store($model); $this->di['logger']->info('Created new client group #%s', $model->id); + return $group_id; } public function deleteGroup(\Model_ClientGroup $model) { - $client = $this->di['db']->findOne('Client', 'client_group_id = ?', array($model->id)); - if($client) { + $client = $this->di['db']->findOne('Client', 'client_group_id = ?', [$model->id]); + if ($client) { throw new \Box_Exception('Can not remove group with clients'); } $this->di['db']->trash($model); $this->di['logger']->info('Removed client group #%s', $model->id); + return true; } @@ -476,48 +485,48 @@ class Service implements InjectionAwareInterface $client = $this->di['db']->dispense('Client'); - $client->auth_type = $this->di['array_get']($data, 'auth_type'); - $client->email = strtolower(trim($this->di['array_get']($data, 'email'))); + $client->auth_type = $this->di['array_get']($data, 'auth_type'); + $client->email = strtolower(trim($this->di['array_get']($data, 'email'))); $client->first_name = ucwords($this->di['array_get']($data, 'first_name')); - $client->pass = $this->di['password']->hashIt($password); + $client->pass = $this->di['password']->hashIt($password); $phoneCC = $this->di['array_get']($data, 'phone_cc', $client->phone_cc); - if(!empty($phoneCC)){ + if (!empty($phoneCC)) { $client->phone_cc = intval($phoneCC); } - $client->aid = $this->di['array_get']($data, 'aid'); - $client->last_name = $this->di['array_get']($data, 'last_name'); + $client->aid = $this->di['array_get']($data, 'aid'); + $client->last_name = $this->di['array_get']($data, 'last_name'); $client->client_group_id = $this->di['array_get']($data, 'group_id'); - $client->status = $this->di['array_get']($data, 'status'); - $client->gender = $this->di['array_get']($data, 'gender'); - $client->birthday = $this->di['array_get']($data, 'birthday'); - $client->phone = $this->di['array_get']($data, 'phone'); - $client->company = $this->di['array_get']($data, 'company'); - $client->company_vat = $this->di['array_get']($data, 'company_vat'); - $client->company_number = $this->di['array_get']($data, 'company_number'); - $client->type = $this->di['array_get']($data, 'type'); - $client->address_1 = $this->di['array_get']($data, 'address_1'); - $client->address_2 = $this->di['array_get']($data, 'address_2'); - $client->city = $this->di['array_get']($data, 'city'); - $client->state = $this->di['array_get']($data, 'state'); - $client->postcode = $this->di['array_get']($data, 'postcode'); - $client->country = $this->di['array_get']($data, 'country'); - $client->document_type = $this->di['array_get']($data, 'document_type'); - $client->document_nr = $this->di['array_get']($data, 'document_nr'); - $client->notes = $this->di['array_get']($data, 'notes'); - $client->lang = $this->di['array_get']($data, 'lang'); - $client->currency = $this->di['array_get']($data, 'currency'); + $client->status = $this->di['array_get']($data, 'status'); + $client->gender = $this->di['array_get']($data, 'gender'); + $client->birthday = $this->di['array_get']($data, 'birthday'); + $client->phone = $this->di['array_get']($data, 'phone'); + $client->company = $this->di['array_get']($data, 'company'); + $client->company_vat = $this->di['array_get']($data, 'company_vat'); + $client->company_number = $this->di['array_get']($data, 'company_number'); + $client->type = $this->di['array_get']($data, 'type'); + $client->address_1 = $this->di['array_get']($data, 'address_1'); + $client->address_2 = $this->di['array_get']($data, 'address_2'); + $client->city = $this->di['array_get']($data, 'city'); + $client->state = $this->di['array_get']($data, 'state'); + $client->postcode = $this->di['array_get']($data, 'postcode'); + $client->country = $this->di['array_get']($data, 'country'); + $client->document_type = $this->di['array_get']($data, 'document_type'); + $client->document_nr = $this->di['array_get']($data, 'document_nr'); + $client->notes = $this->di['array_get']($data, 'notes'); + $client->lang = $this->di['array_get']($data, 'lang'); + $client->currency = $this->di['array_get']($data, 'currency'); - $client->custom_1 = $this->di['array_get']($data, 'custom_1'); - $client->custom_2 = $this->di['array_get']($data, 'custom_2'); - $client->custom_3 = $this->di['array_get']($data, 'custom_3'); - $client->custom_4 = $this->di['array_get']($data, 'custom_4'); - $client->custom_5 = $this->di['array_get']($data, 'custom_5'); - $client->custom_6 = $this->di['array_get']($data, 'custom_6'); - $client->custom_7 = $this->di['array_get']($data, 'custom_7'); - $client->custom_8 = $this->di['array_get']($data, 'custom_8'); - $client->custom_9 = $this->di['array_get']($data, 'custom_9'); + $client->custom_1 = $this->di['array_get']($data, 'custom_1'); + $client->custom_2 = $this->di['array_get']($data, 'custom_2'); + $client->custom_3 = $this->di['array_get']($data, 'custom_3'); + $client->custom_4 = $this->di['array_get']($data, 'custom_4'); + $client->custom_5 = $this->di['array_get']($data, 'custom_5'); + $client->custom_6 = $this->di['array_get']($data, 'custom_6'); + $client->custom_7 = $this->di['array_get']($data, 'custom_7'); + $client->custom_8 = $this->di['array_get']($data, 'custom_8'); + $client->custom_9 = $this->di['array_get']($data, 'custom_9'); $client->custom_10 = $this->di['array_get']($data, 'custom_10'); $client->ip = $this->di['array_get']($data, 'ip'); @@ -526,14 +535,15 @@ class Service implements InjectionAwareInterface $client->created_at = !empty($created_at) ? date('Y-m-d H:i:s', strtotime($created_at)) : date('Y-m-d H:i:s'); $client->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($client); + return $client; } public function adminCreateClient(array $data) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminCreateClient', 'params'=>$data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminCreateClient', 'params' => $data]); $client = $this->createClient($data); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminCreateClient', 'params'=>array('id'=>$client->id, 'password'=>$data['password']))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminCreateClient', 'params' => ['id' => $client->id, 'password' => $data['password']]]); $this->di['logger']->info('Created new client #%s', $client->id); return $client->id; @@ -543,13 +553,13 @@ class Service implements InjectionAwareInterface { $event_params = $data; $event_params['ip'] = $this->di['request']->getClientAddress(); - $this->di['events_manager']->fire(array('event'=>'onBeforeClientSignUp', 'params'=>$event_params)); + $this->di['events_manager']->fire(['event' => 'onBeforeClientSignUp', 'params' => $event_params]); $data['ip'] = $this->di['request']->getClientAddress(); $data['status'] = \Model_Client::ACTIVE; $client = $this->createClient($data); - $this->di['events_manager']->fire(array('event'=>'onAfterClientSignUp', 'params'=>array('id'=>$client->id, 'password'=>$data['password']))); + $this->di['events_manager']->fire(['event' => 'onAfterClientSignUp', 'params' => ['id' => $client->id, 'password' => $data['password']]]); $this->di['logger']->info('Client #%s signed up', $client->id); return $client; @@ -581,25 +591,24 @@ class Service implements InjectionAwareInterface $table = $this->di['table']('ClientPasswordReset'); $table->rmByClient($model); - $pdo = $this->di['pdo']; $stmt = $pdo->prepare('DELETE FROM extension_meta WHERE client_id = :id'); - $stmt->execute(array('id'=>$model->id)); + $stmt->execute(['id' => $model->id]); $this->di['db']->trash($model); } public function authorizeClient($email, $plainTextPassword) { - $model = $this->di['db']->findOne('Client', 'email = ? AND status = ?', array($email, \Model_Client::ACTIVE)); - if ($model == null) { + $model = $this->di['db']->findOne('Client', 'email = ? AND status = ?', [$email, \Model_Client::ACTIVE]); + if (null == $model) { return null; } $config = $this->di['mod_config']('client'); - if (isset($config['require_email_confirmation']) && (int)$config['require_email_confirmation']) { + if (isset($config['require_email_confirmation']) && (int) $config['require_email_confirmation']) { if (!$model->email_approved) { - $meta = $this->di['db']->findOne('ExtensionMeta', ' extension = "mod_client" AND meta_key = "confirm_email" AND client_id = :client_id', array(':client_id' => $model->id)); + $meta = $this->di['db']->findOne('ExtensionMeta', ' extension = "mod_client" AND meta_key = "confirm_email" AND client_id = :client_id', [':client_id' => $model->id]); if (!is_null($meta)) { throw new \Box_Exception('Please check your mailbox and confirm email address.'); } else { @@ -615,11 +624,11 @@ class Service implements InjectionAwareInterface private function sendEmailConfirmationForClient(\Model_Client $client) { try { - $email = array(); - $email['to_client'] = $client->id; - $email['code'] = 'mod_client_confirm'; + $email = []; + $email['to_client'] = $client->id; + $email['code'] = 'mod_client_confirm'; $email['require_email_confirmation'] = true; - $email['email_confirmation_link'] = $this->generateEmailConfirmationLink($client->id); + $email['email_confirmation_link'] = $this->generateEmailConfirmationLink($client->id); $emailService = $this->di['mod_service']('email'); $emailService->sendTemplate($email); @@ -630,25 +639,25 @@ class Service implements InjectionAwareInterface public function canChangeEmail(\Model_Client $client, $email) { - $config = $this->di['mod_config']('client'); + $config = $this->di['mod_config']('client'); if ($client->email != $email && isset($config['allow_change_email']) && !$config['allow_change_email']) { throw new \Box_Exception('Email can not be changed'); } - return true; + return true; } public function checkExtraRequiredFields(array $checkArr) { $config = $this->di['mod_config']('client'); - $required = $this->di['array_get']($config, 'required', array()); - foreach($required as $field) { - if(!isset($checkArr[$field]) || empty($checkArr[$field])) { + $required = $this->di['array_get']($config, 'required', []); + foreach ($required as $field) { + if (!isset($checkArr[$field]) || empty($checkArr[$field])) { $name = ucwords(str_replace('_', ' ', $field)); - throw new \Box_Exception('It is required that you provide details for field ":field"', array(':field'=>$name)); + throw new \Box_Exception('It is required that you provide details for field ":field"', [':field' => $name]); } } } @@ -656,16 +665,16 @@ class Service implements InjectionAwareInterface public function checkCustomFields(array $checkArr) { $config = $this->di['mod_config']('client'); - $customFields = $this->di['array_get']($config, 'custom_fields', array()); + $customFields = $this->di['array_get']($config, 'custom_fields', []); foreach ($customFields as $cFieldName => $cField) { - $active = isset($cField['active']) && $cField['active'] ? true : false; + $active = isset($cField['active']) && $cField['active'] ? true : false; $required = isset($cField['required']) && $cField['required'] ? true : false; if ($active && $required) { if (!isset($checkArr[$cFieldName]) || empty($checkArr[$cFieldName])) { - $name = isset($cField['title']) && !empty($cField['title']) ? $cField['title'] : ucwords(str_replace('_', ' ', $cFieldName));; - throw new \Box_Exception('It is required that you provide details for field ":field"', array(':field' => $name)); + $name = isset($cField['title']) && !empty($cField['title']) ? $cField['title'] : ucwords(str_replace('_', ' ', $cFieldName)); + throw new \Box_Exception('It is required that you provide details for field ":field"', [':field' => $name]); } } } } -} \ No newline at end of file +} diff --git a/src/bb-modules/Client/ServiceBalance.php b/src/bb-modules/Client/ServiceBalance.php index 77e50cbab..fffe9fbe1 100644 --- a/src/bb-modules/Client/ServiceBalance.php +++ b/src/bb-modules/Client/ServiceBalance.php @@ -1,6 +1,6 @@ clientTotal($c); + return (float) $this->clientTotal($c); } public function clientTotal(Model_Client $c) { - $sql=" + $sql = ' SELECT SUM(amount) as client_total FROM client_balance WHERE client_id = ? GROUP BY client_id - "; - return $this->di['db']->getCell($sql, array($c->id)); + '; + + return $this->di['db']->getCell($sql, [$c->id]); } public function rmByClient(Model_Client $client) { - $clientBalances = $this->di['db']->find('ClientBalance', 'client_id = ?', array($client->id)); - foreach ($clientBalances as $balanceModel){ + $clientBalances = $this->di['db']->find('ClientBalance', 'client_id = ?', [$client->id]); + foreach ($clientBalances as $balanceModel) { $this->di['db']->trash($balanceModel); } } @@ -70,13 +70,14 @@ class ServiceBalance implements InjectionAwareInterface public function toApiArray(Model_ClientBalance $model) { $client = $this->di['db']->getExistingModelById('Client', $model->client_id, 'Client not found'); - return array( - 'id' => $model->id, - 'description' => $model->description, - 'amount' => $model->amount, - 'currency' => $client->currency, - 'created_at' => $model->created_at, - ); + + return [ + 'id' => $model->id, + 'description' => $model->description, + 'amount' => $model->amount, + 'currency' => $client->currency, + 'created_at' => $model->created_at, + ]; } public function getSearchQuery($data) @@ -85,57 +86,58 @@ class ServiceBalance implements InjectionAwareInterface FROM client_balance as m LEFT JOIN client as c on c.id = m.client_id'; - $id = $this->di['array_get']($data, 'id', NULL); - $client_id = $this->di['array_get']($data, 'client_id', NULL); - $date_from = $this->di['array_get']($data, 'date_from', NULL); - $date_to = $this->di['array_get']($data, 'date_to', NULL); + $id = $this->di['array_get']($data, 'id', null); + $client_id = $this->di['array_get']($data, 'client_id', null); + $date_from = $this->di['array_get']($data, 'date_from', null); + $date_to = $this->di['array_get']($data, 'date_to', null); - $where = array(); - $params = array(); + $where = []; + $params = []; - if(NULL !== $id) { + if (null !== $id) { $where[] = 'm.id = :id'; $params[':id'] = $id; } - if(NULL !== $client_id) { + if (null !== $client_id) { $where[] = 'm.client_id = :client_id'; $params[':client_id'] = $client_id; } - if(NULL !== $date_from) { + if (null !== $date_from) { $where[] = 'm.created_at >= :date_from'; $params[':date_from'] = strtotime($date_from); } - if(NULL !== $date_to) { + if (null !== $date_to) { $where[] = 'm.created_at <= :date_to'; $params[':date_to'] = strtotime($date_to); } - if (!empty($where)){ + if (!empty($where)) { $q .= ' WHERE '.implode(' AND ', $where); } $q .= ' ORDER by m.id DESC'; - return array($q, $params); + return [$q, $params]; } /** - * @param Model_Client $client - * @param double $amount - * @param string $description - * @param array $data + * @param float $amount + * @param string $description + * @param array $data + * * @return Model_ClientBalance + * * @throws Box_Exception */ public function deductFunds(Model_Client $client, $amount, $description, array $data = null) { - if(!is_numeric($amount)) { + if (!is_numeric($amount)) { throw new Box_Exception('Funds amount is not valid'); } - if(strlen(trim($description)) == 0) { + if (0 == strlen(trim($description))) { throw new Box_Exception('Funds description is not valid'); } @@ -151,4 +153,4 @@ class ServiceBalance implements InjectionAwareInterface return $credit; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cookieconsent/Api/Guest.php b/src/bb-modules/Cookieconsent/Api/Guest.php index 3b9443332..aa5add329 100644 --- a/src/bb-modules/Cookieconsent/Api/Guest.php +++ b/src/bb-modules/Cookieconsent/Api/Guest.php @@ -1,6 +1,6 @@ getService()->getMessage(); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cookieconsent/Controller/Admin.php b/src/bb-modules/Cookieconsent/Controller/Admin.php index b2785b987..90199e465 100644 --- a/src/bb-modules/Cookieconsent/Controller/Admin.php +++ b/src/bb-modules/Cookieconsent/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'extensions', - 'label' => 'Cookie consent', - 'index' => 2000, - 'uri' => $this->di['url']->adminLink('cookieconsent'), - 'class' => '', - ), - ), - ); + return [ + 'subpages' => [ + [ + 'location' => 'extensions', + 'label' => 'Cookie consent', + 'index' => 2000, + 'uri' => $this->di['url']->adminLink('cookieconsent'), + 'class' => '', + ], + ], + ]; } public function register(\Box_App &$app) { - $app->get('/cookieconsent', 'get_index', array(), get_class($this)); + $app->get('/cookieconsent', 'get_index', [], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_cookieconsent_index'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cookieconsent/Service.php b/src/bb-modules/Cookieconsent/Service.php index aa73ea843..b34335abc 100644 --- a/src/bb-modules/Cookieconsent/Service.php +++ b/src/bb-modules/Cookieconsent/Service.php @@ -1,6 +1,6 @@ di['array_get']($config, 'message', 'This website uses cookies. By continuing to use this website, you consent to our use of these cookies.'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cron/Api/Admin.php b/src/bb-modules/Cron/Api/Admin.php index 84770a921..c2e7bce39 100644 --- a/src/bb-modules/Cron/Api/Admin.php +++ b/src/bb-modules/Cron/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getCronInfo(); } - + /** - * Run cron - * + * Run cron. + * * @return bool */ public function run($data) { return $this->getService()->runCrons(); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cron/Api/Guest.php b/src/bb-modules/Cron/Api/Guest.php index f79c6bfc1..52df505c8 100644 --- a/src/bb-modules/Cron/Api/Guest.php +++ b/src/bb-modules/Cron/Api/Guest.php @@ -1,6 +1,6 @@ getService()->isLate(); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Cron/Service.php b/src/bb-modules/Cron/Service.php index f122a881b..85174f1c6 100644 --- a/src/bb-modules/Cron/Service.php +++ b/src/bb-modules/Cron/Service.php @@ -1,6 +1,6 @@ di['mod_service']('system'); - $result = array( - 'cron_url' => BB_URL . 'bb-cron.php', - 'cron_path' => BB_PATH_ROOT . DIRECTORY_SEPARATOR . 'bb-cron.php', - 'last_cron_exec' => $service->getParamValue('last_cron_exec'), - ); + $result = [ + 'cron_url' => BB_URL.'bb-cron.php', + 'cron_path' => BB_PATH_ROOT.DIRECTORY_SEPARATOR.'bb-cron.php', + 'last_cron_exec' => $service->getParamValue('last_cron_exec'), + ]; + return $result; } /** * @param null $interval - parameter from CLI, pass to filter crons to run + * * @return bool + * * @todo finish fixing, time to sleep */ public function runCrons($interval = null) @@ -51,9 +54,9 @@ class Service $api = $this->di['api_system']; $this->di['logger']->info('- Started executing cron'); - //@core tasks + // @core tasks $this->_exec($api, 'hook_batch_connect'); - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminCronRun')); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminCronRun']); $this->_exec($api, 'invoice_batch_pay_with_credits'); $this->_exec($api, 'invoice_batch_activate_paid'); @@ -72,9 +75,10 @@ class Service $ss = $this->di['mod_service']('system'); $ss->setParamValue('last_cron_exec', date('Y-m-d H:i:s'), $create); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminCronRun')); + $this->di['events_manager']->fire(['event' => 'onAfterAdminCronRun']); $this->di['logger']->info('- Finished executing cron'); + return true; } @@ -85,11 +89,11 @@ class Service { try { $api->{$method}($params); - } catch(Exception $e) { + } catch (Exception $e) { throw new Exception($e); } finally { - if (php_sapi_name() == 'cli') { - print ("\e[32mSuccessfully ran " . $method . "(" . $params . ")" . ".\e[0m\n"); + if ('cli' == php_sapi_name()) { + echo "\e[32mSuccessfully ran ".$method.'('.$params.')'.".\e[0m\n"; } } } @@ -101,6 +105,7 @@ class Service { $service = $this->di['mod_service']('system'); $last_exec = $service->getParamValue('last_cron_exec'); + return $last_exec; } @@ -108,6 +113,7 @@ class Service { $t1 = new \DateTime($this->getLastExecutionTime()); $t2 = new \DateTime('-6min'); - return ($t1 < $t2); + + return $t1 < $t2; } } diff --git a/src/bb-modules/Currency/Api/Admin.php b/src/bb-modules/Currency/Api/Admin.php index 37ccaa9a7..db00542c8 100644 --- a/src/bb-modules/Currency/Api/Admin.php +++ b/src/bb-modules/Currency/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getSearchQuery(); + [$query, $params] = $this->getService()->getSearchQuery(); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($query, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $currency = $this->di['db']->getExistingModelById('Currency', $item['id'], 'Currency not found'); + $currency = $this->di['db']->getExistingModelById('Currency', $item['id'], 'Currency not found'); $pager['list'][$key] = $this->getService()->toApiArray($currency); } return $pager; } - + /** - * Get code title pairs of currencies - * + * Get code title pairs of currencies. + * * @return array */ public function get_pairs() { $service = $this->getService(); + return $service->getAvailableCurrencies(); } /** - * Return currency details by cde - * + * Return currency details by cde. + * * @param string $code - currency code USD + * * @return array - * @throws Exception + * + * @throws Exception */ public function get($data) { - $required = array( + $required = [ 'code' => 'Currency code is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); $model = $service->getByCode($data['code']); - if(!$model instanceof \Model_Currency) { + if (!$model instanceof \Model_Currency) { throw new \Box_Exception('Currency not found'); } + return $service->toApiArray($model); } /** - * Return default system currency - * + * Return default system currency. + * * @return array */ public function get_default($data) { $service = $this->getService(); $currency = $service->getDefault(); + return $service->toApiArray($currency); } /** - * Add new currency to system - * - * @param string $code - currency ISO 4217 code - * @param string $format - must have {{price}} tag. - * + * Add new currency to system. + * + * @param string $code - currency ISO 4217 code + * @param string $format - must have {{price}} tag + * * @optional string $title - custom currency title - * + * * @return string - currency code - * - * @throws Exception + * + * @throws Exception */ - public function create($data = array()) + public function create($data = []) { - $required = array( + $required = [ 'code' => 'Currency code is missing', 'format' => 'Currency format is missing', - ); - $this->di['validator']->checkRequiredParamsForArray($required, $data); + ]; + $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); - if($service->getByCode($this->di['array_get']($data, 'code'))) { + if ($service->getByCode($this->di['array_get']($data, 'code'))) { throw new \Box_Exception('Currency already registered'); } - if(!array_key_exists($this->di['array_get']($data, 'code'), $service->getAvailableCurrencies())) { + if (!array_key_exists($this->di['array_get']($data, 'code'), $service->getAvailableCurrencies())) { throw new \Box_Exception('Currency code is not valid'); } - $title = $this->di['array_get']($data, 'title'); + $title = $this->di['array_get']($data, 'title'); $conversionRate = $this->di['array_get']($data, 'conversion_rate', 1); return $service->createCurrency($this->di['array_get']($data, 'code'), $this->di['array_get']($data, 'format'), $title, $conversionRate); } /** - * Updates system currency settings - * + * Updates system currency settings. + * * @param string $code - currency ISO 4217 code - * + * * @optional string $title - new currency title * @optional string $format - new currency format * @optional float $conversion_rate - new currency conversion rate - * + * * @return bool - * - * @throws Exception + * + * @throws Exception */ public function update($data) { - $required = array( + $required = [ 'code' => 'Currency code is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $format = $this->di['array_get']($data, 'format'); - $title = $this->di['array_get']($data, 'title'); - $priceFormat = $this->di['array_get']($data, 'price_format'); + $format = $this->di['array_get']($data, 'format'); + $title = $this->di['array_get']($data, 'title'); + $priceFormat = $this->di['array_get']($data, 'price_format'); $conversionRate = $this->di['array_get']($data, 'conversion_rate'); return $this->getService()->updateCurrency($data['code'], $format, $title, $priceFormat, $conversionRate); } /** - * Gets the API key for currencylayer - * + * Gets the API key for currencylayer. + * * @since 4.22.0 + * * @return string */ public function get_key($data) - { + { return $this->getService()->getKey(); } /** - * Updates the API key for currencylayer - * + * Updates the API key for currencylayer. + * * @since 4.22.0 + * * @return bool */ public function update_rate_settings($data) - { + { $this->getService()->updateKey($this->di['array_get']($data, 'currencylayer_key')); - - if ($this->di['array_get']($data, 'crons_enabled') == "1") { - $set = "1"; + + if ($this->di['array_get']($data, 'crons_enabled') == '1') { + $set = '1'; } else { - $set = "0"; + $set = '0'; } - + $this->getService()->setCron($set); - + return true; } /** - * See if CRON jobs are enabled for currency rates - * + * See if CRON jobs are enabled for currency rates. + * * @todo why does this even return a string instead of a boolean? + * * @since 4.22.0 + * * @return string (0/1) */ public function is_cron_enabled($data) - { + { return $this->getService()->isCronEnabled(); } /** * Automatically update all currency rates. - * + * * @return bool */ public function update_rates($data) @@ -201,17 +211,18 @@ class Admin extends \Api_Abstract /** * Remove currency. Default currency can not be removed. - * + * * @param string $code - currency ISO 4217 code - * + * * @return bool - * @throws Exception + * + * @throws Exception */ public function delete($data) { - $required = array( + $required = [ 'code' => 'Currency code is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->deleteCurrencyByCode($data['code']); @@ -220,21 +231,22 @@ class Admin extends \Api_Abstract /** * Set default currency. If you have active orders or invoices * not recalculation on profits and refunds are made. - * + * * @param string $code - currency ISO 4217 code - * + * * @return bool - * @throws Exception + * + * @throws Exception */ public function set_default($data) { - $required = array( + $required = [ 'code' => 'Currency code is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); - $model = $service->getByCode($data['code']); + $model = $service->getByCode($data['code']); if (!$model instanceof \Model_currency) { throw new \Box_Exception('Currency not found'); } diff --git a/src/bb-modules/Currency/Api/Guest.php b/src/bb-modules/Currency/Api/Guest.php index 3e83d5853..feef95fe4 100644 --- a/src/bb-modules/Currency/Api/Guest.php +++ b/src/bb-modules/Currency/Api/Guest.php @@ -1,6 +1,6 @@ getService(); + return $service->getPairs(); } /** - * Get currency by code - * + * Get currency by code. + * * @param string $code - currency code, ie: USD + * * @return array */ public function get($data) { $service = $this->getService(); - if(isset($data['code']) && !empty($data['code'])) { + if (isset($data['code']) && !empty($data['code'])) { $model = $service->getByCode($data['code']); } else { $model = $service->getDefault(); } - - if(!$model instanceof \Model_Currency) { + + if (!$model instanceof \Model_Currency) { throw new \Box_Exception('Currency not found'); } + return $service->toApiArray($model); } - + /** - * Format price by currency settings - * - * @optional bool $convert - covert to default currency rate. Default - true; + * Format price by currency settings. + * + * @optional bool $convert - covert to default currency rate. Default - true; * @optional bool $without_currency - Show only number. No symbols are attached Default - false; * @optional float $price - Price to be formated. Default 0 * @optional string $code - currency code, ie: USD. Default - default currency - * + * * @return string - formated string */ - public function format($data = array()) + public function format($data = []) { $c = $this->get($data); @@ -69,7 +72,7 @@ class Guest extends \Api_Abstract $without_currency = (bool) $this->di['array_get']($data, 'without_currency', false); $p = $price; - if($convert) { + if ($convert) { $p = $price * $c['conversion_rate']; } @@ -77,29 +80,29 @@ class Guest extends \Api_Abstract case 2: $p = number_format($p, 2, '.', ','); break; - + case 3: $p = number_format($p, 2, ',', '.'); break; - + case 4: $p = number_format($p, 0, '', ','); break; - + case 5: $p = number_format($p, 0, '', ''); break; case 1: default: - $p = number_format($p, 2, '.', ''); + $p = number_format($p, 2, '.', ''); break; } - if($without_currency) { + if ($without_currency) { return $p; } return str_replace('{{price}}', $p, $c['format']); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Currency/Controller/Admin.php b/src/bb-modules/Currency/Controller/Admin.php index cb5ff609e..8f1de1084 100644 --- a/src/bb-modules/Currency/Controller/Admin.php +++ b/src/bb-modules/Currency/Controller/Admin.php @@ -1,6 +1,6 @@ get('/currency/manage/:code', 'get_manage', array('code'=>'[a-zA-Z]+'), get_class($this)); + $app->get('/currency/manage/:code', 'get_manage', ['code' => '[a-zA-Z]+'], get_class($this)); } public function get_manage(\Box_App $app, $code) { $this->di['is_admin_logged']; $guest_api = $this->di['api_guest']; - $currency = $guest_api->currency_get(array('code'=>$code)); - return $app->render('mod_currency_manage', array('currency'=>$currency)); + $currency = $guest_api->currency_get(['code' => $code]); + + return $app->render('mod_currency_manage', ['currency' => $currency]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Currency/Service.php b/src/bb-modules/Currency/Service.php index 999dbdbe1..11740473e 100644 --- a/src/bb-modules/Currency/Service.php +++ b/src/bb-modules/Currency/Service.php @@ -1,6 +1,6 @@ getRateByCode($foreign_code); - if ($f_rate == 0) { + if (0 == $f_rate) { throw new \Box_Exception('Currency conversion rate can not be zero'); } @@ -65,13 +64,13 @@ class Service implements InjectionAwareInterface public function getCurrencyByClientId($client_id) { - $sql = "SELECT currency FROM client WHERE id = :client_id"; - $values = array(':client_id' => $client_id); + $sql = 'SELECT currency FROM client WHERE id = :client_id'; + $values = [':client_id' => $client_id]; - $db = $this->di['db']; + $db = $this->di['db']; $currency = $db->getCell($sql, $values); - if (NULL === $currency) { + if (null === $currency) { return $this->getDefault(); } @@ -88,15 +87,15 @@ class Service implements InjectionAwareInterface */ public function getByCode($code) { - return $this->di['db']->findOne('Currency', 'code = :code', array(':code' => $code)); + return $this->di['db']->findOne('Currency', 'code = :code', [':code' => $code]); } public function getRateByCode($code) { - $sql = "SELECT conversion_rate FROM currency WHERE code = :code"; - $values = array(':code' => $code); + $sql = 'SELECT conversion_rate FROM currency WHERE code = :code'; + $values = [':code' => $code]; - $db = $this->di['db']; + $db = $this->di['db']; $rate = $db->getCell($sql, $values); return is_numeric($rate) ? $rate : 1; @@ -107,7 +106,7 @@ class Service implements InjectionAwareInterface $db = $this->di['db']; $default = $db->findOne('Currency', 'is_default = 1'); - if (is_array($default) && count($default) == 0) { + if (is_array($default) && 0 == count($default)) { $default = $db->load('Currency', '1'); } @@ -116,20 +115,19 @@ class Service implements InjectionAwareInterface public function setAsDefault(\Model_Currency $currency) { - $db = $this->di['db']; if ($currency->is_default) { return true; } - if ($currency->code === null || empty($currency->code)) { + if (null === $currency->code || empty($currency->code)) { throw new \Box_Exception('Currency code not provided'); } - $sql1 = "UPDATE currency SET is_default = 0 WHERE 1"; - $sql2 = "UPDATE currency SET is_default = 1 WHERE code = :code"; - $values2 = array(':code' => $currency->code); + $sql1 = 'UPDATE currency SET is_default = 0 WHERE 1'; + $sql2 = 'UPDATE currency SET is_default = 1 WHERE code = :code'; + $values2 = [':code' => $currency->code]; $db->exec($sql1); $db->exec($sql2, $values2); @@ -141,22 +139,22 @@ class Service implements InjectionAwareInterface public function getPairs() { - $sql = "SELECT code, title FROM currency"; - $db = $this->di['db']; + $sql = 'SELECT code, title FROM currency'; + $db = $this->di['db']; $pairs = $db->getAssoc($sql); return $pairs; } - /** + /** * Returns a list of available currencies. - * + * * @return string List of currencies in the "[short code] - [name]" format - */ + */ public function getAvailableCurrencies() { - $options = array( + $options = [ 'AED' => 'United Arab Emirates dirham', 'AFN' => 'Afghan afghani', 'ALL' => 'Albanian lek', @@ -310,10 +308,10 @@ class Service implements InjectionAwareInterface 'ZAR' => 'South African rand', 'ZMK' => 'Zambian kwacha', 'ZWL' => 'Zimbabwe dollar', - ); + ]; foreach ($options as $key => &$name) { - $name = $key . ' - ' . $name; + $name = $key.' - '.$name; } return $options; @@ -325,103 +323,110 @@ class Service implements InjectionAwareInterface throw new \Box_Exception('Can not remove default currency'); } - if ($model->code === null || empty($model->code)) { + if (null === $model->code || empty($model->code)) { throw new \Box_Exception('Currency code not found'); } - $sql = "DELETE FROM currency WHERE code = :code"; - $values = array(':code' => $model->code); + $sql = 'DELETE FROM currency WHERE code = :code'; + $values = [':code' => $model->code]; $db = $this->di['db']; $db->exec($sql, $values); } - /** + /** * Returns the API credentials for currencylayer. - * + * * @todo maybe make this extensible so people can choose their data provider? + * * @since 4.22.0 + * * @return string - */ + */ public function getKey() { - $sql = "SELECT `param`, `value` FROM setting"; - $db = $this->di['db']; + $sql = 'SELECT `param`, `value` FROM setting'; + $db = $this->di['db']; $pairs = $db->getAssoc($sql); return $pairs['currencylayer']; } - /** + /** * Updates the API credentials for currencylayer. - * + * * @todo maybe make this extensible so people can choose their data provider? + * * @since 4.22.0 + * * @return string - */ + */ public function updateKey($key) { - $sql = "INSERT INTO `setting` (`param`, `value`, `public`, `created_at`, `updated_at`) VALUES ('currencylayer', :key, '0', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()) ON DUPLICATE KEY UPDATE `value`=:key, `updated_at`=CURRENT_TIMESTAMP()"; - $values = array(':key' => $key); + $sql = "INSERT INTO `setting` (`param`, `value`, `public`, `created_at`, `updated_at`) VALUES ('currencylayer', :key, '0', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()) ON DUPLICATE KEY UPDATE `value`=:key, `updated_at`=CURRENT_TIMESTAMP()"; + $values = [':key' => $key]; - $db = $this->di['db']; + $db = $this->di['db']; $currency = $db->exec($sql, $values); } - /** + /** * See if we should update exchange rates whenever the CRON jobs are run. - * + * * @since 4.22.0 + * * @return string - */ + */ public function isCronEnabled() { - $sql = "SELECT `param`, `value` FROM setting"; - $db = $this->di['db']; + $sql = 'SELECT `param`, `value` FROM setting'; + $db = $this->di['db']; $pairs = $db->getAssoc($sql); - if (isset($pairs['currency_cron_enabled']) && $pairs['currency_cron_enabled'] == "1") { + if (isset($pairs['currency_cron_enabled']) && '1' == $pairs['currency_cron_enabled']) { return true; } else { return false; } } - /** + /** * Enable or disable updating exchange rates whenever the CRON jobs are run. - * + * * @since 4.22.0 - * @var int $data + * + * @var int + * * @return string - */ + */ public function setCron($data) { - $sql = "INSERT INTO `setting` (`param`, `value`, `public`, `created_at`, `updated_at`) VALUES ('currency_cron_enabled', :key, '0', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()) ON DUPLICATE KEY UPDATE `value`=:key, `updated_at`=CURRENT_TIMESTAMP()"; - - if ($data == "1") { - $key = "1"; + $sql = "INSERT INTO `setting` (`param`, `value`, `public`, `created_at`, `updated_at`) VALUES ('currency_cron_enabled', :key, '0', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()) ON DUPLICATE KEY UPDATE `value`=:key, `updated_at`=CURRENT_TIMESTAMP()"; + + if ('1' == $data) { + $key = '1'; } else { - $key = "0"; + $key = '0'; } - $values = array(':key' => $key); + $values = [':key' => $key]; - $db = $this->di['db']; + $db = $this->di['db']; $currency = $db->exec($sql, $values); } public function toApiArray(\Model_Currency $model) { - return array( - 'code' => $model->code, - 'title' => $model->title, - 'conversion_rate' => (float)$model->conversion_rate, - 'format' => $model->format, - 'price_format' => $model->price_format, - 'default' => $model->is_default, - ); + return [ + 'code' => $model->code, + 'title' => $model->title, + 'conversion_rate' => (float) $model->conversion_rate, + 'format' => $model->format, + 'price_format' => $model->price_format, + 'default' => $model->is_default, + ]; } public function createCurrency($code, $format, $title = null, $conversionRate = 1) @@ -431,13 +436,13 @@ class Service implements InjectionAwareInterface $this->validateCurrencyFormat($format); - $model = $this->di['db']->dispense('Currency'); - $model->code = $code; - $model->title = $title; - $model->format = $format; + $model = $this->di['db']->dispense('Currency'); + $model->code = $code; + $model->title = $title; + $model->format = $format; $model->conversion_rate = $conversionRate; - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Added new currency %s', $model->code); @@ -447,7 +452,7 @@ class Service implements InjectionAwareInterface public function validateCurrencyFormat($format) { - if (strpos($format, '{{price}}') === false) { + if (false === strpos($format, '{{price}}')) { throw new \Exception('Currency format must include {{price}} tag', 3569); } } @@ -493,7 +498,7 @@ class Service implements InjectionAwareInterface { $dc = $this->getDefault(); - $db = $this->di['db']; + $db = $this->di['db']; $all = $db->find('Currency'); // should return Array of beans @@ -517,37 +522,38 @@ class Service implements InjectionAwareInterface return true; } - /** + /** * Fetch exchange rates from external sources. - * Uses data from the European Central Bank and currencylayer when the base currencies are Euro and US Dollar respectively - * + * Uses data from the European Central Bank and currencylayer when the base currencies are Euro and US Dollar respectively. + * * @todo use Guzzle instead of simplexml_load_file() - * @var string $from Short code for the base currency - * @var string $to Short code for the target currency - * @return float Exchange rate + * + * @var string Short code for the base currency + * @var string Short code for the target currency + * + * @return float Exchange rate */ protected function _getRate($from, $to) { $from_Currency = urlencode($from); - $to_Currency = urlencode($to); + $to_Currency = urlencode($to); - if ($from_Currency == "EUR") { - $XML = simplexml_load_file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"); + if ('EUR' == $from_Currency) { + $XML = simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'); foreach ($XML->Cube->Cube->Cube as $rate) { - if ($rate["currency"] == $to_Currency) { - return (float) $rate["rate"]; - }; + if ($rate['currency'] == $to_Currency) { + return (float) $rate['rate']; + } } - } else if ($from_Currency == "USD") { - $res = $this->di['guzzle_client']->get("http://api.currencylayer.com/live?access_key=". $this->getKey() ."¤cies=". $to_Currency ."&format=1"); + } elseif ('USD' == $from_Currency) { + $res = $this->di['guzzle_client']->get('http://api.currencylayer.com/live?access_key='.$this->getKey().'¤cies='.$to_Currency.'&format=1'); $array = json_decode($res->getBody(), true); - if ($array["success"] !== true) { - throw new \Box_Exception("Currencylayer threw an error:
" . $array["error"]["info"]); + if (true !== $array['success']) { + throw new \Box_Exception('Currencylayer threw an error:
'.$array['error']['info']); } else { - return (float) $array["quotes"]["USD".$to_Currency]; + return (float) $array['quotes']['USD'.$to_Currency]; } } - } public function deleteCurrencyByCode($code) @@ -559,29 +565,30 @@ class Service implements InjectionAwareInterface } $code = $model->code; - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminDeleteCurrency', 'params' => array('code' => $code))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminDeleteCurrency', 'params' => ['code' => $code]]); $this->rm($model); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminDeleteCurrency', 'params' => array('code' => $code))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminDeleteCurrency', 'params' => ['code' => $code]]); $this->di['logger']->info('Removed currency %s', $code); return true; } - /** - * If enabled, automatically call _getRate to fetch exchange rates whenever CRON jobs are run + /** + * If enabled, automatically call _getRate to fetch exchange rates whenever CRON jobs are run. + * * @since 4.22.0 */ public static function onBeforeAdminCronRun(\Box_Event $event) { - $di = $event->getDi(); - $currencyService = $di['mod_service']('currency'); + $di = $event->getDi(); + $currencyService = $di['mod_service']('currency'); try { if ($currencyService->isCronEnabled()) { - $currencyService->updateCurrencyRates(""); + $currencyService->updateCurrencyRates(''); } } catch (\Exception $e) { error_log($e); diff --git a/src/bb-modules/Custompages/Api/Admin.php b/src/bb-modules/Custompages/Api/Admin.php index 5b31d71bf..576b2b1d0 100644 --- a/src/bb-modules/Custompages/Api/Admin.php +++ b/src/bb-modules/Custompages/Api/Admin.php @@ -1,6 +1,6 @@ 'Custom Page ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $this->getService()->deletePage($data['id']); + return true; } /** - * Delete custom pages + * Delete custom pages. * * @param array $ids - custom page IDs * @@ -58,19 +59,20 @@ class Admin extends \Api_Abstract */ public function batch_delete($data) { - $required = array( + $required = [ 'ids' => 'Custom Page IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $this->getService()->deletePage($data['ids']); + return true; } /** - * Create new custom page + * Create new custom page. * - * @param string $title - custom page title + * @param string $title - custom page title * @param string $content - custom page content * * @optional string $description - custom page meta description @@ -80,26 +82,26 @@ class Admin extends \Api_Abstract */ public function create($data) { - $required = array( + $required = [ 'title' => 'Custom page title not passed', 'content' => 'Custom page content not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $title = $data['title']; + $title = $data['title']; - $content = $data['content']; - $description = $this->di['array_get']($data, 'description', NULL); - $keywords = $this->di['array_get']($data, 'keywords', NULL); + $content = $data['content']; + $description = $this->di['array_get']($data, 'description', null); + $keywords = $this->di['array_get']($data, 'keywords', null); return $this->getService()->createPage($title, $description, $keywords, $content); } /** - * Update custom page + * Update custom page. * - * @param string $id - custom page id - * @param string $slug - custom page slug + * @param string $id - custom page id + * @param string $slug - custom page slug * @param string $content - custom page content * * @optional string $description - custom page meta description @@ -109,26 +111,26 @@ class Admin extends \Api_Abstract */ public function update($data) { - $required = array( + $required = [ 'id' => 'Custom page id not passed', 'title' => 'Custom page title not passed', 'slug' => 'Custom page slug not passed', 'content' => 'Custom page content not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $id = $data['id']; $title = $data['title']; $content = $data['content']; $slug = $data['slug']; - $description = $this->di['array_get']($data, 'description', NULL); - $keywords = $this->di['array_get']($data, 'keywords', NULL); + $description = $this->di['array_get']($data, 'description', null); + $keywords = $this->di['array_get']($data, 'keywords', null); return $this->getService()->updatePage($id, $title, $description, $keywords, $content, $slug); } /** - * Get custom page by id + * Get custom page by id. * * @param string $id - custom page id * @@ -138,4 +140,4 @@ class Admin extends \Api_Abstract { return $this->getService()->getPage($data['page_id']); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Custompages/Controller/Admin.php b/src/bb-modules/Custompages/Controller/Admin.php index 24edfc238..468b96f12 100644 --- a/src/bb-modules/Custompages/Controller/Admin.php +++ b/src/bb-modules/Custompages/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'extensions', - 'label' => 'Custom Pages', - 'index' => 2000, - 'uri' => $this->di['url']->adminLink('custompages'), - 'class' => '', - ), - ), - ); - + return [ + 'subpages' => [ + [ + 'location' => 'extensions', + 'label' => 'Custom Pages', + 'index' => 2000, + 'uri' => $this->di['url']->adminLink('custompages'), + 'class' => '', + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/custompages', 'get_index', array(), get_class($this)); - $app->get('/custompages/:id', 'get_page', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/custompages', 'get_index', [], get_class($this)); + $app->get('/custompages/:id', 'get_page', ['id' => '[0-9]+'], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_custompages_index'); } public function get_page(\Box_App $app, $id) { - return $app->render('mod_custompages_page', array('page_id' => $id)); + return $app->render('mod_custompages_page', ['page_id' => $id]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Custompages/Controller/Client.php b/src/bb-modules/Custompages/Controller/Client.php index 2a9dcdf7e..e0844510f 100644 --- a/src/bb-modules/Custompages/Controller/Client.php +++ b/src/bb-modules/Custompages/Controller/Client.php @@ -1,6 +1,6 @@ get('/custompages/:slug', 'get_page', array('slug' => '[a-z0-9-]+'), get_class($this)); + $app->get('/custompages/:slug', 'get_page', ['slug' => '[a-z0-9-]+'], get_class($this)); } public function get_page(\Box_App $app, $slug) @@ -54,11 +54,10 @@ class Client implements \Box\InjectionAwareInterface $service = new \Box\Mod\Custompages\Service(); $service->setDi($this->di); $page = $service->getPage($slug, 'slug'); - if(isset($page['id'])) { - return $app->render('mod_custompages_content', array('page' => $page)); - } - else { - die(header('Location: '.$this->di['url']->get(''))); + if (isset($page['id'])) { + return $app->render('mod_custompages_content', ['page' => $page]); + } else { + exit(header('Location: '.$this->di['url']->get(''))); } } -} \ No newline at end of file +} diff --git a/src/bb-modules/Custompages/Service.php b/src/bb-modules/Custompages/Service.php index 87f593758..1d7971b16 100644 --- a/src/bb-modules/Custompages/Service.php +++ b/src/bb-modules/Custompages/Service.php @@ -1,6 +1,6 @@ di['db']; - $db->exec("CREATE TABLE IF NOT EXISTS `custom_pages` (`id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `description` varchar(555) NOT NULL, `keywords` varchar(555) NOT NULL, `content` text NOT NULL, `slug` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8"); + $db->exec('CREATE TABLE IF NOT EXISTS `custom_pages` (`id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `description` varchar(555) NOT NULL, `keywords` varchar(555) NOT NULL, `content` text NOT NULL, `slug` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8'); + return true; } public function searchPages($search = null, $per_page = 100, $page = null) { - $filter = array(); - $sql = "SELECT * FROM custom_pages WHERE 1"; + $filter = []; + $sql = 'SELECT * FROM custom_pages WHERE 1'; if ($search) { - $sql .= " AND title LIKE :q OR content LIKE :q"; + $sql .= ' AND title LIKE :q OR content LIKE :q'; $filter[':q'] = "%$search%"; } - $sql .= " ORDER BY id DESC"; + $sql .= ' ORDER BY id DESC'; + return $this->di['pager']->getSimpleResultSet($sql, $filter, $per_page, $page); } - public function deletePage($id) { - if(is_array($id)) { - foreach($id as $i => $x) { - $id[$i] = (int)$x; + public function deletePage($id) + { + if (is_array($id)) { + foreach ($id as $i => $x) { + $id[$i] = (int) $x; } $this->di['pdo']->query('DELETE from custom_pages WHERE id in ('.join(', ', $id).')'); - } - else { + } else { $this->di['pdo']->prepare('DELETE from custom_pages WHERE id = ?')->execute([$id]); } } - public function getPage($id, $type = 'id') { + public function getPage($id, $type = 'id') + { $q = $this->di['pdo']->prepare('SELECT * from custom_pages WHERE '.$type.' = ?'); $q->execute([$id]); + return $q->fetch(); } - public function createPage($title, $description, $keywords, $content) { + public function createPage($title, $description, $keywords, $content) + { $slug = $this->di['tools']->slug($title); $i = 0; $ex = $this->di['pdo']->prepare('SELECT id from custom_pages WHERE slug = ?'); $ex->execute([$slug]); $ex = $ex->rowCount(); - while($ex > 0) { + while ($ex > 0) { $slug = $this->di['tools']->slug($title).'-'.++$i; $ex = $this->di['pdo']->prepare('SELECT id from custom_pages WHERE slug = ?'); $ex->execute([$slug]); @@ -73,18 +78,21 @@ class Service $this->di['pdo']->prepare('INSERT into custom_pages (title, description, keywords, content, slug) VALUES (?, ?, ?, ?, ?)')->execute([$title, $description, $keywords, $content, $slug]); $id = $this->di['pdo']->lastInsertId(); $this->di['logger']->info('Created new custom page #%s', $id); + return $id; } - public function updatePage($id, $title, $description, $keywords, $content, $slug) { + public function updatePage($id, $title, $description, $keywords, $content, $slug) + { $slug = $this->di['tools']->slug($slug); $ex = $this->di['pdo']->prepare('SELECT id from custom_pages WHERE slug = ? AND id <> ?'); $ex->execute([$slug, $id]); - if($ex->rowCount() > 0) { - die(json_encode(['result' => null, 'error' => ['message' => 'You need to set unique slug.', 'code' => 9999]])); + if ($ex->rowCount() > 0) { + exit(json_encode(['result' => null, 'error' => ['message' => 'You need to set unique slug.', 'code' => 9999]])); } $this->di['pdo']->prepare('UPDATE custom_pages SET title = ?, description = ?, keywords = ?, content = ?, slug = ? WHERE id = ?')->execute([$title, $description, $keywords, $content, $slug, $id]); $this->di['logger']->info('Updated custom page #%s', $id); + return $id; } } diff --git a/src/bb-modules/Dashboard/Controller/Client.php b/src/bb-modules/Dashboard/Controller/Client.php index 0ce5b4edc..05d57d2ac 100644 --- a/src/bb-modules/Dashboard/Controller/Client.php +++ b/src/bb-modules/Dashboard/Controller/Client.php @@ -1,6 +1,6 @@ get('/dashboard', 'get_dashboard_index', array(), get_class($this)); + $app->get('/dashboard', 'get_dashboard_index', [], get_class($this)); } public function get_dashboard_index(\Box_App $app) { $this->di['is_client_logged']; + return $app->render('mod_dashboard_index'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Email/Api/Admin.php b/src/bb-modules/Email/Api/Admin.php index af4eabb7f..df8bbc273 100644 --- a/src/bb-modules/Email/Api/Admin.php +++ b/src/bb-modules/Email/Api/Admin.php @@ -1,6 +1,6 @@ di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - list($sql, $params) = $this->getService()->getSearchQuery($data); + [$sql, $params] = $this->getService()->getSearchQuery($data); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $pager['list'][$key] = array( - 'id' => $item['id'], - 'client_id' => $item['client_id'], - 'sender' => $item['sender'], - 'recipients' => $item['recipients'], - 'subject' => $item['subject'], + $pager['list'][$key] = [ + 'id' => $item['id'], + 'client_id' => $item['client_id'], + 'sender' => $item['sender'], + 'recipients' => $item['recipients'], + 'subject' => $item['subject'], 'content_html' => $item['content_html'], 'content_text' => $item['content_text'], - 'created_at' => $item['created_at'], - 'updated_at' => $item['updated_at'], - ); + 'created_at' => $item['created_at'], + 'updated_at' => $item['updated_at'], + ]; } return $pager; } /** - * Get sent email details + * Get sent email details. * * @param int $id - email ID + * * @return array + * * @throws Exception * @throws LogicException */ public function email_get($data) { - $required = array( + $required = [ 'id' => 'Email ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); $model = $service->getEmailById($data['id']); + return $service->toApiArray($model); } /** - * Email send + * Email send. * - * @param string $to - email to - * @param string $to_name - to name + * @param string $to - email to + * @param string $to_name - to name * @param string $from_name - from name - * @param string $from - from email - * @param string $subject - from email - * @param string $content - from email + * @param string $from - from email + * @param string $subject - from email + * @param string $content - from email * * @optional int $client_id - log this message to client history * * @return bool + * * @throws Exception */ - public function send($data = array()) + public function send($data = []) { - $required = array( + $required = [ 'to' => 'Receiver Email is required', 'to_name' => 'Receiver Name is required', 'from' => 'Sender Name is required', 'from_name' => 'Sender email is required', 'subject' => 'Email subject is required', 'content' => 'Email content is required', - ); - $this->di['validator']->checkRequiredParamsForArray($required, $data); + ]; + $this->di['validator']->checkRequiredParamsForArray($required, $data); $client_id = $this->di['array_get']($data, 'client_id'); $emailService = $this->getService(); @@ -106,21 +111,23 @@ class Admin extends \Api_Abstract } /** - * Resend email + * Resend email. * * @param int $id - email ID + * * @return bool + * * @throws Exception * @throws LogicException */ public function email_resend($data) { - $required = array( + $required = [ 'id' => 'Email ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('ActivityClientEmail', 'id = ?', array($data['id'])); + $model = $this->di['db']->findOne('ActivityClientEmail', 'id = ?', [$data['id']]); if (!$model instanceof \Model_ActivityClientEmail) { throw new \Box_Exception('Email not found'); @@ -130,21 +137,23 @@ class Admin extends \Api_Abstract } /** - * Delete sent email from logs + * Delete sent email from logs. * * @param int $id - email ID + * * @return bool + * * @throws Exception * @throws LogicException */ public function email_delete($data) { - $required = array( + $required = [ 'id' => 'Email ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('ActivityClientEmail', 'id = ?', array($data['id'])); + $model = $this->di['db']->findOne('ActivityClientEmail', 'id = ?', [$data['id']]); if (!$model instanceof \Model_ActivityClientEmail) { throw new \Box_Exception('Email not found'); @@ -159,44 +168,45 @@ class Admin extends \Api_Abstract } /** - * Return list of email templates + * Return list of email templates. * * @return array */ public function template_get_list($data) { $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - list($sql, $params) = $this->getService()->templateGetSearchQuery($data); + [$sql, $params] = $this->getService()->templateGetSearchQuery($data); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $pager['list'][$key] = array( - 'id' => $this->di['array_get']($item, 'id', ''), + $pager['list'][$key] = [ + 'id' => $this->di['array_get']($item, 'id', ''), 'action_code' => $this->di['array_get']($item, 'action_code', ''), - 'category' => $this->di['array_get']($item, 'category', ''), - 'enabled' => $this->di['array_get']($item, 'enabled', ''), - 'subject' => $this->di['array_get']($item, 'subject', ''), + 'category' => $this->di['array_get']($item, 'category', ''), + 'enabled' => $this->di['array_get']($item, 'enabled', ''), + 'subject' => $this->di['array_get']($item, 'subject', ''), 'description' => $this->di['array_get']($item, 'description', ''), - ); - + ]; } return $pager; } /** - * Get email template full details + * Get email template full details. * * @param int $id - template id + * * @return array + * * @throws Exception * @throws LogicException */ public function template_get($data) { - $required = array( + $required = [ 'id' => 'Email ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('EmailTemplate', $data['id'], 'Email template not found'); @@ -205,21 +215,23 @@ class Admin extends \Api_Abstract } /** - * Delete email template + * Delete email template. * * @param int $id - email template ID + * * @return bool + * * @throws Exception * @throws LogicException */ public function template_delete($data) { - $required = array( + $required = [ 'id' => 'Email ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('EmailTemplate', 'id = ?', array($data['id'])); + $model = $this->di['db']->findOne('EmailTemplate', 'id = ?', [$data['id']]); if (!$model instanceof \Model_EmailTemplate) { throw new \Box_Exception('Email template not found'); @@ -238,22 +250,23 @@ class Admin extends \Api_Abstract * combined with custom event hook. * * @param string $action_code - template action code - * @param string $subject - Email subject - * @param string $content - Email body + * @param string $subject - Email subject + * @param string $content - Email body * * @return int - newly created template id + * * @throws Exception */ public function template_create($data) { - $required = array( + $required = [ 'action_code' => 'Email template code is required', - 'subject' => 'Email template subject is required', - 'content' => 'Email template content is required', - ); + 'subject' => 'Email template subject is required', + 'content' => 'Email template content is required', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $enabled = $this->di['array_get']($data, 'enabled', 0); + $enabled = $this->di['array_get']($data, 'enabled', 0); $category = $this->di['array_get']($data, 'category'); $templateModel = $this->getService()->templateCreate($data['action_code'], $data['subject'], $data['content'], $enabled, $category); @@ -262,104 +275,109 @@ class Admin extends \Api_Abstract } /** - * Update email template + * Update email template. * * @param int $id - template id - * @return boolean + * + * @return bool + * * @throws Exception * @throws LogicException */ public function template_update($data) { - $required = array( + $required = [ 'id' => 'Email ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $enabled = $this->di['array_get']($data, 'enabled'); + $enabled = $this->di['array_get']($data, 'enabled'); $category = $this->di['array_get']($data, 'category'); - $subject = $this->di['array_get']($data, 'subject'); - $content = $this->di['array_get']($data, 'content'); + $subject = $this->di['array_get']($data, 'subject'); + $content = $this->di['array_get']($data, 'content'); $model = $this->di['db']->getExistingModelById('EmailTemplate', $data['id'], 'Email template not found'); return $this->getService()->updateTemplate($model, $enabled, $category, $subject, $content); } - /** - * Reset email template to default + * Reset email template to default. * * @param string $code - template code - * @return boolean + * + * @return bool */ public function template_reset($data) { - $required = array( + $required = [ 'code' => 'Email template code was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->resetTemplateByCode($data['code']); } /** - * Generates email template preview + * Generates email template preview. * * @param int $id - template id * @optional string $_tpl - string to be rendered. Default is email template. - * @return boolean + * + * @return bool */ public function template_render($data) { - $t = $this->template_get($data); - $vars = $t['vars']; + $t = $this->template_get($data); + $vars = $t['vars']; $vars['_tpl'] = $this->di['array_get']($data, '_tpl', $t['content']); $systemService = $this->di['mod_service']('System'); + return $systemService->renderString($vars['_tpl'], true, $vars); } /** - * Generate email templates according to enabled extensions + * Generate email templates according to enabled extensions. * - * @return boolean + * @return bool */ public function batch_template_generate() { - return $this->getService()->templateBatchGenerate(); + return $this->getService()->templateBatchGenerate(); } /** * Disable all email templates at once. * - * @return boolean + * @return bool */ public function batch_template_disable($data) { - return $this->getService()->templateBatchDisable(); + return $this->getService()->templateBatchDisable(); } /** - * Enable all email templates at once + * Enable all email templates at once. * - * @return boolean + * @return bool */ public function batch_template_enable($data) { - return $this->getService()->templateBatchEnable(); + return $this->getService()->templateBatchEnable(); } /** - * Sends test email to admins + * Sends test email to admins. * * @param type $data + * * @return bool */ public function send_test($data) { - $email = array(); + $email = []; $email['to_staff'] = true; - $email['code'] = 'mod_email_test'; + $email['code'] = 'mod_email_test'; return $this->getService()->sendTemplate($email); } @@ -369,10 +387,9 @@ class Admin extends \Api_Abstract return $this->getService()->batchSend(); } - /** * Send email template to email, client or staff members. If template with code does not exist, - * it will be created. Default email template file must exist at mod_example/html_email/mod_example_code.phtml file + * it will be created. Default email template file must exist at mod_example/html_email/mod_example_code.phtml file. * * @param string $code - Template code to send. Must be mod_%s_%s structure * @@ -393,9 +410,9 @@ class Admin extends \Api_Abstract */ public function template_send($data) { - $required = array( - 'code' => 'Template code not passed', - ); + $required = [ + 'code' => 'Template code not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); if (!isset($data['to']) && !isset($data['to_staff']) && !isset($data['to_client'])) { @@ -406,7 +423,7 @@ class Admin extends \Api_Abstract } /** - * Deletes email logs with given IDs + * Deletes email logs with given IDs. * * @param array $ids - IDs for deletion * @@ -414,16 +431,15 @@ class Admin extends \Api_Abstract */ public function batch_delete($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->email_delete(array('id' => $id)); + $this->email_delete(['id' => $id]); } return true; } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Email/Api/Client.php b/src/bb-modules/Email/Api/Client.php index d54818617..3f77b6b7d 100644 --- a/src/bb-modules/Email/Api/Client.php +++ b/src/bb-modules/Email/Api/Client.php @@ -1,6 +1,6 @@ getIdentity(); + $client = $this->getIdentity(); $data['client_id'] = $client->id; - $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - list($sql, $params) = $this->getService()->getSearchQuery($data); + $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + [$sql, $params] = $this->getService()->getSearchQuery($data); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $pager['list'][$key] = array( - 'id' => $item['id'], - 'client_id' => $item['client_id'], - 'sender' => $item['sender'], - 'recipients' => $item['recipients'], - 'subject' => $item['subject'], + $pager['list'][$key] = [ + 'id' => $item['id'], + 'client_id' => $item['client_id'], + 'sender' => $item['sender'], + 'recipients' => $item['recipients'], + 'subject' => $item['subject'], 'content_html' => $item['content_html'], 'content_text' => $item['content_text'], - 'created_at' => $item['created_at'], - 'updated_at' => $item['updated_at'], - ); + 'created_at' => $item['created_at'], + 'updated_at' => $item['updated_at'], + ]; } return $pager; } /** - * Get email details + * Get email details. + * * @param int $id - Email id + * * @return array + * * @throws Exception * @throws LogicException */ public function get($data) { - $required = array( - 'id' => 'Email ID is required', - ); + $required = [ + 'id' => 'Email ID is required', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->getService()->findOneForClientById($this->getIdentity(), $data['id']); @@ -71,22 +75,24 @@ class Client extends \Api_Abstract } /** - * Resend email to client once again - * + * Resend email to client once again. + * * @param int $id - Email id + * * @return type + * * @throws Exception - * @throws LogicException + * @throws LogicException */ public function resend($data) { - $required = array( - 'id' => 'Email ID is required', - ); + $required = [ + 'id' => 'Email ID is required', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->getService()->findOneForClientById($this->getIdentity(), $data['id']); - if(!$model instanceof \Model_ActivityClientEmail) { + if (!$model instanceof \Model_ActivityClientEmail) { throw new \Box_Exception('Email not found'); } @@ -95,16 +101,19 @@ class Client extends \Api_Abstract /** * Remove email from system. + * * @param int $id - Email id + * * @return type + * * @throws Exception * @throws LogicException */ public function delete($data) { - $required = array( - 'id' => 'Email ID is required', - ); + $required = [ + 'id' => 'Email ID is required', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->getService()->findOneForClientById($this->getIdentity(), $data['id']); @@ -114,4 +123,4 @@ class Client extends \Api_Abstract return $this->getService()->rm($model); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Email/Controller/Admin.php b/src/bb-modules/Email/Controller/Admin.php index 3a6642fe4..319754e03 100644 --- a/src/bb-modules/Email/Controller/Admin.php +++ b/src/bb-modules/Email/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'activity', - 'index' => 200, + return [ + 'subpages' => [ + [ + 'location' => 'activity', + 'index' => 200, 'label' => 'Email history', - 'uri' => $this->di['url']->adminLink('email/history'), + 'uri' => $this->di['url']->adminLink('email/history'), 'class' => '', - ), - ), - ); + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/email/history/', 'get_history', array(), get_class($this)); - $app->get('/email/history', 'get_history', array(), get_class($this)); - $app->get('/email/templates', 'get_index', array(), get_class($this)); - $app->get('/email/template/:id', 'get_template', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/email/:id', 'get_email', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/email/history/', 'get_history', [], get_class($this)); + $app->get('/email/history', 'get_history', [], get_class($this)); + $app->get('/email/templates', 'get_index', [], get_class($this)); + $app->get('/email/template/:id', 'get_template', ['id' => '[0-9]+'], get_class($this)); + $app->get('/email/:id', 'get_email', ['id' => '[0-9]+'], get_class($this)); } public function get_history(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_email_history'); } - + public function get_template(\Box_App $app, $id) { $api = $this->di['api_admin']; - $template = $api->email_template_get(array('id'=>$id)); - return $app->render('mod_email_template', array('template'=>$template)); + $template = $api->email_template_get(['id' => $id]); + + return $app->render('mod_email_template', ['template' => $template]); } - + public function get_email(\Box_App $app, $id) { $api = $this->di['api_admin']; - $template = $api->email_email_get(array('id'=>$id)); - return $app->render('mod_email_details', array('email'=>$template)); + $template = $api->email_email_get(['id' => $id]); + + return $app->render('mod_email_details', ['email' => $template]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Email/Controller/Client.php b/src/bb-modules/Email/Controller/Client.php index 7ffcb5668..24173af22 100644 --- a/src/bb-modules/Email/Controller/Client.php +++ b/src/bb-modules/Email/Controller/Client.php @@ -1,6 +1,6 @@ get('/email', 'get_emails', array(), get_class($this)); - $app->get('/email/:id', 'get_email', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/email', 'get_emails', [], get_class($this)); + $app->get('/email/:id', 'get_email', ['id' => '[0-9]+'], get_class($this)); } public function get_emails(\Box_App $app) { $this->di['is_client_logged']; + return $app->render('mod_email_index'); } + public function get_email(\Box_App $app, $id) { $api = $this->di['api_client']; - $data = array('id'=>$id); + $data = ['id' => $id]; $email = $api->email_get($data); - return $app->render('mod_email_email', array('email'=>$email)); - } -} \ No newline at end of file + return $app->render('mod_email_email', ['email' => $email]); + } +} diff --git a/src/bb-modules/Email/Service.php b/src/bb-modules/Email/Service.php index ed59d0920..2cdf825cd 100644 --- a/src/bb-modules/Email/Service.php +++ b/src/bb-modules/Email/Service.php @@ -1,6 +1,6 @@ di['array_get']($data, 'search', NULL); - $client_id = $this->di['array_get']($data, 'client_id', NULL); + $search = $this->di['array_get']($data, 'search', null); + $client_id = $this->di['array_get']($data, 'client_id', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; - if($search) { + if ($search) { $search = "%$search%"; $where[] = '(sender LIKE :sender OR recipients LIKE :recipient OR subject LIKE :subject OR content_text LIKE :content_text OR content_html LIKE :content_html)'; $bindings[':sender'] = $search; @@ -46,37 +46,38 @@ class Service implements \Box\InjectionAwareInterface $bindings[':content_html'] = $search; } - if(NULL !== $client_id) { - $where[] = "client_id = :client_id"; + if (null !== $client_id) { + $where[] = 'client_id = :client_id'; $bindings[':client_id'] = $client_id; } - if (!empty($where)){ - $query = $query . ' WHERE '.implode(' AND ', $where); + if (!empty($where)) { + $query = $query.' WHERE '.implode(' AND ', $where); } $query .= ' ORDER BY id DESC'; - return array($query, $bindings); + return [$query, $bindings]; } public function findOneForClientById(\Model_Client $client, $id) { - $bindings = array( + $bindings = [ ':id' => $id, - ':client_id' => $client->id - ); + ':client_id' => $client->id, + ]; $db = $this->di['db']; + return $db->findOne('ActivityClientEmail', 'id = :id AND client_id = :client_id ORDER BY id DESC', $bindings); } public function rmByClient(\Model_Client $client) { - $models = $this->di['db']->find('ActivityClientEmail', 'client_id = ?', array($client->id)); - foreach($models as $model) - { + $models = $this->di['db']->find('ActivityClientEmail', 'client_id = ?', [$client->id]); + foreach ($models as $model) { $this->di['db']->trash($model); } + return true; } @@ -84,22 +85,24 @@ class Service implements \Box\InjectionAwareInterface { $db = $this->di['db']; $db->trash($email); + return true; } public function toApiArray(\Model_ActivityClientEmail $model, $deep = true) { - $data = array( - 'id' => $model->id, - 'client_id' => $model->client_id, - 'sender' => $model->sender, - 'recipients' => $model->recipients, - 'subject' => $model->subject, + $data = [ + 'id' => $model->id, + 'client_id' => $model->client_id, + 'sender' => $model->sender, + 'recipients' => $model->recipients, + 'subject' => $model->subject, 'content_html' => $model->content_html, 'content_text' => $model->content_text, - 'created_at' => $model->created_at, - 'updated_at' => $model->updated_at, - ); + 'created_at' => $model->created_at, + 'updated_at' => $model->updated_at, + ]; + return $data; } @@ -123,9 +126,9 @@ class Service implements \Box\InjectionAwareInterface public function sendTemplate($data) { - $required = array( + $required = [ 'code' => 'Template code not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); if (!isset($data['to']) && !isset($data['to_staff']) && !isset($data['to_client'])) { @@ -135,69 +138,68 @@ class Service implements \Box\InjectionAwareInterface unset($vars['to'], $vars['to_client'], $vars['to_staff'], $vars['to_name'], $vars['from'], $vars['from_name']); unset($vars['default_description'], $vars['default_subject'], $vars['default_template'], $vars['code']); - //add aditional variables to template + // add aditional variables to template if (isset($data['to_staff']) && $data['to_staff']) { - $staffService = $this->di['mod_service']('staff'); - $staff = $staffService->getList(array('status' => 'active', 'no_cron' => true)); + $staffService = $this->di['mod_service']('staff'); + $staff = $staffService->getList(['status' => 'active', 'no_cron' => true]); $vars['staff'] = $staff['list'][0]; } - //add aditional variables to template + // add aditional variables to template if (isset($data['to_client']) && $data['to_client'] > 0) { - $clientService = $this->di['mod_service']('client'); - $customer = $clientService->get(array('id' => $data['to_client'])); - $customer = $clientService->toApiArray($customer); + $clientService = $this->di['mod_service']('client'); + $customer = $clientService->get(['id' => $data['to_client']]); + $customer = $clientService->toApiArray($customer); $vars['c'] = $customer; } $db = $this->di['db']; - $t = $db->findOne('EmailTemplate', 'action_code = :action', array(':action' => $data['code'])); + $t = $db->findOne('EmailTemplate', 'action_code = :action', [':action' => $data['code']]); if (!$t instanceof \Model_EmailTemplate) { - - list($s, $c, $desc, $enabled, $mod) = $this->_getDefaults($data); - $t = $db->dispense('EmailTemplate'); - $t->enabled = $enabled; + [$s, $c, $desc, $enabled, $mod] = $this->_getDefaults($data); + $t = $db->dispense('EmailTemplate'); + $t->enabled = $enabled; $t->action_code = $data['code']; - $t->category = $mod; - $t->subject = $s; - $t->content = $c; + $t->category = $mod; + $t->subject = $s; + $t->content = $c; $t->description = $desc; $db->store($t); } - //update template vars with latest variables + // update template vars with latest variables $this->setVars($t, $vars); // do not send inactive template if (!$t->enabled) { return false; } - $systemService = $this->di['mod_service']('system'); + $systemService = $this->di['mod_service']('system'); - list($subject, $content) = $this->_parse($t, $vars); - $from = $this->di['array_get']($data, 'from', $systemService->getParamValue('company_email')); + [$subject, $content] = $this->_parse($t, $vars); + $from = $this->di['array_get']($data, 'from', $systemService->getParamValue('company_email')); $from_name = $this->di['array_get']($data, 'from_name', $systemService->getParamValue('company_name')); - $sent = false; + $sent = false; - if (!$from){ + if (!$from) { throw new \Box_Exception('From email address can not be empty'); } if (isset($staff)) { foreach ($staff['list'] as $staff) { - $to = $staff['email']; + $to = $staff['email']; $to_name = $staff['name']; - $sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, null, $staff['id']); + $sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, null, $staff['id']); } - } else if (isset($customer)) { - $to = $customer['email']; - $to_name = $customer['first_name'] . ' ' . $customer['last_name']; - $sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, $customer['id']); + } elseif (isset($customer)) { + $to = $customer['email']; + $to_name = $customer['first_name'].' '.$customer['last_name']; + $sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, $customer['id']); } else { - $to = $data['to']; + $to = $data['to']; $to_name = $this->di['array_get']($data, 'to_name', null); - $sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name); + $sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name); } return $sent; @@ -207,6 +209,7 @@ class Service implements \Box\InjectionAwareInterface { $email = $this->_queue($to, $from, $subject, $content, $to_name, $from_name, $client_id, $admin_id); $this->_sendFromQueue($email); + return true; } @@ -214,26 +217,26 @@ class Service implements \Box\InjectionAwareInterface { $code = $data['code']; - $enabled = 0; - $subject = $this->di['array_get']($data, 'default_subject', ucwords(str_replace('_', ' ', $code))); - $content = $this->di['array_get']($data, 'default_template', $this->_getVarsString()); + $enabled = 0; + $subject = $this->di['array_get']($data, 'default_subject', ucwords(str_replace('_', ' ', $code))); + $content = $this->di['array_get']($data, 'default_template', $this->_getVarsString()); $description = $this->di['array_get']($data, 'default_description', null); - $matches = array(); - preg_match("/mod_([a-zA-Z0-9]+)_([a-zA-Z0-9]+)/i", $code, $matches); - $mod = $matches[1]; - $path = BB_PATH_MODS . '/' . ucfirst($mod) . '/html_email/' . $code . '.phtml'; + $matches = []; + preg_match('/mod_([a-zA-Z0-9]+)_([a-zA-Z0-9]+)/i', $code, $matches); + $mod = $matches[1]; + $path = BB_PATH_MODS.'/'.ucfirst($mod).'/html_email/'.$code.'.phtml'; if (file_exists($path)) { $tpl = file_get_contents($path); - $ms = array(); + $ms = []; preg_match('#{%.?block subject.?%}((.*?)+){%.?endblock.?%}#', $tpl, $ms); if (isset($ms[1])) { $subject = $ms[1]; } - $mc = array(); + $mc = []; preg_match('/{%.?block content.?%}((.*?\n)+){%.?endblock.?%}/m', $tpl, $mc); if (isset($mc[1])) { $content = $mc[1]; @@ -241,27 +244,27 @@ class Service implements \Box\InjectionAwareInterface } } - return array($subject, $content, $description, $enabled, $mod); + return [$subject, $content, $description, $enabled, $mod]; } private function _queue($to, $from, $subject, $content, $to_name = null, $from_name = null, $client_id = null, $admin_id = null) { - $db = $this->di['db']; + $db = $this->di['db']; - $queue = $db->dispense('ModEmailQueue'); - $queue->recipient = $to; - $queue->sender = $from; - $queue->subject = $subject; - $queue->content = $content; - $queue->to_name = $to_name; - $queue->from_name = $from_name; - $queue->client_id = $client_id; - $queue->admin_id = $admin_id; - $queue->status = 'unsent'; + $queue = $db->dispense('ModEmailQueue'); + $queue->recipient = $to; + $queue->sender = $from; + $queue->subject = $subject; + $queue->content = $content; + $queue->to_name = $to_name; + $queue->from_name = $from_name; + $queue->client_id = $client_id; + $queue->admin_id = $admin_id; + $queue->status = 'unsent'; $queue->created_at = date('Y-m-d H:i:s'); $queue->updated_at = date('Y-m-d H:i:s'); - $queue->priority = 1; - $queue->tries = 0; + $queue->priority = 1; + $queue->tries = 0; try { $db->store($queue); } catch (\Exception $e) { @@ -273,15 +276,16 @@ class Service implements \Box\InjectionAwareInterface private function _getVarsString() { - $str = '{% apply markdown %}' . PHP_EOL . PHP_EOL; - $str .= 'This email template was automatically generated by BoxBilling extension. ' . PHP_EOL; - $str .= 'Template is ready to be modified. ' . PHP_EOL; - $str .= 'Email template is just like BoxBilling theme file. ' . PHP_EOL; - $str .= 'Use **admin** and **guest** API calls to get additional information using variables passed to template.' . PHP_EOL . PHP_EOL; - $str .= 'Example API usage in email template:' . PHP_EOL . PHP_EOL; - $str .= '{{ guest.system_version }}' . PHP_EOL . PHP_EOL; - $str .= "{{ now|date('Y-m-d') }}" . PHP_EOL . PHP_EOL; + $str = '{% apply markdown %}'.PHP_EOL.PHP_EOL; + $str .= 'This email template was automatically generated by BoxBilling extension. '.PHP_EOL; + $str .= 'Template is ready to be modified. '.PHP_EOL; + $str .= 'Email template is just like BoxBilling theme file. '.PHP_EOL; + $str .= 'Use **admin** and **guest** API calls to get additional information using variables passed to template.'.PHP_EOL.PHP_EOL; + $str .= 'Example API usage in email template:'.PHP_EOL.PHP_EOL; + $str .= '{{ guest.system_version }}'.PHP_EOL.PHP_EOL; + $str .= "{{ now|date('Y-m-d') }}".PHP_EOL.PHP_EOL; $str .= '{% endapply %}'; + return $str; } @@ -290,9 +294,9 @@ class Service implements \Box\InjectionAwareInterface $systemService = $this->di['mod_service']('System'); $pc = $systemService->renderString($t->content, false, $vars); $ps = $systemService->renderString($t->subject, false, $vars); - return array($ps, $pc); - } + return [$ps, $pc]; + } public function resend(\Model_ActivityClientEmail $email) { @@ -304,27 +308,27 @@ class Service implements \Box\InjectionAwareInterface $mail->setSubject($email->subject); $mail->addTo($email->recipients); - $settings = $this->di['mod_config']('email'); - $transport = $this->di['array_get']($settings, 'mailer', 'sendmail'); + $settings = $this->di['mod_config']('email'); + $transport = $this->di['array_get']($settings, 'mailer', 'sendmail'); if (APPLICATION_ENV == 'testing') { - if (BB_DEBUG) error_log('Skipping email sending in test environment'); + if (BB_DEBUG) { + error_log('Skipping email sending in test environment'); + } + return true; } try { - - $mod = $this->di['mod']('email'); + $mod = $this->di['mod']('email'); $settings = $mod->getConfig(); if (isset($settings['log_enabled']) && $settings['log_enabled']) { - $activityService = $this->di['mod_service']('activity'); + $activityService = $this->di['mod_service']('activity'); $activityService->logEmail($email->subject, $email->client_id, $email->sender, $email->recipients, $email->content_html, $email->content_text); } - - $mail->send($transport, $settings); - + $mail->send($transport, $settings); } catch (\Exception $e) { error_log($e->getMessage()); } @@ -336,52 +340,52 @@ class Service implements \Box\InjectionAwareInterface public function templateGetSearchQuery($data) { - $query = "SELECT * FROM email_template"; + $query = 'SELECT * FROM email_template'; - $code = $this->di['array_get']($data, 'code', NULL); - $search = $this->di['array_get']($data, 'search', NULL); + $code = $this->di['array_get']($data, 'code', null); + $search = $this->di['array_get']($data, 'search', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; if ($code) { - $where[] = "action_code LIKE :code"; + $where[] = 'action_code LIKE :code'; $bindings[':code'] = "%$code%"; } if ($search) { - $search = "%$search%"; + $search = "%$search%"; - $where[] = "(action_code LIKE :action_code OR subject LIKE :subject OR content LIKE :content)"; + $where[] = '(action_code LIKE :action_code OR subject LIKE :subject OR content LIKE :content)'; $bindings[':action_code'] = $search; - $bindings[':subject'] = $search; - $bindings[':content'] = $search; + $bindings[':subject'] = $search; + $bindings[':content'] = $search; } if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); + $query = $query.' WHERE '.implode(' AND ', $where); } - $query .= " ORDER BY category ASC"; + $query .= ' ORDER BY category ASC'; - return array($query, $bindings); + return [$query, $bindings]; } public function templateToApiArray(\Model_EmailTemplate $model, $deep = false) { - $data = array( - 'id' => $model->id, + $data = [ + 'id' => $model->id, 'action_code' => $model->action_code, - 'category' => $model->category, - 'enabled' => $model->enabled, - 'subject' => $model->subject, + 'category' => $model->category, + 'enabled' => $model->enabled, + 'subject' => $model->subject, 'description' => $model->description, - ); + ]; if ($deep) { $data['content'] = $model->content; - $data['vars'] = $this->getVars($model); + $data['vars'] = $this->getVars($model); } return $data; @@ -425,24 +429,23 @@ class Service implements \Box\InjectionAwareInterface public function resetTemplateByCode($code) { - $t = $this->di['db']->findOne('EmailTemplate', 'action_code = :action', array(':action' => $code)); + $t = $this->di['db']->findOne('EmailTemplate', 'action_code = :action', [':action' => $code]); if (!$t instanceof \Model_EmailTemplate) { - throw new \Box_Exception('Email template :code was not found', array(':code' => $code)); + throw new \Box_Exception('Email template :code was not found', [':code' => $code]); } - $d = array('code' => $code); - list($s, $c) = $this->_getDefaults($d); + $d = ['code' => $code]; + [$s, $c] = $this->_getDefaults($d); $this->updateTemplate($t, null, null, $s, $c); $this->di['logger']->info('Reset email template: %s', $t->action_code); return true; } - public function getEmailById($id) { - $model = $this->di['db']->findOne('ActivityClientEmail', 'id = ?', array($id)); + $model = $this->di['db']->findOne('ActivityClientEmail', 'id = ?', [$id]); if (!$model instanceof \Model_ActivityClientEmail) { throw new \Box_Exception('Email not found'); } @@ -452,12 +455,12 @@ class Service implements \Box\InjectionAwareInterface public function templateCreate($actionCode, $subject, $content, $enabled = 0, $category = null) { - $model = $this->di['db']->dispense('EmailTemplate'); + $model = $this->di['db']->dispense('EmailTemplate'); $model->action_code = $actionCode; - $model->subject = $subject; - $model->enabled = $enabled; - $model->category = $category; - $model->content = $content; + $model->subject = $subject; + $model->enabled = $enabled; + $model->category = $category; + $model->content = $content; $modelId = $this->di['db']->store($model); @@ -468,29 +471,28 @@ class Service implements \Box\InjectionAwareInterface public function templateBatchGenerate() { - $pattern = BB_PATH_MODS . '/*/html_email/*.phtml'; - $list = glob($pattern); + $pattern = BB_PATH_MODS.'/*/html_email/*.phtml'; + $list = glob($pattern); foreach ($list as $path) { $code = pathinfo($path, PATHINFO_FILENAME); - $dir = pathinfo($path, PATHINFO_DIRNAME); - $dir = pathinfo($dir, PATHINFO_DIRNAME); - $dir = pathinfo($dir, PATHINFO_FILENAME); + $dir = pathinfo($path, PATHINFO_DIRNAME); + $dir = pathinfo($dir, PATHINFO_DIRNAME); + $dir = pathinfo($dir, PATHINFO_FILENAME); $mod = strtolower($dir); - //skip if disableda + // skip if disableda $extensionService = $this->di['mod_service']('extension'); - if (!$extensionService->isExtensionActive('mod', $mod)) { continue; } // skip if already exists - if ($this->di['db']->findOne('EmailTemplate', 'action_code = :code', array(':code' => $code))) { + if ($this->di['db']->findOne('EmailTemplate', 'action_code = :code', [':code' => $code])) { continue; } - list($subject, $content, $desc, $enabled, $mod) = $this->_getDefaults(array('code' => $code)); + [$subject, $content, $desc, $enabled, $mod] = $this->_getDefaults(['code' => $code]); $t = $this->templateCreate($code, $subject, $content, $enabled, $mod); if ($desc) { $t->description = $desc; @@ -505,7 +507,7 @@ class Service implements \Box\InjectionAwareInterface public function templateBatchDisable() { - $sql = "UPDATE email_template SET enabled = 0 WHERE 1"; + $sql = 'UPDATE email_template SET enabled = 0 WHERE 1'; $this->di['db']->exec($sql); $this->di['logger']->info('Disabled all email templates'); @@ -514,24 +516,29 @@ class Service implements \Box\InjectionAwareInterface public function templateBatchEnable() { - $sql = "UPDATE email_template SET enabled = 1 WHERE 1"; + $sql = 'UPDATE email_template SET enabled = 1 WHERE 1'; $this->di['db']->exec($sql); $this->di['logger']->info('Enabled all email templates'); return true; } - public function batchSend(){ - $mod = $this->di['mod']('email'); - $settings = $mod->getConfig(); - $tries = 0; + public function batchSend() + { + $mod = $this->di['mod']('email'); + $settings = $mod->getConfig(); + $tries = 0; $time_limit = ($this->di['array_get']($settings, 'time_limit', 5)) * 60; - $start = time(); + $start = time(); while ($email = $this->di['db']->findOne('ModEmailQueue', ' status = \'unsent\' ORDER BY updated_at ')) { $this->_sendFromQueue($email); - $tries++; - if (isset($settings['queue_once']) && $settings['queue_once'] && $settings['queue_once'] <= $tries) break; - if ($time_limit && time() - $start > $time_limit) break; + ++$tries; + if (isset($settings['queue_once']) && $settings['queue_once'] && $settings['queue_once'] <= $tries) { + break; + } + if ($time_limit && time() - $start > $time_limit) { + break; + } } } @@ -542,11 +549,11 @@ class Service implements \Box\InjectionAwareInterface $queue->content .= PHP_EOL; - $mod = $this->di['mod']('email'); + $mod = $this->di['mod']('email'); $settings = $mod->getConfig(); if (isset($settings['log_enabled']) && $settings['log_enabled']) { - $activityService = $this->di['mod_service']('activity'); + $activityService = $this->di['mod_service']('activity'); $activityService->logEmail($queue->subject, $queue->client_id, $queue->sender, $queue->recipient, $queue->content); } @@ -561,6 +568,7 @@ class Service implements \Box\InjectionAwareInterface if (APPLICATION_ENV != 'production') { error_log('Skip email sending. Application ENV: '.APPLICATION_ENV); + return true; } @@ -572,16 +580,18 @@ class Service implements \Box\InjectionAwareInterface } } catch (\Exception $e) { error_log($e->getMessage()); - if ($queue->priority) $queue->priority--; + if ($queue->priority) { + --$queue->priority; + } $queue->status = 'unsent'; - $queue->tries++; + ++$queue->tries; $queue->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($queue); - if ($settings['cancel_after'] && $queue->tries > $settings['cancel_after']) $this->di['db']->trash($queue); + if ($settings['cancel_after'] && $queue->tries > $settings['cancel_after']) { + $this->di['db']->trash($queue); + } } + return true; } - - - } diff --git a/src/bb-modules/Embed/Controller/Admin.php b/src/bb-modules/Embed/Controller/Admin.php index ca6bf8d3f..ef87e1db4 100644 --- a/src/bb-modules/Embed/Controller/Admin.php +++ b/src/bb-modules/Embed/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'extensions', - 'label' => 'Embed and integrate', - 'index' => 1500, - 'uri' => $this->di['url']->adminLink('embed'), - 'class' => '', - ), - ), - ); + return [ + 'subpages' => [ + [ + 'location' => 'extensions', + 'label' => 'Embed and integrate', + 'index' => 1500, + 'uri' => $this->di['url']->adminLink('embed'), + 'class' => '', + ], + ], + ]; } public function register(\Box_App &$app) { - $app->get('/embed', 'get_index', array(), get_class($this)); + $app->get('/embed', 'get_index', [], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_embed_index'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Embed/Controller/Client.php b/src/bb-modules/Embed/Controller/Client.php index 293321d91..f2dd272e0 100644 --- a/src/bb-modules/Embed/Controller/Client.php +++ b/src/bb-modules/Embed/Controller/Client.php @@ -1,6 +1,6 @@ get('/embed/:what', 'get_object', array('what' => '[a-z0-9-]+'), get_class($this)); + $app->get('/embed/:what', 'get_object', ['what' => '[a-z0-9-]+'], get_class($this)); } public function get_object(\Box_App $app, $what) { $tpl = 'mod_embed_'.$what; + return $app->render($tpl); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Example/Api/Admin.php b/src/bb-modules/Example/Api/Admin.php index cdf131eab..e783d1e7d 100644 --- a/src/bb-modules/Example/Api/Admin.php +++ b/src/bb-modules/Example/Api/Admin.php @@ -1,6 +1,6 @@ di['events_manager']->fire(array('event'=>'onAfterClientCalledExampleModule', 'params'=>array('key'=>'value'))); - + $this->di['events_manager']->fire(['event' => 'onAfterClientCalledExampleModule', 'params' => ['key' => 'value']]); + // Log message $this->di['logger']->info('Log message to log file'); @@ -40,11 +40,11 @@ class Client extends \Api_Abstract $type = $this->di['array_get']($data, 'type', 'info'); - return array( - 'data' => $data, - 'version' => $systemService->getVersion(), - 'profile' => $clientService->toApiArray($this->di['loggedin_client']), - 'messages' => $systemService->getMessages($type) - ); + return [ + 'data' => $data, + 'version' => $systemService->getVersion(), + 'profile' => $clientService->toApiArray($this->di['loggedin_client']), + 'messages' => $systemService->getMessages($type), + ]; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Example/Api/Guest.php b/src/bb-modules/Example/Api/Guest.php index 5d0e9fd65..d0d1f6804 100644 --- a/src/bb-modules/Example/Api/Guest.php +++ b/src/bb-modules/Example/Api/Guest.php @@ -1,6 +1,6 @@ di['tools']->file_get_contents(BB_PATH_MODS . '/Example/README.md'); + $readme = $this->di['tools']->file_get_contents(BB_PATH_MODS.'/Example/README.md'); + return $readme; } - + /** - * Return a random number between 1 and 100 - * + * Return a random number between 1 and 100. + * * @return int */ public function random_number() { return random_int(1, 100); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Example/Controller/Admin.php b/src/bb-modules/Example/Controller/Admin.php index 4f77fb39a..416be5f07 100644 --- a/src/bb-modules/Example/Controller/Admin.php +++ b/src/bb-modules/Example/Controller/Admin.php @@ -1,6 +1,6 @@ array( - 'index' => 1500, // menu sort order - 'location' => 'example', // menu group identificator for subitems - 'label' => 'Example module', // menu group title - 'class' => 'example', // used for css styling menu item - ), - 'subpages'=> array( - array( - 'location' => 'example', // place this module in extensions group - 'label' => 'Example module submenu', - 'index' => 1500, - 'uri' => $this->di['url']->adminLink('example'), - 'class' => '', - ), - ), - ); + return [ + 'group' => [ + 'index' => 1500, // menu sort order + 'location' => 'example', // menu group identificator for subitems + 'label' => 'Example module', // menu group title + 'class' => 'example', // used for css styling menu item + ], + 'subpages' => [ + [ + 'location' => 'example', // place this module in extensions group + 'label' => 'Example module submenu', + 'index' => 1500, + 'uri' => $this->di['url']->adminLink('example'), + 'class' => '', + ], + ], + ]; } /** * Methods maps admin areas urls to corresponding methods * Always use your module prefix to avoid conflicts with other modules - * in future - * + * in future. * * @example $app->get('/example/test', 'get_test', null, get_class($this)); // calls get_test method on this class * @example $app->get('/example/:id', 'get_index', array('id'=>'[0-9]+'), get_class($this)); - * @param \Box_App $app */ public function register(\Box_App &$app) { - $app->get('/example', 'get_index', array(), get_class($this)); - $app->get('/example/test', 'get_test', array(), get_class($this)); - $app->get('/example/user/:id', 'get_user', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/example/api', 'get_api', array(), get_class($this)); + $app->get('/example', 'get_index', [], get_class($this)); + $app->get('/example/test', 'get_test', [], get_class($this)); + $app->get('/example/user/:id', 'get_user', ['id' => '[0-9]+'], get_class($this)); + $app->get('/example/api', 'get_api', [], get_class($this)); } public function get_index(\Box_App $app) { // always call this method to validate if admin is logged in $this->di['is_admin_logged']; + return $app->render('mod_example_index'); } @@ -95,7 +94,7 @@ class Admin implements \Box\InjectionAwareInterface // always call this method to validate if admin is logged in $this->di['is_admin_logged']; - $params = array(); + $params = []; $params['youparamname'] = 'yourparamvalue'; return $app->render('mod_example_index', $params); @@ -106,21 +105,22 @@ class Admin implements \Box\InjectionAwareInterface // always call this method to validate if admin is logged in $this->di['is_admin_logged']; - $params = array(); + $params = []; $params['userid'] = $id; + return $app->render('mod_example_index', $params); } - + public function get_api(\Box_App $app, $id = null) { // always call this method to validate if admin is logged in $api = $this->di['api_admin']; $list_from_controller = $api->example_get_something(); - $params = array(); + $params = []; $params['api_example'] = true; $params['list_from_controller'] = $list_from_controller; return $app->render('mod_example_index', $params); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Example/Controller/Client.php b/src/bb-modules/Example/Controller/Client.php index 5f643fb6f..9f6d4b60a 100644 --- a/src/bb-modules/Example/Controller/Client.php +++ b/src/bb-modules/Example/Controller/Client.php @@ -1,6 +1,6 @@ get('/example', 'get_index', array(), get_class($this)); - $app->get('/example/protected', 'get_protected', array(), get_class($this)); + $app->get('/example', 'get_index', [], get_class($this)); + $app->get('/example/protected', 'get_protected', [], get_class($this)); } public function get_index(\Box_App $app) @@ -59,6 +59,7 @@ class Client implements \Box\InjectionAwareInterface { // call $this->di['is_client_logged'] method to validate if client is logged in $this->di['is_client_logged']; - return $app->render('mod_example_index', array('show_protected'=>true)); + + return $app->render('mod_example_index', ['show_protected' => true]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Example/Service.php b/src/bb-modules/Example/Service.php index b9c0d6a21..8b6fa528c 100644 --- a/src/bb-modules/Example/Service.php +++ b/src/bb-modules/Example/Service.php @@ -1,6 +1,6 @@ di['db']; - $db->exec("SELECT NOW()"); + $db->exec('SELECT NOW()'); - //throw new \Box_Exception("Throw exception to terminate module installation process with a message", array(), 123); + // throw new \Box_Exception("Throw exception to terminate module installation process with a message", array(), 123); return true; } @@ -56,11 +56,12 @@ class Service * Method to uninstall module. * * @return bool + * * @throws \Box_Exception */ public function uninstall() { - //throw new \Box_Exception("Throw exception to terminate module uninstallation process with a message", array(), 124); + // throw new \Box_Exception("Throw exception to terminate module uninstallation process with a message", array(), 124); return true; } @@ -70,46 +71,50 @@ class Service * after new files are placed. * * @param array $manifest - information about new module version + * * @return bool + * * @throws \Box_Exception */ public function update($manifest) { - //throw new \Box_Exception("Throw exception to terminate module update process with a message", array(), 125); + // throw new \Box_Exception("Throw exception to terminate module update process with a message", array(), 125); return true; } /** * Method is used to create search query for paginated list. - * Usually there is one paginated list per module + * Usually there is one paginated list per module. * * @param array $data + * * @return array() = list of 2 parameters: array($sql, $params) */ public function getSearchQuery($data) { - $params = array(); - $sql="SELECT meta_key, meta_value + $params = []; + $sql = "SELECT meta_key, meta_value FROM extension_meta WHERE extension = 'example' "; - $client_id = $this->di['array_get']($data, 'client_id', NULL); + $client_id = $this->di['array_get']($data, 'client_id', null); - if(NULL !== $client_id) { + if (null !== $client_id) { $sql .= ' AND client_id = :client_id'; $params[':client_id'] = $client_id; } $sql .= ' ORDER BY created_at DESC'; - return array($sql, $params); + + return [$sql, $params]; } /** * Methods is a delegate for one database row. * - * @param array $row - array representing one database row + * @param array $row - array representing one database row * @param string $role - guest|client|admin who is calling this method - * @param bool $deep - true|false deep or light version of result to return to API + * @param bool $deep - true|false deep or light version of result to return to API * * @return array */ @@ -119,7 +124,7 @@ class Service } /** - * Example event hook. Any module can hook to any BoxBilling event and perform actions + * Example event hook. Any module can hook to any BoxBilling event and perform actions. * * Make sure extension is enabled before testing this event. * @@ -130,44 +135,43 @@ class Service * In this example we are going to count how many times client failed * to enter correct login details * - * @param \Box_Event $event * @return void * - * @throws \Box_Exception + * @throws \Box_Exception */ public static function onEventClientLoginFailed(\Box_Event $event) { - //getting Dependency Injector + // getting Dependency Injector $di = $event->getDi(); - //@note almost in all cases you will need Admin API + // @note almost in all cases you will need Admin API $api = $di['api_admin']; - //sometimes you may need guest API - //$api_guest = $di['api_guest']; + // sometimes you may need guest API + // $api_guest = $di['api_guest']; $params = $event->getParameters(); - //@note To debug parameters by throwing an exception - //throw new Exception(print_r($params, 1)); + // @note To debug parameters by throwing an exception + // throw new Exception(print_r($params, 1)); // Use RedBean ORM in any place of BoxBilling where API call is not enough // First we need to find if we already have a counter for this IP // We will use extension_meta table to store this data. - $values = array( - 'ext' => 'example', - 'rel_type' => 'ip', - 'rel_id' => $params['ip'], - 'meta_key' => 'counter', - ); + $values = [ + 'ext' => 'example', + 'rel_type' => 'ip', + 'rel_id' => $params['ip'], + 'meta_key' => 'counter', + ]; $meta = $di['db']->findOne('extension_meta', 'extension = :ext AND rel_type = :rel_type AND rel_id = :rel_id AND meta_key = :meta_key', $values); - if(!$meta) { + if (!$meta) { $meta = $di['db']->dispense('extension_meta'); - //$count->client_id = null; // client id is not known in this situation - $meta->extension = 'mod_example'; - $meta->rel_type = 'ip'; - $meta->rel_id = $params['ip']; - $meta->meta_key = 'counter'; + // $count->client_id = null; // client id is not known in this situation + $meta->extension = 'mod_example'; + $meta->rel_type = 'ip'; + $meta->rel_id = $params['ip']; + $meta->meta_key = 'counter'; $meta->created_at = date('Y-m-d H:i:s'); } $meta->meta_value = $meta->meta_value + 1; @@ -177,30 +181,29 @@ class Service // Now we can perform task depending on how many times wrong details were entered // We can log event if it repeats for 2 time - if($meta->meta_value > 2) { - $api->activity_log(array('m' => 'Client failed to enter correct login details ' . $meta->meta_value . ' time(s)')); + if ($meta->meta_value > 2) { + $api->activity_log(['m' => 'Client failed to enter correct login details '.$meta->meta_value.' time(s)']); } // if client gets funky, we block him - if($meta->meta_value > 30) { + if ($meta->meta_value > 30) { throw new \Box_Exception('You have failed to login too many times. Contact support.'); } } /** - * This event hook is registered in example module client API call - * @param \Box_Event $event + * This event hook is registered in example module client API call. */ public static function onAfterClientCalledExampleModule(\Box_Event $event) { - //error_log('Called event from example module'); + // error_log('Called event from example module'); $di = $event->getDi(); $params = $event->getParameters(); - $meta = $di['db']->dispense('extension_meta'); - $meta->extension = 'mod_example'; - $meta->meta_key = 'event_params'; + $meta = $di['db']->dispense('extension_meta'); + $meta->extension = 'mod_example'; + $meta->meta_key = 'event_params'; $meta->meta_value = json_encode($params); $meta->created_at = date('Y-m-d H:i:s'); $meta->updated_at = date('Y-m-d H:i:s'); @@ -208,12 +211,11 @@ class Service } /** - * Example event hook for public ticket and set event return value - * @param \Box_Event $event + * Example event hook for public ticket and set event return value. */ public static function onBeforeGuestPublicTicketOpen(\Box_Event $event) { - /* Uncomment lines below in order to see this function in action */ + /* Uncomment lines below in order to see this function in action */ /* $data = $event->getParameters(); @@ -225,8 +227,7 @@ class Service } /** - * Example email sending - * @param \Box_Event $event + * Example email sending. */ public static function onAfterClientOrderCreate(\Box_Event $event) { @@ -248,4 +249,4 @@ class Service $api->email_template_send($email); */ } -} \ No newline at end of file +} diff --git a/src/bb-modules/Extension/Api/Admin.php b/src/bb-modules/Extension/Api/Admin.php index a3fdb523a..4828a6648 100644 --- a/src/bb-modules/Extension/Api/Admin.php +++ b/src/bb-modules/Extension/Api/Admin.php @@ -1,6 +1,6 @@ getService(); + return $service->getExtensionsList($data); } - + /** * Get list of extensions from extensions.boxbilling.org - * which can be installed on current version of BoxBilling - * + * which can be installed on current version of BoxBilling. + * * @param string $type - mod, gateway ... - * @return array + * + * @return array */ public function get_latest($data) { - //@todo enable when extensions are available - return array(); + // @todo enable when extensions are available + return []; /* $type = $this->di['array_get']($data, 'type', null); try { @@ -55,238 +56,249 @@ class Admin extends \Api_Abstract } /** - * Get admin area navigation - * - * @return array + * Get admin area navigation. + * + * @return array */ public function get_navigation($data) { $url = null; - if(isset($data['url'])) { + if (isset($data['url'])) { $url = $data['url']; } $service = $this->getService(); + return $service->getAdminNavigation($this->identity, $url); } /** - * Get list of available languages on the system - * - * @return array + * Get list of available languages on the system. + * + * @return array */ public function languages() { $systemService = $this->di['mod_service']('system'); + return $systemService->getLanguages(true); } /** - * Update BoxBilling core - * - * + * Update BoxBilling core. + * * @return bool - * + * * @throws Box_Exception - * @throws Exception + * @throws Exception */ public function update_core($data) { - $updater = $this->di['updater']; - if(!$updater->getCanUpdate()) { + if (!$updater->getCanUpdate()) { throw new \Box_Exception('You have latest version of BoxBilling. You do not need to update.', null, 930); } - + $new_version = $updater->getLatestVersion(); $updater->performUpdate(); - + $this->di['logger']->info('Updated BoxBilling from %s to %s', \Box_Version::VERSION, $new_version); + return true; } /** - * Update existing extension - * + * Update existing extension. + * * @param string $type - extensions type: mod, theme, gateway ... - * @param string $id - extension id - * + * @param string $id - extension id + * * @return array - * + * * @throws Box_Exception - * @throws Exception + * @throws Exception */ public function update($data) { - $ext = $this->_getExtension($data); $service = $this->getService(); + return $service->update($ext); } /** - * Activate existing extension - * + * Activate existing extension. + * * @param string $type - extensions type: mod, theme, gateway ... - * @param string $id - extension id - * + * @param string $id - extension id + * * @return array - * + * * @throws Box_Exception - * @throws Exception + * @throws Exception */ public function activate($data) { - $required = array( - 'id' => 'Extension ID was not passed', + $required = [ + 'id' => 'Extension ID was not passed', 'type' => 'Extension type was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); $result = $service->activateExistingExtension($data); + return $result; } /** - * Deactivate existing extension - * + * Deactivate existing extension. + * * @param string $type - extensions type: mod, theme, gateway ... - * @param string $id - extension id - * + * @param string $id - extension id + * * @return bool - true - * + * * @throws Box_Exception - * @throws Exception + * @throws Exception */ public function deactivate($data) { $ext = $this->_getExtension($data); - - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminDeactivateExtension', 'params'=>array('id'=>$ext->id))); - + + $this->di['events_manager']->fire(['event' => 'onBeforeAdminDeactivateExtension', 'params' => ['id' => $ext->id]]); + $service = $this->getService(); $service->deactivate($ext); - - $this->di['events_manager']->fire(array('event'=>'onAfterAdminDeactivateExtension', 'params'=>array('id'=>$data['id'], 'type'=>$data['type']))); - + + $this->di['events_manager']->fire(['event' => 'onAfterAdminDeactivateExtension', 'params' => ['id' => $data['id'], 'type' => $data['type']]]); + $this->di['logger']->info('Deactivated extension "%s"', $data['type'].' '.$data['id']); + return true; } - + /** - * Completely remove extension from BoxBilling - * + * Completely remove extension from BoxBilling. + * * @param string $type - extensions type: mod, theme, gateway ... - * @param string $id - extension id - * - * @return boolean + * @param string $id - extension id + * + * @return bool */ public function uninstall($data) { $ext = $this->_getExtension($data); - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminUninstallExtension', 'params'=>array('id'=>$ext->id))); - + $this->di['events_manager']->fire(['event' => 'onBeforeAdminUninstallExtension', 'params' => ['id' => $ext->id]]); + $service = $this->getService(); $service->uninstall($ext); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminUninstallExtension', 'params'=>array('id'=>$ext->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminUninstallExtension', 'params' => ['id' => $ext->id]]); + return true; } - + /** - * Install new extension from extensions site - * + * Install new extension from extensions site. + * * @param string $type - extensions type: mod, theme, gateway ... - * @param string $id - extension id + * @param string $id - extension id + * * @return array - * @throws Box_Exception + * + * @throws Box_Exception */ public function install($data) { - $required = array( - 'id' => 'Extension ID was not passed', + $required = [ + 'id' => 'Extension ID was not passed', 'type' => 'Extension type was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminInstallExtension', 'params'=>$data)); + + $this->di['events_manager']->fire(['event' => 'onBeforeAdminInstallExtension', 'params' => $data]); $service = $this->getService(); $service->downloadAndExtract($data['type'], $data['id']); - + try { $this->activate($data); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); } - $this->di['events_manager']->fire(array('event'=>'onAfterAdminInstallExtension', 'params'=>$data)); - return array( - 'success' => true, - 'id' => $data['id'], - 'type' => $data['type'], - ); + $this->di['events_manager']->fire(['event' => 'onAfterAdminInstallExtension', 'params' => $data]); + + return [ + 'success' => true, + 'id' => $data['id'], + 'type' => $data['type'], + ]; } - + /** - * Universal method for BoxBilling extensions + * Universal method for BoxBilling extensions * to retrieve configuration from database * It is recommended to store your extension configuration * using this method. Automatic decryption is available - * All parameters in "public" array will be accessible by guest API - * + * All parameters in "public" array will be accessible by guest API. + * * @param string $ext - extension name, ie: mod_news + * * @return array - configuration parameters + * * @throws \Box_Exception */ public function config_get($data) { - $required = array( + $required = [ 'ext' => 'Parameter ext was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); $config = $service->getConfig($data['ext']); + return $config; } - + /** - * Universal method for BoxBilling extensions + * Universal method for BoxBilling extensions * to update or save extension configuration to database * Always pass all configuration parameters to this method. - * + * * Config is automatically encrypted and stored in database - * + * * @param string $ext - extension name, ie: mod_news * @optional string $any - Any variable passed to this method is config parameter - * + * * @return bool - * @throws Box_Exception + * + * @throws Box_Exception */ public function config_save($data) { - $required = array( - 'ext' => 'Parameter ext was not passed', - ); + $required = [ + 'ext' => 'Parameter ext was not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->setConfig($data); } - + private function _getExtension($data) { - $required = array( - 'id' => 'Extension ID was not passed', + $required = [ + 'id' => 'Extension ID was not passed', 'type' => 'Extension type was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); $ext = $service->findExtension($data['type'], $data['id']); - if(!$ext instanceof \Model_Extension) { + if (!$ext instanceof \Model_Extension) { throw new \Box_Exception('Extension not found'); } - + return $ext; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Extension/Api/Guest.php b/src/bb-modules/Extension/Api/Guest.php index 75653211c..f785ed61d 100644 --- a/src/bb-modules/Extension/Api/Guest.php +++ b/src/bb-modules/Extension/Api/Guest.php @@ -1,6 +1,6 @@ getService(); - if(isset($data['mod']) && !empty($data['mod'])) { + if (isset($data['mod']) && !empty($data['mod'])) { return $service->isExtensionActive('mod', $data['mod']); } - - if(isset($data['id']) && !empty($data['type'])) { + + if (isset($data['id']) && !empty($data['type'])) { return $service->isExtensionActive($data['type'], $data['id']); } + return true; } /** - * Return active theme info + * Return active theme info. + * * @return array */ public function theme($client = true) { $systemService = $this->di['mod_service']('theme'); + return $systemService->getThemeConfig($client, null); } /** - * Retrieve extension public settings + * Retrieve extension public settings. * * @param string $ext - extension name + * * @throws Box_Exception + * * @return array */ public function settings($data) { - if(!isset($data['ext'])) { + if (!isset($data['ext'])) { throw new \Box_Exception('Parameter ext is missing'); } $service = $this->getService(); $config = $service->getConfig($data['ext']); - return (isset($config['public']) && is_array($config['public'])) ? $config['public'] : array(); + + return (isset($config['public']) && is_array($config['public'])) ? $config['public'] : []; } /** - * Retrieve list of available languages + * Retrieve list of available languages. + * * @return array */ public function languages() { $service = $this->di['mod_service']('system'); + return $service->getLanguages(); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Extension/Controller/Admin.php b/src/bb-modules/Extension/Controller/Admin.php index 2fc7193cc..e75a737a8 100644 --- a/src/bb-modules/Extension/Controller/Admin.php +++ b/src/bb-modules/Extension/Controller/Admin.php @@ -1,6 +1,6 @@ array( - 'location' => 'extensions', - 'index' => 1000, + return [ + 'group' => [ + 'location' => 'extensions', + 'index' => 1000, 'label' => 'Extensions', 'class' => 'iPlugin', 'sprite_class' => 'dark-sprite-icon sprite-electroPlug', - ), - 'subpages' => array( - array( - 'location' => 'extensions', + ], + 'subpages' => [ + [ + 'location' => 'extensions', 'label' => 'Overview', 'uri' => $this->di['url']->adminLink('extension'), - 'index' => 100, - 'class' => '', - ), - array( - 'location' => 'extensions', + 'index' => 100, + 'class' => '', + ], + [ + 'location' => 'extensions', 'label' => 'Languages', - 'index' => 200, + 'index' => 200, 'uri' => $this->di['url']->adminLink('extension/languages'), - 'class' => '', - ), - ), - ); + 'class' => '', + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/extension', 'get_index', array(), get_class($this)); - $app->get('/extension/settings/:mod', 'get_settings', array('mod' => '[a-z0-9-]+'), get_class($this)); - $app->get('/extension/languages', 'get_langs', array(), get_class($this)); + $app->get('/extension', 'get_index', [], get_class($this)); + $app->get('/extension/settings/:mod', 'get_settings', ['mod' => '[a-z0-9-]+'], get_class($this)); + $app->get('/extension/languages', 'get_langs', [], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_extension_index'); } public function get_langs(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_extension_languages'); } - + public function get_settings(\Box_App $app, $mod) { $this->di['is_admin_logged']; $file = 'mod_'.$mod.'_settings'; + return $app->render($file); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Extension/Service.php b/src/bb-modules/Extension/Service.php index db5ed9463..c196ef1e3 100644 --- a/src/bb-modules/Extension/Service.php +++ b/src/bb-modules/Extension/Service.php @@ -1,6 +1,6 @@ di['mod']('extension')->getCoreModules(); + return in_array($mod, $core); } public function isExtensionActive($type, $id) { - if($type == 'mod' && $this->isCoreModule($id)) { + if ('mod' == $type && $this->isCoreModule($id)) { return true; } @@ -49,17 +49,18 @@ class Service implements InjectionAwareInterface LIMIT 1 "; - $id_or_null = $this->di['db']->getCell($query, array('type'=>$type, 'id'=>$id)); - return (bool)$id_or_null; + $id_or_null = $this->di['db']->getCell($query, ['type' => $type, 'id' => $id]); + + return (bool) $id_or_null; } public static function onBeforeAdminCronRun(\Box_Event $event) { - $di = $event->getDi(); + $di = $event->getDi(); $extensionService = $di['mod_service']('extension'); try { - $extensionService->getExtensionsList(array()); + $extensionService->getExtensionsList([]); } catch (\Exception $e) { error_log($e); } @@ -71,76 +72,78 @@ class Service implements InjectionAwareInterface { $list = $this->di['db']->find('Extension', "type = 'mod'"); $removedItems = 0; - foreach($list as $ext) { + foreach ($list as $ext) { try { $mod = $this->di['mod']($ext->name); $mod->getManifest(); - } catch(\Exception $e) { + } catch (\Exception $e) { $this->di['db']->trash($ext); - $removedItems++; + ++$removedItems; } } - return $removedItems == 0 ? true : $removedItems; + + return 0 == $removedItems ? true : $removedItems; } public function getSearchQuery($filter) { - $search = $this->di['array_get']($filter, 'search', NULL); - $type = $this->di['array_get']($filter, 'type', NULL); + $search = $this->di['array_get']($filter, 'search', null); + $type = $this->di['array_get']($filter, 'type', null); - $params = array(); - $sql="SELECT * FROM extension + $params = []; + $sql = "SELECT * FROM extension WHERE status = 'installed' "; - if(NULL !== $type) { + if (null !== $type) { $sql .= ' AND type = :type'; $params[':type'] = $type; } - if(NULL !== $search) { + if (null !== $search) { $sql .= ' AND name LIKE :search'; $params[':search'] = '%'.$search.'%'; } $sql .= ' ORDER BY type ASC, status DESC, id ASC'; - return array($sql, $params); + + return [$sql, $params]; } public function getExtensionsList($filter) { $this->removeNotExistingModules(); - list($sql, $params) = $this->getSearchQuery($filter); + [$sql, $params] = $this->getSearchQuery($filter); $installed = $this->di['db']->getAll($sql, $params); - $has_settings = $this->di['array_get']($filter, 'has_settings'); - $only_installed = $this->di['array_get']($filter, 'installed'); + $has_settings = $this->di['array_get']($filter, 'has_settings'); + $only_installed = $this->di['array_get']($filter, 'installed'); $installed_and_core = $this->di['array_get']($filter, 'active'); - $search = isset($filter['search']) ? strtolower($filter['search']) : NULL; - $result = array(); + $search = isset($filter['search']) ? strtolower($filter['search']) : null; + $result = []; if ($installed_and_core) { $core = $this->di['mod']('extension')->getCoreModules(); foreach ($core as $core_mod) { - $m = $this->di['mod']($core_mod); - $manifest = $m->getManifest(); - $manifest['status'] = 'core'; + $m = $this->di['mod']($core_mod); + $manifest = $m->getManifest(); + $manifest['status'] = 'core'; $manifest['has_settings'] = $m->hasSettingsPage(); - $result[] = $manifest; + $result[] = $manifest; } } foreach ($installed as $im) { $manifest = json_decode($im['manifest'], 1); if (!is_array($manifest)) { - error_log('Error decoding module json file. ' . $im['name']); + error_log('Error decoding module json file. '.$im['name']); continue; } - $m = $this->di['mod']($im['name']); + $m = $this->di['mod']($im['name']); $manifest['version'] = $im['version']; $manifest['status'] = $im['status']; - if ($im['type'] == 'mod' && $im['status'] == 'installed' && $m->hasSettingsPage()) { + if ('mod' == $im['type'] && 'installed' == $im['status'] && $m->hasSettingsPage()) { $manifest['has_settings'] = true; } else { $manifest['has_settings'] = false; @@ -150,10 +153,10 @@ class Service implements InjectionAwareInterface } if (!$only_installed && !$installed_and_core) { - //add inactive modules + // add inactive modules $a = $this->_getAvailable(); - //unset installed modules + // unset installed modules foreach ($installed as $ins) { if (in_array($ins['name'], $a)) { $key = array_search($ins['name'], $a); @@ -162,9 +165,9 @@ class Service implements InjectionAwareInterface } foreach ($a as $mod) { - $m = $this->di['mod']($mod); - $manifest = $m->getManifest(); - $manifest['status'] = null; + $m = $this->di['mod']($mod); + $manifest = $m->getManifest(); + $manifest['status'] = null; $manifest['has_settings'] = false; $result[] = $manifest; @@ -182,18 +185,17 @@ class Service implements InjectionAwareInterface if (!empty($search)) { foreach ($result as $idx => $mod) { - if (strpos(strtolower($mod['name']), $search) === false) { + if (false === strpos(strtolower($mod['name']), $search)) { unset($result[$idx]); } - } $result = array_values($result); } - foreach ($result as $key => $value){ + foreach ($result as $key => $value) { $iconPath = 'images/icons/middlenav/cog.png'; $icon_url = $this->di['array_get']($value, 'icon_url'); - if ($icon_url){ + if ($icon_url) { $iconPath = $this->di['config']['url'].$icon_url; } $result[$key]['icon_url'] = $iconPath; @@ -204,17 +206,17 @@ class Service implements InjectionAwareInterface private function _getAvailable() { - $mods = array(); + $mods = []; $handle = opendir(BB_PATH_MODS); - while($name = readdir($handle)) { - if(ctype_alnum($name)) { + while ($name = readdir($handle)) { + if (ctype_alnum($name)) { $m = $name; $mod = $this->di['mod']($m); - if($mod->isCore()) { + if ($mod->isCore()) { continue; } - if(!$mod->hasManifest()) { + if (!$mod->hasManifest()) { error_log('Module '.$m.' manifest file is missing or is not readable.'); continue; } @@ -223,6 +225,7 @@ class Service implements InjectionAwareInterface } } closedir($handle); + return $mods; } @@ -231,37 +234,36 @@ class Service implements InjectionAwareInterface $staff_service = $this->di['mod_service']('staff'); $current_mod = null; $current_url = null; - $nav = array(); - $subpages = array(); + $nav = []; + $subpages = []; $modules = $this->di['mod']('extension')->getCoreModules(); $installed = $this->getInstalledMods(); $list = array_merge($modules, $installed); foreach ($list as $mod) { - if(!$staff_service->hasPermission($admin, $mod)) { + if (!$staff_service->hasPermission($admin, $mod)) { continue; } try { $m = $this->di['mod']($mod); $obj = $m->getAdminController(); - } catch(\Exception $e) { - + } catch (\Exception $e) { continue; } - if(method_exists($obj, 'fetchNavigation')) { + if (method_exists($obj, 'fetchNavigation')) { $n = $obj->fetchNavigation(); - if(isset($n['group'])) { + if (isset($n['group'])) { $l = $n['group']['location']; unset($n['group']['location']); $n['group']['active'] = false; $nav[$l] = $n['group']; } - if(isset($n['subpages'])) { - foreach($n['subpages'] as $nn) { - if(is_array($nn)) { + if (isset($n['subpages'])) { + foreach ($n['subpages'] as $nn) { + if (is_array($nn)) { $nn['active'] = false; array_push($subpages, $nn); } @@ -272,12 +274,12 @@ class Service implements InjectionAwareInterface // groups sorting $nav = $this->di['tools']->sortByOneKey($nav, 'index'); foreach ($subpages as $page) { - if(!isset($page['location'])) { + if (!isset($page['location'])) { error_log('Invalid module menu item: '.print_r($page, 1)); continue; } - if(!isset($nav[$page['location']])) { + if (!isset($nav[$page['location']])) { error_log('Submenu item belongs to not existing location: '.$page['location']); continue; } @@ -288,7 +290,7 @@ class Service implements InjectionAwareInterface } // submenu sorting - foreach($nav as &$group){ + foreach ($nav as &$group) { $group['subpages'] = $this->di['tools']->sortByOneKey($group['subpages'], 'index'); } @@ -300,37 +302,36 @@ class Service implements InjectionAwareInterface */ public function findExtension($type, $id) { - $extension = $this->di['db']->findOne('Extension', 'type = ? and name = ? ', array($type, $id)); + $extension = $this->di['db']->findOne('Extension', 'type = ? and name = ? ', [$type, $id]); + return $extension; } public function update(\Model_Extension $model) { - $result = array(); - - if($model->type == 'mod') { + $result = []; + if ('mod' == $model->type) { $ext = $this->di['extension']; $latest = $ext->getLatestExtensionVersion($model->name); - if(empty($latest)) { - throw new \Box_Exception('Could not retrieve version information for extension :ext', array(':ext'=>$model->name), 745); + if (empty($latest)) { + throw new \Box_Exception('Could not retrieve version information for extension :ext', [':ext' => $model->name], 745); } $haveUpdate = (version_compare($model->version, $latest) < 0); - if(!$haveUpdate) { - throw new \Box_Exception('Latest :mod version installed. No need to update', array(':mod'=>$model->name), 785); + if (!$haveUpdate) { + throw new \Box_Exception('Latest :mod version installed. No need to update', [':mod' => $model->name], 785); } $extension = $ext->getExtension($model->name); - if(empty($extension)) { - throw new \Box_Exception('Could not retrieve :ext information', array(':ext'=>$model->name), 744); + if (empty($extension)) { + throw new \Box_Exception('Could not retrieve :ext information', [':ext' => $model->name], 744); } throw new \Box_Exception('Visit extension site for update information.', null, 252); - - $result = array( + $result = [ 'version_old' => $model->version, 'version_new' => $latest, - ); + ]; } return $result; @@ -338,12 +339,12 @@ class Service implements InjectionAwareInterface public function activate(\Model_Extension $ext) { - $result = array( - 'id' => $ext->name, - 'type' => $ext->type, - 'redirect' => false, - 'has_settings' => false, - ); + $result = [ + 'id' => $ext->name, + 'type' => $ext->type, + 'redirect' => false, + 'has_settings' => false, + ]; switch ($ext->type) { case \Box_Extension::TYPE_MOD: @@ -371,23 +372,23 @@ class Service implements InjectionAwareInterface switch ($ext->type) { case \Box_Extension::TYPE_HOOK: $file = ucfirst($ext->name).'.php'; - $destination = BB_PATH_LIBRARY . '/Hook/'.$file; - if(file_exists($destination)) { + $destination = BB_PATH_LIBRARY.'/Hook/'.$file; + if (file_exists($destination)) { unlink($destination); } break; case \Box_Extension::TYPE_MOD: $mod = $ext->name; - if($this->isCoreModule($mod)) { - throw new \Box_Exception("BoxBilling core modules can not be managed"); + if ($this->isCoreModule($mod)) { + throw new \Box_Exception('BoxBilling core modules can not be managed'); } try { $mm = $this->di['mod']($mod); $mm->uninstall(); } catch (\Box_Exception $e) { - if($e->getCode() != 408) { + if (408 != $e->getCode()) { throw $e; } } @@ -399,6 +400,7 @@ class Service implements InjectionAwareInterface } $this->di['db']->trash($ext); + return true; } @@ -408,7 +410,6 @@ class Service implements InjectionAwareInterface switch ($ext->type) { case \Box_Extension::TYPE_MOD: - break; default: @@ -416,6 +417,7 @@ class Service implements InjectionAwareInterface } $this->di['db']->trash($ext); + return true; } @@ -424,7 +426,7 @@ class Service implements InjectionAwareInterface $ext = $this->di['extension']; $manifest = $ext->getExtension($id, $type); - if(!isset($manifest['download_url'])) { + if (!isset($manifest['download_url'])) { throw new \Exception('Extensions download url is not valid'); } @@ -436,41 +438,41 @@ class Service implements InjectionAwareInterface $em = $this->di['zip_archive']; $res = $em->open($zip); - if ($res === TRUE) { + if (true === $res) { $em->extractTo($extracted); $em->close(); } else { throw new \Box_Exception('Could not extract extension zip file'); } - //install by type + // install by type switch ($type) { case \Box_Extension::TYPE_MOD: - $destination = BB_PATH_MODS . '/mod_'.$id; - if($this->di['tools']->fileExists($destination)) { + $destination = BB_PATH_MODS.'/mod_'.$id; + if ($this->di['tools']->fileExists($destination)) { throw new \Box_Exception('Module already installed.', null, 436); } - if(!$this->di['tools']->rename($extracted, $destination)) { + if (!$this->di['tools']->rename($extracted, $destination)) { throw new \Box_Exception('Extension can not be moved. Make sure your server write permissions to bb-modules folder.', null, 437); } break; case \Box_Extension::TYPE_THEME: - $destination = BB_PATH_THEMES . '/'.$id; - if(!$this->di['tools']->fileExists($destination)) { - if(!$this->di['tools']->rename($extracted, $destination)) { + $destination = BB_PATH_THEMES.'/'.$id; + if (!$this->di['tools']->fileExists($destination)) { + if (!$this->di['tools']->rename($extracted, $destination)) { throw new \Box_Exception('Extension can not be moved. Make sure your server write permissions to bb-themes folder.', null, 439); } } break; case \Box_Extension::TYPE_TRANSLATION: - $destination = BB_PATH_LANGS . '/'.$id.'/LC_MESSAGES'; + $destination = BB_PATH_LANGS.'/'.$id.'/LC_MESSAGES'; $this->di['tools']->emptyFolder($destination); - if(!$this->di['tools']->fileExists($destination)) { + if (!$this->di['tools']->fileExists($destination)) { $this->di['tools']->mkdir($destination, 0777, true); } - if(!$this->di['tools']->rename($extracted, $destination)) { + if (!$this->di['tools']->rename($extracted, $destination)) { throw new \Box_Exception('Extension can not be moved. Make sure your server write permissions to bb-locale folder.', null, 440); } break; @@ -479,7 +481,7 @@ class Service implements InjectionAwareInterface throw new \Box_Exception('Extension does not support auto-install feature. Extension must be installed manually'); } - if (file_exists($zip)){ + if (file_exists($zip)) { unlink($zip); } $this->di['tools']->emptyFolder($extracted); @@ -487,7 +489,6 @@ class Service implements InjectionAwareInterface return true; } - public function getInstalledMods() { $query = "SELECT name @@ -498,21 +499,21 @@ class Service implements InjectionAwareInterface $pdo = $this->di['pdo']; $stmt = $pdo->prepare($query); $stmt->execute(); - return $stmt->fetchAll(\PDO::FETCH_COLUMN); + return $stmt->fetchAll(\PDO::FETCH_COLUMN); } private function installModule(\Model_Extension $ext) { $mod = $this->di['mod']($ext->name); - if($mod->isCore()) { - throw new \Box_Exception("BoxBilling core modules can not be installed or removed"); + if ($mod->isCore()) { + throw new \Box_Exception('BoxBilling core modules can not be installed or removed'); } $info = $mod->getManifest(); - if(isset($info['minimum_boxbilling_version']) && Box_Version::compareVersion($info['minimum_boxbilling_version']) > 0) { - throw new \Box_Exception('Module can not be installed. It requires at least :min version of BoxBilling. You are using :v', array(':min'=>$info['minimum_boxbilling_version'], ':v'=>Box_Version::VERSION)); + if (isset($info['minimum_boxbilling_version']) && Box_Version::compareVersion($info['minimum_boxbilling_version']) > 0) { + throw new \Box_Exception('Module can not be installed. It requires at least :min version of BoxBilling. You are using :v', [':min' => $info['minimum_boxbilling_version'], ':v' => Box_Version::VERSION]); } // Allow install module even if no installer exists @@ -521,37 +522,38 @@ class Service implements InjectionAwareInterface try { $mod->install(); } catch (\Box_Exception $e) { - if($e->getCode() != 408) { + if (408 != $e->getCode()) { throw $e; } } - $ext->version = $info['version']; + $ext->version = $info['version']; $this->di['db']->store($ext); + return true; } public function activateExistingExtension($data) { $ext = $this->findExtension($data['type'], $data['id']); - if(!$ext instanceof \Model_Extension) { + if (!$ext instanceof \Model_Extension) { $ext = $this->di['db']->dispense('Extension'); - $ext->name = $data['id']; - $ext->type = $data['type']; - $ext->version = null; - $ext->status = 'deactivated'; - $ext->manifest = null; + $ext->name = $data['id']; + $ext->type = $data['type']; + $ext->version = null; + $ext->status = 'deactivated'; + $ext->manifest = null; $ext_id = $this->di['db']->store($ext); } - $ext_id = isset($ext_id) ? $ext_id : $ext->id; - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminActivateExtension', 'params'=>array('id'=>$ext_id))); + $ext_id = $ext_id ?? $ext->id; + $this->di['events_manager']->fire(['event' => 'onBeforeAdminActivateExtension', 'params' => ['id' => $ext_id]]); try { $result = $this->activate($ext); - } catch(\Exception $e) { + } catch (\Exception $e) { $this->di['db']->trash($ext); throw $e; } - $this->di['events_manager']->fire(array('event'=>'onAfterAdminActivateExtension', 'params'=>array('id'=>$ext_id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminActivateExtension', 'params' => ['id' => $ext_id]]); $this->di['logger']->info('Activated extension "%s"', $data['id']); return $result; @@ -559,8 +561,8 @@ class Service implements InjectionAwareInterface public function getConfig($ext) { - $c = $this->di['db']->findOne('ExtensionMeta', 'extension = :ext AND meta_key = :key', array(':ext'=>$ext, ':key'=>'config')); - if(is_null($c)) { + $c = $this->di['db']->findOne('ExtensionMeta', 'extension = :ext AND meta_key = :key', [':ext' => $ext, ':key' => 'config']); + if (is_null($c)) { $c = $this->di['db']->dispense('ExtensionMeta'); $c->extension = $ext; $c->meta_key = 'config'; @@ -568,20 +570,21 @@ class Service implements InjectionAwareInterface $c->created_at = date('Y-m-d H:i:s'); $c->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($c); - $config = array(); + $config = []; } else { $config = $this->di['crypt']->decrypt($c->meta_value, $this->_getSalt()); $config = $this->di['tools']->decodeJ($config); } + return $config; } public function setConfig($data) { - $this->getConfig($data['ext']); //Creates new config if it does not exist in DB + $this->getConfig($data['ext']); // Creates new config if it does not exist in DB - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminExtensionConfigSave', 'params'=>$data)); - $sql=" + $this->di['events_manager']->fire(['event' => 'onBeforeAdminExtensionConfigSave', 'params' => $data]); + $sql = " UPDATE extension_meta SET meta_value = :config WHERE extension = :ext @@ -592,12 +595,12 @@ class Service implements InjectionAwareInterface $config = json_encode($data); $config = $this->di['crypt']->encrypt($config, $this->_getSalt()); - $params = array( - 'ext' => $data['ext'], - 'config' => $config, - ); + $params = [ + 'ext' => $data['ext'], + 'config' => $config, + ]; $this->di['db']->exec($sql, $params); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminExtensionConfigSave', 'params'=>$data)); + $this->di['events_manager']->fire(['event' => 'onAfterAdminExtensionConfigSave', 'params' => $data]); $this->di['logger']->info('Updated extension "%s" configuration', $data['ext']); return true; @@ -619,8 +622,8 @@ class Service implements InjectionAwareInterface $stmt->execute(); $extensions = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR); - if(!$extensions) { - $list = array(); + if (!$extensions) { + $list = []; } else { $list = array_values($extensions); } @@ -631,7 +634,6 @@ class Service implements InjectionAwareInterface $result = array_merge($mods, $list); sort($result); - return $result; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Formbuilder/Api/Admin.php b/src/bb-modules/Formbuilder/Api/Admin.php index c81ac25c1..ccfb69aaf 100644 --- a/src/bb-modules/Formbuilder/Api/Admin.php +++ b/src/bb-modules/Formbuilder/Api/Admin.php @@ -1,6 +1,6 @@ 'Form name was not provided', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - if (isset($data["type"]) && (strtolower($data["type"])!= "horizontal" || strtolower($data["type"])!= "default" )){ - throw new \Box_Exception ("Form style was not found in predefined list", null, 3657); + if (isset($data['type']) && ('horizontal' != strtolower($data['type']) || 'default' != strtolower($data['type']))) { + throw new \Box_Exception('Form style was not found in predefined list', null, 3657); } $service = $this->getService(); @@ -47,10 +47,10 @@ class Admin extends \Api_Abstract } /** - * Add new field to form + * Add new field to form. * - * @param string $type - Field type - * @param int $form_id - ID of the field form + * @param string $type - Field type + * @param int $form_id - ID of the field form * * @optional * @optional string $label - Label of the field which will be shown. Default value "Type X" where X is number of fields in form. For example "Checkbox 2" @@ -71,6 +71,7 @@ class Admin extends \Api_Abstract * @optional int $text_size - Prefered text size * * @return int - ID of created field + * * @throws Box_Exception */ public function add_field($data) @@ -87,42 +88,45 @@ class Admin extends \Api_Abstract } $fieldId = $service->addNewField($data); + return $fieldId; } /** - * Get form data by it's id + * Get form data by it's id. * * @param int $id - ID of the form * * @return array + * * @throws Box_Exception */ - public function get_form($data) { - $required = array( + $required = [ 'id' => 'Form id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 2391); $service = $this->getService(); + return $service->getForm($data['id']); } /** - * Get fields data by form's id + * Get fields data by form's id. * * @param int $form_id - ID of form * * @return array + * * @throws Box_Exception */ public function get_form_fields($data) { - $required = array( + $required = [ 'form_id' => 'Form id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 1822); $service = $this->getService(); @@ -131,20 +135,20 @@ class Admin extends \Api_Abstract return $fields; } - /** - * Get field data by field id + * Get field data by field id. * * @param int $id - ID of the fields * * @return array + * * @throws Box_Exception */ public function get_field($data) { - $required = array( + $required = [ 'id' => 'Field id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 3547); $service = $this->getService(); @@ -154,70 +158,70 @@ class Admin extends \Api_Abstract } /** - * Get array of forms - * - * + * Get array of forms. * * @return multidimensional array + * * @throws Box_Exception */ public function get_forms() { $service = $this->getService(); $forms = $service->getForms(); + return $forms; } /** - * Delete form and it's form fields + * Delete form and it's form fields. * * @param int $id - ID of the form * * @return bool + * * @throws Box_Exception */ public function delete_form($data) { - $required = array( + $required = [ 'id' => 'Form id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 9958); $service = $this->getService(); $service->removeForm($data['id']); + return true; } - /** - * Delete field by id + * Delete field by id. * * @param int $id - ID of the field * * @return bool + * * @throws Box_Exception */ public function delete_field($data) { - $required = array( + $required = [ 'id' => 'Field id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 9959); $service = $this->getService(); $service->removeField($data); + return true; } - - /** - * Update form + * Update form. * * @param array - * - * @param string $type - Field type - * @param int $form_id - ID of the field form + * @param string $type - Field type + * @param int $form_id - ID of the field form * * @optional * @optional string $label - Label of the field which will be shown. Default value "Type X" where X is number of fields in form. For example "Checkbox 2" @@ -238,13 +242,14 @@ class Admin extends \Api_Abstract * @optional int $text_size - Prefered text size * * @return int - ID of the field + * * @throws Box_Exception */ public function update_field($data) { - $required = array( + $required = [ 'id' => 'Field id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data, null, 9958); $service = $this->getService(); @@ -257,27 +262,26 @@ class Admin extends \Api_Abstract return $fieldId; } - /** - * Get form pairs + * Get form pairs. * * @return mixed */ public function get_pairs($data) { $service = $this->getService(); + return $service->getFormPairs(); } - /** - * Duplicate form with its fields in database - * - * @param int $form_id - ID of the origin form - * @param string $name - Name of copied form + * Duplicate form with its fields in database. * + * @param int $form_id - ID of the origin form + * @param string $name - Name of copied form * * @return int - ID of the new form + * * @throws Box_Exception */ public function copy_form($data) @@ -291,20 +295,21 @@ class Admin extends \Api_Abstract $service = $this->getService(); $new_form_id = $service->duplicateForm($data); + return $new_form_id; } /** - * Update form name and style + * Update form name and style. * - * @param int $form_id - ID of the form + * @param int $form_id - ID of the form * @param string $form_name - New name of the form * * @return bool */ public function update_form_settings($data) { - if (!isset($data['form_id']) || (trim($data['form_id']) == "")) { + if (!isset($data['form_id']) || ('' == trim($data['form_id']))) { throw new \Box_Exception('Form id was not passed', null, 1654); } if (!isset($data['form_name'])) { @@ -315,14 +320,12 @@ class Admin extends \Api_Abstract throw new \Box_Exception('Form type was not passed', null, 3794); } - if ($data['type'] !='horizontal' && $data['type'] != 'default') { + if ('horizontal' != $data['type'] && 'default' != $data['type']) { throw new \Box_Exception('Field type not supported', null, 3207); } $service = $this->getService(); + return $service->updateFormSettings($data); - } - - } diff --git a/src/bb-modules/Formbuilder/Api/Guest.php b/src/bb-modules/Formbuilder/Api/Guest.php index 3e1cddcba..2d99aa8b0 100644 --- a/src/bb-modules/Formbuilder/Api/Guest.php +++ b/src/bb-modules/Formbuilder/Api/Guest.php @@ -1,6 +1,6 @@ 'Form id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $service = $this->getService(); + return $service->getForm($data['id']); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Formbuilder/Controller/Client.php b/src/bb-modules/Formbuilder/Controller/Client.php index 3e095d3ea..9578e706e 100644 --- a/src/bb-modules/Formbuilder/Controller/Client.php +++ b/src/bb-modules/Formbuilder/Controller/Client.php @@ -1,6 +1,6 @@ get('/formbuilder/:id', 'get_form', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/formbuilder/:id', 'get_form', ['id' => '[0-9]+'], get_class($this)); } public function get_form(\Box_App $app, $id) { - return $app->render('mod_formbuilder_build', array('id'=>$id)); + return $app->render('mod_formbuilder_build', ['id' => $id]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Formbuilder/Service.php b/src/bb-modules/Formbuilder/Service.php index a6b6fa5b7..b882c3d5f 100644 --- a/src/bb-modules/Formbuilder/Service.php +++ b/src/bb-modules/Formbuilder/Service.php @@ -1,6 +1,6 @@ di; } - public function getFormFieldsTypes() { - return array( - "text" => 'Text input', - "select" => 'Dropdown', - "radio" => 'Radio select', - "checkbox" => 'Checkbox', - "textarea" => 'Text area' - ); + return [ + 'text' => 'Text input', + 'select' => 'Dropdown', + 'radio' => 'Radio select', + 'checkbox' => 'Checkbox', + 'textarea' => 'Text area', + ]; } public function typeValidation($type) @@ -57,48 +56,49 @@ class Service implements InjectionAwareInterface public function isArrayUnique($data) { $unique = array_unique($data); - return (count($data) === count($unique)); + return count($data) === count($unique); } public function addNewForm($data) { - $data["style"]["type"] = isset ($data["type"])? $data["type"] : "horizontal"; - $data["style"]["show_title"] = isset ($data["show_title"])? $data["show_title"] : "0"; - $data["style"] = json_encode($data["style"],JSON_FORCE_OBJECT); + $data['style']['type'] = $data['type'] ?? 'horizontal'; + $data['style']['show_title'] = $data['show_title'] ?? '0'; + $data['style'] = json_encode($data['style'], JSON_FORCE_OBJECT); $bean = $this->di['db']->dispense('Form'); $bean->name = $data['name']; - $bean->style = $data['style']; + $bean->style = $data['style']; $bean->created_at = date('Y-m-d H:i:s'); $bean->updated_at = date('Y-m-d H:i:s'); $form_id = $this->di['db']->store($bean); $this->di['logger']->info('Created new form %s with id %s', $data['name'], $form_id); + return $form_id; } - public function addNewField($field) //TODO server-side required check + public function addNewField($field) // TODO server-side required check { - $field_number = (int)$this->getFormFieldsCount($field['form_id']) + 1; + $field_number = (int) $this->getFormFieldsCount($field['form_id']) + 1; $formId = $field['form_id']; $types = $this->getFormFieldsTypes(); - $type = $field["type"]; + $type = $field['type']; - $label = $this->di['array_get']($field, 'label', $types[$type] . " " . $field_number); - $name = $this->di['array_get']($field, 'name', ($this->slugify("new_" . $type) . "_" . $field_number)); + $label = $this->di['array_get']($field, 'label', $types[$type].' '.$field_number); + $name = $this->di['array_get']($field, 'name', ($this->slugify('new_'.$type).'_'.$field_number)); - if ($type == "select" || $type == "checkbox" || $type == "radio") { + if ('select' == $type || 'checkbox' == $type || 'radio' == $type) { $field['options'] = '{"First option":"1", "Second option": "2", "Third option":"3"}'; } - if ($field['type'] == "textarea" && !isset($field['options'])) { + if ('textarea' == $field['type'] && !isset($field['options'])) { $field['options'] = '{"height":"100", "width": "300"}'; } if (isset($field['default_value'])) { $field['default_value'] = is_array($field['default_value']) ? json_encode($field['default_value'], JSON_FORCE_OBJECT) : $field['default_value']; } - if (isset ($field['options']) && is_array($field['options'])) { + if (isset($field['options']) && is_array($field['options'])) { $field['options'] = json_encode($field['options'], JSON_FORCE_OBJECT); } $bean = $this->di['db']->dispense('FormField'); @@ -129,10 +129,8 @@ class Service implements InjectionAwareInterface return $fieldId; } - private function slugify($text) { - // replace non letter or digits by _ $text = preg_replace('~[^\\pL\d]+~u', '_', $text); @@ -149,49 +147,48 @@ class Service implements InjectionAwareInterface $text = preg_replace('~[^-\w]+~', '', $text); if (is_numeric(substr($text, 0, 1))) { - throw new \Box_Exception ('Field name can not start with number.', null, 1649); + throw new \Box_Exception('Field name can not start with number.', null, 1649); } if (empty($text)) { - throw new \Box_Exception ('Field name can not be empty. Please make sure it is not empty and does not contain special characters.', null, 3502); + throw new \Box_Exception('Field name can not be empty. Please make sure it is not empty and does not contain special characters.', null, 3502); } return $text; } - public function updateField($field) { $fieldId = $field['id']; - $label = isset($field['label']) ? $field['label'] : 'New field'; + $label = $field['label'] ?? 'New field'; $name = $this->slugify($field['name']); $get_field = $this->getField($field['id']); $field['form_id'] = $get_field['form_id']; - if ($this->formFieldNameExists(array("form_id" => $field["form_id"], "field_name" => $field["name"], "field_id" => $fieldId))) { - throw new \Box_Exception ('Unfortunately field with this name exists in this form already. Form must have different field names.', null, 7628); + if ($this->formFieldNameExists(['form_id' => $field['form_id'], 'field_name' => $field['name'], 'field_id' => $fieldId])) { + throw new \Box_Exception('Unfortunately field with this name exists in this form already. Form must have different field names.', null, 7628); } - $field['options'] = isset($field['options']) ? json_encode($field['options']) : ""; + $field['options'] = isset($field['options']) ? json_encode($field['options']) : ''; if (isset($field['default_value'])) { $field['default_value'] = is_array($field['default_value']) ? json_encode($field['default_value'], JSON_FORCE_OBJECT) : $field['default_value']; } if (isset($field['type'])) { - if ($field['type'] == "checkbox" || $field['type'] == "radio" || $field['type'] == "select") { + if ('checkbox' == $field['type'] || 'radio' == $field['type'] || 'select' == $field['type']) { if (!$this->isArrayUnique(array_filter($field['values'], 'strlen'))) { - throw new \Box_Exception(ucfirst($field['type']) . ' values must be unique', null, 1597); + throw new \Box_Exception(ucfirst($field['type']).' values must be unique', null, 1597); } if (!$this->isArrayUnique(array_filter($field['labels'], 'strlen'))) { - throw new \Box_Exception(ucfirst($field['type']) . ' labels must be unique', null, 1598); + throw new \Box_Exception(ucfirst($field['type']).' labels must be unique', null, 1598); } $field['options'] = array_combine($field['labels'], $field['values']); $field['options'] = array_filter($field['options'], 'strlen'); $field['options'] = json_encode($field['options'], JSON_FORCE_OBJECT); } - if ($field['type'] == "textarea") { + if ('textarea' == $field['type']) { if (count($field['textarea_size']) != count(array_filter($field['textarea_size'], 'is_numeric'))) { throw new \Box_Exception('Textarea size options must be integer values', null, 3510); } @@ -222,6 +219,7 @@ class Service implements InjectionAwareInterface $this->di['db']->store($bean); $this->di['logger']->info('Updated custom form %s', $fieldId); + return $fieldId; } @@ -233,20 +231,21 @@ class Service implements InjectionAwareInterface $result['style'] = json_decode($result['style'], true); $result['fields'] = $this->getFormFields($result['id']); $result['fields'] = $this->fieldsJsonDecode($result['fields']); + return $result; } public function getFormFields($formId) { - $sql = (" + $sql = (' SELECT * FROM form_field WHERE form_id = :form_id ORDER BY ID asc - "); - $result = $this->di['db']->getAll($sql, array(':form_id' => $formId)); - return $result; + '); + $result = $this->di['db']->getAll($sql, [':form_id' => $formId]); + return $result; } private function fieldsJsonDecode($fields) @@ -255,124 +254,125 @@ class Service implements InjectionAwareInterface $fields[$key]['options'] = json_decode($r['options'], true); $fields[$key]['default_value'] = (json_decode($r['default_value'])) ? (json_decode($r['default_value'], true)) : $r['default_value']; } + return $fields; } public function getFormFieldsCount($form_id) { - $sql = (" + $sql = (' SELECT COUNT(*) FROM form_field WHERE form_id = :form_id - "); + '); - return $this->di['db']->getCell($sql, array(':form_id' => $form_id)); + return $this->di['db']->getCell($sql, [':form_id' => $form_id]); } - public function getFormPairs() { - $sql = " + $sql = ' SELECT id, name FROM form - "; + '; return $this->di['db']->getAssoc($sql); } public function getField($fieldId) { - $field = $this->di['db']->getExistingModelById('FormField', $fieldId, "Field was not found"); + $field = $this->di['db']->getExistingModelById('FormField', $fieldId, 'Field was not found'); $result = $this->di['db']->toArray($field); - $required = array( + $required = [ 'id' => 'Field was not found', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $result, null, 2575); - if (substr($result["options"], 0, 1) == "{" || substr($result["options"], 0, 1) == "[") { + if ('{' == substr($result['options'], 0, 1) || '[' == substr($result['options'], 0, 1)) { $result['options'] = json_decode($result['options']); } - return $result; + return $result; } public function removeForm($form_id) { - $sql = "DELETE + $sql = 'DELETE FROM form_field WHERE form_id = ? - "; - $this->di['db']->exec($sql, array($form_id)); + '; + $this->di['db']->exec($sql, [$form_id]); - $sql2 = "DELETE + $sql2 = 'DELETE FROM form - WHERE id = ?"; - $this->di['db']->exec($sql2, array($form_id)); + WHERE id = ?'; + $this->di['db']->exec($sql2, [$form_id]); - $sql3 = "UPDATE product + $sql3 = 'UPDATE product SET form_id = NULL WHERE form_id = ? - "; - $this->di['db']->exec($sql3, array($form_id)); + '; + $this->di['db']->exec($sql3, [$form_id]); - $sql4 = "UPDATE client_order + $sql4 = 'UPDATE client_order SET form_id = NULL WHERE form_id = :form_id - "; - $this->di['db']->exec($sql4, array(':form_id' => $form_id)); + '; + $this->di['db']->exec($sql4, [':form_id' => $form_id]); $this->di['logger']->info('Deleted custom form %s', $form_id); + return true; } public function removeField($data) { - $fieldModel = $this->di['db']->getExistingModelById('FormField', $data['id'], "Field was not found"); + $fieldModel = $this->di['db']->getExistingModelById('FormField', $data['id'], 'Field was not found'); $this->di['db']->trash($fieldModel); $this->di['logger']->info('Deleted custom field %s', $data['id']); + return true; } - public function formFieldNameExists($data) { $form_id = $data['form_id']; $field_name = $data['field_name']; $field_id = $data['field_id']; - $sql = (" + $sql = (' SELECT COUNT( * ) FROM `form_field` WHERE form_id = :form_id AND name = :field_name AND id != :field_id - "); + '); + + $result = $this->di['db']->findOne('FormField', 'form_id = ? and name = ? and id != ?', [$form_id, $field_name, $field_id]); - $result = $this->di['db']->findOne('FormField', 'form_id = ? and name = ? and id != ?', array($form_id, $field_name, $field_id)); return ($result) ? true : false; } public function getForms() { - $sql = (" + $sql = (' SELECT f.id, f.name, COUNT( p.id ) as product_count, COUNT( co.id ) as order_count FROM `form` f LEFT JOIN product p ON (f.id = p.form_id) LEFT JOIN client_order co ON (f.id = co.form_id) GROUP BY f.id - "); + '); return $this->di['db']->getAll($sql); } public function duplicateForm($data) { - $fields = $this->getFormFields($data['form_id']); - $new_form_id = $this->addNewForm(array( - "name" => $data['name'] - )); + $new_form_id = $this->addNewForm([ + 'name' => $data['name'], + ]); if (isset($fields) && is_array($fields)) { foreach ($fields as $field_data) { @@ -381,33 +381,33 @@ class Service implements InjectionAwareInterface } } $this->di['logger']->info('Copied form with id %s to new form %s with id %s', $data['form_id'], $data['name'], $new_form_id); + return $new_form_id; } public function updateFormSettings($data) { - $show_title = isset($data['show_title'])? $data['show_title'] : "1"; + $show_title = $data['show_title'] ?? '1'; $type = $data['type']; - $sql = "UPDATE `form` + $sql = 'UPDATE `form` SET `name` = :form_name - WHERE id = :id"; - $this->di['db']->exec($sql, array(':form_name' => $data['form_name'], ':id' => $data['form_id'])); + WHERE id = :id'; + $this->di['db']->exec($sql, [':form_name' => $data['form_name'], ':id' => $data['form_id']]); $this->di['logger']->info('Updated form %s name to %s', $data['form_id'], $data['form_name']); - $style = array( - "type" => $type, - "show_title" => $show_title - ); + $style = [ + 'type' => $type, + 'show_title' => $show_title, + ]; - $sql2 = "UPDATE `form` + $sql2 = 'UPDATE `form` SET `style` = :type - WHERE id = :id"; - $this->di['db']->exec($sql2, array(':type' => json_encode($style, JSON_FORCE_OBJECT), ':id' => $data['form_id'])); + WHERE id = :id'; + $this->di['db']->exec($sql2, [':type' => json_encode($style, JSON_FORCE_OBJECT), ':id' => $data['form_id']]); $this->di['logger']->info('Updated form %s type to %s', $data['form_id'], $data['type']); + return true; } - - } diff --git a/src/bb-modules/Forum/Api/Admin.php b/src/bb-modules/Forum/Api/Admin.php index f2133ac82..2030bd7d9 100644 --- a/src/bb-modules/Forum/Api/Admin.php +++ b/src/bb-modules/Forum/Api/Admin.php @@ -1,6 +1,6 @@ di['table']('Forum'); + return $table->getPairs(); } - + /** - * Get paginated list of forums - * + * Get paginated list of forums. + * * @return array */ public function get_list($data) { $table = $this->di['table']('Forum'); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - list ($sql, $params)= $table->getSearchQuery($data); + [$sql, $params] = $table->getSearchQuery($data); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); - foreach($pager['list'] as $key => $item){ + foreach ($pager['list'] as $key => $item) { $forum = $this->di['db']->getExistingModelById('Forum', $item['id'], 'Forum not found'); $pager['list'][$key] = $table->toApiArray($forum); } return $pager; } - + /** - * Get forums list grouped by category name - * + * Get forums list grouped by category name. + * * @return array */ public function get_categories($data) { $table = $this->di['table']('Forum'); $list = $this->di['db']->find('Forum'); - - $result = array(); - foreach($list as $f) { + + $result = []; + foreach ($list as $f) { $result[$f->category][] = $table->toApiArray($f); } + return $result; } - + /** - * Get forum details - * + * Get forum details. + * * @param int $id - forum id + * * @return array - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function get($data) { - $required = array( + $required = [ 'id' => 'Forum id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $table = $this->di['table']('Forum'); @@ -84,74 +88,76 @@ class Admin extends \Api_Abstract return $table->toApiArray($model, true, $this->getIdentity()); } - + /** - * Create new forum - * + * Create new forum. + * * @param string $title - new forum title - * + * * @optional string $category - new forum category - * + * * @return int - new forum id - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function create($data) { - $required = array( + $required = [ 'title' => 'Forum title was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $systemService = $this->di['mod_service']('system'); $systemService->checkLimits('Model_Forum', 3); - $priority = $this->di['db']->getCell("SELECT MAX(priority) FROM forum LIMIT 1"); + $priority = $this->di['db']->getCell('SELECT MAX(priority) FROM forum LIMIT 1'); - $model = $this->di['db']->dispense('Forum'); - $model->category = $this->di['array_get']($data, 'category', NULL); - $model->title = $data['title']; - $model->slug = $this->di['tools']->slug($data['title']); - $model->status = isset($data['status']) ? $data['status'] : \Model_Forum::STATUS_ACTIVE; - $model->description = $this->di['array_get']($data, 'description', NULL); - $model->priority = $priority + 1; - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); + $model = $this->di['db']->dispense('Forum'); + $model->category = $this->di['array_get']($data, 'category', null); + $model->title = $data['title']; + $model->slug = $this->di['tools']->slug($data['title']); + $model->status = $data['status'] ?? \Model_Forum::STATUS_ACTIVE; + $model->description = $this->di['array_get']($data, 'description', null); + $model->priority = $priority + 1; + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Created new forum "%s"', $model->title); return $model->id; } - + /** - * Update existing forum - * + * Update existing forum. + * * @param int $id - forum id - * + * * @optional string $category - new forum category * @optional string $title - new forum title * @optional string $status - new forum status * @optional string $slug - new forum slug * @optional string $description - new forum description * @optional string $priority - new forum priority - * - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function update($data) { - $required = array( + $required = [ 'id' => 'Forum id missing', - ); - $this->di['validator']->checkRequiredParamsForArray($required, $data); + ]; + $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Forum', $data['id'], 'Forum not found'); $category = $this->di['array_get']($data, 'category'); - if($category) { - if($this->di['array_get']($data, 'update_categories')) { - $this->di['db']->exec('UPDATE forum SET category = :cat WHERE category = :old_cat', - array('cat'=>$category, 'old_cat'=>$model->category)); + if ($category) { + if ($this->di['array_get']($data, 'update_categories')) { + $this->di['db']->exec('UPDATE forum SET category = :cat WHERE category = :old_cat', + ['cat' => $category, 'old_cat' => $model->category]); } $model->category = $category; } @@ -166,74 +172,79 @@ class Admin extends \Api_Abstract $this->di['db']->store($model); $this->di['logger']->info('Updated forum "%s"', $model->title); + return true; } /** - * Change forums sorting order - * + * Change forums sorting order. + * * @param array $priority - forum id => priority pairs - * - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function update_priority($data) { - if(!isset($data['priority']) || !is_array($data['priority'])) { + if (!isset($data['priority']) || !is_array($data['priority'])) { throw new \Box_Exception('priority params is missing'); } - foreach($data['priority'] as $id => $p) { + foreach ($data['priority'] as $id => $p) { $model = $this->di['db']->getExistingModelById('Forum', $id); - if($model instanceof \Model_Forum) { + if ($model instanceof \Model_Forum) { $model->priority = $p; $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); } } - + $this->di['logger']->info('Changed forums priorities'); + return true; } /** - * Remove forum with all topics - * + * Remove forum with all topics. + * * @param int $id - forum id - * - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function delete($data) { - $required = array( + $required = [ 'id' => 'Forum id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $table = $this->di['table']('Forum'); $model = $this->di['db']->getExistingModelById('Forum', $data['id'], 'Forum not found'); - + $id = $model->id; $table->rm($model); - + $this->di['logger']->info('Deleted forum #%s', $id); + return true; } /** - * Get paginated list of topics - * + * Get paginated list of topics. + * * @return array */ public function topic_get_list($data) { $table = $this->di['table']('ForumTopic'); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - list($sql, $params) = $table->getSearchQuery($data); + [$sql, $params] = $table->getSearchQuery($data); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $topic = $this->di['db']->getExistingModelById('ForumTopic', $item['id'], 'Forum topic not found'); + $topic = $this->di['db']->getExistingModelById('ForumTopic', $item['id'], 'Forum topic not found'); $pager['list'][$key] = $table->toApiArray($topic); } @@ -241,37 +252,41 @@ class Admin extends \Api_Abstract } /** - * Get topic details - * + * Get topic details. + * * @param int $id - topic id + * * @return array - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function topic_get($data) { - $required = array( + $required = [ 'id' => 'Topic id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $table = $this->di['table']('ForumTopic'); $model = $this->di['db']->getExistingModelById('ForumTopic', $data['id'], 'Forum Topic not found'); - + return $table->toApiArray($model, true, $this->getIdentity()); } /** - * Remove topic - * + * Remove topic. + * * @param int $id - topic id - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function topic_delete($data) { - $required = array( + $required = [ 'id' => 'Topic id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $table = $this->di['table']('ForumTopic'); @@ -280,31 +295,33 @@ class Admin extends \Api_Abstract $id = $model->id; $table->rm($model); $this->di['logger']->info('Deleted forum topic #%s', $id); + return true; } /** - * Create new topic - * - * @param int $forum_id - forum id - * @param string $title - topic title - * @param string $message - topic message - * + * Create new topic. + * + * @param int $forum_id - forum id + * @param string $title - topic title + * @param string $message - topic message + * * @optional string $status - initial topic status - * + * * @return int - new topic id - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function topic_create($data) { - $required = array( + $required = [ 'forum_id' => 'Forum ID was not passed', - 'title' => 'Forum topic title not passed', - 'message' => 'Forum topic message not passed', - ); + 'title' => 'Forum topic title not passed', + 'message' => 'Forum topic message not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - if(strlen($data['message']) < 2) { + if (strlen($data['message']) < 2) { throw new \Box_Exception('Your message is too short'); } @@ -315,7 +332,7 @@ class Admin extends \Api_Abstract $topic->forum_id = $forum->id; $topic->title = $data['title']; $topic->slug = $this->di['tools']->slug($data['title']); - $topic->status = isset($data['status']) ? $data['status'] : \Model_ForumTopic::STATUS_ACTIVE; + $topic->status = $data['status'] ?? \Model_ForumTopic::STATUS_ACTIVE; $topic->created_at = date('Y-m-d H:i:s'); $topic->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($topic); @@ -331,33 +348,34 @@ class Admin extends \Api_Abstract $this->di['logger']->info('Started new forum topic "%s"', $topic->title); - return (int)$topic->id; + return (int) $topic->id; } /** - * Update forum topic - * + * Update forum topic. + * * @param int $id - topic id - * + * * @optional string $title - topic title * @optional string $message - topic message * @optional string $status - topic status * @optional string $slug - topic slug * @optional int $views - topic views count * @optional bool $sticky - topic sticky flag - * - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function topic_update($data) { - $required = array( + $required = [ 'id' => 'Forum topic id was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ForumTopic', $data['id'], 'Forum Topic not found'); - + $model->forum_id = $this->di['array_get']($data, 'forum_id', $model->forum_id); $model->title = $this->di['array_get']($data, 'title', $model->title); $model->status = $this->di['array_get']($data, 'status', $model->status); @@ -368,49 +386,54 @@ class Admin extends \Api_Abstract $this->di['db']->store($model); $this->di['logger']->info('Updated forum topic "%s"', $model->title); + return true; } - + /** - * Get topic messages list - * + * Get topic messages list. + * * @optional int $forum_topic_id - topic id * @optional int $client_id - filter by client id * @optional bool $with_points - get messages with points only - * + * * @return array - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function message_get_list($data) { - $data['orderby'] = 'created_at'; - $data['sortorder'] = 'desc'; + $data['orderby'] = 'created_at'; + $data['sortorder'] = 'desc'; $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - list($sql, $params) = $this->getService()->getMessagesQuery($data); + [$sql, $params] = $this->getService()->getMessagesQuery($data); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); - foreach($pager['list'] as &$entry) { + foreach ($pager['list'] as &$entry) { $entry['author'] = $this->getService()->getProfile($entry['client_id']); - if (!$entry['client_id'] && $entry['admin_id']){ + if (!$entry['client_id'] && $entry['admin_id']) { $admin = $this->di['db']->getExistingModelById('Admin', $entry['admin_id'], 'Admin not found'); - $entry['author']['gravatar'] = 'https://gravatar.com/avatar/' . md5($admin->email); + $entry['author']['gravatar'] = 'https://gravatar.com/avatar/'.md5($admin->email); } } + return $pager; } - + /** - * Get forum topic message - * + * Get forum topic message. + * * @param int $id - message id + * * @return type - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function message_get($data) { - $required = array( + $required = [ 'id' => 'Forum Topic message ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $table = $this->di['table']('ForumTopicMessage'); @@ -421,20 +444,21 @@ class Admin extends \Api_Abstract } /** - * Update forum topic message - * + * Update forum topic message. + * * @param int $id - message id - * + * * @optional string $message - topic message - * - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function message_update($data) { - $required = array( + $required = [ 'id' => 'Forum Topic message ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ForumTopicMessage', $data['id'], 'Forum Topic Message not found'); @@ -444,52 +468,56 @@ class Admin extends \Api_Abstract $this->di['db']->store($model); $this->di['logger']->info('Updated forum topic message #%s', $model->id); + return true; } /** - * Delete topic message - * + * Delete topic message. + * * @param int $id - message id - * - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function message_delete($data) { - $required = array( + $required = [ 'id' => 'Forum Topic message ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $table = $table = $this->di['table']('ForumTopicMessage'); - $model = $this->di['db']->getExistingModelById('ForumTopicMessage', $data['id'], 'Forum Topic Message not found'); + $model = $this->di['db']->getExistingModelById('ForumTopicMessage', $data['id'], 'Forum Topic Message not found'); $id = $model->id; $table->rm($model); $this->di['logger']->info('Admin removed forum topic message #%s', $id); + return true; } /** - * Post new message to topic - * - * @param int $forum_topic_id - forum topic id - * @param string $message - topic message - * + * Post new message to topic. + * + * @param int $forum_topic_id - forum topic id + * @param string $message - topic message + * * @return id - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function message_create($data) { - $required = array( + $required = [ 'forum_topic_id' => 'Forum Topic ID not passed', - 'message' => 'Topic message not passed', - ); + 'message' => 'Topic message not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - if(strlen($data['message']) < 2) { + if (strlen($data['message']) < 2) { throw new \Box_Exception('Your message is too short'); } @@ -509,73 +537,81 @@ class Admin extends \Api_Abstract $topic->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($topic); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminRepliedInForum', 'params'=>array('id'=>$topic->id, 'message_id'=>$msg->id, 'admin_id'=>$admin->id))); - + $this->di['events_manager']->fire(['event' => 'onAfterAdminRepliedInForum', 'params' => ['id' => $topic->id, 'message_id' => $msg->id, 'admin_id' => $admin->id]]); + $this->di['logger']->info('Posted new forum message %s', $msg->id); - return (int)$msg->id; + + return (int) $msg->id; } /** * Decline post. Post will be considered as not worth the points. - * + * * @param int $id - message id - * + * * @return bool + * * @throws \Box_Exception */ public function points_deduct($data) { - $required = array( + $required = [ 'id' => 'Message ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $service = $service = $this->di['mod_service']('forum'); - $service->declinePointsForPost($data['id']); - + $service->declinePointsForPost($data['id']); + $this->di['logger']->info('Deducted points from forum message #%s', $data['id']); + return true; } - + /** - * Update total points for client - * - * @param int $client_id - client id - * @param float $amount - new points total - * - * @return boolean + * Update total points for client. + * + * @param int $client_id - client id + * @param float $amount - new points total + * + * @return bool + * * @throws \Box_Exception */ public function points_update($data) { - $required = array( + $required = [ 'client_id' => 'Client ID not passed', 'amount' => 'Amount not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $service = $service = $this->di['mod_service']('forum'); - $service->updateTotalPoints($data['client_id'], $data['amount']); - + $service->updateTotalPoints($data['client_id'], $data['amount']); + $this->di['logger']->info('Updated client %s forum points balance to %s', $data['client_id'], $data['amount']); + return true; } - + /** - * Client forum profile - * + * Client forum profile. + * * @param int $client_id - client id + * * @return array + * * @throws \Box_Exception */ public function profile_get($data) { - $required = array( + $required = [ 'client_id' => 'Client ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $forumService = $this->di['mod_service']('forum'); + return $forumService->getProfile($data['client_id']); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Forum/Api/Client.php b/src/bb-modules/Forum/Api/Client.php index 63bd98c42..df759ce73 100644 --- a/src/bb-modules/Forum/Api/Client.php +++ b/src/bb-modules/Forum/Api/Client.php @@ -1,6 +1,6 @@ di['table']('Forum'); - list($sql, $params) = $table->getSearchQuery($data); + [$sql, $params] = $table->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $forum = $this->di['db']->getExistingModelById('Forum', $item['id'], 'Forum not found'); + $forum = $this->di['db']->getExistingModelById('Forum', $item['id'], 'Forum not found'); $pager['list'][$key] = $table->toApiArray($forum); } @@ -38,7 +38,7 @@ class Client extends \Api_Abstract } /** - * Get forums list grouped by category name + * Get forums list grouped by category name. * * @return array */ @@ -48,7 +48,7 @@ class Client extends \Api_Abstract $list = $this->di['db']->find('Forum', 'ORDER BY priority ASC, category ASC'); - $result = array(); + $result = []; foreach ($list as $f) { $result[$f->category][] = $table->toApiArray($f); } @@ -57,11 +57,12 @@ class Client extends \Api_Abstract } /** - * Get forum details + * Get forum details. * * @param int $id - forum id * * @return array + * * @throws Box_Exception */ public function get($data) @@ -70,12 +71,12 @@ class Client extends \Api_Abstract throw new \Box_Exception('ID or slug is missing'); } - $id = $this->di['array_get']($data, 'id', NULL); - $slug = $this->di['array_get']($data, 'slug', NULL); + $id = $this->di['array_get']($data, 'id', null); + $slug = $this->di['array_get']($data, 'slug', null); $table = $this->di['table']('Forum'); - $model = FALSE; + $model = false; if ($id) { $model = $table->findOneActiveById($id); } else { @@ -90,24 +91,26 @@ class Client extends \Api_Abstract } /** - * Get paginated list of topics + * Get paginated list of topics. * * @return array */ public function get_topic_list($data) { $table = $this->di['table']('ForumTopic'); - list($sql, $params) = $table->getSearchQuery($data); + [$sql, $params] = $table->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); return $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); } /** - * Get topic details + * Get topic details. * * @param int $id - topic id + * * @return array + * * @throws Box_Exception */ public function get_topic($data) @@ -116,16 +119,16 @@ class Client extends \Api_Abstract throw new \Box_Exception('ID or slug is missing'); } - $id = $this->di['array_get']($data, 'id', NULL); - $slug = $this->di['array_get']($data, 'slug', NULL); + $id = $this->di['array_get']($data, 'id', null); + $slug = $this->di['array_get']($data, 'slug', null); $table = $this->di['table']('ForumTopic'); - $model = FALSE; + $model = false; if ($id) { $model = $this->di['db']->getExistingModelById('ForumTopic', $id, 'Forum topic not found'); } else { - $model = $this->di['db']->findOne('ForumTopic', 'slug = :slug', array(':slug' => $slug)); + $model = $this->di['db']->findOne('ForumTopic', 'slug = :slug', [':slug' => $slug]); } if (!$model instanceof \Model_ForumTopic) { @@ -137,15 +140,16 @@ class Client extends \Api_Abstract } /** - * Create new topic + * Create new topic. * - * @param int $forum_id - forum id - * @param string $topic - topic title - * @param string $message - topic message + * @param int $forum_id - forum id + * @param string $topic - topic title + * @param string $message - topic message * * @optional string $status - initial topic status * * @return int - new topic id + * * @throws Box_Exception */ public function start_topic($data) @@ -164,59 +168,61 @@ class Client extends \Api_Abstract throw new \Box_Exception('Your message is too short'); } - $event_params = $data; + $event_params = $data; $event_params['client_id'] = $this->getIdentity()->id; - $this->di['events_manager']->fire(array('event' => 'onBeforeClientCreateForumTopic', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onBeforeClientCreateForumTopic', 'params' => $event_params]); - $table = $this->di['table']('Forum');; + $table = $this->di['table']('Forum'); $forum = $table->findOneActiveById($data['forum_id']); if (!$forum instanceof \Model_Forum) { throw new \Box_Exception('Forum not found'); } - if ($forum->status == \Model_Forum::STATUS_LOCKED) { + if (\Model_Forum::STATUS_LOCKED == $forum->status) { throw new \Box_Exception('Forum is locked. No new topics can be started'); } $client = $this->getIdentity(); - $topic = $this->di['db']->dispense('ForumTopic'); - $topic->forum_id = $forum->id; - $topic->title = $data['topic']; - $topic->slug = $this->di['tools']->slug($data['topic']); - $topic->status = 'active'; + $topic = $this->di['db']->dispense('ForumTopic'); + $topic->forum_id = $forum->id; + $topic->title = $data['topic']; + $topic->slug = $this->di['tools']->slug($data['topic']); + $topic->status = 'active'; $topic->created_at = date('Y-m-d H:i:s'); $topic->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($topic); - $msg = $this->di['db']->dispense('ForumTopicMessage'); - $msg->client_id = $client->id; + $msg = $this->di['db']->dispense('ForumTopicMessage'); + $msg->client_id = $client->id; $msg->forum_topic_id = $topic->id; - $msg->message = $data['message']; - $msg->ip = $this->getIp(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); + $msg->message = $data['message']; + $msg->ip = $this->getIp(); + $msg->created_at = date('Y-m-d H:i:s'); + $msg->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($msg); - $this->di['events_manager']->fire(array('event' => 'onAfterClientCreateForumTopic', 'params' => array('id' => $topic->id))); + $this->di['events_manager']->fire(['event' => 'onAfterClientCreateForumTopic', 'params' => ['id' => $topic->id]]); - $this->subscribe(array('id' => $topic->id)); + $this->subscribe(['id' => $topic->id]); $this->di['logger']->info('Started new forum topic "%s"', $topic->title); - //@EasterEgg to return slug instead of id - if (isset($data['return']) && $data['return'] == 'slug') { + // @EasterEgg to return slug instead of id + if (isset($data['return']) && 'slug' == $data['return']) { return $topic->slug; } - return (int)$topic->id; + return (int) $topic->id; } /** - * Get topic messages list + * Get topic messages list. * * @param int $forum_topic_id - topic id + * * @return array + * * @throws Box_Exception */ public function get_topic_message_list($data) @@ -225,19 +231,20 @@ class Client extends \Api_Abstract throw new \Box_Exception('Forum Topic ID not passed'); } $table = $this->di['table']('ForumTopicMessage'); - list($sql, $params) = $table->getSearchQuery($data); + [$sql, $params] = $table->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); return $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); } /** - * Post new message to topic + * Post new message to topic. * - * @param int $forum_topic_id - forum topic id - * @param string $message - topic message + * @param int $forum_topic_id - forum topic id + * @param string $message - topic message * * @return id + * * @throws Box_Exception */ public function post_message($data) @@ -256,38 +263,39 @@ class Client extends \Api_Abstract $topic = $this->di['db']->getExistingModelById('ForumTopic', $data['forum_topic_id'], 'Forum Topic not found'); - if ($topic->status == \Model_ForumTopic::STATUS_LOCKED) { + if (\Model_ForumTopic::STATUS_LOCKED == $topic->status) { throw new \Box_Exception('Forum topic is locked. No new message can be posted'); } $client = $this->getIdentity(); $data['client_id'] = $client->id; - $this->di['events_manager']->fire(array('event' => 'onBeforeClientRepliedInForum', 'params' => $data)); + $this->di['events_manager']->fire(['event' => 'onBeforeClientRepliedInForum', 'params' => $data]); - $msg = $this->di['db']->dispense('ForumTopicMessage'); - $msg->client_id = $client->id; + $msg = $this->di['db']->dispense('ForumTopicMessage'); + $msg->client_id = $client->id; $msg->forum_topic_id = $topic->id; - $msg->message = $data['message']; - $msg->ip = $this->getIp(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); + $msg->message = $data['message']; + $msg->ip = $this->getIp(); + $msg->created_at = date('Y-m-d H:i:s'); + $msg->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($msg); $topic->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($topic); - $this->di['events_manager']->fire(array('event' => 'onAfterClientRepliedInForum', 'params' => array('id' => $topic->id, 'message_id' => $msg->id, 'client_id' => $client->id))); + $this->di['events_manager']->fire(['event' => 'onAfterClientRepliedInForum', 'params' => ['id' => $topic->id, 'message_id' => $msg->id, 'client_id' => $client->id]]); $this->di['logger']->info('Posted message in topic #%s', $topic->id); - return (int)$msg->id; + return (int) $msg->id; } /** - * Check if current client is subscribed to forum notifications + * Check if current client is subscribed to forum notifications. * * @return bool + * * @throws Box_Exception */ public function is_subscribed($data) @@ -297,7 +305,7 @@ class Client extends \Api_Abstract } $client = $this->getIdentity(); - $sql = " + $sql = ' SELECT meta_value FROM extension_meta WHERE client_id = :cid @@ -305,18 +313,19 @@ class Client extends \Api_Abstract AND rel_type = :type AND rel_id = :rid AND meta_key = :key - "; - $tid = $data['id']; + '; + $tid = $data['id']; - $value = $this->di['db']->getCell($sql, array('cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'rid' => $tid, 'key' => 'notification')); + $value = $this->di['db']->getCell($sql, ['cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'rid' => $tid, 'key' => 'notification']); - return (bool)$value; + return (bool) $value; } /** - * Unsubscribe client from topic notifications + * Unsubscribe client from topic notifications. * * @return bool + * * @throws Box_Exception */ public function unsubscribe($data) @@ -326,17 +335,17 @@ class Client extends \Api_Abstract } $client = $this->getIdentity(); - $sql = " + $sql = ' DELETE FROM extension_meta WHERE client_id = :cid AND extension = :ext AND rel_type = :type AND rel_id = :rid AND meta_key = :key - "; - $tid = $data['id']; + '; + $tid = $data['id']; - $this->di['db']->exec($sql, array('cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'rid' => $tid, 'key' => 'notification')); + $this->di['db']->exec($sql, ['cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'rid' => $tid, 'key' => 'notification']); $this->di['logger']->info('Unsubscribed from forum topic %s', $data['id']); @@ -344,10 +353,12 @@ class Client extends \Api_Abstract } /** - * Subscribe client to forum topic notifications + * Subscribe client to forum topic notifications. * * @param int $id - forum topic id + * * @return bool + * * @throws Box_Exception */ public function subscribe($data) @@ -360,13 +371,13 @@ class Client extends \Api_Abstract throw new \Exception('You have already subscribed to this topic notifications'); } - $client = $this->getIdentity(); - $meta = $this->di['db']->dispense('extension_meta'); - $meta->extension = 'mod_forum'; - $meta->client_id = $client->id; - $meta->rel_type = 'forum_topic'; - $meta->rel_id = $data['id']; - $meta->meta_key = 'notification'; + $client = $this->getIdentity(); + $meta = $this->di['db']->dispense('extension_meta'); + $meta->extension = 'mod_forum'; + $meta->client_id = $client->id; + $meta->rel_type = 'forum_topic'; + $meta->rel_id = $data['id']; + $meta->meta_key = 'notification'; $meta->meta_value = 1; $meta->created_at = date('Y-m-d H:i:s'); $meta->updated_at = date('Y-m-d H:i:s'); @@ -378,24 +389,24 @@ class Client extends \Api_Abstract } /** - * Get list of topics added to favorites + * Get list of topics added to favorites. * * @return array */ public function favorites($data) { $client = $this->getIdentity(); - $sql = " + $sql = ' SELECT rel_id FROM extension_meta WHERE client_id = :cid AND extension = :ext AND rel_type = :type AND meta_key = :key - "; - $list = $this->di['db']->getAssoc($sql, array('cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'key' => 'favorite')); - $result = array(); - $table = $this->di['table']('ForumTopic'); + '; + $list = $this->di['db']->getAssoc($sql, ['cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'key' => 'favorite']); + $result = []; + $table = $this->di['table']('ForumTopic'); $topics = $table->getTopicsByIds(array_values($list)); foreach ($topics as $topic) { $result[] = $table->toApiArray($topic); @@ -405,10 +416,12 @@ class Client extends \Api_Abstract } /** - * Check if topic is added to favorites + * Check if topic is added to favorites. * * @param int $id - forum topic id + * * @return bool + * * @throws Box_Exception */ public function is_favorite($data) @@ -418,7 +431,7 @@ class Client extends \Api_Abstract } $client = $this->getIdentity(); - $sql = " + $sql = ' SELECT meta_value FROM extension_meta WHERE client_id = :cid @@ -426,19 +439,21 @@ class Client extends \Api_Abstract AND rel_type = :type AND rel_id = :rid AND meta_key = :key - "; - $tid = $data['id']; + '; + $tid = $data['id']; - $value = $this->di['db']->getCell($sql, array('cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'rid' => $tid, 'key' => 'favorite')); + $value = $this->di['db']->getCell($sql, ['cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'rid' => $tid, 'key' => 'favorite']); - return (bool)$value; + return (bool) $value; } /** - * Add topic to favorites + * Add topic to favorites. * * @param int $id - forum topic id - * @return boolean + * + * @return bool + * * @throws Box_Exception * @throws Exception */ @@ -452,13 +467,13 @@ class Client extends \Api_Abstract throw new \Exception('You have already added this topic to favorites'); } - $client = $this->getIdentity(); - $meta = $this->di['db']->dispense('extension_meta'); - $meta->extension = 'mod_forum'; - $meta->client_id = $client->id; - $meta->rel_type = 'forum_topic'; - $meta->rel_id = $data['id']; - $meta->meta_key = 'favorite'; + $client = $this->getIdentity(); + $meta = $this->di['db']->dispense('extension_meta'); + $meta->extension = 'mod_forum'; + $meta->client_id = $client->id; + $meta->rel_type = 'forum_topic'; + $meta->rel_id = $data['id']; + $meta->meta_key = 'favorite'; $meta->meta_value = 1; $meta->created_at = date('Y-m-d H:i:s'); $meta->updated_at = date('Y-m-d H:i:s'); @@ -470,10 +485,12 @@ class Client extends \Api_Abstract } /** - * Remove topic from favorites + * Remove topic from favorites. * * @param int $id - forum topic id - * @return boolean + * + * @return bool + * * @throws Box_Exception */ public function favorite_remove($data) @@ -483,17 +500,17 @@ class Client extends \Api_Abstract } $client = $this->getIdentity(); - $sql = " + $sql = ' DELETE FROM extension_meta WHERE client_id = :cid AND extension = :ext AND rel_type = :type AND rel_id = :rid AND meta_key = :key - "; - $tid = $data['id']; + '; + $tid = $data['id']; - $this->di['db']->exec($sql, array('cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'rid' => $tid, 'key' => 'favorite')); + $this->di['db']->exec($sql, ['cid' => $client->id, 'ext' => 'mod_forum', 'type' => 'forum_topic', 'rid' => $tid, 'key' => 'favorite']); $this->di['logger']->info('Removed forum topic %s from favorites', $data['id']); @@ -501,13 +518,14 @@ class Client extends \Api_Abstract } /** - * Forum profile + * Forum profile. * * @return array + * * @throws Box_Exception */ public function profile($data) { return $this->getService()->getProfile($this->getIdentity()->id); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Forum/Api/Guest.php b/src/bb-modules/Forum/Api/Guest.php index 61f6f4f71..2627f2cc3 100644 --- a/src/bb-modules/Forum/Api/Guest.php +++ b/src/bb-modules/Forum/Api/Guest.php @@ -1,6 +1,6 @@ di['table']('Forum'); - list ($sql, $params) = $table->getSearchQuery($data); + [$sql, $params] = $table->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $forum = $this->di['db']->getExistingModelById('Forum', $item['id'], 'Forum not found'); + $forum = $this->di['db']->getExistingModelById('Forum', $item['id'], 'Forum not found'); $pager['list'][$key] = $table->toApiArray($forum); } @@ -38,7 +38,7 @@ class Guest extends \Api_Abstract } /** - * Get forums list grouped by category name + * Get forums list grouped by category name. * * @return array */ @@ -48,7 +48,7 @@ class Guest extends \Api_Abstract $list = $this->di['db']->find('Forum', 'ORDER BY priority ASC, category ASC'); - $result = array(); + $result = []; foreach ($list as $f) { $result[$f->category][] = $table->toApiArray($f); } @@ -57,11 +57,12 @@ class Guest extends \Api_Abstract } /** - * Get forum details + * Get forum details. * * @param int $id - forum id * * @return array + * * @throws Box_Exception */ public function get($data) @@ -70,12 +71,12 @@ class Guest extends \Api_Abstract throw new \Box_Exception('ID or slug is missing'); } - $id = $this->di['array_get']($data, 'id', NULL); - $slug = $this->di['array_get']($data, 'slug', NULL); + $id = $this->di['array_get']($data, 'id', null); + $slug = $this->di['array_get']($data, 'slug', null); $table = $this->di['table']('Forum'); - $model = FALSE; + $model = false; if ($id) { $model = $table->findOneActiveById($id); } else { @@ -90,18 +91,18 @@ class Guest extends \Api_Abstract } /** - * Get paginated list of topics + * Get paginated list of topics. * * @return array */ public function get_topic_list($data) { $table = $this->di['table']('ForumTopic'); - list($sql, $params) = $table->getSearchQuery($data); + [$sql, $params] = $table->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); - foreach($pager['list'] as $key => $item){ + foreach ($pager['list'] as $key => $item) { $forum = $this->di['db']->getExistingModelById('ForumTopic', $item['id'], 'Forum topic not found'); $pager['list'][$key] = $table->toApiArray($forum); } @@ -110,10 +111,12 @@ class Guest extends \Api_Abstract } /** - * Get topic details + * Get topic details. * * @param int $id - topic id + * * @return array + * * @throws Box_Exception */ public function get_topic($data) @@ -122,16 +125,16 @@ class Guest extends \Api_Abstract throw new \Box_Exception('ID or slug is missing'); } - $id = $this->di['array_get']($data, 'id', NULL); - $slug = $this->di['array_get']($data, 'slug', NULL); + $id = $this->di['array_get']($data, 'id', null); + $slug = $this->di['array_get']($data, 'slug', null); $table = $this->di['table']('ForumTopic'); - $model = FALSE; + $model = false; if ($id) { $model = $this->di['db']->getExistingModelById('ForumTopic', $id, 'Forum topic not found'); } else { - $model = $this->di['db']->findOne('ForumTopic', 'slug = :slug', array(':slug' => $slug)); + $model = $this->di['db']->findOne('ForumTopic', 'slug = :slug', [':slug' => $slug]); } if (!$model instanceof \Model_ForumTopic) { throw new \Box_Exception('Forum Topic not found'); @@ -142,10 +145,12 @@ class Guest extends \Api_Abstract } /** - * Get topic messages list + * Get topic messages list. * * @param int $forum_topic_id - topic id + * * @return array + * * @throws Box_Exception */ public function get_topic_message_list($data) @@ -154,11 +159,11 @@ class Guest extends \Api_Abstract throw new \Box_Exception('Forum Topic ID not passed'); } $table = $this->di['table']('ForumTopicMessage'); - list($sql, $params) = $table->getSearchQuery($data); + [$sql, $params] = $table->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); - foreach($pager['list'] as $key => $item){ + foreach ($pager['list'] as $key => $item) { $forum = $this->di['db']->getExistingModelById('ForumTopicMessage', $item['id'], 'Forum topic message not found'); $pager['list'][$key] = $table->toApiArray($forum); } @@ -167,17 +172,19 @@ class Guest extends \Api_Abstract } /** - * Search topic messages + * Search topic messages. * * @param string $q - query string + * * @return array - paginated list of results + * * @throws Box_Exception */ public function search($data) { - $required = array( + $required = [ 'q' => 'Enter some keywords for search', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); if (strlen($data['q']) < 3) { @@ -185,16 +192,18 @@ class Guest extends \Api_Abstract } $table = $this->di['table']('ForumTopicMessage'); - list($sql, $params) = $table->getSearchQuery($data); + [$sql, $params] = $table->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + return $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); } public function members_list($data) { - list($sql, $params) = $this->getService()->getMembersListQuery($data); + [$sql, $params] = $this->getService()->getMembersListQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + return $this->di['pager']->getAdvancedResultSet($sql, $params, $per_page); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Forum/Controller/Admin.php b/src/bb-modules/Forum/Controller/Admin.php index ead60ba07..fdd17e38e 100644 --- a/src/bb-modules/Forum/Controller/Admin.php +++ b/src/bb-modules/Forum/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'support', - 'index' => 700, + return [ + 'subpages' => [ + [ + 'location' => 'support', + 'index' => 700, 'label' => 'Forum', - 'uri' => $this->di['url']->adminLink('forum'), + 'uri' => $this->di['url']->adminLink('forum'), 'class' => '', - ), - ), - ); + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/forum', 'get_index', array(), get_class($this)); - $app->get('/forum/profile/:id', 'get_profile', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/forum/:id', 'get_forum', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/forum/topic/:id', 'get_topic', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/forum', 'get_index', [], get_class($this)); + $app->get('/forum/profile/:id', 'get_profile', ['id' => '[0-9]+'], get_class($this)); + $app->get('/forum/:id', 'get_forum', ['id' => '[0-9]+'], get_class($this)); + $app->get('/forum/topic/:id', 'get_topic', ['id' => '[0-9]+'], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_forum_index'); } - + public function get_forum(\Box_App $app, $id) { $api = $this->di['api_admin']; - $forum = $api->forum_get(array('id'=>$id)); - return $app->render('mod_forum_forum', array('forum'=>$forum)); + $forum = $api->forum_get(['id' => $id]); + + return $app->render('mod_forum_forum', ['forum' => $forum]); } - + public function get_topic(\Box_App $app, $id) { $api = $this->di['api_admin']; - $topic = $api->forum_topic_get(array('id'=>$id)); - return $app->render('mod_forum_topic', array('topic'=>$topic)); + $topic = $api->forum_topic_get(['id' => $id]); + + return $app->render('mod_forum_topic', ['topic' => $topic]); } - + public function get_profile(\Box_App $app, $id) { $this->di['is_admin_logged']; - return $app->render('mod_forum_profile', array('client_id'=>$id)); + + return $app->render('mod_forum_profile', ['client_id' => $id]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Forum/Controller/Client.php b/src/bb-modules/Forum/Controller/Client.php index 71f60f3cb..6ac949f72 100644 --- a/src/bb-modules/Forum/Controller/Client.php +++ b/src/bb-modules/Forum/Controller/Client.php @@ -1,6 +1,6 @@ get('/forum', 'get_index', array(), get_class($this)); - $app->get('/forum/members-list', 'get_members', array(), get_class($this)); - $app->get('/forum/topics.rss', 'get_rss', array(), get_class($this)); - $app->get('/forum/:forum', 'get_forum', array('forum' => '[a-z0-9-]+'), get_class($this)); - $app->get('/forum/:forum/:topic', 'get_forum_topic', array('forum' => '[a-z0-9-]+', 'topic' => '[a-z0-9-]+'), get_class($this)); + $app->get('/forum', 'get_index', [], get_class($this)); + $app->get('/forum/members-list', 'get_members', [], get_class($this)); + $app->get('/forum/topics.rss', 'get_rss', [], get_class($this)); + $app->get('/forum/:forum', 'get_forum', ['forum' => '[a-z0-9-]+'], get_class($this)); + $app->get('/forum/:forum/:topic', 'get_forum_topic', ['forum' => '[a-z0-9-]+', 'topic' => '[a-z0-9-]+'], get_class($this)); } public function get_index(\Box_App $app) @@ -50,36 +49,39 @@ class Client implements \Box\InjectionAwareInterface public function get_rss(\Box_App $app) { header('Content-Type: application/rss+xml;'); + return $app->render('mod_forum_rss'); } - + public function get_forum(\Box_App $app, $forum) { $api = $this->di['api_guest']; - $data = array( - 'slug' => $forum, - ); + $data = [ + 'slug' => $forum, + ]; $f = $api->forum_get($data); - return $app->render('mod_forum_forum', array('forum'=>$f)); + + return $app->render('mod_forum_forum', ['forum' => $f]); } public function get_forum_topic(\Box_App $app, $forum, $topic) { $api = $this->di['api_guest']; - $data = array( - 'slug' => $forum, - ); + $data = [ + 'slug' => $forum, + ]; $f = $api->forum_get($data); - $data = array( - 'slug' => $topic, - ); + $data = [ + 'slug' => $topic, + ]; $t = $api->forum_get_topic($data); - return $app->render('mod_forum_topic', array('topic'=>$t, 'forum'=>$f)); + + return $app->render('mod_forum_topic', ['topic' => $t, 'forum' => $f]); } - + public function get_members(\Box_App $app) { - return $app->render('mod_forum_members_list', array()); + return $app->render('mod_forum_members_list', []); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Forum/Service.php b/src/bb-modules/Forum/Service.php index 5b8a392c5..0606a5000 100644 --- a/src/bb-modules/Forum/Service.php +++ b/src/bb-modules/Forum/Service.php @@ -1,6 +1,6 @@ di['db']->getRow($sql, array(':cid'=>$client_id)); - $posts = $this->di['db']->getCell('SELECT COUNT(id) FROM forum_topic_message WHERE client_id = :cid', array(':cid'=>$client_id)); - + + $details = $this->di['db']->getRow($sql, [':cid' => $client_id]); + $posts = $this->di['db']->getCell('SELECT COUNT(id) FROM forum_topic_message WHERE client_id = :cid', [':cid' => $client_id]); + $points = $this->di['db']->getCell('SELECT meta_value FROM extension_meta WHERE extension = "mod_forum" AND meta_key = "points_total" - AND client_id = :cid', - array('cid'=>$client_id)); + AND client_id = :cid', + ['cid' => $client_id]); + + $profile = []; + $profile['id'] = $details['id']; + $profile['posts'] = $posts; + $profile['points'] = ($points) ? $points : 0; + $profile['gravatar'] = $details['gravatar']; + $profile['name'] = $details['name']; + $profile['created_at'] = $details['created_at']; - $profile = array(); - $profile['id'] = $details['id']; - $profile['posts'] = $posts; - $profile['points'] = ($points) ? $points : 0; - $profile['gravatar'] = $details['gravatar']; - $profile['name'] = $details['name']; - $profile['created_at'] = $details['created_at']; return $profile; } - + public function getMembersListQuery($data) { - $sql=' + $sql = ' SELECT 0 as posts, CONCAT(c.first_name, " ", c.last_name) as name, @@ -72,23 +72,24 @@ class Service implements InjectionAwareInterface RIGHT JOIN forum_topic_message fp ON (fp.client_id = c.id) WHERE fp.id > 0 '; - - $params = array(); - - $first_char = $this->di['array_get']($data, 'first_char', NULL); - - if(NULL !== $first_char) { + + $params = []; + + $first_char = $this->di['array_get']($data, 'first_char', null); + + if (null !== $first_char) { $sql .= ' AND c.first_name LIKE :first_char'; $params['first_char'] = $first_char.'%'; } $sql .= ' ORDER BY c.first_name DESC '; - return array($sql, $params); + + return [$sql, $params]; } - + public function getMessagesQuery($data) { - $sql=' + $sql = ' SELECT fp.id, fp.client_id, fp.admin_id, fp.message, fp.points, ft.slug as forum_topic_slug, f.slug as forum_slug, @@ -102,61 +103,61 @@ class Service implements InjectionAwareInterface LEFT JOIN forum f ON (f.id = ft.forum_id) WHERE 1 '; - - $params = array(); - - $search = (isset($data['q']) && !empty($data['q'])) ? $data['q'] : NULL; - $search2 = (isset($data['search']) && !empty($data['search'])) ? $data['search'] : NULL; - $forum_topic_id = (isset($data['forum_topic_id']) && !empty($data['forum_topic_id'])) ? $data['forum_topic_id'] : NULL; - $forum_id = $this->di['array_get']($data, 'forum_id', NULL); - $client_id = $this->di['array_get']($data, 'client_id', NULL); - $with_points = $this->di['array_get']($data, 'with_points', NULL); - if($with_points) { + $params = []; + + $search = (isset($data['q']) && !empty($data['q'])) ? $data['q'] : null; + $search2 = (isset($data['search']) && !empty($data['search'])) ? $data['search'] : null; + $forum_topic_id = (isset($data['forum_topic_id']) && !empty($data['forum_topic_id'])) ? $data['forum_topic_id'] : null; + $forum_id = $this->di['array_get']($data, 'forum_id', null); + $client_id = $this->di['array_get']($data, 'client_id', null); + $with_points = $this->di['array_get']($data, 'with_points', null); + + if ($with_points) { $sql .= ' AND fp.points IS NOT NULL AND fp.points != "" '; } - - if($forum_topic_id) { + + if ($forum_topic_id) { $sql .= ' AND ft.id = :forum_topic_id'; $params['forum_topic_id'] = $forum_topic_id; } - if($forum_id) { + if ($forum_id) { $sql .= ' AND f.id = :forum_id'; $params['forum_id'] = $forum_id; } - - if($client_id) { + + if ($client_id) { $sql .= ' AND fp.client_id = :cid'; $params['cid'] = $client_id; } - if($search) { + if ($search) { $sql .= ' AND fp.message LIKE :search'; $params['search'] = "%$search%"; } - - if($search2) { + + if ($search2) { $sql .= ' AND fp.message LIKE :search2'; $params['search2'] = "%$search2%"; } - - if(isset($data['orderby'])) { - if(in_array(strtolower($data['orderby']), array('id', 'created_at'))) { - $sortorder = (isset($data['sortorder']) && in_array(strtolower($data['sortorder']), array('asc', 'desc'))) ? $data['sortorder'] : 'asc' ; + + if (isset($data['orderby'])) { + if (in_array(strtolower($data['orderby']), ['id', 'created_at'])) { + $sortorder = (isset($data['sortorder']) && in_array(strtolower($data['sortorder']), ['asc', 'desc'])) ? $data['sortorder'] : 'asc'; $sql .= ' ORDER BY '.sprintf('fp.%s %s', $data['orderby'], strtoupper($sortorder)); } } else { $sql .= ' ORDER BY fp.id DESC'; } - - return array($sql, $params); + + return [$sql, $params]; } - + public function updateTotalPoints($client_id, $amount, $increment = false) { $meta = $this->getTotalPointsMeta($client_id); - if($increment) { + if ($increment) { $amount = $meta->meta_value + $amount; } $meta->meta_value = $amount; @@ -170,19 +171,19 @@ class Service implements InjectionAwareInterface $minus_points = -$post->points; - $post->points = null; + $post->points = null; $post->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($post); $this->updateTotalPoints($post->client_id, $minus_points, true); } - + private function getTotalPointsMeta($client_id) { - $meta = $this->di['db']->findOne('extension_meta', - 'extension = "mod_forum" AND meta_key = "points_total" AND client_id = :cid', - array('cid'=>$client_id)); - if(!$meta) { + $meta = $this->di['db']->findOne('extension_meta', + 'extension = "mod_forum" AND meta_key = "points_total" AND client_id = :cid', + ['cid' => $client_id]); + if (!$meta) { $meta = $this->di['db']->dispense('extension_meta'); $meta->extension = 'mod_forum'; $meta->client_id = $client_id; @@ -191,13 +192,14 @@ class Service implements InjectionAwareInterface $meta->created_at = date('Y-m-d H:i:s'); $meta->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($meta); - } + } + return $meta; } - + public function getTopicSubscribers($topic_id) { - $sql=" + $sql = " SELECT client_id FROM extension_meta WHERE extension = 'mod_forum' @@ -206,15 +208,15 @@ class Service implements InjectionAwareInterface AND meta_key = 'notification' "; - return $this->di['db']->getAssoc($sql, array(':rid'=>$topic_id)); + return $this->di['db']->getAssoc($sql, [':rid' => $topic_id]); } - + public static function onAfterClientCreateForumTopic(\Box_Event $event) { $params = $event->getParameters(); $id = $params['id']; } - + public static function onAfterAdminRepliedInForum(\Box_Event $event) { $di = $event->getDi(); @@ -226,27 +228,27 @@ class Service implements InjectionAwareInterface $service = $di['mod_service']('forum'); $list = $service->getTopicSubscribers($id); - $message = $api->forum_message_get(array('id'=>$message_id)); - $topic = $api->forum_topic_get(array('id'=>$id)); - - foreach($list as $cid) { - $email = array(); + $message = $api->forum_message_get(['id' => $message_id]); + $topic = $api->forum_topic_get(['id' => $id]); + + foreach ($list as $cid) { + $email = []; $email['to_client'] = $cid; $email['code'] = 'mod_forum_new_post'; $email['topic_id'] = $id; $email['message_id'] = $message_id; - + $email['message'] = $message; $email['topic'] = $topic; - + try { $api->email_template_send($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } } - + public static function onAfterClientRepliedInForum(\Box_Event $event) { $di = $event->getDi(); @@ -255,54 +257,53 @@ class Service implements InjectionAwareInterface $id = $params['id']; $message_id = $params['message_id']; $client_id = $params['client_id']; - + $service = $di['mod_service']('forum'); $list = $service->getTopicSubscribers($id); - $message = $api->forum_message_get(array('id'=>$message_id)); - $topic = $api->forum_topic_get(array('id'=>$id)); - - foreach($list as $cid) { - if($client_id == $cid) { - //do not send email to author + $message = $api->forum_message_get(['id' => $message_id]); + $topic = $api->forum_topic_get(['id' => $id]); + + foreach ($list as $cid) { + if ($client_id == $cid) { + // do not send email to author continue; } - - $email = array(); + + $email = []; $email['to_client'] = $cid; $email['code'] = 'mod_forum_new_post'; $email['topic_id'] = $id; $email['message_id'] = $message_id; - + $email['message'] = $message; $email['topic'] = $topic; - + try { $api->email_template_send($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } - - //forum points + + // forum points $mod = $di['mod']('forum'); $config = $mod->getConfig(); $points = $di['array_get']($config, 'points', 0); - $points_forums = $di['array_get']($config, 'points_forums', array()); + $points_forums = $di['array_get']($config, 'points_forums', []); - if(isset($config['forum_points_enable']) - && $config['forum_points_enable'] + if (isset($config['forum_points_enable']) + && $config['forum_points_enable'] && !empty($points_forums) && in_array($topic['forum']['id'], $points_forums) && strlen($message['message']) >= $config['post_length'] && $points > 0) { - $di['db']->exec('UPDATE forum_topic_message SET points = :points WHERE id = :id', - array('points'=>$points, 'id'=>$message_id)); - + ['points' => $points, 'id' => $message_id]); + $service = $mod->getService(); $service->updateTotalPoints($client_id, $points, true); } } -} \ No newline at end of file +} diff --git a/src/bb-modules/Hook/Api/Admin.php b/src/bb-modules/Hook/Api/Admin.php index 64aca5510..2a842bb10 100644 --- a/src/bb-modules/Hook/Api/Admin.php +++ b/src/bb-modules/Hook/Api/Admin.php @@ -1,6 +1,6 @@ getService(); - list($sql, $params) = $service->getSearchQuery($data); + [$sql, $params] = $service->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + return $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); } - + /** - * Invoke hook with params - * + * Invoke hook with params. + * * @param string $event - event name, ie: onEventBeforeInvoiceIsDue * @optional array $params - what params are passed to event method $event->getParams() - * + * * @return mixed - event return value */ public function call($data) { - if(!isset($data['event']) || empty($data['event'])) { + if (!isset($data['event']) || empty($data['event'])) { error_log('Invoked event call without providing event name'); + return false; } - + $event = $data['event']; $params = $this->di['array_get']($data, 'params', null); - if($this->di['config']['debug']) { + if ($this->di['config']['debug']) { try { - $this->di['logger']->info($event. ': '. var_export($params, 1)); - } catch(\Exception $e) { + $this->di['logger']->info($event.': '.var_export($params, 1)); + } catch (\Exception $e) { error_log($e->getMessage()); } } return $this->di['events_manager']->fire($data); } - + /** - * Reinstall and activate all existing hooks from module or all - * activated modules. Does not connect already connected event - * + * Reinstall and activate all existing hooks from module or all + * activated modules. Does not connect already connected event. + * * @optional string $mod - module name to connect hooks - * + * * @return bool */ public function batch_connect($data) { $mod = $this->di['array_get']($data, 'mod', null); $service = $this->getService(); + return $service->batchConnect($mod); } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Hook/Service.php b/src/bb-modules/Hook/Service.php index 7917a393f..f31129919 100644 --- a/src/bb-modules/Hook/Service.php +++ b/src/bb-modules/Hook/Service.php @@ -1,6 +1,6 @@ getParameters(); - if(!isset($params['id'])) { - $event->setReturnValue(FALSE); + if (!isset($params['id'])) { + $event->setReturnValue(false); } else { $di = $event->getDi(); $ext = $di['db']->load('extension', $params['id']); - if(is_object($ext) && $ext->type == 'mod') { + if (is_object($ext) && 'mod' == $ext->type) { $service = $di['mod_service']('hook'); $service->batchConnect($ext->name); } - $event->setReturnValue(TRUE); + $event->setReturnValue(true); } } - + public static function onAfterAdminDeactivateExtension(\Box_Event $event) { $di = $event->getDi(); $params = $event->getParameters(); - if($params['type'] == 'mod') { - $q="DELETE FROM extension_meta + if ('mod' == $params['type']) { + $q = "DELETE FROM extension_meta WHERE extension = 'mod_hook' AND rel_type = 'mod' AND rel_id = :mod AND meta_key = 'listener'"; - $di['db']->exec($q, array('mod'=>$params['id'])); + $di['db']->exec($q, ['mod' => $params['id']]); } - - $event->setReturnValue(TRUE); + + $event->setReturnValue(true); } /** * @param string $mod module name + * * @return bool */ public function batchConnect($mod_name = null) { - $mods = array(); - if(null !== $mod_name) { + $mods = []; + if (null !== $mod_name) { $mods[] = $mod_name; } else { $extensionService = $this->di['mod_service']('extension'); $mods = $extensionService->getCoreAndActiveModules(); } - foreach($mods as $m) { + foreach ($mods as $m) { $mod = $this->di['mod']($m); - if($mod->hasService()) { + if ($mod->hasService()) { $class = $mod->getService(); - $reflector = new \Reflectionclass($class); - foreach($reflector->getMethods() as $method) { + $reflector = new \ReflectionClass($class); + foreach ($reflector->getMethods() as $method) { $p = $method->getParameters(); - if($method->isPublic() + if ($method->isPublic() && isset($p[0]) && $p[0]->getclass() - && in_array($p[0]->getclass()->getName(), array('Box_Event', '\Box_Event'))) { - $this->connect(array('event'=>$method->getName(), 'mod'=>$mod->getName())); + && in_array($p[0]->getclass()->getName(), ['Box_Event', '\Box_Event'])) { + $this->connect(['event' => $method->getName(), 'mod' => $mod->getName()]); } } } @@ -122,26 +124,27 @@ class Service implements InjectionAwareInterface } /** - * Connect event for module + * Connect event for module. * * @param string $event - event name, ie: onAfterAdminDeactivateExtension - * @param string $mod - module name where hook is located + * @param string $mod - module name where hook is located + * + * @return bool * - * @return boolean * @throws Box_Exception */ private function connect($data) { - $required = array( + $required = [ 'event' => 'Hook event not passed', - 'mod' => 'Param mod not passed', - ); + 'mod' => 'Param mod not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $event = $data['event']; $mod = $data['mod']; - $q="SELECT id + $q = "SELECT id FROM extension_meta WHERE extension = 'mod_hook' AND rel_type = 'mod' @@ -149,32 +152,32 @@ class Service implements InjectionAwareInterface AND meta_key = 'listener' AND meta_value = :event "; - if($this->di['db']->getCell($q, array('mod'=>$mod, 'event'=>$event))) { + if ($this->di['db']->getCell($q, ['mod' => $mod, 'event' => $event])) { // already connected return true; } $meta = $this->di['db']->dispense('extension_meta'); - $meta->extension = 'mod_hook'; - $meta->rel_type = 'mod'; - $meta->rel_id = $mod; - $meta->meta_key = 'listener'; - $meta->meta_value = $event; - $meta->created_at = date('Y-m-d H:i:s'); - $meta->updated_at = date('Y-m-d H:i:s'); + $meta->extension = 'mod_hook'; + $meta->rel_type = 'mod'; + $meta->rel_id = $mod; + $meta->meta_key = 'listener'; + $meta->meta_value = $event; + $meta->created_at = date('Y-m-d H:i:s'); + $meta->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($meta); return true; } /** - * Disconnect unavailable listeners + * Disconnect unavailable listeners. */ private function _disconnectUnavailable() { - $rm_sql="DELETE FROM extension_meta WHERE id = :id"; + $rm_sql = 'DELETE FROM extension_meta WHERE id = :id'; - $sql="SELECT id, rel_id, meta_value + $sql = "SELECT id, rel_id, meta_value FROM extension_meta WHERE extension = 'mod_hook' AND rel_type = 'mod' @@ -182,37 +185,37 @@ class Service implements InjectionAwareInterface "; $list = $this->di['db']->getAll($sql); $extensionService = $this->di['mod_service']('extension'); - foreach($list as $listener) { + foreach ($list as $listener) { try { $mod_name = $listener['rel_id']; $event = $listener['meta_value']; // do not disconnect core modules - if($extensionService->isCoreModule($mod_name)) { + if ($extensionService->isCoreModule($mod_name)) { continue; } // disconect modules without service class $mod = $this->di['mod']($mod_name); - if(!$mod->hasService()) { - $this->di['db']->exec($rm_sql, array('id'=>$listener['id'])); + if (!$mod->hasService()) { + $this->di['db']->exec($rm_sql, ['id' => $listener['id']]); continue; } - $ext = $this->di['db']->findOne('extension', "type = 'mod' AND name = :mod AND status = 'installed'", array('mod'=>$mod_name)); - if(!$ext) { - $this->di['db']->exec($rm_sql, array('id'=>$listener['id'])); + $ext = $this->di['db']->findOne('extension', "type = 'mod' AND name = :mod AND status = 'installed'", ['mod' => $mod_name]); + if (!$ext) { + $this->di['db']->exec($rm_sql, ['id' => $listener['id']]); continue; } $s = $mod->getService(); - if(!method_exists($s, $event)) { - $this->di['db']->exec($rm_sql, array('id'=>$listener['id'])); + if (!method_exists($s, $event)) { + $this->di['db']->exec($rm_sql, ['id' => $listener['id']]); continue; } - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); } } } -} \ No newline at end of file +} diff --git a/src/bb-modules/Index/Controller/Admin.php b/src/bb-modules/Index/Controller/Admin.php index c98ef0bcb..79480ba68 100644 --- a/src/bb-modules/Index/Controller/Admin.php +++ b/src/bb-modules/Index/Controller/Admin.php @@ -1,6 +1,6 @@ get('', 'get_index', array(), get_class($this)); - $app->get('/', 'get_index', array(), get_class($this)); - $app->get('/index', 'get_index', array(), get_class($this)); - $app->get('/index/', 'get_index', array(), get_class($this)); + $app->get('', 'get_index', [], get_class($this)); + $app->get('/', 'get_index', [], get_class($this)); + $app->get('/index', 'get_index', [], get_class($this)); + $app->get('/index/', 'get_index', [], get_class($this)); } public function get_index(\Box_App $app) { - if($this->di['auth']->isAdminLoggedIn()) { + if ($this->di['auth']->isAdminLoggedIn()) { return $app->render('mod_index_dashboard'); } else { return $app->redirect('/staff/login'); } } -} \ No newline at end of file +} diff --git a/src/bb-modules/Invoice/Api/Admin.php b/src/bb-modules/Invoice/Api/Admin.php index 37fd7af1b..78459a70c 100644 --- a/src/bb-modules/Invoice/Api/Admin.php +++ b/src/bb-modules/Invoice/Api/Admin.php @@ -1,6 +1,6 @@ getService(); - list ($sql, $params) = $service->getSearchQuery($data); + [$sql, $params] = $service->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getAdvancedResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $invoice = $this->di['db']->getExistingModelById('Invoice', $item['id'], 'Invoice not found'); + $invoice = $this->di['db']->getExistingModelById('Invoice', $item['id'], 'Invoice not found'); $pager['list'][$key] = $this->getService()->toApiArray($invoice, true, $this->getIdentity()); } @@ -37,13 +38,16 @@ class Admin extends \Api_Abstract } /** - * Get invoice details + * Get invoice details. + * * @param int $id - invoice id + * * @return array */ public function get($data) { $model = $this->_getInvoice($data); + return $this->getService()->toApiArray($model, true, $this->getIdentity()); } @@ -51,57 +55,60 @@ class Admin extends \Api_Abstract * Sets invoce status to paid. This method differs from invoice update method * in a way that it sends notification to Events system, so emails are sent. * Also this will try to automatically apply payment if clients balance is - * available - * + * available. + * * @param int $id - invoice id - * + * * @optional bool $execute - execute related tasks on invoice items. Default false. - * + * * @return array */ public function mark_as_paid($data) { $execute = false; - if(isset($data['execute']) && $data['execute']) { + if (isset($data['execute']) && $data['execute']) { $execute = true; } $model = $this->_getInvoice($data); - return $this->getService()->markAsPaid($model, FALSE, $execute); + + return $this->getService()->markAsPaid($model, false, $execute); } /** * Prepare invoice for editing and updating. * Uses clients details, such as currency assigned to client. - * If client currency is not defined, sets default currency for client + * If client currency is not defined, sets default currency for client. * * @param int $client_id - Client id. Client must have defined currency on profile. - * + * * @optional bool $approve - set true to approve invoice after preparation. Defaults to false * @optional int $gateway_id - Selected payment gateway id * @optional array $items - list of invoice lines. One line is array of line parameters * @optional string $text_1 - text to be displayed before invoice items table * @optional string $text_2 - text to be displayed after invoice items table - * + * * @return int $id - newly generated invoice ID */ public function prepare($data) { - $required = array( + $required = [ 'client_id' => 'Client id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found'); $invoice = $this->getService()->prepareInvoice($client, $data); + return $invoice->id; } /** * Approve invoice. - * - * @param int $id - invoice id + * + * @param int $id - invoice id * @param bool $use_credits - default = false + * * @return bool */ public function approve($data) @@ -112,7 +119,8 @@ class Admin extends \Api_Abstract } /** - * Add refunds + * Add refunds. + * * @param int $id - invoice id * * @optional string $note - note for refund @@ -122,20 +130,20 @@ class Admin extends \Api_Abstract public function refund($data) { $model = $this->_getInvoice($data); - $note = $this->di['array_get']($data, 'note', NULL); + $note = $this->di['array_get']($data, 'note', null); return $this->getService()->refundInvoice($model, $note); } /** - * Update invoice details - * + * Update invoice details. + * * @param int $id - invoice id - * + * * @optional string $paid_at - Invoice payment date (Y-m-d) or empty to remove * @optional string $due_at - Invoice due date (Y-m-d)or empty to remove * @optional string $created_at - Invoice issue date (Y-m-d) or empty to remove - * + * * @optional string $serie - Invoice serie * @optional string $nr - Invoice number * @optional string $status - Invoice status: paid|unpaid @@ -146,17 +154,17 @@ class Admin extends \Api_Abstract * @optional int $gateway_id - selected payment method - gateway id * @optional array $new_item - [title] [price] - * + * * @optional string $text_1 - Custom invoice text 1 * @optional string $text_2 - Custom invoice text 1 - * + * * @optional string $seller_company - Seller company name * @optional string $seller_company_vat - Seller company VAT number * @optional string $seller_company_number - Seller company number * @optional string $seller_address - Seller address * @optional string $seller_phone - Seller phone * @optional string $seller_email - Seller email - * + * * @optional string $buyer_first_name - Buyer first name * @optional string $buyer_last_name - Buyer last name * @optional string $buyer_company - Buyer company name @@ -167,70 +175,76 @@ class Admin extends \Api_Abstract * @optional string $buyer_state - Buyer state * @optional string $buyer_country - Buyer country * @optional string $buyer_zip - Buyer zip - * @optional string $buyer_phone - Buyer phone + * @optional string $buyer_phone - Buyer phone * @optional string $buyer_email - Buyer email - * + * * @return bool */ public function update($data) { $model = $this->_getInvoice($data); + return $this->getService()->updateInvoice($model, $data); } /** - * Remove one line from invoice + * Remove one line from invoice. * * @param int $id - invoice line id + * * @return bool */ public function item_delete($data) { - $required = array( + $required = [ 'id' => 'Invoice item id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('InvoiceItem', $data['id'], 'Invoice item was not found'); $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); + return $invoiceItemService->remove($model); } /** - * Delete invoice + * Delete invoice. * * @param int $id - Invoice id + * * @return bool */ public function delete($data) { $model = $this->_getInvoice($data); + return $this->getService()->deleteInvoiceByAdmin($model); } /** * Generates new invoice for order. If unpaid invoice for selected order * already exists, new invoice will not be generated, and existing invoice id - * is returned - * + * is returned. + * * @param int $id - ID of order to generate new invoice for * @optional int $due_days - Days number until invoice is due - * + * * @return string - invoice id + * * @throws Exception - * @throws LogicException + * @throws LogicException */ public function renewal_invoice($data) { - $required = array( + $required = [ 'id' => 'Order id required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ClientOrder', $data['id'], 'Order not found'); - if($model->price <= 0) { - throw new \Box_Exception('Order :id is free. No need to generate invoice.', array(':id'=>$model->id)); + if ($model->price <= 0) { + throw new \Box_Exception('Order :id is free. No need to generate invoice.', [':id' => $model->id]); } return $this->getService()->renewInvoice($model, $data); @@ -238,10 +252,10 @@ class Admin extends \Api_Abstract /** * Use credits to pay for invoices - * if credits are available in clients balance + * if credits are available in clients balance. * * @optional int $client_id - cover only one client invoices - * + * * @return bool */ public function batch_pay_with_credits($data) @@ -250,7 +264,7 @@ class Admin extends \Api_Abstract } /** - * Cover one invoice with credits + * Cover one invoice with credits. * * @param int $id - Invoice id * @@ -259,11 +273,12 @@ class Admin extends \Api_Abstract public function pay_with_credits($data) { $invoice = $this->_getInvoice($data); + return $this->getService()->payInvoiceWithCredits($invoice); } /** - * Generate invoices for expiring orders + * Generate invoices for expiring orders. * * @return bool */ @@ -273,7 +288,7 @@ class Admin extends \Api_Abstract } /** - * Action to activate paid invoices lines + * Action to activate paid invoices lines. * * @return bool */ @@ -283,7 +298,7 @@ class Admin extends \Api_Abstract } /** - * Send buyer reminders about upcoming payment + * Send buyer reminders about upcoming payment. * * @return bool */ @@ -291,16 +306,16 @@ class Admin extends \Api_Abstract { return $this->getService()->doBatchRemindersSend(); } - + /** * Calls due events on unpaid and approved invoices. - * Attach custom event hooks events: - * + * Attach custom event hooks events:. + * * onEventBeforeInvoiceIsDue - event receives params: id and days_left * onEventAfterInvoiceIsDue - event receives params: id and days_passed - * - * @optional bool $once_per_day - default true. Pass false if you want to execute this action more than once per day - * + * + * @optional bool $once_per_day - default true. Pass false if you want to execute this action more than once per day + * * @return bool - true if executed, false - if it was already executed */ public function batch_invoke_due_event($data) @@ -310,20 +325,22 @@ class Admin extends \Api_Abstract /** * Send payment reminder notification for client. - * Calls event hook, so you can attach your custom notification code + * Calls event hook, so you can attach your custom notification code. * * @param int $id - invoice id + * * @return bool */ public function send_reminder($data) { $invoice = $this->_getInvoice($data); + return $this->getService()->sendInvoiceReminder($invoice); } /** - * Return invoice statuses with counter - * + * Return invoice statuses with counter. + * * @return array */ public function get_statuses($data) @@ -332,41 +349,45 @@ class Admin extends \Api_Abstract } /** - * Process all received transactions - * + * Process all received transactions. + * * @return bool */ public function transaction_process_all($data) { $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->proccessReceivedATransactions(); } /** - * Process selected transaction + * Process selected transaction. + * * @param int $id - Transaction id - * + * * @return transaction output or true; */ public function transaction_process($data) { - $required = array( + $required = [ 'id' => 'Transaction id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found'); $output = null; - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminTransactionProcess', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminTransactionProcess', 'params' => ['id' => $model->id]]); $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); - return $transactionService->preProcessTransaction ($model); + + return $transactionService->preProcessTransaction($model); } - + /** - * Update transaction details + * Update transaction details. + * * @param int $id - transaction id * * @optional int $invoice_id - new invoice id @@ -384,87 +405,94 @@ class Admin extends \Api_Abstract */ public function transaction_update($data) { - $required = array( + $required = [ 'id' => 'Transaction id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found'); $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->update($model, $data); } /** - * Create custom transaction + * Create custom transaction. * * @param int $bb_invoice_id - BoxBilling invoice id * @param int $bb_gateway_id - BoxBilling gateway id - * + * * @optional array $get - $_GET data * @optional array $post - $_POST data * @optional array $server - $_SERVER data * @optional array $http_raw_post_data - file_get_contents("php://input") * @optional string $txn_id - transaction id on payment gateway * @optional bool $skip_validation - makes params bb_invoice_id and bb_gateway_id optional - * + * * @return int $id - new transaction id */ public function transaction_create($data) { $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->create($data); } /** - * Remove transaction + * Remove transaction. * * @param int $id - Transaction id + * * @return bool */ public function transaction_delete($data) { - $required = array( + $required = [ 'id' => 'Transaction id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found'); $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->delete($model); } /** - * Get transaction details + * Get transaction details. + * * @param int $id - Transaction id + * * @return array */ public function transaction_get($data) { - $required = array( + $required = [ 'id' => 'Transaction id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Transaction', $data['id'], 'Transaction not found'); $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->toApiArray($model, true); } /** - * Get paginated list of transactions - * + * Get paginated list of transactions. + * * @optional string $txn_id - search for transactions by transaction id on payment gateway - * + * * @return array */ public function transaction_get_list($data) { $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); - list ($sql, $params) = $transactionService->getSearchQuery($data); + [$sql, $params] = $transactionService->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $transaction = $this->di['db']->getExistingModelById('Transaction', $item['id'], 'Transaction not found'); + $transaction = $this->di['db']->getExistingModelById('Transaction', $item['id'], 'Transaction not found'); $pager['list'][$key] = $transactionService->toApiArray($transaction); } @@ -472,70 +500,79 @@ class Admin extends \Api_Abstract } /** - * Return transactions statuses with counter + * Return transactions statuses with counter. + * * @return array */ public function transaction_get_statuses($data) { $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->counter(); } /** - * Get available transaction statuses + * Get available transaction statuses. + * * @return array */ public function transaction_get_statuses_pairs($data) { $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->getStatusPairs(); } /** - * Get available transaction statuses + * Get available transaction statuses. + * * @return array */ public function transaction_statuses($data) { $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->getStatuses(); } /** - * Get available transaction statuses on gateways - * + * Get available transaction statuses on gateways. + * * @return array */ public function transaction_gateway_statuses($data) { $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->getGatewayStatuses(); } /** - * Get available transaction types + * Get available transaction types. + * * @return array */ public function transaction_types($data) { $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); + return $transactionService->getTypes(); } /** - * Get available gateways - * + * Get available gateways. + * * @return array */ public function gateway_get_list($data) { $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); - list ($sql, $params) = $gatewayService->getSearchQuery($data); + [$sql, $params] = $gatewayService->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $gateway = $this->di['db']->getExistingModelById('PayGateway', $item['id'], 'Gateway not found'); + $gateway = $this->di['db']->getExistingModelById('PayGateway', $item['id'], 'Gateway not found'); $pager['list'][$key] = $gatewayService->toApiArray($gateway, false, $this->getIdentity()); } @@ -543,84 +580,97 @@ class Admin extends \Api_Abstract } /** - * Get available gateways pairs + * Get available gateways pairs. + * * @return array */ public function gateway_get_pairs($data) { $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); + return $gatewayService->getPairs(); } /** - * Return existing module but not activated + * Return existing module but not activated. * * @param none + * * @return array */ public function gateway_get_available($data) { $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); + return $gatewayService->getAvailable(); } /** - * Install available payment gateway + * Install available payment gateway. + * * @param code - available payment gateway code + * * @return true */ public function gateway_install($data) { - $required = array( - 'code' => 'Payment gateway code is missing' - ); + $required = [ + 'code' => 'Payment gateway code is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $code = $data['code']; $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); + return $gatewayService->install($code); } /** - * Get gateway details - * + * Get gateway details. + * * @param int $id - gateway id + * * @return array - * @throws Box_Exception + * + * @throws Box_Exception */ public function gateway_get($data) { - $required = array( - 'id' => 'Gateway id not passed' - ); + $required = [ + 'id' => 'Gateway id not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found'); $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); + return $gatewayService->toApiArray($model, true, $this->getIdentity()); } /** - * Copy gateway from existing one - * + * Copy gateway from existing one. + * * @param int $id - id of gateway to be copied + * * @return int - new id of gateway - * @throws Box_Exception + * + * @throws Box_Exception */ public function gateway_copy($data) { - $required = array( - 'id' => 'Gateway id not passed' - ); + $required = [ + 'id' => 'Gateway id not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found'); $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); + return $gatewayService->copy($model); } /** - * Change gateway settings - * + * Change gateway settings. + * * @param int $id - gateway id * @optional string $title - gateway title * @optional array $config - gateway config array @@ -629,219 +679,235 @@ class Admin extends \Api_Abstract * @optional bool $allow_single - flag to enable or disable single payment option * @optional bool $allow_recurrent - flag to enable or disable recurrent payment option * @optional bool $test_mode - flag to enable or disable test mode for gateway - * - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function gateway_update($data) { - $required = array( - 'id' => 'Gateway id not passed' - ); + $required = [ + 'id' => 'Gateway id not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found'); $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); + return $gatewayService->update($model, $data); } /** - * Remove payment gateway from system - * + * Remove payment gateway from system. + * * @param int $id - gateway id - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function gateway_delete($data) { - $required = array( - 'id' => 'Gateway id not passed' - ); + $required = [ + 'id' => 'Gateway id not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('PayGateway', $data['id'], 'Gateway not found'); $gatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); + return $gatewayService->delete($model); } /** - * Get list of subscribtions - * + * Get list of subscribtions. + * * @return array */ public function subscription_get_list($data) { $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription'); - list ($sql, $params) = $subscriptionService->getSearchQuery($data); + [$sql, $params] = $subscriptionService->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $subscription = $this->di['db']->getExistingModelById('Subscription', $item['id'], 'Subscription not found'); + $subscription = $this->di['db']->getExistingModelById('Subscription', $item['id'], 'Subscription not found'); $pager['list'][$key] = $subscriptionService->toApiArray($subscription); } return $pager; } - + /** - * Add new subscription - * - * @param int $client_id - client id - * @param int $gateway_id - payment gateway id - * @param string $currency - currency - * + * Add new subscription. + * + * @param int $client_id - client id + * @param int $gateway_id - payment gateway id + * @param string $currency - currency + * * @optional string $sid - subscription id on payment gateway * @optional string $status - status: active|canceled * @optional string $period - example: 1W - every week, 2M - every 2 months * @optional string $amount - billed amount * @optional string $rel_type - related item type * @optional string $rel_id - related item id - * + * * @return int - id - * @throws Box_Exception + * + * @throws Box_Exception */ public function subscription_create($data) { - $required = array( - 'client_id' => 'Client id not passed', - 'gateway_id' => 'Payment gateway id not passed', - 'currency' => 'Subscription currency not passed' - ); + $required = [ + 'client_id' => 'Client id not passed', + 'gateway_id' => 'Payment gateway id not passed', + 'currency' => 'Subscription currency not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found'); $payGateway = $this->di['db']->getExistingModelById('PayGateway', $data['gateway_id'], 'Payment gateway not found'); - if($client->currency != $data['currency']) { + if ($client->currency != $data['currency']) { throw new \Box_Exception('Client currency must match subscription currency. Check if clients currency is defined.'); } $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription'); + return $subscriptionService->create($client, $payGateway, $data); } - + /** - * Update subscription options - * + * Update subscription options. + * * @param int $id - subscription id - * + * * @optional int $status - subscription status * @optional string $sid - subscription id on payment gateway * @optional string $period - subscription period code * @optional string $amount - subscription amount * @optional string $currency - subscription currency - * - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function subscription_update($data) { - $required = array( - 'id' => 'Subscription id not passed' - ); + $required = [ + 'id' => 'Subscription id not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Subscription', $data['id'], 'Subscription not found'); $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription'); + return $subscriptionService->update($model, $data); } - + /** * Get subscription details. - * - * @param int $id - subscription id + * + * @param int $id - subscription id * @param string $sid - subscription id on payment gateway - required if id is not passed - * + * * @return array - * @throws Box_Exception + * + * @throws Box_Exception */ public function subscription_get($data) { if (!isset($data['id']) && !isset($data['sid'])) { - $required = array( - 'id' => 'Subscription id not passed', + $required = [ + 'id' => 'Subscription id not passed', 'sid' => 'Subscription sid not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); } $model = null; - if(isset($data['id'])) { + if (isset($data['id'])) { $model = $this->di['db']->load('Subscription', $data['id']); } - - if(!$model && isset($data['sid'])) { - $model = $this->di['db']->findOne('Subscription', 'sid = ?', array($data['sid'])); + + if (!$model && isset($data['sid'])) { + $model = $this->di['db']->findOne('Subscription', 'sid = ?', [$data['sid']]); } - - if(!$model instanceof \Model_Subscription) { + + if (!$model instanceof \Model_Subscription) { throw new \Box_Exception('Subscription not found'); } $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription'); + return $subscriptionService->toApiArray($model, true, $this->getIdentity()); } /** - * Remove subscription - * + * Remove subscription. + * * @param int $id - subscription id - * - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function subscription_delete($data) { - $required = array( - 'id' => 'Subscription id not passed' - ); + $required = [ + 'id' => 'Subscription id not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Subscription', $data['id'], 'Subscription not found'); $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription'); + return $subscriptionService->delete($model); } /** - * Remove tax rule - * + * Remove tax rule. + * * @param int $id - tax id - * - * @return boolean + * + * @return bool + * * @throws \Box_Exception */ public function tax_delete($data) { - $required = array( - 'id' => 'Tax id is missing' - ); + $required = [ + 'id' => 'Tax id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Tax', $data['id'], 'Tax rule not found'); $taxService = $this->di['mod_service']('Invoice', 'Tax'); + return $taxService->delete($model); } /** - * Create new tax rule - * - * @param string $name - tax name - * @param float $taxrate - tax rate - * + * Create new tax rule. + * + * @param string $name - tax name + * @param float $taxrate - tax rate + * * @return int - new tax id */ public function tax_create($data) { - $required = array( + $required = [ 'name' => 'Tax name is missing', 'taxrate' => 'Tax rate is missing or is not valid', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $taxService = $this->di['mod_service']('Invoice', 'Tax'); + return $taxService->create($data); } /** - * Update tax rule + * Update tax rule. * * @param string $id - tax ID * @@ -849,34 +915,35 @@ class Admin extends \Api_Abstract */ public function tax_get($data) { - $required = array( - 'id' => 'Tax id is missing' - ); + $required = [ + 'id' => 'Tax id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $tax = $this->di['db']->getExistingModelById('Tax', $data['id'], 'Tax rule not found'); $taxService = $this->di['mod_service']('Invoice', 'Tax'); + return $taxService->toApiArray($tax); } /** - * Update tax rule + * Update tax rule. * - * @param int $id - tax ID - * @param string $name - tax name - * @param float $taxrate - tax rate + * @param int $id - tax ID + * @param string $name - tax name + * @param float $taxrate - tax rate * - * @return boolean + * @return bool */ public function tax_update($data) { - $required = array( + $required = [ 'id' => 'Tax id is missing', 'taxrate' => 'Tax rate is missing', - 'name' => 'Tax name is missing' - ); + 'name' => 'Tax name is missing', + ]; $tax = $this->di['db']->getExistingModelById('Tax', $data['id'], 'Tax rule not found'); @@ -887,38 +954,41 @@ class Admin extends \Api_Abstract } /** - * Get list of taxes - * + * Get list of taxes. + * * @return array */ public function tax_get_list($data) { $taxService = $this->di['mod_service']('Invoice', 'Tax'); - list ($sql, $params) = $taxService->getSearchQuery($data); + [$sql, $params] = $taxService->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + return $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); } - + /** * Automatically setup the EU VAT tax rules for you for all EU Member States. - * This action will delete any existing tax rules and configure the VAT rates + * This action will delete any existing tax rules and configure the VAT rates * for all EU countries. - * - * @param string $name - VAT label + * + * @param string $name - VAT label * @param string $taxrate - VAT rate - * @return type + * + * @return type */ public function tax_setup_eu($data) { $taxService = $this->di['mod_service']('Invoice', 'Tax'); + return $taxService->setupEUTaxes($data); } private function _getInvoice($data) { - $required = array( + $required = [ 'id' => 'Invoice id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Invoice', $data['id'], 'Invoice was not found'); @@ -927,7 +997,7 @@ class Admin extends \Api_Abstract } /** - * Deletes invoices with given IDs + * Deletes invoices with given IDs. * * @param array $ids - IDs for deletion * @@ -935,20 +1005,20 @@ class Admin extends \Api_Abstract */ public function batch_delete($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->delete(array('id' => $id)); + $this->delete(['id' => $id]); } return true; } /** - * Deletes subscriptions with given IDs + * Deletes subscriptions with given IDs. * * @param array $ids - IDs for deletion * @@ -956,20 +1026,20 @@ class Admin extends \Api_Abstract */ public function batch_delete_subscription($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->subscription_delete(array('id' => $id)); + $this->subscription_delete(['id' => $id]); } return true; } /** - * Deletes transactions with given IDs + * Deletes transactions with given IDs. * * @param array $ids - IDs for deletion * @@ -977,20 +1047,20 @@ class Admin extends \Api_Abstract */ public function batch_delete_transaction($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->transaction_delete(array('id' => $id)); + $this->transaction_delete(['id' => $id]); } return true; } /** - * Deletes taxes with given IDs + * Deletes taxes with given IDs. * * @param array $ids - IDs for deletion * @@ -998,15 +1068,15 @@ class Admin extends \Api_Abstract */ public function batch_delete_tax($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->tax_delete(array('id' => $id)); + $this->tax_delete(['id' => $id]); } return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Invoice/Api/Client.php b/src/bb-modules/Invoice/Api/Client.php index a33b65ce3..6153768fc 100644 --- a/src/bb-modules/Invoice/Api/Client.php +++ b/src/bb-modules/Invoice/Api/Client.php @@ -1,6 +1,6 @@ getIdentity()->id; - $data['approved'] = true; - list ($sql, $params) = $this->getService()->getSearchQuery($data); + $data['approved'] = true; + [$sql, $params] = $this->getService()->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getAdvancedResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $invoice = $this->di['db']->getExistingModelById('Invoice', $item['id'], 'Invoice not found'); + $invoice = $this->di['db']->getExistingModelById('Invoice', $item['id'], 'Invoice not found'); $pager['list'][$key] = $this->getService()->toApiArray($invoice); } @@ -39,85 +39,93 @@ class Client extends \Api_Abstract } /** - * Get invoice details - * + * Get invoice details. + * * @param string $hash - invoice hash + * * @return type - * @throws Exception + * + * @throws Exception */ public function get($data) { - $required = array( + $required = [ 'hash' => 'Invoice hash not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('Invoice', 'hash = :hash', array('hash'=>$data['hash'])); - if(!$model) { + $model = $this->di['db']->findOne('Invoice', 'hash = :hash', ['hash' => $data['hash']]); + if (!$model) { throw new \Box_Exception('Invoice was not found'); } + return $this->getService()->toApiArray($model, true, $this->getIdentity()); } - + /** * Update Invoice details. Only unpaid invoice details can be updated. - * + * * @param string $hash - invoice hash - * + * * @optional int $gateway_id - selected payment gateway id - * + * * @return bool - * @throws Exception + * + * @throws Exception */ public function update($data) { - $required = array( + $required = [ 'hash' => 'Invoice hash not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $invoice = $this->di['db']->findOne('Invoice', 'hash = :hash', array('hash'=>$data['hash'])); - if(!$invoice) { + $invoice = $this->di['db']->findOne('Invoice', 'hash = :hash', ['hash' => $data['hash']]); + if (!$invoice) { throw new \Box_Exception('Invoice was not found'); } - if($invoice->status == 'paid') { + if ('paid' == $invoice->status) { throw new \Box_Exception('Paid Invoice can not be modified'); } - $updateParams = array(); + $updateParams = []; $updateParams['gateway_id'] = $this->di['array_get']($data, 'gateway_id', null); + return $this->getService()->updateInvoice($invoice, $updateParams); } /** * Generates new invoice for selected order. If unpaid invoice for selected order * already exists, new invoice will not be generated, and old invoice hash - * is returned - * + * is returned. + * * @param int $order_id - ID of order to generate new invoice for + * * @return string - invoice hash + * * @throws Exception - * @throws LogicException + * @throws LogicException */ public function renewal_invoice($data) { - $required = array( + $required = [ 'order_id' => 'Order id required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('ClientOrder', 'client_id = ? and id = ?', array($this->getIdentity()->id, $data['order_id'])); - if(!$model instanceof \Model_ClientOrder) { + $model = $this->di['db']->findOne('ClientOrder', 'client_id = ? and id = ?', [$this->getIdentity()->id, $data['order_id']]); + if (!$model instanceof \Model_ClientOrder) { throw new \Box_Exception('Order not found'); } - if($model->price <= 0) { - throw new \Box_Exception('Order :id is free. No need to generate invoice.', array(':id'=>$model->id)); + if ($model->price <= 0) { + throw new \Box_Exception('Order :id is free. No need to generate invoice.', [':id' => $model->id]); } $service = $this->getService(); $invoice = $service->generateForOrder($model); - $service->approveInvoice($invoice, array('id'=>$invoice->id, 'use_credits'=>true)); + $service->approveInvoice($invoice, ['id' => $invoice->id, 'use_credits' => true]); $this->di['logger']->info('Generated new renewal invoice #%s', $invoice->id); + return $invoice->hash; } @@ -125,14 +133,15 @@ class Client extends \Api_Abstract * Deposit money in advance. Generates new invoice for depositing money. * Clients currency must be defined. * - * @param float $amount - amount to be deposited. + * @param float $amount - amount to be deposited + * * @return string - invoice hash */ public function funds_invoice($data) { - $required = array( + $required = [ 'amount' => 'Amount is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); @@ -142,27 +151,30 @@ class Client extends \Api_Abstract $service = $this->getService(); $invoice = $service->generateFundsInvoice($this->getIdentity(), $data['amount']); - $service->approveInvoice($invoice, array('id'=>$invoice->id)); + $service->approveInvoice($invoice, ['id' => $invoice->id]); $this->di['logger']->info('Generated add funds invoice #%s', $invoice->id); + return $invoice->hash; } /** * Client removes unpaid invoice. - * + * * @param string $hash - invoice hash - * @return boolean - * @throws Exception + * + * @return bool + * + * @throws Exception */ public function delete($data) { - $required = array( + $required = [ 'hash' => 'Invoice hash not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('Invoice', 'hash = :hash', array('hash'=>$data['hash'])); - if(!$model) { + $model = $this->di['db']->findOne('Invoice', 'hash = :hash', ['hash' => $data['hash']]); + if (!$model) { throw new \Box_Exception('Invoice was not found'); } @@ -171,26 +183,27 @@ class Client extends \Api_Abstract /** * Get paginated list of transactions. - * + * * @optional string $invoice_hash - filter transactions by invoice hash * @optional int $gateway_id - filter transactions by payment gateway id * @optional string $status - filter transactions by status * @optional string $currency - filter transactions by currency code * @optional string $date_from - filter transactions by date * @optional string $date_to - filter transactions by date - * @return type + * + * @return type */ public function transaction_get_list($data) { - $data['client_id'] = $this->getIdentity()->id; - $data['status'] = 'processed'; + $data['client_id'] = $this->getIdentity()->id; + $data['status'] = 'processed'; $transactionService = $this->di['mod_service']('Invoice', 'Transaction'); - list ($sql, $params) = $transactionService->getSearchQuery($data); + [$sql, $params] = $transactionService->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $transaction = $this->di['db']->getExistingModelById('Transaction', $item['id'], 'Transaction not found'); + $transaction = $this->di['db']->getExistingModelById('Transaction', $item['id'], 'Transaction not found'); $pager['list'][$key] = $transactionService->toApiArray($transaction); } @@ -200,6 +213,7 @@ class Client extends \Api_Abstract public function get_tax_rate() { $service = $this->di['mod_service']('Invoice', 'Tax'); + return $service->getTaxRateForClient($this->identity); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Invoice/Api/Guest.php b/src/bb-modules/Invoice/Api/Guest.php index e44f24c1a..2072ba602 100644 --- a/src/bb-modules/Invoice/Api/Guest.php +++ b/src/bb-modules/Invoice/Api/Guest.php @@ -1,6 +1,6 @@ 'Invoice hash not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('Invoice', 'hash = :hash', array('hash' => $data['hash'])); + $model = $this->di['db']->findOne('Invoice', 'hash = :hash', ['hash' => $data['hash']]); if (!$model) { throw new \Box_Exception('Invoice was not found'); } @@ -48,31 +50,32 @@ class Guest extends \Api_Abstract * @optional int $gateway_id - selected payment gateway id * * @return bool + * * @throws Exception */ public function update($data) { - $required = array( + $required = [ 'hash' => 'Invoice hash not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $invoice = $this->di['db']->findOne('Invoice', 'hash = :hash', array('hash' => $data['hash'])); + $invoice = $this->di['db']->findOne('Invoice', 'hash = :hash', ['hash' => $data['hash']]); if (!$invoice) { throw new \Box_Exception('Invoice was not found'); } - if ($invoice->status == 'paid') { + if ('paid' == $invoice->status) { throw new \Box_Exception('Paid Invoice can not be modified'); } - $updateParams = array(); + $updateParams = []; $updateParams['gateway_id'] = $this->di['array_get']($data, 'gateway_id', null); return $this->getService()->updateInvoice($invoice, $updateParams); } /** - * Get list of available payment gateways to pay for invoices + * Get list of available payment gateways to pay for invoices. * * @optional string $format - if format is "pairs" then id=>name values are returned * @@ -93,12 +96,13 @@ class Guest extends \Api_Abstract * Tries to detect if invoice can be subscribed and if payment gateway supports subscriptions * uses subscription payment. * - * @param string $hash - invoice hash - * @param int $gateway_id - payment gateway id + * @param string $hash - invoice hash + * @param int $gateway_id - payment gateway id * * @optional bool $auto_redirect - should payment adapter automatically redirect client or just print pay now button * * @return array + * * @throws Exception * @throws LogicException */ @@ -115,23 +119,20 @@ class Guest extends \Api_Abstract return $this->getService()->processInvoice($data); } - /** - * Generates PDF for given invoice + * Generates PDF for given invoice. * * @param string $hash - invoice hash * - * - * * @throws Exception */ public function pdf($data) { - $required = array( + $required = [ 'hash' => 'Invoice hash is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->generatePDF($data['hash'], $this->getIdentity()); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Invoice/Controller/Admin.php b/src/bb-modules/Invoice/Controller/Admin.php index c052daca8..ff715c7e1 100644 --- a/src/bb-modules/Invoice/Controller/Admin.php +++ b/src/bb-modules/Invoice/Controller/Admin.php @@ -1,6 +1,6 @@ array( - 'index' => 400, + return [ + 'group' => [ + 'index' => 400, 'location' => 'invoice', - 'label' => 'Invoices', - 'uri' => 'invoice', - 'class' => 'invoices', + 'label' => 'Invoices', + 'uri' => 'invoice', + 'class' => 'invoices', 'sprite_class' => 'dark-sprite-icon sprite-money', - ), - 'subpages' => array( - array( + ], + 'subpages' => [ + [ 'location' => 'invoice', 'label' => 'Overview', 'uri' => $this->di['url']->adminLink('invoice'), - 'index' => 100, - 'class' => '', - ), - array( + 'index' => 100, + 'class' => '', + ], + [ 'location' => 'invoice', 'label' => 'Advanced search', - 'uri' => $this->di['url']->adminLink('invoice', array('show_filter' => 1)), - 'index' => 200, - 'class' => '', - ), - array( + 'uri' => $this->di['url']->adminLink('invoice', ['show_filter' => 1]), + 'index' => 200, + 'class' => '', + ], + [ 'location' => 'invoice', 'label' => 'Subscriptions', 'uri' => $this->di['url']->adminLink('invoice/subscriptions'), - 'index' => 300, - 'class' => '', - ), - array( + 'index' => 300, + 'class' => '', + ], + [ 'location' => 'invoice', 'label' => 'Transactions overview', 'uri' => $this->di['url']->adminLink('invoice/transactions'), - 'index' => 400, - 'class' => '', - ), - array( + 'index' => 400, + 'class' => '', + ], + [ 'location' => 'invoice', 'label' => 'Transactions search', - 'uri' => $this->di['url']->adminLink('invoice/transactions', array('show_filter' => 1)), - 'index' => 500, - 'class' => '', - ), - array( + 'uri' => $this->di['url']->adminLink('invoice/transactions', ['show_filter' => 1]), + 'index' => 500, + 'class' => '', + ], + [ 'location' => 'system', 'label' => 'Tax rules', 'uri' => $this->di['url']->adminLink('invoice/tax'), - 'index' => 180, - 'class' => '', - ), - array( + 'index' => 180, + 'class' => '', + ], + [ 'location' => 'system', 'label' => 'Payment gateways', 'uri' => $this->di['url']->adminLink('invoice/gateways'), - 'index' => 160, - 'class' => '', - ), - ), - ); + 'index' => 160, + 'class' => '', + ], + ], + ]; } public function register(\Box_App &$app) { - $app->get('/invoice', 'get_index', array(), get_class($this)); - $app->get('/invoice/subscriptions', 'get_subscriptions', array(), get_class($this)); - $app->get('/invoice/transactions', 'get_transactions', array(), get_class($this)); - $app->get('/invoice/gateways', 'get_gateways', array(), get_class($this)); - $app->get('/invoice/gateway/:id', 'get_gateway', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/invoice/manage/:id','get_invoice', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/invoice/transaction/:id','get_transaction', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/invoice/subscription/:id','get_subscription', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/invoice/tax', 'get_taxes', array(), get_class($this)); - $app->get('/invoice/tax/:id', 'get_tax', array(), get_class($this)); - $app->get('/invoice/pdf/:hash', 'get_pdf', array('hash'=>'[a-z0-9]+'), get_class($this)); + $app->get('/invoice', 'get_index', [], get_class($this)); + $app->get('/invoice/subscriptions', 'get_subscriptions', [], get_class($this)); + $app->get('/invoice/transactions', 'get_transactions', [], get_class($this)); + $app->get('/invoice/gateways', 'get_gateways', [], get_class($this)); + $app->get('/invoice/gateway/:id', 'get_gateway', ['id' => '[0-9]+'], get_class($this)); + $app->get('/invoice/manage/:id', 'get_invoice', ['id' => '[0-9]+'], get_class($this)); + $app->get('/invoice/transaction/:id', 'get_transaction', ['id' => '[0-9]+'], get_class($this)); + $app->get('/invoice/subscription/:id', 'get_subscription', ['id' => '[0-9]+'], get_class($this)); + $app->get('/invoice/tax', 'get_taxes', [], get_class($this)); + $app->get('/invoice/tax/:id', 'get_tax', [], get_class($this)); + $app->get('/invoice/pdf/:hash', 'get_pdf', ['hash' => '[a-z0-9]+'], get_class($this)); } public function get_taxes(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_invoice_tax'); } public function get_tax(\Box_App $app, $id) { $api = $this->di['api_admin']; - $tax = $api->invoice_tax_get(array('id' => $id)); + $tax = $api->invoice_tax_get(['id' => $id]); - return $app->render('mod_invoice_taxupdate', array('tax' => $tax)); + return $app->render('mod_invoice_taxupdate', ['tax' => $tax]); } - + public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_invoice_index'); } - + public function get_invoice(\Box_App $app, $id) { $api = $this->di['api_admin']; - $invoice = $api->invoice_get(array('id'=>$id)); - return $app->render('mod_invoice_invoice', array('invoice'=>$invoice)); + $invoice = $api->invoice_get(['id' => $id]); + + return $app->render('mod_invoice_invoice', ['invoice' => $invoice]); } public function get_transaction(\Box_App $app, $id) { $api = $this->di['api_admin']; - $tx = $api->invoice_transaction_get(array('id'=>$id)); - return $app->render('mod_invoice_transaction', array('transaction'=>$tx)); + $tx = $api->invoice_transaction_get(['id' => $id]); + + return $app->render('mod_invoice_transaction', ['transaction' => $tx]); } public function get_transactions(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_invoice_transactions'); } - + public function get_subscriptions(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_invoice_subscriptions'); } public function get_subscription(\Box_App $app, $id) { $api = $this->di['api_admin']; - $tx = $api->invoice_subscription_get(array('id'=>$id)); - return $app->render('mod_invoice_subscription', array('subscription'=>$tx)); + $tx = $api->invoice_subscription_get(['id' => $id]); + + return $app->render('mod_invoice_subscription', ['subscription' => $tx]); } public function get_gateways(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_invoice_gateways'); } public function get_gateway(\Box_App $app, $id) { $api = $this->di['api_admin']; - $gateway = $api->invoice_gateway_get(array('id'=>$id)); - return $app->render('mod_invoice_gateway', array('gateway'=>$gateway)); + $gateway = $api->invoice_gateway_get(['id' => $id]); + + return $app->render('mod_invoice_gateway', ['gateway' => $gateway]); } - public function get_pdf (\Box_App $app, $hash) + public function get_pdf(\Box_App $app, $hash) { $api = $this->di['api_guest']; - $data = array( + $data = [ 'hash' => $hash, - ); + ]; $invoice = $api->invoice_pdf($data); - return $app->render('mod_invoice_pdf', array('invoice'=>$invoice)); - } -} \ No newline at end of file + return $app->render('mod_invoice_pdf', ['invoice' => $invoice]); + } +} diff --git a/src/bb-modules/Invoice/Controller/Client.php b/src/bb-modules/Invoice/Controller/Client.php index 8b23794d6..d9ef33d09 100644 --- a/src/bb-modules/Invoice/Controller/Client.php +++ b/src/bb-modules/Invoice/Controller/Client.php @@ -1,6 +1,6 @@ get('/invoice', 'get_invoices', array(), get_class($this)); - $app->post('/invoice', 'get_invoices', array(), get_class($this)); - $app->get('/invoice/:hash', 'get_invoice', array('hash'=>'[a-z0-9]+'), get_class($this)); - $app->post('/invoice/:hash', 'get_invoice', array('hash'=>'[a-z0-9]+'), get_class($this)); - $app->get('/invoice/print/:hash', 'get_invoice_print', array('hash'=>'[a-z0-9]+'), get_class($this)); - $app->post('/invoice/print/:hash', 'get_invoice_print', array('hash'=>'[a-z0-9]+'), get_class($this)); - $app->get('/invoice/banklink/:hash/:id', 'get_banklink', array('id'=>'[0-9]+', 'hash'=>'[a-z0-9]+'), get_class($this)); - $app->get('/invoice/thank-you/:hash', 'get_thankyoupage', array('hash'=>'[a-z0-9]+'), get_class($this)); - $app->get('/invoice/pdf/:hash', 'get_pdf', array('hash'=>'[a-z0-9]+'), get_class($this)); + $app->get('/invoice', 'get_invoices', [], get_class($this)); + $app->post('/invoice', 'get_invoices', [], get_class($this)); + $app->get('/invoice/:hash', 'get_invoice', ['hash' => '[a-z0-9]+'], get_class($this)); + $app->post('/invoice/:hash', 'get_invoice', ['hash' => '[a-z0-9]+'], get_class($this)); + $app->get('/invoice/print/:hash', 'get_invoice_print', ['hash' => '[a-z0-9]+'], get_class($this)); + $app->post('/invoice/print/:hash', 'get_invoice_print', ['hash' => '[a-z0-9]+'], get_class($this)); + $app->get('/invoice/banklink/:hash/:id', 'get_banklink', ['id' => '[0-9]+', 'hash' => '[a-z0-9]+'], get_class($this)); + $app->get('/invoice/thank-you/:hash', 'get_thankyoupage', ['hash' => '[a-z0-9]+'], get_class($this)); + $app->get('/invoice/pdf/:hash', 'get_pdf', ['hash' => '[a-z0-9]+'], get_class($this)); } public function get_invoices(\Box_App $app) { $this->di['is_client_logged']; + return $app->render('mod_invoice_index'); } public function get_invoice(\Box_App $app, $hash) { $api = $this->di['api_guest']; - $data = array( + $data = [ 'hash' => $hash, - ); + ]; $invoice = $api->invoice_get($data); - return $app->render('mod_invoice_invoice', array('invoice'=>$invoice)); + + return $app->render('mod_invoice_invoice', ['invoice' => $invoice]); } public function get_invoice_print(\Box_App $app, $hash) { $api = $this->di['api_guest']; - $data = array( + $data = [ 'hash' => $hash, - ); + ]; $invoice = $api->invoice_get($data); - return $app->render('mod_invoice_print', array('invoice'=>$invoice)); + + return $app->render('mod_invoice_print', ['invoice' => $invoice]); } public function get_thankyoupage(\Box_App $app, $hash) { $api = $this->di['api_guest']; - $data = array( + $data = [ 'hash' => $hash, - ); + ]; $invoice = $api->invoice_get($data); - return $app->render('mod_invoice_thankyou', array('invoice'=>$invoice)); + + return $app->render('mod_invoice_thankyou', ['invoice' => $invoice]); } - + public function get_banklink(\Box_App $app, $hash, $id) { $api = $this->di['api_guest']; - $data = array( - 'subscription' => $this->di['request']->getQuery('subscription'), - 'hash' => $hash, - 'gateway_id' => $id, - 'auto_redirect' => true, - ); + $data = [ + 'subscription' => $this->di['request']->getQuery('subscription'), + 'hash' => $hash, + 'gateway_id' => $id, + 'auto_redirect' => true, + ]; $invoice = $api->invoice_get($data); $result = $api->invoice_payment($data); - return $app->render('mod_invoice_banklink', array('payment'=>$result, 'invoice'=>$invoice)); + + return $app->render('mod_invoice_banklink', ['payment' => $result, 'invoice' => $invoice]); } - public function get_pdf (\Box_App $app, $hash) + public function get_pdf(\Box_App $app, $hash) { $api = $this->di['api_guest']; - $data = array( + $data = [ 'hash' => $hash, - ); + ]; $invoice = $api->invoice_pdf($data); - return $app->render('mod_invoice_pdf', array('invoice'=>$invoice)); + + return $app->render('mod_invoice_pdf', ['invoice' => $invoice]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Invoice/Service.php b/src/bb-modules/Invoice/Service.php index 64f4b4b26..e661e0df7 100644 --- a/src/bb-modules/Invoice/Service.php +++ b/src/bb-modules/Invoice/Service.php @@ -1,6 +1,6 @@ di['array_get']($data, 'search', NULL); - $order_id = $this->di['array_get']($data, 'order_id', NULL); - $id = $this->di['array_get']($data, 'id', NULL); - $id_nr = $this->di['array_get']($data, 'nr', NULL); - $client_id = $this->di['array_get']($data, 'client_id', NULL); - $client = $this->di['array_get']($data, 'client', NULL); - $created_at = $this->di['array_get']($data, 'created_at', NULL); - $date_from = $this->di['array_get']($data, 'date_from', NULL); - $date_to = $this->di['array_get']($data, 'date_to', NULL); - $paid_at = $this->di['array_get']($data, 'paid_at', NULL); - $status = $this->di['array_get']($data, 'status', NULL); - $approved = $this->di['array_get']($data, 'approved', NULL); - $currency = $this->di['array_get']($data, 'currency', NULL); - - if($order_id) { + $search = $this->di['array_get']($data, 'search', null); + $order_id = $this->di['array_get']($data, 'order_id', null); + $id = $this->di['array_get']($data, 'id', null); + $id_nr = $this->di['array_get']($data, 'nr', null); + $client_id = $this->di['array_get']($data, 'client_id', null); + $client = $this->di['array_get']($data, 'client', null); + $created_at = $this->di['array_get']($data, 'created_at', null); + $date_from = $this->di['array_get']($data, 'date_from', null); + $date_to = $this->di['array_get']($data, 'date_to', null); + $paid_at = $this->di['array_get']($data, 'paid_at', null); + $status = $this->di['array_get']($data, 'status', null); + $approved = $this->di['array_get']($data, 'approved', null); + $currency = $this->di['array_get']($data, 'currency', null); + + if ($order_id) { $sql .= ' AND pi.type = :item_type AND pi.rel_id = :order_id'; $params['item_type'] = \Model_InvoiceItem::TYPE_ORDER; $params['order_id'] = $order_id; } - - if($id) { + + if ($id) { $sql .= ' AND p.id = :id'; $params['id'] = $id; } - - if($id_nr) { + + if ($id_nr) { $sql .= ' AND (p.id = :id_nr OR p.nr = :id_nr)'; $params['id_nr'] = $id_nr; } - - if($approved) { + + if ($approved) { $sql .= ' AND p.approved = :approved'; $params['approved'] = $approved; } - - if($status) { + + if ($status) { $sql .= ' AND p.status = :status'; $params['status'] = $status; } - - if($currency) { + + if ($currency) { $sql .= ' AND p.currency = :currency'; $params['currency'] = $currency; } - - if(NULL !== $client_id) { + + if (null !== $client_id) { $sql .= ' AND p.client_id = :client_id'; $params['client_id'] = $client_id; } - - if(NULL !== $client) { + + if (null !== $client) { $sql .= ' AND (cl.first_name LIKE :client_search OR cl.last_name LIKE :client_search OR cl.id = :client OR cl.email = :client)'; $params['client_search'] = $client.'%'; $params['client'] = $client; } - - if($created_at) { + + if ($created_at) { $sql .= " AND DATE_FORMAT(p.created_at, '%Y-%m-%d') = :created_at"; $params['created_at'] = date('Y-m-d', strtotime($created_at)); } - - if($date_from) { - $sql .= " AND UNIX_TIMESTAMP(p.created_at) >= :date_from"; + + if ($date_from) { + $sql .= ' AND UNIX_TIMESTAMP(p.created_at) >= :date_from'; $params['date_from'] = strtotime($date_from); } - - if($date_to) { - $sql .= " AND UNIX_TIMESTAMP(p.created_at) <= :date_to"; + + if ($date_to) { + $sql .= ' AND UNIX_TIMESTAMP(p.created_at) <= :date_to'; $params['date_to'] = strtotime($date_to); } - - if($paid_at) { + + if ($paid_at) { $sql .= " AND DATE_FORMAT(p.paid_at, '%Y-%m-%d') = :paid_at"; $params['paid_at'] = date('Y-m-d', strtotime($paid_at)); } - if($search) { - $sql .= " AND (p.id = :int OR p.nr LIKE :search_like OR p.id LIKE :search OR pi.title LIKE :search_like)"; - $params['int'] = (int)preg_replace("/[^0-9]/","",$search); + if ($search) { + $sql .= ' AND (p.id = :int OR p.nr LIKE :search_like OR p.id LIKE :search OR pi.title LIKE :search_like)'; + $params['int'] = (int) preg_replace('/[^0-9]/', '', $search); $params['search_like'] = '%'.$search.'%'; $params['search'] = $search; } - + $sql .= ' GROUP BY p.id ORDER BY p.id DESC'; - return array($sql, $params); + + return [$sql, $params]; } public function toApiArray(\Model_Invoice $invoice, $deep = true, $identity = null) { $row = $this->di['db']->toArray($invoice); - - $items = $this->di['db']->find('InvoiceItem', 'invoice_id = :iid', array('iid'=>$row['id'])); - - $lines = array(); + + $items = $this->di['db']->find('InvoiceItem', 'invoice_id = :iid', ['iid' => $row['id']]); + + $lines = []; $total = $tax_total = 0; $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); - foreach($items as $item) { - $order_id = ($item->type == \Model_InvoiceItem::TYPE_ORDER) ? $item->rel_id : null; - - $line_total = $item->price * $item->quantity; - $total += $line_total; + foreach ($items as $item) { + $order_id = (\Model_InvoiceItem::TYPE_ORDER == $item->type) ? $item->rel_id : null; + + $line_total = $item->price * $item->quantity; + $total += $line_total; $line_tax = $invoiceItemService->getTax($item) * $item->quantity; $tax_total += $line_tax; - $line = array( - 'id' => $item->id, - 'title' => $item->title, - 'period' => $item->period, - 'quantity' => $item->quantity, - 'unit' => $item->unit, - 'price' => $item->price, - 'tax' => $line_tax, - 'taxed' => $item->taxed, - 'charged' => $item->charged, - 'total' => $line_total, - 'order_id' => $order_id, - 'type' => $item->type, - 'rel_id' => $item->rel_id, - 'task' => $item->task, - 'status' => $item->status, - ); + $line = [ + 'id' => $item->id, + 'title' => $item->title, + 'period' => $item->period, + 'quantity' => $item->quantity, + 'unit' => $item->unit, + 'price' => $item->price, + 'tax' => $line_tax, + 'taxed' => $item->taxed, + 'charged' => $item->charged, + 'total' => $line_total, + 'order_id' => $order_id, + 'type' => $item->type, + 'rel_id' => $item->rel_id, + 'task' => $item->task, + 'status' => $item->status, + ]; $lines[] = $line; } $tax = $tax_total; - $result = array(); + $result = []; $result['id'] = $row['id']; $result['serie'] = $row['serie']; $result['nr'] = $row['nr']; $nr = (is_numeric($result['nr'])) ? $result['nr'] : $result['id']; - $result['serie_nr'] = $result['serie'] . sprintf('%05s', $nr); + $result['serie_nr'] = $result['serie'].sprintf('%05s', $nr); $result['hash'] = $row['hash']; $result['gateway_id'] = $row['gateway_id']; @@ -196,68 +197,68 @@ class Service implements InjectionAwareInterface $result['paid_at'] = $row['paid_at']; $result['created_at'] = $row['created_at']; $result['updated_at'] = $row['updated_at']; - $result['lines'] = $lines; - - $result['buyer'] = array( - 'first_name'=> $row['buyer_first_name'], + $result['lines'] = $lines; + + $result['buyer'] = [ + 'first_name' => $row['buyer_first_name'], 'last_name' => $row['buyer_last_name'], - 'company' => $row['buyer_company'], + 'company' => $row['buyer_company'], 'company_vat' => $row['buyer_company_vat'], 'company_number' => $row['buyer_company_number'], - 'address' => $row['buyer_address'], - 'city' => $row['buyer_city'], - 'state' => $row['buyer_state'], - 'country' => $row['buyer_country'], - 'phone' => $row['buyer_phone'], - 'phone_cc' => $row['buyer_phone_cc'], - 'email' => $row['buyer_email'], - 'zip' => $row['buyer_zip'], - ); + 'address' => $row['buyer_address'], + 'city' => $row['buyer_city'], + 'state' => $row['buyer_state'], + 'country' => $row['buyer_country'], + 'phone' => $row['buyer_phone'], + 'phone_cc' => $row['buyer_phone_cc'], + 'email' => $row['buyer_email'], + 'zip' => $row['buyer_zip'], + ]; $systemService = $this->di['mod_service']('system'); $c = $systemService->getCompany(); - $result['seller'] = array( - 'company' => !empty($row['seller_company']) ? $row['seller_company'] : $c['name'], - 'company_vat'=> $row['seller_company_vat'], - 'company_number'=> $row['seller_company_number'], - 'address' => !empty($row['seller_address']) ? $row['seller_address'] : trim($c['address_1'] .' '. $c['address_2'] .' '. $c['address_2']), - 'phone' => !empty($row['seller_phone']) ? $row['seller_phone'] : $c['tel'], - 'email' => !empty($row['seller_email']) ? $row['seller_email'] : $c['email'], + $result['seller'] = [ + 'company' => !empty($row['seller_company']) ? $row['seller_company'] : $c['name'], + 'company_vat' => $row['seller_company_vat'], + 'company_number' => $row['seller_company_number'], + 'address' => !empty($row['seller_address']) ? $row['seller_address'] : trim($c['address_1'].' '.$c['address_2'].' '.$c['address_2']), + 'phone' => !empty($row['seller_phone']) ? $row['seller_phone'] : $c['tel'], + 'email' => !empty($row['seller_email']) ? $row['seller_email'] : $c['email'], 'account_number' => !empty($c['account_number']) ? $c['account_number'] : null, - ); + ]; - /** - * Removed if($identity instanceof \Model_Admin) {} - * Generates error when this function is called by cron - */ - $client = $this->di['db']->load('Client', $row['client_id']); - $clientService = $this->di['mod_service']('client'); - if($client instanceof \Model_Client) { - $result['client'] = $clientService->toApiArray($client); - } else { - $result['client'] = null; - } - $result['reminded_at'] = $row['reminded_at']; - $result['approved'] = (bool)$row['approved']; - $result['income'] = $row['base_income'] - $row['base_refund']; - $result['refund'] = $row['refund']; - $result['credit'] = $row['credit']; + /** + * Removed if($identity instanceof \Model_Admin) {} + * Generates error when this function is called by cron. + */ + $client = $this->di['db']->load('Client', $row['client_id']); + $clientService = $this->di['mod_service']('client'); + if ($client instanceof \Model_Client) { + $result['client'] = $clientService->toApiArray($client); + } else { + $result['client'] = null; + } + $result['reminded_at'] = $row['reminded_at']; + $result['approved'] = (bool) $row['approved']; + $result['income'] = $row['base_income'] - $row['base_refund']; + $result['refund'] = $row['refund']; + $result['credit'] = $row['credit']; $subscriptionService = $this->di['mod_service']('Invoice', 'Subscription'); $result['subscribable'] = $subscriptionService->isSubscribable($row['id']); - if($deep && $result['subscribable']) { - $ip = $this->di['db']->getCell('SELECT period FROM invoice_item WHERE invoice_id = :id', array('id'=>$row['id'])); + if ($deep && $result['subscribable']) { + $ip = $this->di['db']->getCell('SELECT period FROM invoice_item WHERE invoice_id = :id', ['id' => $row['id']]); $period = $this->di['period']($ip); - $result['subscription'] = array( - 'unit' => $period->getUnit(), - 'cycle' => $period->getQty(), - 'period' => $ip, - ); + $result['subscription'] = [ + 'unit' => $period->getUnit(), + 'cycle' => $period->getQty(), + 'period' => $ip, + ]; } - + return $result; } - + public static function onAfterAdminInvoicePaymentReceived(\Box_Event $event) { $params = $event->getParameters(); @@ -266,22 +267,22 @@ class Service implements InjectionAwareInterface try { $invoiceModel = $di['db']->load('Invoice', $params['id']); - $invoice = $service->toApiArray($invoiceModel, array('id' =>$params['id'])); - if($invoice['total'] > 0) { - $email = array(); + $invoice = $service->toApiArray($invoiceModel, ['id' => $params['id']]); + if ($invoice['total'] > 0) { + $email = []; $email['to_client'] = $invoiceModel->client_id; - $email['code'] = 'mod_invoice_paid'; - $email['invoice'] = $invoice; + $email['code'] = 'mod_invoice_paid'; + $email['invoice'] = $invoice; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } - + return true; } - + public static function onAfterAdminInvoiceApprove(\Box_Event $event) { $params = $event->getParameters(); @@ -290,17 +291,17 @@ class Service implements InjectionAwareInterface try { $invoiceModel = $di['db']->load('Invoice', $params['id']); - $invoice = $service->toApiArray($invoiceModel, array('id' =>$params['id'])); - $email = array(); + $invoice = $service->toApiArray($invoiceModel, ['id' => $params['id']]); + $email = []; $email['to_client'] = $invoiceModel->client_id; - $email['code'] = 'mod_invoice_created'; - $email['invoice'] = $invoice; + $email['code'] = 'mod_invoice_created'; + $email['invoice'] = $invoice; $emailService = $di['mod_service']('Email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } - + return true; } @@ -312,14 +313,14 @@ class Service implements InjectionAwareInterface try { $invoiceModel = $di['db']->load('Invoice', $params['id']); - $invoice = $service->toApiArray($invoiceModel, array('id' =>$params['id'])); - $email = array(); + $invoice = $service->toApiArray($invoiceModel, ['id' => $params['id']]); + $email = []; $email['to_client'] = $invoiceModel->client_id; - $email['code'] = 'mod_invoice_payment_reminder'; - $email['invoice'] = $invoice; + $email['code'] = 'mod_invoice_payment_reminder'; + $email['invoice'] = $invoice; $emailService = $di['mod_service']('Email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } @@ -329,10 +330,10 @@ class Service implements InjectionAwareInterface $di = $event->getDi(); $systemService = $di['mod_service']('System'); $remove_after_days = $systemService->getParamValue('remove_after_days'); - if(isset($remove_after_days) && $remove_after_days) { - //removing old invoices - $days = (int)$remove_after_days; - $sql="DELETE FROM invoice WHERE status = 'unpaid' AND DATEDIFF(NOW(), due_at) > $days"; + if (isset($remove_after_days) && $remove_after_days) { + // removing old invoices + $days = (int) $remove_after_days; + $sql = "DELETE FROM invoice WHERE status = 'unpaid' AND DATEDIFF(NOW(), due_at) > $days"; $di['db']->exec($sql); } } @@ -343,67 +344,67 @@ class Service implements InjectionAwareInterface $di = $event->getDi(); $service = $di['mod_service']('invoice'); - //send reminder once a day when 5 days has passed - if($params['days_passed'] != 5) { + // send reminder once a day when 5 days has passed + if (5 != $params['days_passed']) { return; } - + try { $invoiceModel = $di['db']->load('Invoice', $params['id']); - $invoice = $service->toApiArray($invoiceModel, array('id' =>$params['id'])); - $email = array(); + $invoice = $service->toApiArray($invoiceModel, ['id' => $params['id']]); + $email = []; $email['to_client'] = $invoice['client']['id']; - $email['code'] = 'mod_invoice_due_after'; - $email['days_passed']= $params['days_passed']; - $email['invoice'] = $invoice; + $email['code'] = 'mod_invoice_due_after'; + $email['days_passed'] = $params['days_passed']; + $email['invoice'] = $invoice; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } - public function markAsPaid(\Model_Invoice $invoice, $charge = TRUE, $execute = false) + public function markAsPaid(\Model_Invoice $invoice, $charge = true, $execute = false) { - if($invoice->status == \Model_Invoice::STATUS_PAID) { - return TRUE; + if (\Model_Invoice::STATUS_PAID == $invoice->status) { + return true; } - $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', array($invoice->id)); + $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$invoice->id]); $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); - foreach($invoiceItems as $item) { + foreach ($invoiceItems as $item) { $invoiceItemService->markAsPaid($item, $charge); } $systemService = $this->di['mod_service']('system'); $ctable = $this->di['mod_service']('Currency'); - $invoice->serie = $systemService->getParamValue('invoice_series_paid'); - $invoice->nr = $this->getNextInvoiceNumber($invoice); - $invoice->approved = TRUE; + $invoice->serie = $systemService->getParamValue('invoice_series_paid'); + $invoice->nr = $this->getNextInvoiceNumber($invoice); + $invoice->approved = true; $invoice->currency_rate = $ctable->getRateByCode($invoice->currency); - $invoice->status = \Model_Invoice::STATUS_PAID; - $invoice->paid_at = date('Y-m-d H:i:s'); - $invoice->updated_at = date('Y-m-d H:i:s'); + $invoice->status = \Model_Invoice::STATUS_PAID; + $invoice->paid_at = date('Y-m-d H:i:s'); + $invoice->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($invoice); $this->countIncome($invoice); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminInvoicePaymentReceived', 'params'=>array('id'=>$invoice->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminInvoicePaymentReceived', 'params' => ['id' => $invoice->id]]); - if($execute) { - - foreach($invoiceItems as $item) { + if ($execute) { + foreach ($invoiceItems as $item) { try { $invoiceItemService->executeTask($item); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e); } } } $this->di['logger']->info('Marked invoice "%s" as paid', $invoice->id); + return true; } @@ -412,17 +413,18 @@ class Service implements InjectionAwareInterface $p = 'invoice_starting_number'; $systemService = $this->di['mod_service']('system'); $next_nr = $systemService->getParamValue($p); - if(empty($next_nr)) { + if (empty($next_nr)) { $next_nr = $model->id; - //get last invoice number + // get last invoice number $r = $this->di['db']->findOne('Invoice', 'nr is not null order by id desc'); - if($r instanceof \Model_Invoice && is_numeric($r->nr)) { + if ($r instanceof \Model_Invoice && is_numeric($r->nr)) { $next_nr = $r->nr + 1; } } - $systemService->setParamValue($p, $next_nr+1); + $systemService->setParamValue($p, $next_nr + 1); + return $next_nr; } @@ -437,7 +439,7 @@ class Service implements InjectionAwareInterface public function prepareInvoice(\Model_Client $client, array $data) { - if(!$client->currency) { + if (!$client->currency) { $currencyService = $this->di['mod_service']('Currency'); $currency = $currencyService->getDefault(); $client->currency = $currency->code; @@ -460,20 +462,20 @@ class Service implements InjectionAwareInterface $this->setInvoiceDefaults($model); - if(isset($data['items']) && is_array($data['items'])) { + if (isset($data['items']) && is_array($data['items'])) { $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); - foreach($data['items'] as $d) { + foreach ($data['items'] as $d) { $invoiceItemService->addNew($model, $d); } } $this->di['logger']->info('Prepared new invoice "%s"', $invoiceId); - if(isset($data['approve']) && $data['approve']) { + if (isset($data['approve']) && $data['approve']) { try { - $this->approveInvoice($model, array('id'=>$invoiceId)); + $this->approveInvoice($model, ['id' => $invoiceId]); $this->di['logger']->info('Approved invoice %s instantly', $invoiceId); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); } } @@ -490,32 +492,31 @@ class Service implements InjectionAwareInterface $buyer = $clientService->toApiArray($client); - $model->seller_company = $seller['name']; - $model->seller_company_vat = $seller['vat_number']; - $model->seller_company_number = $seller['number']; - $model->seller_address = trim($seller['address_1'] .' '. $seller['address_2'] .' '. $seller['address_3']); - $model->seller_phone = $seller['tel']; - $model->seller_email = $seller['email']; - - $model->buyer_first_name = $buyer['first_name']; - $model->buyer_last_name = $buyer['last_name']; - $model->buyer_company = $buyer['company']; - $model->buyer_company_vat = $buyer['company_vat']; - $model->buyer_company_number = $buyer['company_number']; - $model->buyer_address = $buyer['address_1'] .' '. $buyer['address_2']; - $model->buyer_city = $buyer['city']; - $model->buyer_state = $buyer['state']; - $model->buyer_country = $buyer['country']; - $model->buyer_phone = $buyer['phone_cc'] .' '.$buyer['phone']; - $model->buyer_email = $buyer['email']; - $model->buyer_zip = $buyer['postcode']; + $model->seller_company = $seller['name']; + $model->seller_company_vat = $seller['vat_number']; + $model->seller_company_number = $seller['number']; + $model->seller_address = trim($seller['address_1'].' '.$seller['address_2'].' '.$seller['address_3']); + $model->seller_phone = $seller['tel']; + $model->seller_email = $seller['email']; + $model->buyer_first_name = $buyer['first_name']; + $model->buyer_last_name = $buyer['last_name']; + $model->buyer_company = $buyer['company']; + $model->buyer_company_vat = $buyer['company_vat']; + $model->buyer_company_number = $buyer['company_number']; + $model->buyer_address = $buyer['address_1'].' '.$buyer['address_2']; + $model->buyer_city = $buyer['city']; + $model->buyer_state = $buyer['state']; + $model->buyer_country = $buyer['country']; + $model->buyer_phone = $buyer['phone_cc'].' '.$buyer['phone']; + $model->buyer_email = $buyer['email']; + $model->buyer_zip = $buyer['postcode']; $invoice_due_days = $systemService->getParamValue('invoice_due_days'); if (!is_numeric($invoice_due_days)) { $invoice_due_days = 1; } - $due_time = strtotime('+' . $invoice_due_days . ' day'); + $due_time = strtotime('+'.$invoice_due_days.' day'); $model->due_at = date('Y-m-d H:i:s', $due_time); $model->serie = $systemService->getParamValue('invoice_series'); @@ -533,29 +534,30 @@ class Service implements InjectionAwareInterface public function approveInvoice(\Model_Invoice $invoice, array $data) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminInvoiceApprove', 'params'=>array('id'=>$invoice->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminInvoiceApprove', 'params' => ['id' => $invoice->id]]); $invoice->approved = 1; $invoice->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($invoice); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminInvoiceApprove', 'params'=>array('id'=>$invoice->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminInvoiceApprove', 'params' => ['id' => $invoice->id]]); - if(isset($data['use_credits']) && $data['use_credits']) { + if (isset($data['use_credits']) && $data['use_credits']) { $this->tryPayWithCredits($invoice); } $this->di['logger']->info('Approved invoice "%s"', $invoice->id); + return true; } public function tryPayWithCredits(\Model_Invoice $invoice) { - if(!$invoice->approved) { - return ; + if (!$invoice->approved) { + return; } - if ($this->isInvoiceTypeDeposit($invoice)){ + if ($this->isInvoiceTypeDeposit($invoice)) { $this->markAsPaid($invoice, false); } @@ -565,67 +567,76 @@ class Service implements InjectionAwareInterface $required = $this->getTotalWithTax($invoice); $epsilon = 0.05; - if(abs($balance-$required) < $epsilon) { - if($this->di['config']['debug']) error_log(sprintf('Setting invoice %s as paid with credits', $invoice->id)); + if (abs($balance - $required) < $epsilon) { + if ($this->di['config']['debug']) { + error_log(sprintf('Setting invoice %s as paid with credits', $invoice->id)); + } $this->markAsPaid($invoice); + return true; } - if($balance-$required > 0.00001) { - if($this->di['config']['debug']) error_log(sprintf('Setting invoice %s as paid with credits', $invoice->id)); + if ($balance - $required > 0.00001) { + if ($this->di['config']['debug']) { + error_log(sprintf('Setting invoice %s as paid with credits', $invoice->id)); + } $this->markAsPaid($invoice); + return true; } - if($this->di['config']['debug']) error_log(sprintf('Invoice %s could not be paid with credits. Money in balance %s Required: %s', $invoice->id, $balance, $required)); + if ($this->di['config']['debug']) { + error_log(sprintf('Invoice %s could not be paid with credits. Money in balance %s Required: %s', $invoice->id, $balance, $required)); + } } public function getTotalWithTax(\Model_Invoice $invoice) { $total = $this->getTotal($invoice) + $this->getTax($invoice); - return (float)$total; + + return (float) $total; } public function getTax(\Model_Invoice $invoice) { - if($invoice->taxrate <= 0) { + if ($invoice->taxrate <= 0) { return 0; } $iiService = $this->di['mod_service']('Invoice', 'InvoiceItem'); - $items = $this->di['db']->find('InvoiceItem', 'invoice_id = ? ', array($invoice->id)); + $items = $this->di['db']->find('InvoiceItem', 'invoice_id = ? ', [$invoice->id]); $tax = 0; - foreach($items as $item) { + foreach ($items as $item) { $tax += $iiService->getTax($item) * $item->quantity; } + return $tax; } public function getTotal(\Model_Invoice $invoice) { $total = 0; - $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', array($invoice->id)); + $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$invoice->id]); $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); - foreach($invoiceItems as $item) { + foreach ($invoiceItems as $item) { $total += $invoiceItemService->getTotal($item); } - return (float)$total; + + return (float) $total; } public function refundInvoice(\Model_Invoice $invoice, $note = null) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminInvoiceRefund', 'params'=>array('id'=>$invoice->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminInvoiceRefund', 'params' => ['id' => $invoice->id]]); $systemService = $this->di['mod_service']('system'); $logic = $systemService->getParamValue('invoice_refund_logic', 'manual'); $result = null; switch ($logic) { - case 'credit_note': case 'negative_invoice': - $total = $this->getTotalWithTax($invoice); - if($total <= 0) { + if ($total <= 0) { throw new \Box_Exception('Can not refund invoice with negative amount'); } @@ -638,44 +649,44 @@ class Service implements InjectionAwareInterface $new->taxname = $invoice->taxname; $new->taxrate = $invoice->taxrate; - $new->seller_company = $invoice->seller_company; - $new->seller_address = $invoice->seller_address; - $new->seller_phone = $invoice->seller_phone; - $new->seller_email = $invoice->seller_email; + $new->seller_company = $invoice->seller_company; + $new->seller_address = $invoice->seller_address; + $new->seller_phone = $invoice->seller_phone; + $new->seller_email = $invoice->seller_email; - $new->buyer_first_name= $invoice->buyer_first_name; + $new->buyer_first_name = $invoice->buyer_first_name; $new->buyer_last_name = $invoice->buyer_last_name; - $new->buyer_company = $invoice->buyer_company; - $new->buyer_address = $invoice->buyer_address; - $new->buyer_city = $invoice->buyer_city; - $new->buyer_state = $invoice->buyer_state; - $new->buyer_country = $invoice->buyer_country; - $new->buyer_phone = $invoice->buyer_phone; - $new->buyer_email = $invoice->buyer_email; - $new->buyer_zip = $invoice->buyer_zip; + $new->buyer_company = $invoice->buyer_company; + $new->buyer_address = $invoice->buyer_address; + $new->buyer_city = $invoice->buyer_city; + $new->buyer_state = $invoice->buyer_state; + $new->buyer_country = $invoice->buyer_country; + $new->buyer_phone = $invoice->buyer_phone; + $new->buyer_email = $invoice->buyer_email; + $new->buyer_zip = $invoice->buyer_zip; - $new->paid_at = date('Y-m-d H:i:s'); + $new->paid_at = date('Y-m-d H:i:s'); $new->created_at = date('Y-m-d H:i:s'); $new->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($new); - $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', array($invoice->id)); - foreach($invoiceItems as $item) { + $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$invoice->id]); + foreach ($invoiceItems as $item) { $pi = $this->di['db']->dispense('InvoiceItem'); - $pi->invoice_id = $new->id; - $pi->type = $item->type; - $pi->rel_id = $item->rel_id; - $pi->task = $item->task; - $pi->status = \Model_InvoiceItem::STATUS_EXECUTED; // ark refund invoce as executed - $pi->title = $item->title; - $pi->period = $item->period; - $pi->quantity = $item->quantity; - $pi->unit = $item->unit; - $pi->charged = 1; - $pi->price = -$item->price; - $pi->taxed = $item->taxed; - $pi->created_at = date('Y-m-d H:i:s'); - $pi->updated_at = date('Y-m-d H:i:s'); + $pi->invoice_id = $new->id; + $pi->type = $item->type; + $pi->rel_id = $item->rel_id; + $pi->task = $item->task; + $pi->status = \Model_InvoiceItem::STATUS_EXECUTED; // ark refund invoce as executed + $pi->title = $item->title; + $pi->period = $item->period; + $pi->quantity = $item->quantity; + $pi->unit = $item->unit; + $pi->charged = 1; + $pi->price = -$item->price; + $pi->taxed = $item->taxed; + $pi->created_at = date('Y-m-d H:i:s'); + $pi->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($pi); } @@ -683,44 +694,44 @@ class Service implements InjectionAwareInterface $this->addNote($invoice, sprintf('Refund invoice #%s generated', $new->id)); $this->addNote($new, sprintf('Refund for #%s invoice', $invoice->id)); - if(!empty($note)) { + if (!empty($note)) { $this->addNote($new, $note); } - if($logic == 'negative_invoice') { + if ('negative_invoice' == $logic) { $new->serie = $systemService->getParamValue('invoice_series_paid'); $new->nr = $this->getNextInvoiceNumber($new); $this->di['db']->store($new); } - if($logic == 'credit_note') { + if ('credit_note' == $logic) { $next_nr = $systemService->getParamValue('invoice_cn_starting_number', 1); $new->serie = $systemService->getParamValue('invoice_cn_series', 'CN-'); $new->nr = $next_nr; $this->di['db']->store($new); - //update next credit note starting number + // update next credit note starting number $systemService->setParamValue('invoice_cn_starting_number', ++$next_nr, true); } - $result = (int)$new->id; + $result = (int) $new->id; break; - //@todo undocumented - //@deprecated + // @todo undocumented + // @deprecated case 'same_invoice': $amount = $this->getTotalWithTax($invoice); $invoice->refund = empty($amount) ? null : $amount; $invoice->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($invoice); - if(!empty($note)) { + if (!empty($note)) { $this->addNote($invoice, $note); } // mark invoice as refunded if refund amount is equal or greater // than refund amount $total = $this->getTotalWithTax($invoice); - if($invoice->refund >= $total) { + if ($invoice->refund >= $total) { $invoice->status = \Model_Invoice::STATUS_REFUNDED; $this->di['db']->store($invoice); } @@ -729,83 +740,85 @@ class Service implements InjectionAwareInterface break; case 'manual': - if($this->di['config']['debug']) error_log('Refunds are managed manually. No actions performed'); + if ($this->di['config']['debug']) { + error_log('Refunds are managed manually. No actions performed'); + } break; default: break; } - $this->di['events_manager']->fire(array('event'=>'onAfterAdminInvoiceRefund', 'params'=>array('id'=>$invoice->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminInvoiceRefund', 'params' => ['id' => $invoice->id]]); $this->di['logger']->info('Refunded invoice #%s', $invoice->id); + return $result; } public function updateInvoice(\Model_Invoice $model, array $data) { - $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminInvoiceUpdate', 'params'=>$data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminInvoiceUpdate', 'params' => $data]); - $model->gateway_id = $this->di['array_get']($data, 'gateway_id', $model->gateway_id); - $model->text_1 = $this->di['array_get']($data, 'text_1', $model->text_1); - $model->text_2 = $this->di['array_get']($data, 'text_2', $model->text_2); - $model->seller_company = $this->di['array_get']($data, 'seller_company', $model->seller_company); - $model->seller_company_vat = $this->di['array_get']($data, 'seller_company_vat', $model->seller_company_vat); + $model->gateway_id = $this->di['array_get']($data, 'gateway_id', $model->gateway_id); + $model->text_1 = $this->di['array_get']($data, 'text_1', $model->text_1); + $model->text_2 = $this->di['array_get']($data, 'text_2', $model->text_2); + $model->seller_company = $this->di['array_get']($data, 'seller_company', $model->seller_company); + $model->seller_company_vat = $this->di['array_get']($data, 'seller_company_vat', $model->seller_company_vat); $model->seller_company_number = $this->di['array_get']($data, 'seller_company_number', $model->seller_company_number); - $model->seller_address = $this->di['array_get']($data, 'seller_address', $model->seller_address); - $model->seller_phone = $this->di['array_get']($data, 'seller_phone', $model->seller_phone); - $model->seller_email = $this->di['array_get']($data, 'seller_email', $model->seller_email); - $model->buyer_first_name = $this->di['array_get']($data, 'buyer_first_name', $model->buyer_first_name); - $model->buyer_last_name = $this->di['array_get']($data, 'buyer_last_name', $model->buyer_last_name); - $model->buyer_company = $this->di['array_get']($data, 'buyer_company', $model->buyer_company); - $model->buyer_company_vat = $this->di['array_get']($data, 'buyer_company_vat', $model->buyer_company_vat); - $model->buyer_company_number = $this->di['array_get']($data, 'buyer_company_number', $model->buyer_company_number); - $model->buyer_address = $this->di['array_get']($data, 'buyer_address', $model->buyer_address); - $model->buyer_city = $this->di['array_get']($data, 'buyer_city', $model->buyer_city); - $model->buyer_state = $this->di['array_get']($data, 'buyer_state', $model->buyer_state); - $model->buyer_country = $this->di['array_get']($data, 'buyer_country', $model->buyer_country); - $model->buyer_zip = $this->di['array_get']($data, 'buyer_zip', $model->buyer_zip); - $model->buyer_phone = $this->di['array_get']($data, 'buyer_phone', $model->buyer_phone); - $model->buyer_email = $this->di['array_get']($data, 'buyer_email', $model->buyer_email); + $model->seller_address = $this->di['array_get']($data, 'seller_address', $model->seller_address); + $model->seller_phone = $this->di['array_get']($data, 'seller_phone', $model->seller_phone); + $model->seller_email = $this->di['array_get']($data, 'seller_email', $model->seller_email); + $model->buyer_first_name = $this->di['array_get']($data, 'buyer_first_name', $model->buyer_first_name); + $model->buyer_last_name = $this->di['array_get']($data, 'buyer_last_name', $model->buyer_last_name); + $model->buyer_company = $this->di['array_get']($data, 'buyer_company', $model->buyer_company); + $model->buyer_company_vat = $this->di['array_get']($data, 'buyer_company_vat', $model->buyer_company_vat); + $model->buyer_company_number = $this->di['array_get']($data, 'buyer_company_number', $model->buyer_company_number); + $model->buyer_address = $this->di['array_get']($data, 'buyer_address', $model->buyer_address); + $model->buyer_city = $this->di['array_get']($data, 'buyer_city', $model->buyer_city); + $model->buyer_state = $this->di['array_get']($data, 'buyer_state', $model->buyer_state); + $model->buyer_country = $this->di['array_get']($data, 'buyer_country', $model->buyer_country); + $model->buyer_zip = $this->di['array_get']($data, 'buyer_zip', $model->buyer_zip); + $model->buyer_phone = $this->di['array_get']($data, 'buyer_phone', $model->buyer_phone); + $model->buyer_email = $this->di['array_get']($data, 'buyer_email', $model->buyer_email); $paid_at = $this->di['array_get']($data, 'paid_at', $model->paid_at); - if(empty($paid_at)) { - $model->paid_at = null; + if (empty($paid_at)) { + $model->paid_at = null; } else { $model->paid_at = date('Y-m-d H:i:s', strtotime($paid_at)); } $due_at = $this->di['array_get']($data, 'due_at', $model->due_at); - if(empty($due_at)) { + if (empty($due_at)) { $model->due_at = null; } else { $model->due_at = date('Y-m-d H:i:s', strtotime($due_at)); } - $model->serie = $this->di['array_get']($data, 'serie', $model->serie); - $model->nr = $this->di['array_get']($data, 'nr', $model->nr); - $model->status = $this->di['array_get']($data, 'status', $model->status); - $model->taxrate = $this->di['array_get']($data, 'taxrate', $model->taxrate); - $model->taxname = $this->di['array_get']($data, 'taxname', $model->taxname); - $model->approved = (int)$this->di['array_get']($data, 'approved', $model->approved); - $model->notes = $this->di['array_get']($data, 'notes', $model->notes); + $model->serie = $this->di['array_get']($data, 'serie', $model->serie); + $model->nr = $this->di['array_get']($data, 'nr', $model->nr); + $model->status = $this->di['array_get']($data, 'status', $model->status); + $model->taxrate = $this->di['array_get']($data, 'taxrate', $model->taxrate); + $model->taxname = $this->di['array_get']($data, 'taxname', $model->taxname); + $model->approved = (int) $this->di['array_get']($data, 'approved', $model->approved); + $model->notes = $this->di['array_get']($data, 'notes', $model->notes); $created_at = $this->di['array_get']($data, 'created_at', ''); - if(!empty($created_at)) { + if (!empty($created_at)) { $model->created_at = date('Y-m-d H:i:s', strtotime($created_at)); } - $ni = $this->di['array_get']($data, 'new_item', array()); - if(isset($ni['title']) && !empty($ni['title'])) { + $ni = $this->di['array_get']($data, 'new_item', []); + if (isset($ni['title']) && !empty($ni['title'])) { $invoiceItemService->addNew($model, $ni); } - $items = $this->di['array_get']($data, 'items', array()); - foreach($items as $id=>$d) { + $items = $this->di['array_get']($data, 'items', []); + foreach ($items as $id => $d) { $item = $this->di['db']->load('InvoiceItem', $id); - if($item instanceof \Model_InvoiceItem) { + if ($item instanceof \Model_InvoiceItem) { $invoiceItemService->update($item, $d); } } @@ -813,87 +826,93 @@ class Service implements InjectionAwareInterface $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminInvoiceUpdate', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminInvoiceUpdate', 'params' => ['id' => $model->id]]); $this->di['logger']->info('Updated invoice "%s"', $model->id); + return true; } public function rmInvoice(\Model_Invoice $model) { - //remove related invoice from orders - $sql=" + // remove related invoice from orders + $sql = ' UPDATE client_order SET unpaid_invoice_id = NULL - WHERE unpaid_invoice_id = :id"; - $this->di['db']->exec($sql, array('id'=>$model->id)); + WHERE unpaid_invoice_id = :id'; + $this->di['db']->exec($sql, ['id' => $model->id]); - $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', array($model->id)); - foreach($invoiceItems as $item) { + $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$model->id]); + foreach ($invoiceItems as $item) { $this->di['db']->trash($item); } $this->di['db']->trash($model); + return true; } public function deleteInvoiceByAdmin(\Model_Invoice $model) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminInvoiceDelete','params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminInvoiceDelete', 'params' => ['id' => $model->id]]); $id = $model->id; $this->rmInvoice($model); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminInvoiceDelete', 'params'=>array('id'=>$id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminInvoiceDelete', 'params' => ['id' => $id]]); $this->di['logger']->info('Removed invoice #%s', $id); - return TRUE; + + return true; } public function deleteInvoiceByClient(\Model_Invoice $model) { - $this->di['events_manager']->fire(array('event'=>'onBeforeClientInvoiceDelete', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeClientInvoiceDelete', 'params' => ['id' => $model->id]]); // check if invoice is associated with order - $invoiceItem = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', array($model->id)); - foreach($invoiceItem as $item) { - if($item->type == \Model_InvoiceItem::TYPE_ORDER) { - throw new \Box_Exception('Invoice is related to order #:id. Please cancel order first.', array(':id'=>$item->rel_id)); + $invoiceItem = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$model->id]); + foreach ($invoiceItem as $item) { + if (\Model_InvoiceItem::TYPE_ORDER == $item->type) { + throw new \Box_Exception('Invoice is related to order #:id. Please cancel order first.', [':id' => $item->rel_id]); } } $this->rmInvoice($model); $this->di['logger']->info('Removed invoice #%s', $model->id); - return TRUE; + + return true; } public function renewInvoice(\Model_ClientOrder $model, array $data) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminGenerateRenewalInvoice', 'params'=>array('order_id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminGenerateRenewalInvoice', 'params' => ['order_id' => $model->id]]); - $due_days = isset($data['due_days']) ? (int)$data['due_days'] : null; + $due_days = isset($data['due_days']) ? (int) $data['due_days'] : null; $invoice = $this->generateForOrder($model, $due_days); - $this->approveInvoice($invoice, (array('id'=>$invoice->id, 'use_credits'=>true))); + $this->approveInvoice($invoice, (['id' => $invoice->id, 'use_credits' => true])); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminGenerateRenewalInvoice', 'params'=>array('order_id'=>$model->id, 'id'=>$invoice->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminGenerateRenewalInvoice', 'params' => ['order_id' => $model->id, 'id' => $invoice->id]]); $this->di['logger']->info('Generated renewal invoice #%s', $invoice->id); + return $invoice->id; } public function doBatchPayWithCredits(array $data) { $unpaid = $this->findAllUnpaid($data); - foreach($unpaid as $proforma) { + foreach ($unpaid as $proforma) { try { $model = $this->di['db']->getExistingModelById('Invoice', $proforma['id']); $this->tryPayWithCredits($model); - } catch(\Exception $e) { - if($this->di['config']['debug']) { + } catch (\Exception $e) { + if ($this->di['config']['debug']) { error_log($e->getMessage()); } } } $this->di['logger']->info('Executed action to try cover unpaid invoices with client credits'); + return true; } @@ -901,25 +920,26 @@ class Service implements InjectionAwareInterface { $this->tryPayWithCredits($model); $this->di['logger']->info('Cover invoice with client credits'); + return true; } /** - * @param integer $due_days + * @param int $due_days * * @return \Model_Invoice */ public function generateForOrder(\Model_ClientOrder $order, $due_days = null) { - //check if we do have invoice prepared already - if(NULL !== $order->unpaid_invoice_id) { + // check if we do have invoice prepared already + if (null !== $order->unpaid_invoice_id) { $p = $this->di['db']->load('Invoice', $order->unpaid_invoice_id); - if($p instanceof \Model_Invoice) { + if ($p instanceof \Model_Invoice) { return $p; } } - if($order->price <= 0) { + if ($order->price <= 0) { throw new \Box_Exception('Invoices are not generated for 0 amount orders'); } @@ -939,14 +959,14 @@ class Service implements InjectionAwareInterface $price = $order->price; - $invoiceItemService = $this->di['mod_service']('Invoice', "InvoiceItem"); + $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); $invoiceItemService->generateFromOrder($proforma, $order, \Model_InvoiceItem::TASK_RENEW, $price); // invoice due date - if($due_days > 0) { + if ($due_days > 0) { $proforma->due_at = date('Y-m-d H:i:s', strtotime('+'.$due_days.' days')); $this->di['db']->store($proforma); - } else if($order->expires_at) { + } elseif ($order->expires_at) { $proforma->due_at = $order->expires_at; $this->di['db']->store($proforma); } @@ -959,21 +979,22 @@ class Service implements InjectionAwareInterface $orderService = $this->di['mod_service']('Order'); $orders = $orderService->getSoonExpiringActiveOrders(); - if(count($orders) == 0) { - return TRUE; + if (0 == count($orders)) { + return true; } - foreach($orders as $order) { + foreach ($orders as $order) { try { $model = $this->di['db']->getExistingModelById('ClientOrder', $order['id']); $invoice = $this->generateForOrder($model); - $this->approveInvoice($invoice, array('id'=>$invoice->id, 'use_credits'=>true)); - } catch(\Exception $e) { + $this->approveInvoice($invoice, ['id' => $invoice->id, 'use_credits' => true]); + } catch (\Exception $e) { error_log($e->getMessage()); } } $this->di['logger']->info('Executed action to generate new invoices for expiring orders'); + return true; } @@ -982,73 +1003,77 @@ class Service implements InjectionAwareInterface $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); $invoiceItems = (array) $invoiceItemService->getAllNotExecutePaidItems(); - foreach($invoiceItems as $item) { + foreach ($invoiceItems as $item) { try { $model = $this->di['db']->getExistingModelById('InvoiceItem', $item['id']); $invoiceItemService->executeTask($model); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); } } $this->di['logger']->info('Executed action to activate paid invoices'); + return true; } public function doBatchRemindersSend() { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminInvoiceSendReminders')); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminInvoiceSendReminders']); $list = $this->getUnpaidInvoicesLateFor(); - foreach($list as $invoice) { + foreach ($list as $invoice) { $this->sendInvoiceReminder($invoice); } $this->di['logger']->info('Executed action to send invoice payment reminders'); + return true; } public function doBatchInvokeDueEvent(array $data) { - $once_per_day = isset($data['once_per_day']) ? (bool)$data['once_per_day']: true; + $once_per_day = isset($data['once_per_day']) ? (bool) $data['once_per_day'] : true; $key = 'invoice_overdue_invoked'; - //do not use api call to get system param to avoid invoking system module event hooks + // do not use api call to get system param to avoid invoking system module event hooks $ss = $this->di['mod_service']('System'); $last_time = $ss->getParamValue($key); - if($once_per_day && $last_time && (time() - strtotime($last_time)) < 86400) { - //error_log('Already executed today.'); + if ($once_per_day && $last_time && (time() - strtotime($last_time)) < 86400) { + // error_log('Already executed today.'); return false; } $before_due_list = $this->di['db']->getAll("SELECT id, DATEDIFF(due_at, NOW()) as days_left FROM invoice WHERE status = 'unpaid' AND approved = 1 AND due_at > NOW()"); - foreach($before_due_list as $params) { - $this->di['events_manager']->fire(array('event'=>'onEventBeforeInvoiceIsDue', 'params'=>$params)); + foreach ($before_due_list as $params) { + $this->di['events_manager']->fire(['event' => 'onEventBeforeInvoiceIsDue', 'params' => $params]); } $after_due_list = $this->di['db']->getAll("SELECT id, ABS(DATEDIFF(due_at, NOW())) as days_passed FROM invoice WHERE status = 'unpaid' AND approved = 1 AND ((due_at < NOW()) OR (ABS(DATEDIFF(due_at, NOW())) = 0 ))"); - foreach($after_due_list as $params) { - $this->di['events_manager']->fire(array('event'=>'onEventAfterInvoiceIsDue', 'params'=>$params)); + foreach ($after_due_list as $params) { + $this->di['events_manager']->fire(['event' => 'onEventAfterInvoiceIsDue', 'params' => $params]); } $ss->setParamValue($key, date('Y-m-d H:i:s')); $this->di['logger']->info('Executed action to invoke invoice due event'); + return true; } public function sendInvoiceReminder(\Model_Invoice $invoice) { // do not send accidental reminder for paid invoices - if($invoice->status == \Model_Invoice::STATUS_PAID) { + if (\Model_Invoice::STATUS_PAID == $invoice->status) { return true; } - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminInvoiceSendReminder', 'params'=>array('id'=>$invoice->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminInvoiceSendReminder', 'params' => ['id' => $invoice->id]]); $invoice->reminded_at = date('Y-m-d H:i:s'); $invoice->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($invoice); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminInvoiceReminderSent', 'params'=>array('id'=>$invoice->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminInvoiceReminderSent', 'params' => ['id' => $invoice->id]]); $this->di['logger']->info('Invoice payment reminder sent'); + return true; } @@ -1058,35 +1083,36 @@ class Service implements InjectionAwareInterface FROM invoice group by status'; $rows = $this->di['db']->getAll($sql); - $data = array(); - foreach ($rows as $row){ - $data [ $row['status'] ] = $row['counter']; + $data = []; + foreach ($rows as $row) { + $data[$row['status']] = $row['counter']; } - return array( - 'total' => array_sum($data), - \Model_Invoice::STATUS_PAID => isset($data[\Model_Invoice::STATUS_PAID]) ? $data[\Model_Invoice::STATUS_PAID] : 0, - \Model_Invoice::STATUS_UNPAID => isset($data[\Model_Invoice::STATUS_UNPAID]) ? $data[\Model_Invoice::STATUS_UNPAID] : 0, - \Model_Invoice::STATUS_REFUNDED => isset($data[\Model_Invoice::STATUS_REFUNDED]) ? $data[\Model_Invoice::STATUS_REFUNDED] : 0, - \Model_Invoice::STATUS_CANCELED => isset($data[\Model_Invoice::STATUS_CANCELED]) ? $data[\Model_Invoice::STATUS_CANCELED] : 0, - ); + + return [ + 'total' => array_sum($data), + \Model_Invoice::STATUS_PAID => $data[\Model_Invoice::STATUS_PAID] ?? 0, + \Model_Invoice::STATUS_UNPAID => $data[\Model_Invoice::STATUS_UNPAID] ?? 0, + \Model_Invoice::STATUS_REFUNDED => $data[\Model_Invoice::STATUS_REFUNDED] ?? 0, + \Model_Invoice::STATUS_CANCELED => $data[\Model_Invoice::STATUS_CANCELED] ?? 0, + ]; } public function generateFundsInvoice(\Model_Client $client, $amount) { - if(!$client->currency) { + if (!$client->currency) { throw new \Box_Exception('You must have at least one active order before you can add funds so you cannot proceed at the current time!'); } $systemService = $this->di['mod_service']('system'); - $min_amount = $systemService->getParamValue('funds_min_amount', NULL); - $max_amount = $systemService->getParamValue('funds_max_amount', NULL); + $min_amount = $systemService->getParamValue('funds_min_amount', null); + $max_amount = $systemService->getParamValue('funds_max_amount', null); - if($min_amount && $amount < $min_amount) { + if ($min_amount && $amount < $min_amount) { throw new \Box_Exception('Amount is not valid', null, 981); } - if($max_amount && $amount > $max_amount) { + if ($max_amount && $amount > $max_amount) { throw new \Box_Exception('Amount is not valid', null, 982); } @@ -1111,48 +1137,48 @@ class Service implements InjectionAwareInterface { $subscribe = false; - $invoice = $this->di['db']->findOne('Invoice', 'hash = ?', array($data['hash'])); - if(!$invoice instanceof \Model_Invoice) { + $invoice = $this->di['db']->findOne('Invoice', 'hash = ?', [$data['hash']]); + if (!$invoice instanceof \Model_Invoice) { throw new \Box_Exception('Invoice not found', null, 812); } $gtw = $this->di['db']->load('PayGateway', $data['gateway_id']); - if(!$gtw instanceof \Model_PayGateway) { + if (!$gtw instanceof \Model_PayGateway) { throw new \Box_Exception('Payment method not found', null, 813); } - if(!$gtw->enabled) { + if (!$gtw->enabled) { throw new \Box_Exception('Payment method not enabled', null, 814); } $subscribeService = $this->di['mod_service']('Invoice', 'Subscription'); $payGatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); - if($subscribeService->isSubscribable($invoice->id) && $payGatewayService->canPerformRecurrentPayment($gtw)) { + if ($subscribeService->isSubscribable($invoice->id) && $payGatewayService->canPerformRecurrentPayment($gtw)) { $subscribe = true; } - $adapter = $payGatewayService->getPaymentAdapter($gtw, $invoice, $data); if (method_exists($adapter, 'setDi')) { $adapter->setDi($this->di); } - + if (method_exists($adapter, 'setLog')) { $adapter->setLog($this->di['logger']); } $pgc = $adapter->getConfig(); - //@since v2.9.15 - if(method_exists($adapter, 'getHtml')) { + // @since v2.9.15 + if (method_exists($adapter, 'getHtml')) { $html = $adapter->getHtml($this->di['api_system'], $invoice->id, $subscribe); - return array( - 'iframe' => isset($pgc['can_load_in_iframe']) ? (bool)$pgc['can_load_in_iframe'] : false, - 'type' => 'html', - 'service_url' => '', - 'subscription' => $subscribe, - 'result' => $html, - ); + + return [ + 'iframe' => isset($pgc['can_load_in_iframe']) ? (bool) $pgc['can_load_in_iframe'] : false, + 'type' => 'html', + 'service_url' => '', + 'subscription' => $subscribe, + 'result' => $html, + ]; } $i = clone $invoice; @@ -1160,22 +1186,22 @@ class Service implements InjectionAwareInterface $r = ($subscribe) ? $adapter->recurrentPayment($mpi) : $adapter->singlePayment($mpi); $this->di['logger']->info('Went to pay for invoice #%s via %s', $invoice->id, $gtw->gateway); - //@bug https://github.com/boxbilling/BoxBilling/issues/108 - if($adapter->getType() != 'html') { - $r = (array)$r; + // @bug https://github.com/boxbilling/BoxBilling/issues/108 + if ('html' != $adapter->getType()) { + $r = (array) $r; } - return array( - 'type' => $adapter->getType(), - 'service_url' => $adapter->getServiceURL(), - 'subscription' => $subscribe, - 'result' => $r, - ); + return [ + 'type' => $adapter->getType(), + 'service_url' => $adapter->getServiceURL(), + 'subscription' => $subscribe, + 'result' => $r, + ]; } public function generatePDF($hash, $identity) { - $invoice = $this->di['db']->findOne('Invoice', 'hash = :hash', array(':hash' => $hash)); + $invoice = $this->di['db']->findOne('Invoice', 'hash = :hash', [':hash' => $hash]); if (!$invoice instanceof \Model_Invoice) { throw new \Box_Exception('Invoice not found'); } @@ -1183,21 +1209,21 @@ class Service implements InjectionAwareInterface if (isset($invoice->currency)) { $currencyCode = $invoice->currency; } else { - $client = $this->di['db']->getExistingModelById('Client', $invoice->client_id, 'Client not found'); + $client = $this->di['db']->getExistingModelById('Client', $invoice->client_id, 'Client not found'); $currencyCode = $client->currency; } - $invoice = $this->toApiArray($invoice, false, $identity); + $invoice = $this->toApiArray($invoice, false, $identity); $systemService = $this->di['mod_service']('System'); - $company = $systemService->getCompany(); - $pdf = $this->di['pdf']; + $company = $systemService->getCompany(); + $pdf = $this->di['pdf']; $pdf->AddPage(); $pdf->AddFont('DejaVu', '', 'DejaVuSansCondensed.ttf', true); $pdf->AddFont('DejaVu', 'B', 'DejaVuSansCondensed-Bold.ttf', true); $pdf->SetFont('DejaVu', 'B', 20); $font_size = 8; - $left = 10; + $left = 10; $pdf->text(90, 20, $invoice['serie_nr']); @@ -1205,10 +1231,10 @@ class Service implements InjectionAwareInterface if (isset($company['logo_url']) && !empty($company['logo_url'])) { $url = $company['logo_url']; - if (substr($url, -4) === '.png') { - $pdf->ImagePngWithAlpha($_SERVER['DOCUMENT_ROOT'] . $url, $left + 75, 35, 50); + if ('.png' === substr($url, -4)) { + $pdf->ImagePngWithAlpha($_SERVER['DOCUMENT_ROOT'].$url, $left + 75, 35, 50); } else { - //Converting to .png + // Converting to .png $img = imagecreatefromstring(file_get_contents($url)); if ($img) { $filename = 'logo.png'; @@ -1223,58 +1249,59 @@ class Service implements InjectionAwareInterface } $localeDateFormat = $this->di['config']['locale_date_format']; - $invoiceDate = strftime($localeDateFormat, strtotime( $this->di['array_get']($invoice, 'due_at', $invoice['created_at']) )); - $invoice_info = __("Invoice number: ") . $invoice['nr'] . "\n" . - __("Invoice date: ") . $invoiceDate . "\n" . - __("Due date: ") . strftime($localeDateFormat, strtotime($invoice['due_at'])) . "\n" . - __("Invoice status: ") . ucfirst($invoice['status']); + $invoiceDate = strftime($localeDateFormat, strtotime($this->di['array_get']($invoice, 'due_at', $invoice['created_at']))); + $invoice_info = __('Invoice number: ').$invoice['nr']."\n". + __('Invoice date: ').$invoiceDate."\n". + __('Due date: ').strftime($localeDateFormat, strtotime($invoice['due_at']))."\n". + __('Invoice status: ').ucfirst($invoice['status']); $pdf->SetFont('DejaVu', 'B', $font_size); - $pdf->text($left + 15, 75, __("Invoice")); + $pdf->text($left + 15, 75, __('Invoice')); $pdf->SetFont('DejaVu', '', $font_size); $pdf->SetXY($left, 70); - $pdf->MultiCell(60, 10, "\n" . $invoice_info, 0, "L", 0); + $pdf->MultiCell(60, 10, "\n".$invoice_info, 0, 'L', 0); - $company_info = __("Name: ") . $invoice['seller']['company'] . "\n" . - __("Address: ") . $invoice['seller']['address'] . "\n" . - __("Company VAT: ") . $invoice['seller']['company_vat'] . "\n" . - __("Company number: ") . $invoice['seller']['company_number'] . "\n" . - __("Account: ") . $invoice['seller']['account_number'] . "\n" . - __("Phone: ") . $invoice['seller']['phone'] . "\n" . - __("Email: ") . $invoice['seller']['email']; + $company_info = __('Name: ').$invoice['seller']['company']."\n". + __('Address: ').$invoice['seller']['address']."\n". + __('Company VAT: ').$invoice['seller']['company_vat']."\n". + __('Company number: ').$invoice['seller']['company_number']."\n". + __('Account: ').$invoice['seller']['account_number']."\n". + __('Phone: ').$invoice['seller']['phone']."\n". + __('Email: ').$invoice['seller']['email']; $pdf->SetFont('DejaVu', 'B', $font_size); - $pdf->text(95, 75, __("Company")); + $pdf->text(95, 75, __('Company')); $pdf->SetFont('DejaVu', '', $font_size); $pdf->SetXY(75, 70); - $pdf->MultiCell(60, 10, "\n" . $company_info, 0, "L", 0); + $pdf->MultiCell(60, 10, "\n".$company_info, 0, 'L', 0); - $buyer_info = __("Name: ") . $invoice['buyer']['first_name'].' ' . $invoice['buyer']['last_name'] . "\n" . - __("Company: ") . $invoice['buyer']['company'] . "\n" . - __("Address: ") . $invoice['buyer']['address'] . "\n" . - __("Company VAT: ") . $invoice['seller']['company_vat'] . "\n" . - __("Company number: ") . $invoice['seller']['company_number'] . "\n" . - __("Phone: ") . $invoice['buyer']['phone']; + $buyer_info = __('Name: ').$invoice['buyer']['first_name'].' '.$invoice['buyer']['last_name']."\n". + __('Company: ').$invoice['buyer']['company']."\n". + __('Address: ').$invoice['buyer']['address']."\n". + __('Company VAT: ').$invoice['seller']['company_vat']."\n". + __('Company number: ').$invoice['seller']['company_number']."\n". + __('Phone: ').$invoice['buyer']['phone']; $pdf->SetFont('DejaVu', 'B', $font_size); - $pdf->text(145, 75, __("Billing and delivery address")); + $pdf->text(145, 75, __('Billing and delivery address')); $pdf->SetFont('DejaVu', '', $font_size); $pdf->SetXY(140, 70); - $pdf->MultiCell(60, 10, "\n" . $buyer_info, 0, "L", 0); + $pdf->MultiCell(60, 10, "\n".$buyer_info, 0, 'L', 0); - $header = array(__('#'), __('Title'), __('Price'), __('Total')); + $header = [__('#'), __('Title'), __('Price'), __('Total')]; $pdf->SetXY($left, 175); - $w = array(10, 120, 30, 30); + $w = [10, 120, 30, 30]; $counted = count($header); - for ($i = 0; $i < $counted; $i++) + for ($i = 0; $i < $counted; ++$i) { $pdf->Cell($w[$i], 7, $header[$i], 1, 0, 'C'); + } $pdf->Ln(); $nr = 1; foreach ($invoice['lines'] as $row) { $pdf->Cell($w[0], 6, $nr++, 'LR'); $pdf->Cell($w[1], 6, $row['title'], 'LR'); - $pdf->Cell($w[2], 6, ($row['quantity'] > 1) ? $row['quantity'] . ' x ' . $this->money($row['price'], $currencyCode) : $this->money($row['price'], $currencyCode), 'LR', 0, 'R'); + $pdf->Cell($w[2], 6, ($row['quantity'] > 1) ? $row['quantity'].' x '.$this->money($row['price'], $currencyCode) : $this->money($row['price'], $currencyCode), 'LR', 0, 'R'); $pdf->Cell($w[3], 6, $this->money($row['total'], $currencyCode), 'LR', 0, 'R'); $pdf->Ln(); } @@ -1283,7 +1310,7 @@ class Service implements InjectionAwareInterface $y = $pdf->GetY(); $pdf->SetXY(120, $y + 10); if ($invoice['tax'] > 0) { - $pdf->Cell(40, 6, $invoice['taxname'] . ' ' . $invoice['taxrate'] . "%", 'LRTB', 0, 'C'); + $pdf->Cell(40, 6, $invoice['taxname'].' '.$invoice['taxrate'].'%', 'LRTB', 0, 'C'); $pdf->Cell(40, 6, $this->money($invoice['tax'], $currencyCode), 'LRTB', 0, 'C'); $pdf->Ln(); $pdf->SetX(120); @@ -1302,26 +1329,29 @@ class Service implements InjectionAwareInterface $pdf->Cell(40, 10, $this->money($invoice['total'], $currencyCode), 'LRTB', 0, 'C'); $pdf->Ln(); - $pdf->Output($invoice["serie_nr"] . ".pdf", "I"); + $pdf->Output($invoice['serie_nr'].'.pdf', 'I'); } private function money($price, $currencyCode) { - return $this->di['api_guest']->currency_format(array("price" => $price, 'code' => $currencyCode, 'convert' => false)); + return $this->di['api_guest']->currency_format(['price' => $price, 'code' => $currencyCode, 'convert' => false]); } public function addNote(\Model_Invoice $model, $note) { $n = $model->notes; - $model->notes = $n . date('Y-m-d H:i:s') .': '.$note.' '.PHP_EOL; + $model->notes = $n.date('Y-m-d H:i:s').': '.$note.' '.PHP_EOL; $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return true; } /** - * Return list of unpaid invoices which can be covered from client balance + * Return list of unpaid invoices which can be covered from client balance. + * * @param array $filter + * * @return array */ public function findAllUnpaid(array $filter = null) @@ -1334,11 +1364,11 @@ class Service implements InjectionAwareInterface WHERE m.status = :status AND m.approved = 1 AND cb.amount >= pi.price'; - $params = array('status' => \Model_Invoice::STATUS_UNPAID); + $params = ['status' => \Model_Invoice::STATUS_UNPAID]; - $client_id = isset($filter['client_id']) ? (int)$filter['client_id'] : null; + $client_id = isset($filter['client_id']) ? (int) $filter['client_id'] : null; - if($client_id) { + if ($client_id) { $sql .= ' AND m.client_id = :client_id '; $params['client_id'] = $client_id; } @@ -1351,13 +1381,14 @@ class Service implements InjectionAwareInterface public function findAllPaid() { - return $this->di['db']->find('Invoice', 'status = ? order by id desc', array(\Model_Invoice::STATUS_PAID)); + return $this->di['db']->find('Invoice', 'status = ? order by id desc', [\Model_Invoice::STATUS_PAID]); } public function getUnpaidInvoicesLateFor($days_after_issue = 2) { $conditions = 'status = ? and approved = 1 and reminded_at is null and DATEDIFF(NOW(), created_at) > ?'; - return $this->di['db']->find('Invoice', $conditions, array(\Model_Invoice::STATUS_UNPAID, $days_after_issue)); + + return $this->di['db']->find('Invoice', $conditions, [\Model_Invoice::STATUS_UNPAID, $days_after_issue]); } /** @@ -1369,12 +1400,13 @@ class Service implements InjectionAwareInterface * @var \Box\Mod\System\Service $systemService */ $systemService = $this->di['mod_service']('system'); + return (bool) $systemService->getParamValue('invoice_auto_approval', true); } /** - * @param \Model_Invoice $invoice * @param bool $subscribe + * * @return \Payment_Invoice */ public function getPaymentInvoice(\Model_Invoice $invoice, $subscribe = false) @@ -1397,8 +1429,8 @@ class Service implements InjectionAwareInterface ->setCountry($client['country']); $first_title = null; - $items = array(); - foreach($proforma['lines'] as $item) { + $items = []; + foreach ($proforma['lines'] as $item) { $pi = new \Payment_Invoice_Item(); $pi ->setId($item['id']) @@ -1408,16 +1440,16 @@ class Service implements InjectionAwareInterface ->setTax($item['tax']) ->setQuantity($item['quantity']); $items[] = $pi; - if(is_null($first_title) && count($proforma['lines']) == 1) { + if (is_null($first_title) && 1 == count($proforma['lines'])) { $first_title = $item['title']; } } - $params = array( - ':id'=>sprintf('%05s', $proforma['nr']), - ':serie'=>$proforma['serie'], - ':title'=>$first_title); - if($first_title) { + $params = [ + ':id' => sprintf('%05s', $proforma['nr']), + ':serie' => $proforma['serie'], + ':title' => $first_title, ]; + if ($first_title) { $title = __('Payment for invoice :serie:id [:title]', $params); } else { $title = __('Payment for invoice :serie:id', $params); @@ -1433,8 +1465,7 @@ class Service implements InjectionAwareInterface $subscribeService = $this->di['mod_service']('Invoice', 'Subscription'); // can subscribe only if proforma has one item with defined period - if($subscribe && $subscribeService->isSubscribable($invoice->id)) { - + if ($subscribe && $subscribeService->isSubscribable($invoice->id)) { $subitem = $invoice->InvoiceItem->getFirst(); $period = $this->di['period']($subitem->period); @@ -1453,27 +1484,27 @@ class Service implements InjectionAwareInterface public function getBuyer(\Model_Invoice $invoice) { - return array( - 'first_name'=> $invoice->buyer_first_name, + return [ + 'first_name' => $invoice->buyer_first_name, 'last_name' => $invoice->buyer_last_name, - 'company' => $invoice->buyer_company, - 'address' => $invoice->buyer_address, - 'city' => $invoice->buyer_city, - 'state' => $invoice->buyer_state, - 'country' => $invoice->buyer_country, - 'phone' => $invoice->buyer_phone, - 'phone_cc' => '', - 'email' => $invoice->buyer_email, - 'zip' => $invoice->buyer_zip, - ); + 'company' => $invoice->buyer_company, + 'address' => $invoice->buyer_address, + 'city' => $invoice->buyer_city, + 'state' => $invoice->buyer_state, + 'country' => $invoice->buyer_country, + 'phone' => $invoice->buyer_phone, + 'phone_cc' => '', + 'email' => $invoice->buyer_email, + 'zip' => $invoice->buyer_zip, + ]; } public function rmByClient(\Model_Client $client) { - $invoices = $this->di['db']->find('Invoice', 'client_id = ?', array($client->id)); - foreach($invoices as $invoice) { - $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', array($invoice->id)); - foreach ($invoiceItems as $invoiceItem){ + $invoices = $this->di['db']->find('Invoice', 'client_id = ?', [$client->id]); + foreach ($invoices as $invoice) { + $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$invoice->id]); + foreach ($invoiceItems as $invoiceItem) { $this->di['db']->trash($invoiceItem); } $this->di['db']->trash($invoice); @@ -1481,17 +1512,17 @@ class Service implements InjectionAwareInterface } /** - * @param \Model_Invoice $invoice * @return bool */ public function isInvoiceTypeDeposit(\Model_Invoice $invoice) { - $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', array($invoice->id)); - foreach($invoiceItems as $item) { - if($item->type == \Model_InvoiceItem::TYPE_DEPOSIT) { + $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$invoice->id]); + foreach ($invoiceItems as $item) { + if (\Model_InvoiceItem::TYPE_DEPOSIT == $item->type) { return true; } } + return false; } } diff --git a/src/bb-modules/Invoice/ServiceInvoiceItem.php b/src/bb-modules/Invoice/ServiceInvoiceItem.php index d4758fe05..cbdb3ed7a 100644 --- a/src/bb-modules/Invoice/ServiceInvoiceItem.php +++ b/src/bb-modules/Invoice/ServiceInvoiceItem.php @@ -1,6 +1,6 @@ di; } - public function markAsPaid(\Model_InvoiceItem $item, $charge = TRUE) + public function markAsPaid(\Model_InvoiceItem $item, $charge = true) { - if($charge && !$item->charged) { + if ($charge && !$item->charged) { $this->creditInvoiceItem($item); - $item->charged = TRUE; - $item->updated_at = date('Y-m-d H:i:s'); + $item->charged = true; + $item->updated_at = date('Y-m-d H:i:s'); } - $item->status = \Model_InvoiceItem::STATUS_PENDING_SETUP; - $item->updated_at = date('Y-m-d H:i:s'); + $item->status = \Model_InvoiceItem::STATUS_PENDING_SETUP; + $item->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($item); $oid = $this->getOrderId($item); - if(NULL !== $oid) { + if (null !== $oid) { $orderService = $this->di['mod_service']('Order'); $order = $this->di['db']->load('ClientOrder', $oid); - if($order instanceof \Model_ClientOrder) { + if ($order instanceof \Model_ClientOrder) { $orderService->unsetUnpaidInvoice($order); } } @@ -60,24 +61,24 @@ class ServiceInvoiceItem implements InjectionAwareInterface public function executeTask(\Model_InvoiceItem $item) { - if($item->status == \Model_InvoiceItem::STATUS_EXECUTED) { + if (\Model_InvoiceItem::STATUS_EXECUTED == $item->status) { return true; } - if($item->type == \Model_InvoiceItem::TYPE_ORDER) { + if (\Model_InvoiceItem::TYPE_ORDER == $item->type) { $order_id = $this->getOrderId($item); $order = $this->di['db']->load('ClientOrder', $order_id); - if(!$order instanceof \Model_ClientOrder) { - throw new \Box_Exception('Could not activate proforma item. Order :id not found', array(':id'=>$order_id)); + if (!$order instanceof \Model_ClientOrder) { + throw new \Box_Exception('Could not activate proforma item. Order :id not found', [':id' => $order_id]); } $orderService = $this->di['mod_service']('Order'); switch ($item->task) { case \Model_InvoiceItem::TASK_ACTIVATE: $product = $this->di['db']->getExistingModelById('Product', $order->product_id); - if($product->setup == \Model_Product::SETUP_AFTER_PAYMENT) { + if (\Model_Product::SETUP_AFTER_PAYMENT == $product->setup) { try { $orderService->activateOrder($order); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); $orderService->saveStatusChange($order, 'Order could not be activated due to error: '.$e->getMessage()); } @@ -86,14 +87,14 @@ class ServiceInvoiceItem implements InjectionAwareInterface case \Model_InvoiceItem::TASK_RENEW: try { - //Unsuspend order if suspended before renew - if($order->status == \Model_ClientOrder::STATUS_SUSPENDED) { - $orderService->unsuspendFromOrder($order); - } - + // Unsuspend order if suspended before renew + if (\Model_ClientOrder::STATUS_SUSPENDED == $order->status) { + $orderService->unsuspendFromOrder($order); + } + $order = $this->di['db']->load('ClientOrder', $order_id); $orderService->renewOrder($order); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); $orderService->saveStatusChange($order, 'Order could not renew due to error: '.$e->getMessage()); } @@ -107,32 +108,32 @@ class ServiceInvoiceItem implements InjectionAwareInterface $this->markAsExecuted($item); } - if($item->type == \Model_InvoiceItem::TYPE_HOOK_CALL) { + if (\Model_InvoiceItem::TYPE_HOOK_CALL == $item->type) { try { $params = json_decode($item->rel_id); - $this->di['events_manager']->fire(array('event'=>$item->task, 'params'=>$params)); - } catch(\Exception $e) { + $this->di['events_manager']->fire(['event' => $item->task, 'params' => $params]); + } catch (\Exception $e) { error_log($e->getMessage()); } $this->markAsExecuted($item); } - if($item->type == \Model_InvoiceItem::TYPE_DEPOSIT) { + if (\Model_InvoiceItem::TYPE_DEPOSIT == $item->type) { $clientService = $this->di['mod_service']('Client'); $invoice = $this->di['db']->getExistingModelById('Invoice', $item->invoice_id); $client = $this->di['db']->getExistingModelById('Client', $invoice->client_id); - $data = array( + $data = [ 'type' => 'invoice', 'rel_id' => $item->invoice_id, - ); + ]; $clientService->addFunds($client, $this->getTotal($item), $item->title, $data); $this->markAsExecuted($item); } - if($item->type == \Model_InvoiceItem::TYPE_CUSTOM) { - //@todo ? + if (\Model_InvoiceItem::TYPE_CUSTOM == $item->type) { + // @todo ? $this->markAsExecuted($item); } } @@ -140,12 +141,12 @@ class ServiceInvoiceItem implements InjectionAwareInterface public function addNew(\Model_Invoice $proforma, array $data) { $title = $this->di['array_get']($data, 'title', ''); - if(empty($title)) { + if (empty($title)) { throw new \Box_Exception('Invoice item title is missing'); } $period = $this->di['array_get']($data, 'period', 0); - if($period) { + if ($period) { $periodCheck = $this->di['period']($period); } @@ -155,20 +156,20 @@ class ServiceInvoiceItem implements InjectionAwareInterface $status = $this->di['array_get']($data, 'status', \Model_InvoiceItem::STATUS_PENDING_PAYMENT); $pi = $this->di['db']->dispense('InvoiceItem'); - $pi->invoice_id = $proforma->id; - $pi->type = $type; - $pi->rel_id = $rel_id; - $pi->task = $task; - $pi->status = $status; - $pi->title = $data['title']; - $pi->period = $period; - $pi->quantity = $this->di['array_get']($data, 'quantity', 1); - $pi->unit = $this->di['array_get']($data, 'unit'); - $pi->charged = $this->di['array_get']($data, 'charged', 0); - $pi->price = (double) $this->di['array_get']($data, 'price', 0); - $pi->taxed = $this->di['array_get']($data, 'taxed', false); - $pi->created_at = date('Y-m-d H:i:s'); - $pi->updated_at = date('Y-m-d H:i:s'); + $pi->invoice_id = $proforma->id; + $pi->type = $type; + $pi->rel_id = $rel_id; + $pi->task = $task; + $pi->status = $status; + $pi->title = $data['title']; + $pi->period = $period; + $pi->quantity = $this->di['array_get']($data, 'quantity', 1); + $pi->unit = $this->di['array_get']($data, 'unit'); + $pi->charged = $this->di['array_get']($data, 'charged', 0); + $pi->price = (float) $this->di['array_get']($data, 'price', 0); + $pi->taxed = $this->di['array_get']($data, 'taxed', false); + $pi->created_at = date('Y-m-d H:i:s'); + $pi->updated_at = date('Y-m-d H:i:s'); $itemId = $this->di['db']->store($pi); return (int) $itemId; @@ -181,12 +182,12 @@ class ServiceInvoiceItem implements InjectionAwareInterface public function getTax(\Model_InvoiceItem $item) { - if(!$item->taxed) { + if (!$item->taxed) { return 0; } - $rate = $this->di['db']->getCell('SELECT taxrate FROM invoice WHERE id = :id', array('id'=>$item->invoice_id)); - if($rate <= 0) { + $rate = $this->di['db']->getCell('SELECT taxrate FROM invoice WHERE id = :id', ['id' => $item->invoice_id]); + if ($rate <= 0) { return 0; } @@ -197,15 +198,15 @@ class ServiceInvoiceItem implements InjectionAwareInterface { $item->title = $this->di['array_get']($data, 'title', $item->title); $item->price = $this->di['array_get']($data, 'price', $item->price); - - $item_quantity = $this->di['array_get']($data, 'quantity', 1); - - if($item_quantity != $item->quantity){ - $item->quantity = $item_quantity > 0 ? $item_quantity : 1 ; - } - - if(isset($data['taxed']) && !empty($data['taxed'])) { - $item->taxed = (bool)$data['taxed']; + + $item_quantity = $this->di['array_get']($data, 'quantity', 1); + + if ($item_quantity != $item->quantity) { + $item->quantity = $item_quantity > 0 ? $item_quantity : 1; + } + + if (isset($data['taxed']) && !empty($data['taxed'])) { + $item->taxed = (bool) $data['taxed']; } else { $item->taxed = false; } @@ -214,40 +215,40 @@ class ServiceInvoiceItem implements InjectionAwareInterface $this->di['db']->store($item); } - public function remove(\Model_InvoiceItem $model) { $id = $model->id; $this->di['db']->trash($model); $this->di['logger']->info('Removed invoice item "%s"', $id); + return true; } public function generateForAddFunds(\Model_Invoice $proforma, $amount) { $pi = $this->di['db']->dispense('InvoiceItem'); - $pi->invoice_id = $proforma->id; - $pi->type = \Model_InvoiceItem::TYPE_DEPOSIT; - $pi->rel_id = NULL; - $pi->task = \Model_InvoiceItem::TASK_VOID; - $pi->status = \Model_InvoiceItem::STATUS_PENDING_PAYMENT; - $pi->title = __('Add funds to account'); - $pi->period = NULL; - $pi->quantity = 1; - $pi->unit = NULL; - $pi->charged = 1; - $pi->price = $amount; - $pi->taxed = FALSE; - $pi->created_at = date('Y-m-d H:i:s'); - $pi->updated_at = date('Y-m-d H:i:s'); + $pi->invoice_id = $proforma->id; + $pi->type = \Model_InvoiceItem::TYPE_DEPOSIT; + $pi->rel_id = null; + $pi->task = \Model_InvoiceItem::TASK_VOID; + $pi->status = \Model_InvoiceItem::STATUS_PENDING_PAYMENT; + $pi->title = __('Add funds to account'); + $pi->period = null; + $pi->quantity = 1; + $pi->unit = null; + $pi->charged = 1; + $pi->price = $amount; + $pi->taxed = false; + $pi->created_at = date('Y-m-d H:i:s'); + $pi->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($pi); } public function creditInvoiceItem(\Model_InvoiceItem $item) { $total = $this->getTotalWithTax($item); - if($total <= 0) { - return TRUE; + if ($total <= 0) { + return true; } $invoice = $this->di['db']->getExistingModelById('Invoice', $item->invoice_id, 'Invoice not found'); @@ -274,16 +275,17 @@ class ServiceInvoiceItem implements InjectionAwareInterface public function getOrderId(\Model_InvoiceItem $item) { - if($item->type == \Model_InvoiceItem::TYPE_ORDER) { + if (\Model_InvoiceItem::TYPE_ORDER == $item->type) { return (int) $item->rel_id; } + return 0; } protected function markAsExecuted(\Model_InvoiceItem $item) { - $item->status = \Model_InvoiceItem::STATUS_EXECUTED; - $item->updated_at = date('Y-m-d H:i:s'); + $item->status = \Model_InvoiceItem::STATUS_EXECUTED; + $item->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($item); } @@ -296,61 +298,62 @@ class ServiceInvoiceItem implements InjectionAwareInterface $taxed = $clientService->isClientTaxable($client); $pi = $this->di['db']->dispense('InvoiceItem'); - $pi->invoice_id = $proforma->id; - $pi->type = \Model_InvoiceItem::TYPE_ORDER; - $pi->rel_id = $order->id; - $pi->task = $task; - $pi->status = \Model_InvoiceItem::STATUS_PENDING_PAYMENT; - $pi->title = $order->title; - $pi->period = $order->period; - $pi->quantity = $order->quantity; - $pi->unit = $order->unit; - $pi->price = $price; - $pi->taxed = $taxed; - $pi->created_at = date('Y-m-d H:i:s'); - $pi->updated_at = date('Y-m-d H:i:s'); + $pi->invoice_id = $proforma->id; + $pi->type = \Model_InvoiceItem::TYPE_ORDER; + $pi->rel_id = $order->id; + $pi->task = $task; + $pi->status = \Model_InvoiceItem::STATUS_PENDING_PAYMENT; + $pi->title = $order->title; + $pi->period = $order->period; + $pi->quantity = $order->quantity; + $pi->unit = $order->unit; + $pi->price = $price; + $pi->taxed = $taxed; + $pi->created_at = date('Y-m-d H:i:s'); + $pi->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($pi); $corderService->setUnpaidInvoice($order, $proforma); - + // apply discount for new invoice if promo code is recurrent - if($order->promo_recurring) { + if ($order->promo_recurring) { $order_total = $order->price * $order->quantity; $promo_discount = $order->discount; - if($promo_discount > $order_total) { + if ($promo_discount > $order_total) { $promo_discount = $order_total; } $discount_title = $this->_getTitleForPromoDiscount($order->promo_id, $order->currency); $pd = [ - 'title' => $discount_title, - 'price' => $promo_discount * -1, + 'title' => $discount_title, + 'price' => $promo_discount * -1, 'quantity' => 1, - 'unit' => 'discount', - 'rel_id' => $order->id, - 'taxed' => $taxed, + 'unit' => 'discount', + 'rel_id' => $order->id, + 'taxed' => $taxed, ]; $this->addNew($proforma, $pd); - $order->promo_used +=1; + ++$order->promo_used; $this->di['db']->store($order); } } - + private function _getTitleForPromoDiscount($promo_id, $currency) - { + { $promo = $this->di['db']->findOne('Promo', 'id = ?', [$promo_id]); $api_guest = $this->di['api_guest']; - + switch ($promo->type) { case \Model_Promo::ABSOLUTE: $currencyAmount = $api_guest->currency_format(['code' => $currency, 'price' => $promo->value]); - return __('Promotional Code: :code - :value Discount', [':code' => $promo->code, ':value' => $currencyAmount]); + + return __('Promotional Code: :code - :value Discount', [':code' => $promo->code, ':value' => $currencyAmount]); case \Model_Promo::PERCENTAGE: - return __('Promotional Code: :code - :value%', [':code' => $promo->code, ':value' => $promo->value]); + return __('Promotional Code: :code - :value%', [':code' => $promo->code, ':value' => $promo->value]); default: break; @@ -358,20 +361,21 @@ class ServiceInvoiceItem implements InjectionAwareInterface } /** - * Get list of paid invoice not executed invoice items + * Get list of paid invoice not executed invoice items. + * * @return array - array of Model_InvoiceItem items */ public function getAllNotExecutePaidItems() { - $sql = 'SELECT invoice_item.* + $sql = 'SELECT invoice_item.* FROM invoice_item left join invoice on invoice_item.invoice_id = invoice.id WHERE invoice_item.status != :item_status and invoice.status = :invoice_status'; - $bindings = array( - ':item_status' => \Model_InvoiceItem::STATUS_EXECUTED, + $bindings = [ + ':item_status' => \Model_InvoiceItem::STATUS_EXECUTED, ':invoice_status' => \Model_Invoice::STATUS_PAID, - ); + ]; return $this->di['db']->getAll($sql, $bindings); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Invoice/ServicePayGateway.php b/src/bb-modules/Invoice/ServicePayGateway.php index 771d16b4f..d332b2a3d 100644 --- a/src/bb-modules/Invoice/ServicePayGateway.php +++ b/src/bb-modules/Invoice/ServicePayGateway.php @@ -1,6 +1,6 @@ di; } - public function getSearchQuery(array $data) { $sql = 'SELECT * FROM pay_gateway WHERE 1 '; - $search = $this->di['array_get']($data, 'search', NULL); - $params = array(); - if($search) { + $search = $this->di['array_get']($data, 'search', null); + $params = []; + if ($search) { $sql .= 'AND m.name LIKE :search'; $params['search'] = "%$search%"; } $sql .= ' ORDER by gateway ASC'; - return array($sql, $params); + return [$sql, $params]; } public function getPairs() @@ -61,10 +61,11 @@ class ServicePayGateway implements InjectionAwareInterface FROM pay_gateway'; $rows = $this->di['db']->getAll($sql); - $result = array(); - foreach ($rows as $row){ - $result[ $row['id'] ] = $row['name']; + $result = []; + foreach ($rows as $row) { + $result[$row['id']] = $row['name']; } + return $result; } @@ -74,16 +75,16 @@ class ServicePayGateway implements InjectionAwareInterface FROM pay_gateway'; $rows = $this->di['db']->getAll($sql); - $exists = array(); - foreach ($rows as $row){ - $exists[ $row['gateway'] ] = $row['name']; + $exists = []; + foreach ($rows as $row) { + $exists[$row['gateway']] = $row['name']; } $pattern = BB_PATH_LIBRARY.'/Payment/Adapter/*.php'; - $adapters = array(); - foreach(glob($pattern) as $path) { + $adapters = []; + foreach (glob($pattern) as $path) { $adapter = pathinfo($path, PATHINFO_FILENAME); - if(!array_key_exists($adapter, $exists)) { + if (!array_key_exists($adapter, $exists)) { $adapters[] = $adapter; } } @@ -94,7 +95,7 @@ class ServicePayGateway implements InjectionAwareInterface public function install($code) { $available = $this->getAvailable(); - if(!in_array($code, $available)) { + if (!in_array($code, $available)) { throw new \Box_Exception('Payment gateway is not available for installation.'); } @@ -102,37 +103,38 @@ class ServicePayGateway implements InjectionAwareInterface $new->name = $code; $new->gateway = $code; $new->enabled = 0; - $new->accepted_currencies = NULL; + $new->accepted_currencies = null; $new->test_mode = 0; - $new->config = NULL; + $new->config = null; $this->di['db']->store($new); $this->di['logger']->info('Installed new payment gateway %s', $code); + return true; } public function toApiArray(\Model_PayGateway $model, $deep = false, $identity = null) { - list($single, $recurrent) = $this->_getAllowTuple($model); + [$single, $recurrent] = $this->_getAllowTuple($model); - $result = array( - 'id' => $model->id, - 'code' => $model->gateway, - 'title' => $model->name, - 'allow_single' => $model->allow_single, - 'allow_recurrent' => $model->allow_recurrent, - 'accepted_currencies' => $this->getAcceptedCurrencies($model), - ); + $result = [ + 'id' => $model->id, + 'code' => $model->gateway, + 'title' => $model->name, + 'allow_single' => $model->allow_single, + 'allow_recurrent' => $model->allow_recurrent, + 'accepted_currencies' => $this->getAcceptedCurrencies($model), + ]; - if($identity instanceof \Model_Admin) { - $result['supports_one_time_payments'] = $single; - $result['supports_subscriptions'] = $recurrent; - $result['config'] = json_decode($model->config, 1); - $result['form'] = $this->getFormElements($model); - $result['description'] = $this->getDescription($model); - $result['enabled'] = $model->enabled; - $result['test_mode'] = $model->test_mode; - $result['callback'] = $this->getCallbackUrl($model); + if ($identity instanceof \Model_Admin) { + $result['supports_one_time_payments'] = $single; + $result['supports_subscriptions'] = $recurrent; + $result['config'] = json_decode($model->config, 1); + $result['form'] = $this->getFormElements($model); + $result['description'] = $this->getDescription($model); + $result['enabled'] = $model->enabled; + $result['test_mode'] = $model->test_mode; + $result['callback'] = $this->getCallbackUrl($model); } return $result; @@ -141,7 +143,7 @@ class ServicePayGateway implements InjectionAwareInterface public function copy(\Model_PayGateway $model) { $new = $this->di['db']->dispense('PayGateway'); - $new->name = $model->name . ' (Copy)'; + $new->name = $model->name.' (Copy)'; $new->gateway = $model->gateway; $new->enabled = 0; $new->accepted_currencies = $model->accepted_currencies; @@ -149,26 +151,28 @@ class ServicePayGateway implements InjectionAwareInterface $new->config = $model->config; $newId = $this->di['db']->store($new); $this->di['logger']->info('Copied payment gateway #%s - %s', $newId, $model->gateway); + return $newId; } public function update(\Model_PayGateway $model, array $data) { $model->name = $this->di['array_get']($data, 'title', $model->name); - if(isset($data['config']) && is_array($data['config'])) { + if (isset($data['config']) && is_array($data['config'])) { $model->config = json_encode($data['config']); } - if(isset($data['accepted_currencies']) && is_array($data['accepted_currencies'])) { + if (isset($data['accepted_currencies']) && is_array($data['accepted_currencies'])) { $model->accepted_currencies = json_encode($data['accepted_currencies']); } - $model->enabled = $this->di['array_get']($data, 'enabled', $model->enabled); - $model->allow_single = (bool)$this->di['array_get']($data, 'allow_single', $model->allow_single); - $model->allow_recurrent = (bool)$this->di['array_get']($data, 'allow_recurrent', $model->allow_recurrent); - $model->test_mode = $this->di['array_get']($data, 'test_mode', $model->test_mode); + $model->enabled = $this->di['array_get']($data, 'enabled', $model->enabled); + $model->allow_single = (bool) $this->di['array_get']($data, 'allow_single', $model->allow_single); + $model->allow_recurrent = (bool) $this->di['array_get']($data, 'allow_recurrent', $model->allow_recurrent); + $model->test_mode = $this->di['array_get']($data, 'test_mode', $model->test_mode); $this->di['db']->store($model); $this->di['logger']->info('Updated payment gateway %s', $model->gateway); + return true; } @@ -186,40 +190,41 @@ class ServicePayGateway implements InjectionAwareInterface $format = $this->di['array_get']($data, 'format', null); $gateways = $this->di['db']->find('PayGateway', 'enabled = 1 ORDER BY id desc'); - $result = array(); - foreach($gateways as $gtw) { - if($format == 'pairs') { + $result = []; + foreach ($gateways as $gtw) { + if ('pairs' == $format) { $result[$gtw->id] = $gtw->name; } else { $result[] = $this->toApiArray($gtw); } } + return $result; } public function canPerformRecurrentPayment(\Model_PayGateway $model) { - return (bool)$model->allow_recurrent; + return (bool) $model->allow_recurrent; } - public function getPaymentAdapter(\Model_PayGateway $pg, \Model_Invoice $model = null, $optional = array()) + public function getPaymentAdapter(\Model_PayGateway $pg, \Model_Invoice $model = null, $optional = []) { $config = $this->di['tools']->decodeJ($pg->config); - $defaults = array(); - $defaults['auto_redirect'] = false; - $defaults['test_mode'] = $pg->test_mode; - $defaults['return_url'] = $this->getReturnUrl($pg, $model); - $defaults['cancel_url'] = $this->getCancelUrl($pg, $model); - $defaults['notify_url'] = $this->getCallbackUrl($pg, $model); - $defaults['redirect_url'] = $this->getCallbackRedirect($pg, $model); + $defaults = []; + $defaults['auto_redirect'] = false; + $defaults['test_mode'] = $pg->test_mode; + $defaults['return_url'] = $this->getReturnUrl($pg, $model); + $defaults['cancel_url'] = $this->getCancelUrl($pg, $model); + $defaults['notify_url'] = $this->getCallbackUrl($pg, $model); + $defaults['redirect_url'] = $this->getCallbackRedirect($pg, $model); $defaults['continue_shopping_url'] = $this->di['tools']->url('/order'); $defaults['single_page'] = true; - if($model instanceof \Model_Invoice) { - $defaults['thankyou_url'] = $this->di['tools']->url('/invoice/thank-you/'.$model->hash); - $defaults['invoice_url'] = $this->di['tools']->url('/invoice/'.$model->hash); + if ($model instanceof \Model_Invoice) { + $defaults['thankyou_url'] = $this->di['tools']->url('/invoice/thank-you/'.$model->hash); + $defaults['invoice_url'] = $this->di['tools']->url('/invoice/'.$model->hash); } - if(isset($optional['auto_redirect'])) { + if (isset($optional['auto_redirect'])) { $defaults['auto_redirect'] = $optional['auto_redirect']; } @@ -227,13 +232,13 @@ class ServicePayGateway implements InjectionAwareInterface $class = $this->getAdapterClassName($pg); - if(!class_exists($class)) { - throw new \Box_Exception("Payment gateway :adapter was not found", array(':adapter'=>$class)); + if (!class_exists($class)) { + throw new \Box_Exception('Payment gateway :adapter was not found', [':adapter' => $class]); } $adapter = new $class($config); - if(method_exists($adapter, 'setDi')) { + if (method_exists($adapter, 'setDi')) { $adapter->setDi($this->di); } @@ -243,32 +248,33 @@ class ServicePayGateway implements InjectionAwareInterface private function _getAllowTuple(\Model_PayGateway $model) { $adapter_config = $this->getAdapterConfig($model); - $single = $this->di['array_get']($adapter_config, 'supports_one_time_payments', FALSE); - $recurrent = $this->di['array_get']($adapter_config, 'supports_subscriptions', FALSE); + $single = $this->di['array_get']($adapter_config, 'supports_one_time_payments', false); + $recurrent = $this->di['array_get']($adapter_config, 'supports_subscriptions', false); - return array( + return [ $single, $recurrent, - ); + ]; } public function getAdapterConfig(\Model_PayGateway $pg) { $class = $this->getAdapterClassName($pg); - if(!file_exists(BB_PATH_LIBRARY.'/Payment/Adapter/'.$pg->gateway.'.php')) { - throw new \Box_Exception("Payment gateway :adapter was not found", array(':adapter'=>$pg->gateway)); + if (!file_exists(BB_PATH_LIBRARY.'/Payment/Adapter/'.$pg->gateway.'.php')) { + throw new \Box_Exception('Payment gateway :adapter was not found', [':adapter' => $pg->gateway]); } - if(!class_exists($class)) { + if (!class_exists($class)) { throw new \Box_Exception("Payment gateway class $class was not found"); } - if(!method_exists($class, 'getConfig')) { + if (!method_exists($class, 'getConfig')) { error_log("Payment $class gateway does not have getConfig method"); - return array(); + + return []; } - return call_user_func(array($class, 'getConfig')); + return call_user_func([$class, 'getConfig']); } public function getAdapterClassName(\Model_PayGateway $pg) @@ -278,8 +284,9 @@ class ServicePayGateway implements InjectionAwareInterface public function getAcceptedCurrencies(\Model_PayGateway $model) { - if(null === $model->accepted_currencies || empty($model->accepted_currencies)) { + if (null === $model->accepted_currencies || empty($model->accepted_currencies)) { $currencyService = $this->di['mod_service']('Currency'); + return array_keys($currencyService->getPairs()); } @@ -289,16 +296,18 @@ class ServicePayGateway implements InjectionAwareInterface public function getFormElements(\Model_PayGateway $model) { $config = $this->getAdapterConfig($model); - if(isset($config['form']) && is_array($config['form'])) { + if (isset($config['form']) && is_array($config['form'])) { return $config['form']; } - return array(); + + return []; } public function getDescription(\Model_PayGateway $model) { $config = $this->getAdapterConfig($model); - return (isset($config['description'])) ? $config['description'] : NULL; + + return (isset($config['description'])) ? $config['description'] : null; } /** @@ -306,13 +315,14 @@ class ServicePayGateway implements InjectionAwareInterface */ public function getCallbackUrl(\Model_PayGateway $pg, $model = null) { - $p = array( - 'bb_gateway_id' => $pg->id, - ); - if($model instanceof \Model_Invoice) { + $p = [ + 'bb_gateway_id' => $pg->id, + ]; + if ($model instanceof \Model_Invoice) { $p['bb_invoice_id'] = $model->id; } - return $this->di['config']['url'] . 'bb-ipn.php?'.http_build_query($p); + + return $this->di['config']['url'].'bb-ipn.php?'.http_build_query($p); } /** @@ -320,22 +330,23 @@ class ServicePayGateway implements InjectionAwareInterface */ private function getReturnUrl(\Model_PayGateway $pg, $model = null) { - if($model instanceof \Model_Invoice) { - return $this->di['url']->link('/invoice/'.$model->hash, array('status'=> 'ok')); + if ($model instanceof \Model_Invoice) { + return $this->di['url']->link('/invoice/'.$model->hash, ['status' => 'ok']); } - return $this->di['url']->link('/invoice', array('status'=> 'ok')); - } + return $this->di['url']->link('/invoice', ['status' => 'ok']); + } /** * @param \Model_Invoice $model */ private function getCancelUrl(\Model_PayGateway $pg, $model = null) { - if($model instanceof \Model_Invoice) { - return $this->di['url']->link('/invoice/'.$model->hash, array('status'=> 'cancel')); + if ($model instanceof \Model_Invoice) { + return $this->di['url']->link('/invoice/'.$model->hash, ['status' => 'cancel']); } - return $this->di['url']->link('/invoice', array('status'=> 'cancel')); + + return $this->di['url']->link('/invoice', ['status' => 'cancel']); } /** @@ -343,15 +354,16 @@ class ServicePayGateway implements InjectionAwareInterface */ private function getCallbackRedirect(\Model_PayGateway $pg, $model = null) { - $p = array( - 'bb_gateway_id' => $pg->id, - ); + $p = [ + 'bb_gateway_id' => $pg->id, + ]; - if($model instanceof \Model_Invoice) { - $p['bb_invoice_id'] = $model->id; - $p['bb_invoice_hash'] = $model->hash; - $p['bb_redirect'] = 1; + if ($model instanceof \Model_Invoice) { + $p['bb_invoice_id'] = $model->id; + $p['bb_invoice_hash'] = $model->hash; + $p['bb_redirect'] = 1; } - return $this->di['config']['url'] . 'bb-ipn.php?'.http_build_query($p); + + return $this->di['config']['url'].'bb-ipn.php?'.http_build_query($p); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Invoice/ServiceSubscription.php b/src/bb-modules/Invoice/ServiceSubscription.php index 3f755888e..301302ed6 100644 --- a/src/bb-modules/Invoice/ServiceSubscription.php +++ b/src/bb-modules/Invoice/ServiceSubscription.php @@ -1,6 +1,6 @@ di['db']->dispense('Subscription'); - $model->client_id = $data['client_id']; + $model = $this->di['db']->dispense('Subscription'); + $model->client_id = $data['client_id']; $model->pay_gateway_id = $data['gateway_id']; - $model->sid = $this->di['array_get']($data, 'sid', NULL); - $model->status = $this->di['array_get']($data, 'status', NULL); - $model->period = $this->di['array_get']($data, 'period', NULL); - $model->amount = $this->di['array_get']($data, 'amount', NULL); - $model->currency = $this->di['array_get']($data, 'currency', NULL); - $model->rel_id = $this->di['array_get']($data, 'rel_id', NULL); - $model->rel_type = $this->di['array_get']($data, 'rel_type', NULL); + $model->sid = $this->di['array_get']($data, 'sid', null); + $model->status = $this->di['array_get']($data, 'status', null); + $model->period = $this->di['array_get']($data, 'period', null); + $model->amount = $this->di['array_get']($data, 'amount', null); + $model->currency = $this->di['array_get']($data, 'currency', null); + $model->rel_id = $this->di['array_get']($data, 'rel_id', null); + $model->rel_type = $this->di['array_get']($data, 'rel_type', null); $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); - $newId = $this->di['db']->store($model); + $newId = $this->di['db']->store($model); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminSubscriptionCreate', 'params' => array('id' => $newId))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminSubscriptionCreate', 'params' => ['id' => $newId]]); $this->di['logger']->info('Created subscription %s', $newId); @@ -61,37 +63,37 @@ class ServiceSubscription implements InjectionAwareInterface public function update(\Model_Subscription $model, array $data) { - $model->status = $this->di['array_get']($data, 'status', $model->status); - $model->sid = $this->di['array_get']($data, 'sid', $model->sid); - $model->period = $this->di['array_get']($data, 'period', $model->period); - $model->amount = $this->di['array_get']($data, 'amount', $model->amount); - $model->currency = $this->di['array_get']($data, 'currency', $model->currency); + $model->status = $this->di['array_get']($data, 'status', $model->status); + $model->sid = $this->di['array_get']($data, 'sid', $model->sid); + $model->period = $this->di['array_get']($data, 'period', $model->period); + $model->amount = $this->di['array_get']($data, 'amount', $model->amount); + $model->currency = $this->di['array_get']($data, 'currency', $model->currency); $model->updated_at = date('Y-m-d H:i:s'); - $newId = $this->di['db']->store($model); + $newId = $this->di['db']->store($model); $this->di['logger']->info('Updated subscription %s', $newId); + return true; } - public function toApiArray(\Model_Subscription $model, $deep = false, $identity = null) { - $result = array( - 'id' => $model->id, - 'sid' => $model->sid, - 'period' => $model->period, - 'amount' => $model->amount, - 'currency' => $model->currency, - 'status' => $model->status, + $result = [ + 'id' => $model->id, + 'sid' => $model->sid, + 'period' => $model->period, + 'amount' => $model->amount, + 'currency' => $model->currency, + 'status' => $model->status, 'created_at' => $model->created_at, 'updated_at' => $model->updated_at, - ); + ]; $client = $this->di['db']->load('Client', $model->client_id); if ($client instanceof \Model_Client) { - $clientService = $this->di['mod_service']('Client'); + $clientService = $this->di['mod_service']('Client'); $result['client'] = $clientService->toApiArray($client, false, $identity); } else { - $result['client'] = array(); + $result['client'] = []; } $gtw = $this->di['db']->load('PayGateway', $model->pay_gateway_id); @@ -99,7 +101,7 @@ class ServiceSubscription implements InjectionAwareInterface $payGatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); $result['gateway'] = $payGatewayService->toApiArray($gtw, false, $identity); } else { - $result['gateway'] = array(); + $result['gateway'] = []; } return $result; @@ -110,9 +112,10 @@ class ServiceSubscription implements InjectionAwareInterface $id = $model->id; $this->di['db']->trash($model); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminSubscriptionDelete', 'params'=>array('id'=>$id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminSubscriptionDelete', 'params' => ['id' => $id]]); $this->di['logger']->info('Removed subscription %s', $id); + return true; } @@ -122,19 +125,18 @@ class ServiceSubscription implements InjectionAwareInterface FROM subscription WHERE 1 '; + $id = $this->di['array_get']($data, 'id', null); + $sid = $this->di['array_get']($data, 'sid', null); + $search = $this->di['array_get']($data, 'search', null); + $invoice_id = $this->di['array_get']($data, 'invoice_id', null); + $gateway_id = $this->di['array_get']($data, 'gateway_id', null); + $client_id = $this->di['array_get']($data, 'client_id', null); + $status = $this->di['array_get']($data, 'status', null); + $currency = $this->di['array_get']($data, 'currency', null); - $id = $this->di['array_get']($data, 'id', NULL); - $sid = $this->di['array_get']($data, 'sid', NULL); - $search = $this->di['array_get']($data, 'search', NULL); - $invoice_id = $this->di['array_get']($data, 'invoice_id', NULL); - $gateway_id = $this->di['array_get']($data, 'gateway_id', NULL); - $client_id = $this->di['array_get']($data, 'client_id', NULL); - $status = $this->di['array_get']($data, 'status', NULL); - $currency = $this->di['array_get']($data, 'currency', NULL); - - $date_from = $this->di['array_get']($data, 'date_from', NULL); - $date_to = $this->di['array_get']($data, 'date_to', NULL); - $params = array(); + $date_from = $this->di['array_get']($data, 'date_from', null); + $date_to = $this->di['array_get']($data, 'date_to', null); + $params = []; if ($status) { $sql .= ' AND status = :status'; $params['status'] = $status; @@ -163,7 +165,6 @@ class ServiceSubscription implements InjectionAwareInterface if ($date_from) { $sql .= ' AND UNIX_TIMESTAMP(m.created_at) >= :date_from'; $params['date_from'] = $date_from; - } if ($date_to) { @@ -187,33 +188,32 @@ class ServiceSubscription implements InjectionAwareInterface $params['sid'] = $sid; } - $sql .= ' ORDER BY id DESC'; - return array($sql, $params); + return [$sql, $params]; } public function isSubscribable($invoice_id) { - $query = "SELECT COUNT(id) as cc + $query = 'SELECT COUNT(id) as cc FROM invoice_item WHERE invoice_id = :id GROUP BY invoice_id - "; - $count = $this->di['db']->getCell($query, array('id'=>$invoice_id)); - if($count > 1) { + '; + $count = $this->di['db']->getCell($query, ['id' => $invoice_id]); + if ($count > 1) { return false; } // check if first invoice line has deined period - $query = "SELECT id, period + $query = 'SELECT id, period FROM invoice_item WHERE invoice_id = :id LIMIT 1 - "; - $list = $this->di['db']->getAll($query, array(':id' => $invoice_id)); + '; + $list = $this->di['db']->getAll($query, [':id' => $invoice_id]); - if(isset($list[0]) + if (isset($list[0]) && isset($list[0]['period']) && !empty($list[0]['period'])) { return true; @@ -224,16 +224,17 @@ class ServiceSubscription implements InjectionAwareInterface public function getSubscriptionPeriod(\Model_Invoice $invoice) { - if(!$this->isSubscribable($invoice->id)) { - return NULL; + if (!$this->isSubscribable($invoice->id)) { + return null; } - $query = "SELECT period + $query = 'SELECT period FROM invoice_item WHERE invoice_id = :id LIMIT 1 - "; - return $this->di['db']->getCell($query, array('id'=>$invoice->id)); + '; + + return $this->di['db']->getCell($query, ['id' => $invoice->id]); } public function unsubscribe(\Model_Subscription $model) @@ -242,4 +243,4 @@ class ServiceSubscription implements InjectionAwareInterface $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Invoice/ServiceTax.php b/src/bb-modules/Invoice/ServiceTax.php index e042ecc35..91675477f 100644 --- a/src/bb-modules/Invoice/ServiceTax.php +++ b/src/bb-modules/Invoice/ServiceTax.php @@ -1,6 +1,6 @@ di['mod_service']('client'); - if(!$clientService->isClientTaxable($model)) { + if (!$clientService->isClientTaxable($model)) { return 0; } - $tax = $this->di['db']->findOne('Tax', 'state = ? and country = ?', array($model->state, $model->country)); + $tax = $this->di['db']->findOne('Tax', 'state = ? and country = ?', [$model->state, $model->country]); // find rate which matches clients country and state - if($tax instanceof \Model_Tax) { + if ($tax instanceof \Model_Tax) { $title = $tax->name; + return $tax->taxrate; } // find rate which matches clients country - $tax = $this->di['db']->findOne('Tax', 'country = ?', array($model->country)); - if($tax instanceof \Model_Tax) { + $tax = $this->di['db']->findOne('Tax', 'country = ?', [$model->country]); + if ($tax instanceof \Model_Tax) { $title = $tax->name; + return $tax->taxrate; } // find global rate $tax = $this->di['db']->findOne('Tax', '(state is NULL or state = "") and (country is null or country = "")'); - if($tax instanceof \Model_Tax) { + if ($tax instanceof \Model_Tax) { $title = $tax->name; + return $tax->taxrate; } @@ -69,16 +74,17 @@ class ServiceTax implements InjectionAwareInterface public function getTax(\Model_Invoice $invoice) { - if($invoice->taxrate <= 0) { + if ($invoice->taxrate <= 0) { return 0; } $tax = 0; - $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', array($invoice->id)); + $invoiceItems = $this->di['db']->find('InvoiceItem', 'invoice_id = ?', [$invoice->id]); $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); - foreach($invoiceItems as $item) { + foreach ($invoiceItems as $item) { $tax += $invoiceItemService->getTax($item) * $item->quantity; } + return $tax; } @@ -87,6 +93,7 @@ class ServiceTax implements InjectionAwareInterface $name = $model->name; $this->di['db']->trash($model); $this->di['logger']->info('Deleted tax rule %s', $name); + return true; } @@ -97,29 +104,31 @@ class ServiceTax implements InjectionAwareInterface $model = $this->di['db']->dispense('Tax'); $model->name = $data['name']; - $model->country = (!isset($data['country']) || empty($data['country'])) ? NULL : $data['country']; - $model->state = (!isset($data['state']) || empty($data['state'])) ? NULL : $data['state']; + $model->country = (!isset($data['country']) || empty($data['country'])) ? null : $data['country']; + $model->state = (!isset($data['state']) || empty($data['state'])) ? null : $data['state']; $model->taxrate = $data['taxrate']; $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); $newId = $this->di['db']->store($model); $this->di['logger']->info('Created new tax rule %s', $model->name); - return $newId ; + + return $newId; } public function update(\Model_Tax $model, array $data) { $model->name = $data['name']; - $model->country = (!isset($data['country']) || empty($data['country'])) ? NULL : $data['country']; - $model->state = (!isset($data['state']) || empty($data['state'])) ? NULL : $data['state']; + $model->country = (!isset($data['country']) || empty($data['country'])) ? null : $data['country']; + $model->state = (!isset($data['state']) || empty($data['state'])) ? null : $data['state']; $model->taxrate = $data['taxrate']; $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Created new tax rule %s', $model->name); - return true ; + + return true; } public function getSearchQuery($data) @@ -128,19 +137,19 @@ class ServiceTax implements InjectionAwareInterface FROM tax ORDER BY id desc'; - return array($sql, array()); + return [$sql, []]; } public function setupEUTaxes(array $data) { - $sql = "TRUNCATE tax;"; + $sql = 'TRUNCATE tax;'; $this->di['db']->exec($sql); $systemService = $this->di['mod_service']('System'); - $eu_countries = $systemService->getEuCountries(); - $eu_vat = $systemService->getEuVat(); + $eu_countries = $systemService->getEuCountries(); + $eu_vat = $systemService->getEuVat(); foreach ($eu_vat as $code => $taxRate) { - $this->create(array('name' => $eu_countries[$code], 'taxrate' => $taxRate, 'country' => $code)); + $this->create(['name' => $eu_countries[$code], 'taxrate' => $taxRate, 'country' => $code]); } return true; @@ -150,5 +159,4 @@ class ServiceTax implements InjectionAwareInterface { return $this->di['db']->toArray($model); } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Invoice/ServiceTransaction.php b/src/bb-modules/Invoice/ServiceTransaction.php index a1996262a..9f05575c5 100644 --- a/src/bb-modules/Invoice/ServiceTransaction.php +++ b/src/bb-modules/Invoice/ServiceTransaction.php @@ -1,6 +1,6 @@ di['logger']->info('Executed action to process received transactions'); $received = $this->getReceived(); - foreach($received as $transaction) { + foreach ($received as $transaction) { $model = $this->di['db']->getExistingModelById('Transaction', $transaction['id']); $this->preProcessTransaction($model); } + return true; } public function update(\Model_Transaction $model, array $data) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminTransactionUpdate', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminTransactionUpdate', 'params' => ['id' => $model->id]]); $model->invoice_id = $this->di['array_get']($data, 'invoice_id', $model->invoice_id); $model->txn_id = $this->di['array_get']($data, 'txn_id', $model->txn_id); @@ -64,9 +67,10 @@ class ServiceTransaction implements InjectionAwareInterface $model->validate_ipn = $this->di['array_get']($data, 'validate_ipn', $model->validate_ipn); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminTransactionUpdate', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminTransactionUpdate', 'params' => ['id' => $model->id]]); $this->di['logger']->info('Updated transaction #%s', $model->id); + return true; } @@ -74,48 +78,49 @@ class ServiceTransaction implements InjectionAwareInterface { $id = $this->create($ipn); $this->processTransaction($id); + return $id; } public function create(array $data) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminTransactionCreate', 'params'=>$data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminTransactionCreate', 'params' => $data]); - $skip_validation = isset($data['skip_validation']) ? (bool)$data['skip_validation'] : false; - if(!$skip_validation) { - if(!isset($data['bb_invoice_id'])) { + $skip_validation = isset($data['skip_validation']) ? (bool) $data['skip_validation'] : false; + if (!$skip_validation) { + if (!isset($data['bb_invoice_id'])) { throw new \Box_Exception('Transaction invoice id is missing'); } - if(!isset($data['bb_gateway_id'])) { + if (!isset($data['bb_gateway_id'])) { throw new \Box_Exception('Payment gateway id is missing'); } $this->di['db']->getExistingModelById('Invoice', $data['bb_invoice_id'], 'Invoice was not found'); $this->di['db']->getExistingModelById('PayGateway', $data['bb_gateway_id'], 'Gateway was not found'); } - $ipn = array( - 'get' => (isset($data['get']) && is_array($data['get'])) ? $data['get'] : NULL, - 'post' => (isset($data['post']) && is_array($data['post'])) ? $data['post'] : NULL, - 'http_raw_post_data' => $this->di['array_get']($data, 'http_raw_post_data', NULL), - 'server' => $this->di['array_get']($data, 'server', NULL), - ); + $ipn = [ + 'get' => (isset($data['get']) && is_array($data['get'])) ? $data['get'] : null, + 'post' => (isset($data['post']) && is_array($data['post'])) ? $data['post'] : null, + 'http_raw_post_data' => $this->di['array_get']($data, 'http_raw_post_data', null), + 'server' => $this->di['array_get']($data, 'server', null), + ]; $transaction = $this->di['db']->dispense('Transaction'); - $transaction->gateway_id = $this->di['array_get']($data, 'bb_gateway_id', NULL); - $transaction->invoice_id = $this->di['array_get']($data, 'bb_invoice_id', NULL); - $transaction->txn_id = $this->di['array_get']($data, 'txn_id', NULL); - $transaction->status = 'received'; - $transaction->ip = $this->di['request']->getClientAddress(); - $transaction->ipn = json_encode($ipn); - $transaction->note = (isset($data['note'])) ? $data['note'] : NULL; - $transaction->created_at = date('Y-m-d H:i:s'); - $transaction->updated_at = date('Y-m-d H:i:s'); + $transaction->gateway_id = $this->di['array_get']($data, 'bb_gateway_id', null); + $transaction->invoice_id = $this->di['array_get']($data, 'bb_invoice_id', null); + $transaction->txn_id = $this->di['array_get']($data, 'txn_id', null); + $transaction->status = 'received'; + $transaction->ip = $this->di['request']->getClientAddress(); + $transaction->ipn = json_encode($ipn); + $transaction->note = (isset($data['note'])) ? $data['note'] : null; + $transaction->created_at = date('Y-m-d H:i:s'); + $transaction->updated_at = date('Y-m-d H:i:s'); $newId = $this->di['db']->store($transaction); $this->di['logger']->info('Received transaction %s from payment gateway %s', $newId, $transaction->gateway_id); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminTransactionCreate', 'params'=>array('id'=>$newId))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminTransactionCreate', 'params' => ['id' => $newId]]); return $newId; } @@ -125,41 +130,43 @@ class ServiceTransaction implements InjectionAwareInterface $id = $model->id; $this->di['db']->trash($model); $this->di['logger']->info('Removed transaction #%s', $id); + return true; } public function toApiArray(\Model_Transaction $model, $deep = false, $identity = null) { - $gateway = NULL; - if($model->gateway_id) { + $gateway = null; + if ($model->gateway_id) { $gtw = $this->di['db']->load('PayGateway', $model->gateway_id); - if($gtw instanceof \Model_PayGateway) { + if ($gtw instanceof \Model_PayGateway) { $gateway = $gtw->name; } } - $result = array( - 'id' => $model->id, - 'invoice_id' => $model->invoice_id, - 'txn_id' => $model->txn_id, - 'txn_status' => $model->txn_status, - 'gateway_id' => $model->gateway_id, - 'gateway' => $gateway, - 'amount' => $model->amount, - 'currency' => $model->currency, - 'type' => $model->type, - 'status' => $model->status, - 'ip' => $model->ip, - 'validate_ipn' => $model->validate_ipn, - 'error' => $model->error, - 'error_code' => $model->error_code, - 'note' => $model->note, - 'created_at' => $model->created_at, - 'updated_at' => $model->updated_at, - ); - if($deep) { + $result = [ + 'id' => $model->id, + 'invoice_id' => $model->invoice_id, + 'txn_id' => $model->txn_id, + 'txn_status' => $model->txn_status, + 'gateway_id' => $model->gateway_id, + 'gateway' => $gateway, + 'amount' => $model->amount, + 'currency' => $model->currency, + 'type' => $model->type, + 'status' => $model->status, + 'ip' => $model->ip, + 'validate_ipn' => $model->validate_ipn, + 'error' => $model->error, + 'error_code' => $model->error_code, + 'note' => $model->note, + 'created_at' => $model->created_at, + 'updated_at' => $model->updated_at, + ]; + if ($deep) { $result['ipn'] = json_decode($model->ipn, true); } + return $result; } @@ -170,21 +177,21 @@ class ServiceTransaction implements InjectionAwareInterface LEFT JOIN invoice as i on m.invoice_id = i.id WHERE 1 '; - $id = $this->di['array_get']($data, 'id', NULL); - $search = $this->di['array_get']($data, 'search', NULL); - $invoice_hash = $this->di['array_get']($data, 'invoice_hash', NULL); - $invoice_id = $this->di['array_get']($data, 'invoice_id', NULL); - $gateway_id = $this->di['array_get']($data, 'gateway_id', NULL); - $client_id = $this->di['array_get']($data, 'client_id', NULL); - $status = $this->di['array_get']($data, 'status', NULL); - $currency = $this->di['array_get']($data, 'currency', NULL); - $type = $this->di['array_get']($data, 'type', NULL); - $txn_id = $this->di['array_get']($data, 'txn_id', NULL); + $id = $this->di['array_get']($data, 'id', null); + $search = $this->di['array_get']($data, 'search', null); + $invoice_hash = $this->di['array_get']($data, 'invoice_hash', null); + $invoice_id = $this->di['array_get']($data, 'invoice_id', null); + $gateway_id = $this->di['array_get']($data, 'gateway_id', null); + $client_id = $this->di['array_get']($data, 'client_id', null); + $status = $this->di['array_get']($data, 'status', null); + $currency = $this->di['array_get']($data, 'currency', null); + $type = $this->di['array_get']($data, 'type', null); + $txn_id = $this->di['array_get']($data, 'txn_id', null); - $date_from = $this->di['array_get']($data, 'date_from', NULL); - $date_to = $this->di['array_get']($data, 'date_to', NULL); + $date_from = $this->di['array_get']($data, 'date_from', null); + $date_to = $this->di['array_get']($data, 'date_to', null); - $params = array(); + $params = []; if ($id) { $sql .= ' AND m.id = :id'; $params['id'] = $id; @@ -242,15 +249,15 @@ class ServiceTransaction implements InjectionAwareInterface if ($search) { $sql .= ' AND m.note LIKE :note OR m.invoice_id LIKE :search_invoice_id OR m.txn_id LIKE :search_txn_id OR m.ipn LIKE :ipn'; - $params['note'] = "%$search%"; + $params['note'] = "%$search%"; $params['search__invoice_id'] = "%$search%"; - $params['search_txn_id'] = "%$search%"; - $params['ipn'] = "%$search%"; + $params['search_txn_id'] = "%$search%"; + $params['ipn'] = "%$search%"; } $sql .= ' ORDER BY m.id DESC'; - return array($sql, $params); + return [$sql, $params]; } public function counter() @@ -259,59 +266,58 @@ class ServiceTransaction implements InjectionAwareInterface FROM transaction GROUP BY status'; $rows = $this->di['db']->getAll($sql); - $data = array(); - foreach($rows as $row){ - $data[ $row['status'] ] = $row['counter']; + $data = []; + foreach ($rows as $row) { + $data[$row['status']] = $row['counter']; } - return array( - 'total' => array_sum($data), - \Model_Transaction::STATUS_RECEIVED => isset($data[\Model_Transaction::STATUS_RECEIVED]) ? $data[\Model_Transaction::STATUS_RECEIVED] : 0, - \Model_Transaction::STATUS_APPROVED => isset($data[\Model_Transaction::STATUS_APPROVED]) ? $data[\Model_Transaction::STATUS_APPROVED] : 0, - \Model_Transaction::STATUS_PROCESSED => isset($data[\Model_Transaction::STATUS_PROCESSED]) ? $data[\Model_Transaction::STATUS_PROCESSED] : 0, - \Model_Transaction::STATUS_ERROR => isset($data[\Model_Transaction::STATUS_ERROR]) ? $data[\Model_Transaction::STATUS_ERROR] : 0, - ); + return [ + 'total' => array_sum($data), + \Model_Transaction::STATUS_RECEIVED => $data[\Model_Transaction::STATUS_RECEIVED] ?? 0, + \Model_Transaction::STATUS_APPROVED => $data[\Model_Transaction::STATUS_APPROVED] ?? 0, + \Model_Transaction::STATUS_PROCESSED => $data[\Model_Transaction::STATUS_PROCESSED] ?? 0, + \Model_Transaction::STATUS_ERROR => $data[\Model_Transaction::STATUS_ERROR] ?? 0, + ]; } public function getStatusPairs() { - return array( - \Model_Transaction::STATUS_RECEIVED => 'Received', - \Model_Transaction::STATUS_APPROVED => 'Approved', + return [ + \Model_Transaction::STATUS_RECEIVED => 'Received', + \Model_Transaction::STATUS_APPROVED => 'Approved', \Model_Transaction::STATUS_PROCESSED => 'Processed', - \Model_Transaction::STATUS_ERROR => 'Error', - ); + \Model_Transaction::STATUS_ERROR => 'Error', + ]; } public function getStatuses() { - return array( - \Model_Transaction::STATUS_RECEIVED => 'Received', - \Model_Transaction::STATUS_APPROVED => 'Approved/Verified', - \Model_Transaction::STATUS_PROCESSED => 'Processed', - \Model_Transaction::STATUS_ERROR => 'Error', - ); + return [ + \Model_Transaction::STATUS_RECEIVED => 'Received', + \Model_Transaction::STATUS_APPROVED => 'Approved/Verified', + \Model_Transaction::STATUS_PROCESSED => 'Processed', + \Model_Transaction::STATUS_ERROR => 'Error', + ]; } public function getGatewayStatuses() { - return array( - \Payment_Transaction::STATUS_PENDING => 'Pending validation', - \Payment_Transaction::STATUS_COMPLETE => 'Complete', - \Payment_Transaction::STATUS_UNKNOWN => 'Unknown', - - ); + return [ + \Payment_Transaction::STATUS_PENDING => 'Pending validation', + \Payment_Transaction::STATUS_COMPLETE => 'Complete', + \Payment_Transaction::STATUS_UNKNOWN => 'Unknown', + ]; } public function getTypes() { - return array( - \Payment_Transaction::TXTYPE_PAYMENT => 'Payment', - \Payment_Transaction::TXTYPE_REFUND => 'Refund', - \Payment_Transaction::TXTYPE_SUBSCR_CREATE => 'Subscription create', - \Payment_Transaction::TXTYPE_SUBSCR_CANCEL => 'Subscription cancel', - \Payment_Transaction::TXTYPE_UNKNOWN => 'Unknown', - ); + return [ + \Payment_Transaction::TXTYPE_PAYMENT => 'Payment', + \Payment_Transaction::TXTYPE_REFUND => 'Refund', + \Payment_Transaction::TXTYPE_SUBSCR_CREATE => 'Subscription create', + \Payment_Transaction::TXTYPE_SUBSCR_CANCEL => 'Subscription cancel', + \Payment_Transaction::TXTYPE_UNKNOWN => 'Unknown', + ]; } /** @@ -320,6 +326,7 @@ class ServiceTransaction implements InjectionAwareInterface public function oldProcessLogic($model) { $tx = $this->process($model); + return !empty($tx->output) ? $tx->output : null; } @@ -329,7 +336,7 @@ class ServiceTransaction implements InjectionAwareInterface $output = $this->processTransaction($model->id); } catch (\Box_Exception $e) { // if gateway does not support new logic use old logic - if($e->getCode() == 705) { + if (705 == $e->getCode()) { $output = $this->oldProcessLogic($model); } else { $model->status = \Model_Transaction::STATUS_ERROR; @@ -341,52 +348,56 @@ class ServiceTransaction implements InjectionAwareInterface } } - $this->di['events_manager']->fire(array('event'=>'onAfterAdminTransactionProcess', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminTransactionProcess', 'params' => ['id' => $model->id]]); $this->di['logger']->info('Processed transaction #%s', $model->id); - return !empty($output) ? $output : true; + return !empty($output) ? $output : true; } /** - * New simplified transaction processing logic + * New simplified transaction processing logic. * * @since 2.9.11 + * * @param type $id + * * @return mixed + * * @throws Box_Exception */ public function processTransaction($id) { $tx = $this->di['db']->load('Transaction', $id); - if(!$tx) { - throw new \Box_Exception('Transaction :id not found.', array('id'=>$id), 404); + if (!$tx) { + throw new \Box_Exception('Transaction :id not found.', ['id' => $id], 404); } - if(empty($tx->gateway_id)) { + if (empty($tx->gateway_id)) { throw new \Box_Exception('Could not determine transaction origin. Transaction payment gateway is unknown.', null, 701); } $gtw = $this->di['db']->load('PayGateway', $tx->gateway_id); - if(!$gtw instanceof \Model_PayGateway) { - throw new \Box_Exception('Can not handle transaction received from unknown payment gateway: :id', array(':id'=>$tx->gateway_id), 704); + if (!$gtw instanceof \Model_PayGateway) { + throw new \Box_Exception('Can not handle transaction received from unknown payment gateway: :id', [':id' => $tx->gateway_id], 704); } $payGatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); $adapter = $payGatewayService->getPaymentAdapter($gtw); - if(!method_exists($adapter, 'processTransaction')) { - throw new \Box_Exception('Payment adapter :adapter does not support action :action', array(':adapter'=>$gtw->name, ':action'=>'processTransaction'), 705); + if (!method_exists($adapter, 'processTransaction')) { + throw new \Box_Exception('Payment adapter :adapter does not support action :action', [':adapter' => $gtw->name, ':action' => 'processTransaction'], 705); } $ipn = json_decode($tx->ipn, 1); + return $adapter->processTransaction($this->di['api_system'], $id, $ipn, $tx->gateway_id); } public function getReceived() { - $filter = array( - 'status' => 'received' - ); - list($sql, $params) = $this->getSearchQuery($filter); + $filter = [ + 'status' => 'received', + ]; + [$sql, $params] = $this->getSearchQuery($filter); return $this->di['db']->getAll($sql, $params); } @@ -395,7 +406,7 @@ class ServiceTransaction implements InjectionAwareInterface { $transaction = $this->di['db']->load('Transaction', $tx->id); - if($this->_isProcessed($transaction)) { + if ($this->_isProcessed($transaction)) { return $transaction; } @@ -420,17 +431,21 @@ class ServiceTransaction implements InjectionAwareInterface break; default: - throw new \Box_Exception('Unknown transaction #:id type: :type', array(':id'=>$transaction->id, ':type'=>$transaction->type), 632); + throw new \Box_Exception('Unknown transaction #:id type: :type', [':id' => $transaction->id, ':type' => $transaction->type], 632); } - } catch(\Exception $e) { + } catch (\Exception $e) { $transaction->status = \Model_Transaction::STATUS_ERROR; $transaction->error = $e->getMessage(); $transaction->error_code = $e->getCode(); $transaction->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($transaction); - if(BB_DEBUG) error_log($e->getMessage()); - if(APPLICATION_ENV == 'testing') throw $e; + if (BB_DEBUG) { + error_log($e->getMessage()); + } + if (APPLICATION_ENV == 'testing') { + throw $e; + } } return $transaction; @@ -438,21 +453,22 @@ class ServiceTransaction implements InjectionAwareInterface private function _isProcessed(\Model_Transaction $tx) { - if($tx->status == \Model_Transaction::STATUS_PROCESSED) { - $tx->error = NULL; - $tx->error_code = NULL; + if (\Model_Transaction::STATUS_PROCESSED == $tx->status) { + $tx->error = null; + $tx->error_code = null; $tx->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($tx); + return true; } - if($this->hasProcessedTransaction($tx)) { - - $tx->note .= 'Transaction was marked as processed. Transaction with same ID is already processed'; + if ($this->hasProcessedTransaction($tx)) { + $tx->note .= 'Transaction was marked as processed. Transaction with same ID is already processed'; $tx->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($tx); $this->_markAsProcessed($tx); + return true; } @@ -461,18 +477,19 @@ class ServiceTransaction implements InjectionAwareInterface private function hasProcessedTransaction(\Model_Transaction $tx) { - if(!$tx->txn_id) { + if (!$tx->txn_id) { return false; } - $res = $this->di['db']->findOne('Transaction', 'status = "processed" and txn_id = ?', array($tx->txn_id)); + $res = $this->di['db']->findOne('Transaction', 'status = "processed" and txn_id = ?', [$tx->txn_id]); + return empty($res); } private function _markAsProcessed(\Model_Transaction $tx) { - $tx->error = NULL; - $tx->error_code = NULL; + $tx->error = null; + $tx->error_code = null; $tx->status = \Model_Transaction::STATUS_PROCESSED; $tx->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($tx); @@ -480,7 +497,7 @@ class ServiceTransaction implements InjectionAwareInterface private function _parseIpnAndApprove(\Model_Transaction &$tx) { - if($tx->status == \Model_Transaction::STATUS_APPROVED) { + if (\Model_Transaction::STATUS_APPROVED == $tx->status) { return $tx; } @@ -488,63 +505,63 @@ class ServiceTransaction implements InjectionAwareInterface $payGatewayService = $this->di['mod_service']('Invoice', 'PayGateway'); $ipn = $this->di['tools']->decodeJ($tx->ipn); - if(empty($tx->gateway_id)) { + if (empty($tx->gateway_id)) { throw new \Box_Exception('Could not determine transaction origin. Transaction payment gateway is unknown.', null, 701); } $gtw = $this->di['db']->load('PayGateway', $tx->gateway_id); - if(!$gtw instanceof \Model_PayGateway) { - throw new \Box_Exception('Can not handle transaction received from unknown payment gateway: :id', array(':id'=>$tx->gateway_id), 704); + if (!$gtw instanceof \Model_PayGateway) { + throw new \Box_Exception('Can not handle transaction received from unknown payment gateway: :id', [':id' => $tx->gateway_id], 704); } $adapter = $payGatewayService->getPaymentAdapter($gtw); - if(!$tx->invoice_id && method_exists($adapter, 'getInvoiceId')) { + if (!$tx->invoice_id && method_exists($adapter, 'getInvoiceId')) { $tx->invoice_id = $adapter->getInvoiceId($ipn); } - if(!$tx->invoice_id) { - throw new \Box_Exception('Transaction :id is not associated with an invoice.', array(':id'=>$tx->id), 702); + if (!$tx->invoice_id) { + throw new \Box_Exception('Transaction :id is not associated with an invoice.', [':id' => $tx->id], 702); } $invoice = $this->di['db']->load('Invoice', $tx->invoice_id); - if(!$invoice instanceof \Model_Invoice) { - throw new \Box_Exception('Invoice #:id not found', array(':id'=>$tx->invoice_id), 703); + if (!$invoice instanceof \Model_Invoice) { + throw new \Box_Exception('Invoice #:id not found', [':id' => $tx->invoice_id], 703); } $adapter = $payGatewayService->getPaymentAdapter($gtw, $invoice); $mpi = $invoiceService->getPaymentInvoice($invoice); - if(APPLICATION_ENV != 'testing' && $tx->validate_ipn) { - if(!$adapter->isIpnValid($ipn, $mpi)) { - $tx->output = $adapter->getOutput(); - throw new \Box_Exception('Instant payment notification (IPN) did not pass gateway :id validation', array(':id'=>$gtw->gateway), 706); + if (APPLICATION_ENV != 'testing' && $tx->validate_ipn) { + if (!$adapter->isIpnValid($ipn, $mpi)) { + $tx->output = $adapter->getOutput(); + throw new \Box_Exception('Instant payment notification (IPN) did not pass gateway :id validation', [':id' => $gtw->gateway], 706); } - $tx->output = $adapter->getOutput(); + $tx->output = $adapter->getOutput(); } - if(!method_exists($adapter, 'getTransaction')) { - throw new \Box_Exception('Payment adapter :adapter does not support action :action', array(':adapter'=>$gtw->name, ':action'=>'getTransaction'), 705); + if (!method_exists($adapter, 'getTransaction')) { + throw new \Box_Exception('Payment adapter :adapter does not support action :action', [':adapter' => $gtw->name, ':action' => 'getTransaction'], 705); } $response = $adapter->getTransaction($ipn, $mpi); - if(!$response instanceof \Payment_Transaction) { - throw new \Box_Exception('Payment gateway :id method getTransaction should return Payment_Transaction object', array(':id'=>$gtw->gateway), 705); + if (!$response instanceof \Payment_Transaction) { + throw new \Box_Exception('Payment gateway :id method getTransaction should return Payment_Transaction object', [':id' => $gtw->gateway], 705); } // if tx type is already defined, do not set them again - if($response->getType()) { - $tx->type = $response->getType(); + if ($response->getType()) { + $tx->type = $response->getType(); } - if($response->getId()) { - $tx->txn_id = $response->getId(); + if ($response->getId()) { + $tx->txn_id = $response->getId(); } - if($response->getStatus()) { - $tx->txn_status = $response->getStatus(); + if ($response->getStatus()) { + $tx->txn_status = $response->getStatus(); } - if($response->getSubscriptionId()) { + if ($response->getSubscriptionId()) { $tx->s_id = $response->getSubscriptionId(); } @@ -556,7 +573,7 @@ class ServiceTransaction implements InjectionAwareInterface $tx->currency = $response->getCurrency(); } - $tx->status = \Model_Transaction::STATUS_APPROVED; + $tx->status = \Model_Transaction::STATUS_APPROVED; $tx->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($tx); @@ -565,7 +582,7 @@ class ServiceTransaction implements InjectionAwareInterface private function _debit(\Model_Transaction $tx) { - if($this->_isProcessed($tx)) { + if ($this->_isProcessed($tx)) { return $tx; } @@ -576,12 +593,12 @@ class ServiceTransaction implements InjectionAwareInterface $this->_markAsProcessed($tx); // try pay for invoice after debit - if($tx->invoice_id) { + if ($tx->invoice_id) { try { $invoiceService = $this->di['mod_service']('Invoice'); $invoiceService->tryPayWithCredits($tx->Invoice); - } catch(\Exception $e) { - if($this->di['config']['debug']){ + } catch (\Exception $e) { + if ($this->di['config']['debug']) { error_log($e->getMessage()); } } @@ -590,7 +607,7 @@ class ServiceTransaction implements InjectionAwareInterface private function _refund(\Model_Transaction $tx) { - if($this->_isProcessed($tx)) { + if ($this->_isProcessed($tx)) { return $tx; } @@ -603,18 +620,19 @@ class ServiceTransaction implements InjectionAwareInterface $invoiceService->refund($invoice, $note); $this->_markAsProcessed($tx); + return $tx; } private function _subscribe(\Model_Transaction $tx) { - if($this->_isProcessed($tx)) { + if ($this->_isProcessed($tx)) { return $tx; } $this->_validateApprovedTransaction($tx); - if(empty($tx->s_id)) { + if (empty($tx->s_id)) { throw new \Box_Exception('Can not create subscription. Subscription id from payment gateway was not received'); } @@ -637,62 +655,63 @@ class ServiceTransaction implements InjectionAwareInterface $this->di['db']->store($s); $this->_markAsProcessed($tx); + return $tx; } private function _unsubscribe(\Model_Transaction $tx) { - if($this->_isProcessed($tx)) { + if ($this->_isProcessed($tx)) { return $tx; } - - $serviceSubscription = $this->di['mod_service']("Subscription"); + $serviceSubscription = $this->di['mod_service']('Subscription'); $model = $this->di['db']->load('Subscription', $tx->s_id); - if(!$model instanceof \Model_Subscription) { - throw new \Box_Exception('Subscription #:id was not found. Could not unsubscribe', array(':id'=>$tx->s_id)); + if (!$model instanceof \Model_Subscription) { + throw new \Box_Exception('Subscription #:id was not found. Could not unsubscribe', [':id' => $tx->s_id]); } $serviceSubscription->unsubscribe($model); $this->_markAsProcessed($tx); + return $tx; } private function _validateApprovedTransaction(\Model_Transaction $tx) { - if($tx->status != \Model_Transaction::STATUS_APPROVED) { + if (\Model_Transaction::STATUS_APPROVED != $tx->status) { throw new \Box_Exception('Only approved transaction can be processed'); } - if(empty($tx->invoice_id)) { - throw new \Box_Exception('Transaction :id is not associated with an invoice.', array(':id'=>$tx->id), 7022); + if (empty($tx->invoice_id)) { + throw new \Box_Exception('Transaction :id is not associated with an invoice.', [':id' => $tx->id], 7022); } $invoice = $this->di['db']->load('Invoice', $tx->invoice_id); // check that payment currency is correct - if($invoice->currency != $tx->currency) { - throw new \Box_Exception('Transaction currency :code do not match required currency :required', array(':code'=>$tx->currency, ':required'=>$invoice->currency), 709); + if ($invoice->currency != $tx->currency) { + throw new \Box_Exception('Transaction currency :code do not match required currency :required', [':code' => $tx->currency, ':required' => $invoice->currency], 709); } // check that payment status is completed if - if($tx->txn_status == \Payment_Transaction::STATUS_PENDING) { + if (\Payment_Transaction::STATUS_PENDING == $tx->txn_status) { throw new \Box_Exception('Transaction status on payment gateway is Pending. Only Complete or Unknown transactions can be processed.', null, 712); } } public function debitTransaction(\Model_Transaction $tx) { - $proforma = $this->di['db']->load('Invoice', $tx->invoice_id); - $client = $this->di['db']->load('Client', $proforma->client_id); + $proforma = $this->di['db']->load('Invoice', $tx->invoice_id); + $client = $this->di['db']->load('Client', $proforma->client_id); - if($client->currency != $proforma->currency) { + if ($client->currency != $proforma->currency) { throw new \Box_Exception('Client currency do not match invoice currency'); } // do not debit negative or zero amount - if($tx->amount < 0) { + if ($tx->amount < 0) { throw new \Box_Exception('Can not add negative amount to client balance for debit transaction'); } @@ -700,11 +719,10 @@ class ServiceTransaction implements InjectionAwareInterface $credit->client_id = $client->id; $credit->type = 'transaction'; $credit->rel_id = $tx->id; - $credit->description = "Invoice #".$proforma->id . ' payment received from transaction #'.$tx->id; + $credit->description = 'Invoice #'.$proforma->id.' payment received from transaction #'.$tx->id; $credit->amount = $tx->amount; $credit->created_at = date('Y-m-d H:i:s'); $credit->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($credit); } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Kb/Api/Admin.php b/src/bb-modules/Kb/Api/Admin.php index 13f206927..6bc486edd 100644 --- a/src/bb-modules/Kb/Api/Admin.php +++ b/src/bb-modules/Kb/Api/Admin.php @@ -1,6 +1,6 @@ di['array_get']($data, 'status', null); $search = $this->di['array_get']($data, 'search', null); - $cat = $this->di['array_get']($data, 'cat', null); + $cat = $this->di['array_get']($data, 'cat', null); $pager = $this->getService()->searchArticles($status, $search, $cat); foreach ($pager['list'] as $key => $item) { - $article = $this->di['db']->getExistingModelById('KbArticle', $item['id'], 'KB Article not found'); + $article = $this->di['db']->getExistingModelById('KbArticle', $item['id'], 'KB Article not found'); $pager['list'][$key] = $this->getService()->toApiArray($article); } @@ -40,7 +40,7 @@ class Admin extends \Api_Abstract } /** - * Get knowledge base article + * Get knowledge base article. * * @param int $id - knowledge base article ID * @@ -48,12 +48,12 @@ class Admin extends \Api_Abstract */ public function article_get($data) { - $required = array( + $required = [ 'id' => 'Article id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('KbArticle', 'id = ?', array($data['id'])); + $model = $this->di['db']->findOne('KbArticle', 'id = ?', [$data['id']]); if (!$model instanceof \Model_KbArticle) { throw new \Box_Exception('Article not found'); @@ -63,10 +63,10 @@ class Admin extends \Api_Abstract } /** - * Create new knowledge base article + * Create new knowledge base article. * - * @param int $kb_article_category_id - knowledge base category ID - * @param string $title - knowledge base article title + * @param int $kb_article_category_id - knowledge base category ID + * @param string $title - knowledge base article title * * @optional string $status - knowledge base article status * @optional string $content - knowledge base article content @@ -75,22 +75,22 @@ class Admin extends \Api_Abstract */ public function article_create($data) { - $required = array( + $required = [ 'kb_article_category_id' => 'Article category id not passed', - 'title' => 'Article title not passed', - ); + 'title' => 'Article title not passed', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $articleCategoryId = $data['kb_article_category_id']; - $title = $data['title']; - $status = isset($data['status']) ? $data['status'] : \Model_KbArticle::DRAFT; - $content = $this->di['array_get']($data, 'content', NULL); + $title = $data['title']; + $status = $data['status'] ?? \Model_KbArticle::DRAFT; + $content = $this->di['array_get']($data, 'content', null); return $this->getService()->createArticle($articleCategoryId, $title, $status, $content); } /** - * Update knowledge base article + * Update knowledge base article. * * @param int $id - knowledge base article ID * @@ -105,24 +105,23 @@ class Admin extends \Api_Abstract */ public function article_update($data) { - $required = array( + $required = [ 'id' => 'Article ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $articleCategoryId = $this->di['array_get']($data, 'kb_article_category_id', null); - $title = $this->di['array_get']($data, 'title', null); - $slug = $this->di['array_get']($data, 'slug', null); - $status = $this->di['array_get']($data, 'status', null); - $content = $this->di['array_get']($data, 'content', null); - $views = $this->di['array_get']($data, 'views', null); - + $title = $this->di['array_get']($data, 'title', null); + $slug = $this->di['array_get']($data, 'slug', null); + $status = $this->di['array_get']($data, 'status', null); + $content = $this->di['array_get']($data, 'content', null); + $views = $this->di['array_get']($data, 'views', null); return $this->getService()->updateArticle($data['id'], $articleCategoryId, $title, $slug, $status, $content, $views); } /** - * Delete knowledge base article + * Delete knowledge base article. * * @param int $id - knowledge base article ID * @@ -130,12 +129,12 @@ class Admin extends \Api_Abstract */ public function article_delete($data) { - $required = array( + $required = [ 'id' => 'Article ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('KbArticle', 'id = ?', array($data['id'])); + $model = $this->di['db']->findOne('KbArticle', 'id = ?', [$data['id']]); if (!$model instanceof \Model_KbArticle) { throw new \Box_Exception('Article not found'); @@ -147,18 +146,18 @@ class Admin extends \Api_Abstract } /** - * Get paginated list of knowledge base categories + * Get paginated list of knowledge base categories. * * @return array */ public function category_get_list($data) { - list($sql, $bindings) = $this->getService()->categoryGetSearchQuery($data); + [$sql, $bindings] = $this->getService()->categoryGetSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getAdvancedResultSet($sql, $bindings, $per_page); foreach ($pager['list'] as $key => $item) { - $category = $this->di['db']->getExistingModelById('KbArticleCategory', $item['id'], 'KB Article not found'); + $category = $this->di['db']->getExistingModelById('KbArticleCategory', $item['id'], 'KB Article not found'); $pager['list'][$key] = $this->getService()->categoryToApiArray($category, $this->getIdentity()); } @@ -166,7 +165,7 @@ class Admin extends \Api_Abstract } /** - * Get knowledge base category + * Get knowledge base category. * * @param int $id - knowledge base category ID * @@ -174,12 +173,12 @@ class Admin extends \Api_Abstract */ public function category_get($data) { - $required = array( + $required = [ 'id' => 'Category ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('KbArticleCategory', 'id = ?', array($data['id'])); + $model = $this->di['db']->findOne('KbArticleCategory', 'id = ?', [$data['id']]); if (!$model instanceof \Model_KbArticleCategory) { throw new \Box_Exception('Article Category not found'); @@ -189,7 +188,7 @@ class Admin extends \Api_Abstract } /** - * Create new knowledge base category + * Create new knowledge base category. * * @param string $title - knowledge base category title * @@ -199,19 +198,19 @@ class Admin extends \Api_Abstract */ public function category_create($data) { - $required = array( + $required = [ 'title' => 'Category title not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $title = $data['title']; - $description = $this->di['array_get']($data, 'description', NULL); + $title = $data['title']; + $description = $this->di['array_get']($data, 'description', null); return $this->getService()->createCategory($title, $description); } /** - * Update knowledge base category + * Update knowledge base category. * * @param int $id - knowledge base category ID * @@ -223,26 +222,26 @@ class Admin extends \Api_Abstract */ public function category_update($data) { - $required = array( + $required = [ 'id' => 'Category ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('KbArticleCategory', 'id = ?', array($data['id'])); + $model = $this->di['db']->findOne('KbArticleCategory', 'id = ?', [$data['id']]); if (!$model instanceof \Model_KbArticleCategory) { throw new \Box_Exception('Article Category not found'); } - $title = $this->di['array_get']($data, 'title', NULL); - $slug = $this->di['array_get']($data, 'slug', NULL); - $description = $this->di['array_get']($data, 'description', NULL); + $title = $this->di['array_get']($data, 'title', null); + $slug = $this->di['array_get']($data, 'slug', null); + $description = $this->di['array_get']($data, 'description', null); return $this->getService()->updateCategory($model, $title, $slug, $description); } /** - * Delete knowledge base category + * Delete knowledge base category. * * @param int $id - knowledge base category ID * @@ -250,12 +249,12 @@ class Admin extends \Api_Abstract */ public function category_delete($data) { - $required = array( + $required = [ 'id' => 'Category ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->findOne('KbArticleCategory', 'id = ?', array($data['id'])); + $model = $this->di['db']->findOne('KbArticleCategory', 'id = ?', [$data['id']]); if (!$model instanceof \Model_KbArticleCategory) { throw new \Box_Exception('Category not found'); @@ -265,7 +264,7 @@ class Admin extends \Api_Abstract } /** - * Get knowledge base categories id, title pairs + * Get knowledge base categories id, title pairs. * * @return array */ @@ -273,4 +272,4 @@ class Admin extends \Api_Abstract { return $this->getService()->categoryGetPairs(); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Kb/Api/Guest.php b/src/bb-modules/Kb/Api/Guest.php index 6ddc35225..c14854101 100644 --- a/src/bb-modules/Kb/Api/Guest.php +++ b/src/bb-modules/Kb/Api/Guest.php @@ -1,6 +1,6 @@ di['array_get']($data, 'status', NULL); - $search = $this->di['array_get']($data, 'search', NULL); - $cat = $this->di['array_get']($data, 'kb_article_category_id', NULL); + $status = $this->di['array_get']($data, 'status', null); + $search = $this->di['array_get']($data, 'search', null); + $cat = $this->di['array_get']($data, 'kb_article_category_id', null); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $page = $this->di['array_get']($data, 'page'); $pager = $this->getService()->searchArticles($status, $search, $cat, $per_page, $page); foreach ($pager['list'] as $key => $item) { - $article = $this->di['db']->getExistingModelById('KbArticle', $item['id'], 'KB Article not found'); + $article = $this->di['db']->getExistingModelById('KbArticle', $item['id'], 'KB Article not found'); $pager['list'][$key] = $this->getService()->toApiArray($article); } @@ -45,9 +45,9 @@ class Guest extends \Api_Abstract } /** - * Get active knowledge base article + * Get active knowledge base article. * - * @param int $id - knowledge base article ID. Required only if SLUG is not passed. + * @param int $id - knowledge base article ID. Required only if SLUG is not passed. * @param string $slug - knowledge base article slug. Required only if ID is not passed. * * @return array @@ -58,10 +58,10 @@ class Guest extends \Api_Abstract throw new \Box_Exception('ID or slug is missing'); } - $id = $this->di['array_get']($data, 'id', NULL); - $slug = $this->di['array_get']($data, 'slug', NULL); + $id = $this->di['array_get']($data, 'id', null); + $slug = $this->di['array_get']($data, 'slug', null); - $model = FALSE; + $model = false; if ($id) { $model = $this->getService()->findActiveArticleById($id); } else { @@ -77,13 +77,14 @@ class Guest extends \Api_Abstract } /** - * Get paginated list of knowledge base categories + * Get paginated list of knowledge base categories. + * * @return array */ public function category_get_list($data) { $data['article_status'] = \Model_KbArticle::ACTIVE; - list($query, $bindings) = $this->getService()->categoryGetSearchQuery($data); + [$query, $bindings] = $this->getService()->categoryGetSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getAdvancedResultSet($query, $bindings, $per_page); @@ -91,14 +92,15 @@ class Guest extends \Api_Abstract $q = $this->di['array_get']($data, 'q', null); foreach ($pager['list'] as $key => $item) { - $category = $this->di['db']->getExistingModelById('KbArticleCategory', $item['id'], 'KB Article not found'); + $category = $this->di['db']->getExistingModelById('KbArticleCategory', $item['id'], 'KB Article not found'); $pager['list'][$key] = $this->getService()->categoryToApiArray($category, $this->getIdentity(), $q); } + return $pager; } /** - * Get knowledge base categories id, title pairs + * Get knowledge base categories id, title pairs. * * @return array */ @@ -108,9 +110,9 @@ class Guest extends \Api_Abstract } /** - * Get knowledge base category by ID or SLUG + * Get knowledge base category by ID or SLUG. * - * @param int $id - knowledge base category ID. Required only if SLUG is not passed. + * @param int $id - knowledge base category ID. Required only if SLUG is not passed. * @param string $slug - knowledge base category slug. Required only if ID is not passed. * * @return array @@ -121,11 +123,10 @@ class Guest extends \Api_Abstract throw new \Box_Exception('Category ID or slug is missing'); } - $id = $this->di['array_get']($data, 'id', NULL); - $slug = $this->di['array_get']($data, 'slug', NULL); + $id = $this->di['array_get']($data, 'id', null); + $slug = $this->di['array_get']($data, 'slug', null); - - $model = FALSE; + $model = false; if ($id) { $model = $this->getService()->findCategoryById($id); } else { @@ -138,4 +139,4 @@ class Guest extends \Api_Abstract return $this->getService()->categoryToApiArray($model, $this->getIdentity()); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Kb/Controller/Admin.php b/src/bb-modules/Kb/Controller/Admin.php index d8247e8af..634d2e8f6 100644 --- a/src/bb-modules/Kb/Controller/Admin.php +++ b/src/bb-modules/Kb/Controller/Admin.php @@ -1,6 +1,6 @@ array( + return [ + 'group' => [ 'index' => 501, 'location' => 'kb', 'label' => 'Knowledge Base', 'uri' => $this->di['url']->adminLink('kb'), 'class' => 'support', 'sprite_class' => 'dark-sprite-icon sprite-docs', - ), - 'subpages' => array( - array( - 'location' => 'kb', - 'index' => 800, + ], + 'subpages' => [ + [ + 'location' => 'kb', + 'index' => 800, 'label' => 'Knowledge Base', - 'uri' => $this->di['url']->adminLink('kb'), + 'uri' => $this->di['url']->adminLink('kb'), 'class' => '', - ), - ), - ); + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/kb', 'get_index', array(), get_class($this)); - $app->get('/kb/article/:id', 'get_post', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/kb/category/:id', 'get_cat', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/kb', 'get_index', [], get_class($this)); + $app->get('/kb/article/:id', 'get_post', ['id' => '[0-9]+'], get_class($this)); + $app->get('/kb/category/:id', 'get_cat', ['id' => '[0-9]+'], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_kb_index'); } - + public function get_post(\Box_App $app, $id) { $api = $this->di['api_admin']; - $post = $api->kb_article_get(array('id'=>$id)); - return $app->render('mod_kb_article', array('post'=>$post)); + $post = $api->kb_article_get(['id' => $id]); + + return $app->render('mod_kb_article', ['post' => $post]); } public function get_cat(\Box_App $app, $id) { $api = $this->di['api_admin']; - $cat = $api->kb_category_get(array('id'=>$id)); - return $app->render('mod_kb_category', array('category'=>$cat)); - } + $cat = $api->kb_category_get(['id' => $id]); -} \ No newline at end of file + return $app->render('mod_kb_category', ['category' => $cat]); + } +} diff --git a/src/bb-modules/Kb/Controller/Client.php b/src/bb-modules/Kb/Controller/Client.php index 41c34e5c8..b64a423da 100644 --- a/src/bb-modules/Kb/Controller/Client.php +++ b/src/bb-modules/Kb/Controller/Client.php @@ -1,6 +1,6 @@ get('/kb', 'get_kb', array(), get_class($this)); - $app->get('/kb/:category', 'get_kb_category', array('category' => '[a-z0-9-]+'), get_class($this)); - $app->get('/kb/:category/:slug', 'get_kb_article', array('category' => '[a-z0-9-]+', 'slug' => '[a-z0-9-]+'), get_class($this)); + $app->get('/kb', 'get_kb', [], get_class($this)); + $app->get('/kb/:category', 'get_kb_category', ['category' => '[a-z0-9-]+'], get_class($this)); + $app->get('/kb/:category/:slug', 'get_kb_article', ['category' => '[a-z0-9-]+', 'slug' => '[a-z0-9-]+'], get_class($this)); } public function get_kb(\Box_App $app) @@ -48,16 +47,18 @@ class Client implements \Box\InjectionAwareInterface public function get_kb_category(\Box_App $app, $category) { $api = $this->di['api_guest']; - $data = array('slug'=>$category); + $data = ['slug' => $category]; $model = $api->kb_category_get($data); - return $app->render('mod_kb_category', array('category'=>$model)); + + return $app->render('mod_kb_category', ['category' => $model]); } public function get_kb_article(\Box_App $app, $category, $slug) { $api = $this->di['api_guest']; - $data = array('slug'=>$slug); + $data = ['slug' => $slug]; $article = $api->kb_article_get($data); - return $app->render('mod_kb_article', array('article'=>$article)); + + return $app->render('mod_kb_article', ['article' => $article]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Kb/Service.php b/src/bb-modules/Kb/Service.php index e9448b135..c64408484 100644 --- a/src/bb-modules/Kb/Service.php +++ b/src/bb-modules/Kb/Service.php @@ -1,6 +1,6 @@ di['pager']->getSimpleResultSet($sql, $filter, $per_page, $page); } - public function findActiveArticleById($id) { - $bindings = array( - ':id' => $id, - ':status' => \Model_KbArticle::ACTIVE - ); + $bindings = [ + ':id' => $id, + ':status' => \Model_KbArticle::ACTIVE, + ]; return $this->di['db']->findOne('KbArticle', 'id = :id AND status=:status', $bindings); } public function findActiveArticleBySlug($slug) { - $bindings = array( - ':slug' => $slug, - ':status' => \Model_KbArticle::ACTIVE - ); + $bindings = [ + ':slug' => $slug, + ':status' => \Model_KbArticle::ACTIVE, + ]; return $this->di['db']->findOne('KbArticle', 'slug = :slug AND status=:status', $bindings); } public function findActive() { - return $this->di['db']->find('KbArticle', 'status=:status', array(':status' => \Model_KbArticle::ACTIVE)); + return $this->di['db']->find('KbArticle', 'status=:status', [':status' => \Model_KbArticle::ACTIVE]); } public function hitView(\Model_KbArticle $model) { - $model->views++; + ++$model->views; $this->di['db']->store($model); } @@ -96,29 +94,29 @@ class Service public function toApiArray(\Model_KbArticle $model, $deep = false, $identity = null) { - $data = array( - 'id' => $model->id, - 'slug' => $model->slug, - 'title' => $model->title, - 'views' => $model->views, + $data = [ + 'id' => $model->id, + 'slug' => $model->slug, + 'title' => $model->title, + 'views' => $model->views, 'created_at' => $model->created_at, - 'status' => $model->status, + 'status' => $model->status, 'updated_at' => $model->updated_at, - ); + ]; $cat = $this->di['db']->getExistingModelById('KbArticleCategory', $model->kb_article_category_id, 'Knowledge Base category not found'); - $data['category'] = array( - 'id' => $cat->id, - 'slug' => $cat->slug, + $data['category'] = [ + 'id' => $cat->id, + 'slug' => $cat->slug, 'title' => $cat->title, - ); + ]; if ($deep) { $data['content'] = $model->content; } if ($identity instanceof \Model_Admin) { - $data['status'] = $model->status; + $data['status'] = $model->status; $data['kb_article_category_id'] = $model->kb_article_category_id; } @@ -127,19 +125,19 @@ class Service public function createArticle($articleCategoryId, $title, $status = null, $content = null) { - if(!isset($status)){ + if (!isset($status)) { $status = \Model_KbArticle::DRAFT; } - $model = $this->di['db']->dispense('KbArticle'); + $model = $this->di['db']->dispense('KbArticle'); $model->kb_article_category_id = $articleCategoryId; - $model->title = $title; - $model->slug = $this->di['tools']->slug($title); - $model->status = $status; - $model->content = $content; - $model->updated_at = date('Y-m-d H:i:s'); - $model->created_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $model->title = $title; + $model->slug = $this->di['tools']->slug($title); + $model->status = $status; + $model->content = $content; + $model->updated_at = date('Y-m-d H:i:s'); + $model->created_at = date('Y-m-d H:i:s'); + $id = $this->di['db']->store($model); $this->di['logger']->info('Created new knowledge base article #%s', $id); @@ -148,7 +146,7 @@ class Service public function updateArticle($id, $articleCategoryId = null, $title = null, $slug = null, $status = null, $content = null, $views = null) { - $model = $this->di['db']->findOne('KbArticle', 'id = ?', array($id)); + $model = $this->di['db']->findOne('KbArticle', 'id = ?', [$id]); if (!$model instanceof \Model_KbArticle) { throw new \Box_Exception('Article not found'); @@ -188,52 +186,52 @@ class Service public function categoryGetSearchQuery($data) { - $sql = " + $sql = ' SELECT kac.* FROM kb_article_category kac - LEFT JOIN kb_article ka ON kac.id = ka.kb_article_category_id"; + LEFT JOIN kb_article ka ON kac.id = ka.kb_article_category_id'; - $article_status = $this->di['array_get']($data, 'article_status', NULL); - $query = $this->di['array_get']($data, 'q', NULL); + $article_status = $this->di['array_get']($data, 'article_status', null); + $query = $this->di['array_get']($data, 'q', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; if ($article_status) { - $where[] = "ka.status = :status"; + $where[] = 'ka.status = :status'; $bindings[':status'] = $article_status; } if ($query) { - $where[] = "(ka.title LIKE :title OR ka.content LIKE :content)"; + $where[] = '(ka.title LIKE :title OR ka.content LIKE :content)'; - $bindings[':title'] = "%$query%"; + $bindings[':title'] = "%$query%"; $bindings[':content'] = "%$query%"; } if (!empty($where)) { - $sql = $sql . ' WHERE ' . implode(' AND ', $where); + $sql = $sql.' WHERE '.implode(' AND ', $where); } - $sql = $sql . " GROUP BY kac.id ORDER BY kac.id DESC"; + $sql = $sql.' GROUP BY kac.id ORDER BY kac.id DESC'; - return array($sql, $bindings); + return [$sql, $bindings]; } public function categoryFindAll() { - $sql = "SELECT kac.*, a.* + $sql = 'SELECT kac.*, a.* FROM kb_article_category kac LEFT JOIN kb_article ka ON kac.id = ka.kb_article_category_id - "; + '; return $this->di['db']->getAll($sql); } public function categoryGetPairs() { - $sql = "SELECT id, title FROM kb_article_category"; + $sql = 'SELECT id, title FROM kb_article_category'; $pairs = $this->di['db']->getAssoc($sql); return $pairs; @@ -241,11 +239,11 @@ class Service public function categoryRm(\Model_KbArticleCategory $model) { - $bindings = array( - ':kb_article_category_id' => $model->id - ); + $bindings = [ + ':kb_article_category_id' => $model->id, + ]; - $articlesCount = $this->di['db']->getCell("SELECT count(*) as cnt FROM kb_article WHERE kb_article_category_id = :kb_article_category_id", $bindings); + $articlesCount = $this->di['db']->getCell('SELECT count(*) as cnt FROM kb_article WHERE kb_article_category_id = :kb_article_category_id', $bindings); if ($articlesCount > 0) { throw new \Box_Exception('Can not remove category which has articles'); @@ -264,17 +262,17 @@ class Service { $data = $this->di['db']->toArray($model); - $sql = "kb_article_category_id = :category_id"; - $bindings = array( - ':category_id' => $model->id - ); + $sql = 'kb_article_category_id = :category_id'; + $bindings = [ + ':category_id' => $model->id, + ]; - if (!$identity instanceof \Model_Admin){ + if (!$identity instanceof \Model_Admin) { $sql .= " AND status = 'active'"; } - if ($query){ - $sql .= "AND (title LIKE :title OR content LIKE :content)"; + if ($query) { + $sql .= 'AND (title LIKE :title OR content LIKE :content)'; $query = "%$query%"; $bindings[':content'] = $query; $bindings[':title'] = $query; @@ -294,12 +292,12 @@ class Service $systemService = $this->di['mod_service']('system'); $systemService->checkLimits('Model_KbArticleCategory', 2); - $model = $this->di['db']->dispense('KbArticleCategory'); - $model->title = $title; + $model = $this->di['db']->dispense('KbArticleCategory'); + $model->title = $title; $model->description = $description; - $model->slug = $this->di['tools']->slug($title); - $model->updated_at = date('Y-m-d H:i:s'); - $model->created_at = date('Y-m-d H:i:s'); + $model->slug = $this->di['tools']->slug($title); + $model->updated_at = date('Y-m-d H:i:s'); + $model->created_at = date('Y-m-d H:i:s'); $id = $this->di['db']->store($model); @@ -338,10 +336,10 @@ class Service public function findCategoryBySlug($slug) { - $bindings = array( - ':slug' => $slug, - ); + $bindings = [ + ':slug' => $slug, + ]; return $this->di['db']->findOne('KbArticleCategory', 'slug = :slug', $bindings); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Massmailer/Api/Admin.php b/src/bb-modules/Massmailer/Api/Admin.php index 96f083824..de7ba67ac 100644 --- a/src/bb-modules/Massmailer/Api/Admin.php +++ b/src/bb-modules/Massmailer/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getSearchQuery($data); + [$sql, $params] = $this->getService()->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { $pager['list'][$key] = $this->getService()->toApiArray($item); } + return $pager; } /** - * Get mail message by id + * Get mail message by id. * * @param int $id - mail message ID * @@ -44,11 +44,12 @@ class Admin extends \Api_Abstract public function get($data) { $model = $this->_getMessage($data); + return $this->getService()->toApiArray($model); } /** - * Update mail message + * Update mail message. * * @param int $id - mail message id * @@ -68,18 +69,18 @@ class Admin extends \Api_Abstract $model->content = $this->di['array_get']($data, 'content', $model->content); $model->subject = $this->di['array_get']($data, 'subject', $model->subject); $model->status = $this->di['array_get']($data, 'status', $model->status); - if(isset($data['filter'])) { + if (isset($data['filter'])) { $model->filter = json_encode($data['filter']); } - if(isset($data['from_name'])) { - if(empty($data['from_name'])) { + if (isset($data['from_name'])) { + if (empty($data['from_name'])) { throw new \Box_Exception('Message from name can not be empty'); } $model->from_name = $data['from_name']; } - if(isset($data['from_email'])) { + if (isset($data['from_email'])) { $this->di['validator']->isEmailValid($data['from_email']); $model->from_email = $data['from_email']; } @@ -88,11 +89,12 @@ class Admin extends \Api_Abstract $this->di['db']->store($model); $this->di['logger']->info('Updated mail message #%s', $model->id); - return TRUE; + + return true; } /** - * Create mail message + * Create mail message. * * @param string $subject - mail message subject * @@ -102,9 +104,9 @@ class Admin extends \Api_Abstract */ public function create($data) { - $required = array( + $required = [ 'subject' => 'Message subject not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $default_content = '{% apply markdown %} @@ -132,7 +134,7 @@ Order our services at {{ "order"|link }} $model->from_email = $company['email']; $model->from_name = $company['name']; $model->subject = $data['subject']; - $model->content = isset($data['content']) ? $data['content'] : $default_content; + $model->content = $data['content'] ?? $default_content; $model->status = 'draft'; $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); @@ -140,11 +142,12 @@ Order our services at {{ "order"|link }} $id = $this->di['db']->store($model); $this->di['logger']->info('Created mail message #%s', $model->id); + return $id; } /** - * Send test mail message by ID to client + * Send test mail message by ID to client. * * @param int $id - mail message ID * @@ -155,18 +158,19 @@ Order our services at {{ "order"|link }} $model = $this->_getMessage($data); $client_id = $this->_getTestClientId(); - if(empty($model->content)) { + if (empty($model->content)) { throw new \Box_Exception('Add some content before sending message'); } $this->getService()->sendMessage($model, $client_id); $this->di['logger']->info('Sent test mail message #%s to client ', $model->id); + return true; } /** - * Send mail message by ID + * Send mail message by ID. * * @param int $id - mail message ID * @@ -176,25 +180,25 @@ Order our services at {{ "order"|link }} { $model = $this->_getMessage($data); - if(empty($model->content)) { + if (empty($model->content)) { throw new \Box_Exception('Add some content before sending message'); } $mod = $this->di['mod']('massmailer'); $c = $mod->getConfig(); - $interval = isset($c['interval']) ? (int)$c['interval'] : 30; - $max = isset($c['limit']) ? (int)$c['limit'] : 25; + $interval = isset($c['interval']) ? (int) $c['interval'] : 30; + $max = isset($c['limit']) ? (int) $c['limit'] : 25; $clients = $this->getService()->getMessageReceivers($model, $data); - foreach($clients as $c) { - $d = array( - 'queue' => 'massmailer', - 'mod' => 'massmailer', - 'handler' => 'sendMail', - 'max' => $max, - 'interval' => $interval, - 'params' => array('msg_id'=>$model->id, 'client_id'=>$c['id']), - ); + foreach ($clients as $c) { + $d = [ + 'queue' => 'massmailer', + 'mod' => 'massmailer', + 'handler' => 'sendMail', + 'max' => $max, + 'interval' => $interval, + 'params' => ['msg_id' => $model->id, 'client_id' => $c['id']], + ]; $this->di['api_admin']->queue_message_add($d); } @@ -203,11 +207,12 @@ Order our services at {{ "order"|link }} $id = $this->di['db']->store($model); $this->di['logger']->info('Added mass mail messages #%s to queue', $id); + return true; } /** - * Copy mail message by ID + * Copy mail message by ID. * * @param int $id - mail message ID * @@ -217,13 +222,13 @@ Order our services at {{ "order"|link }} { $model = $this->_getMessage($data); - $copy = $this->di['db']->dispense('mod_massmailer'); + $copy = $this->di['db']->dispense('mod_massmailer'); $copy->from_email = $model->from_email; - $copy->from_name = $model->from_name; - $copy->subject = $model->subject . ' (Copy)'; - $copy->content = $model->content; - $copy->filter = $model->filter; - $copy->status = 'draft'; + $copy->from_name = $model->from_name; + $copy->subject = $model->subject.' (Copy)'; + $copy->content = $model->content; + $copy->filter = $model->filter; + $copy->status = 'draft'; $copy->created_at = date('Y-m-d H:i:s'); $copy->updated_at = date('Y-m-d H:i:s'); @@ -235,7 +240,7 @@ Order our services at {{ "order"|link }} } /** - * Get message receivers list + * Get message receivers list. * * @param int $id - mail message ID * @@ -244,11 +249,12 @@ Order our services at {{ "order"|link }} public function receivers($data) { $model = $this->_getMessage($data); + return $this->getService()->getMessageReceivers($model, $data); } /** - * Delete mail message by ID + * Delete mail message by ID. * * @param int $id - mail message ID * @@ -262,11 +268,12 @@ Order our services at {{ "order"|link }} $this->di['db']->trash($model); $this->di['logger']->info('Removed mail message #%s', $id); + return true; } /** - * Generate preview text + * Generate preview text. * * @param int $id - message id * @@ -276,11 +283,12 @@ Order our services at {{ "order"|link }} { $model = $this->_getMessage($data); $client_id = $this->_getTestClientId(); - list($ps, $pc) = $this->getService()->getParsed($model, $client_id); - return array( - 'subject' => $ps, - 'content' => $pc, - ); + [$ps, $pc] = $this->getService()->getParsed($model, $client_id); + + return [ + 'subject' => $ps, + 'content' => $pc, + ]; } private function _getTestClientId() @@ -288,23 +296,23 @@ Order our services at {{ "order"|link }} $mod = $this->di['mod']('massmailer'); $c = $mod->getConfig(); - $required = array( + $required = [ 'test_client_id' => 'Client ID needs to be configured in mass mailer settings.', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $c); - return (int)$c['test_client_id']; + return (int) $c['test_client_id']; } private function _getMessage($data) { - $required = array( + $required = [ 'id' => 'Message ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('mod_massmailer', $data['id'], 'Message not found'); return $model; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Massmailer/Controller/Admin.php b/src/bb-modules/Massmailer/Controller/Admin.php index b65d5cc74..811f41bb2 100644 --- a/src/bb-modules/Massmailer/Controller/Admin.php +++ b/src/bb-modules/Massmailer/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'extensions', - 'index' => 4000, + return [ + 'subpages' => [ + [ + 'location' => 'extensions', + 'index' => 4000, 'label' => 'Mass mailer', - 'uri' => $this->di['url']->adminLink('massmailer'), + 'uri' => $this->di['url']->adminLink('massmailer'), 'class' => '', - ), - ), - ); + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/massmailer', 'get_index', array(), get_class($this)); - $app->get('/massmailer/message/:id', 'get_edit', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/massmailer', 'get_index', [], get_class($this)); + $app->get('/massmailer/message/:id', 'get_edit', ['id' => '[0-9]+'], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_massmailer_index'); } - + public function get_edit(\Box_App $app, $id) { $api = $this->di['api_admin']; - $model = $api->massmailer_get(array('id'=>$id)); - return $app->render('mod_massmailer_message', array('msg'=>$model)); + $model = $api->massmailer_get(['id' => $id]); + + return $app->render('mod_massmailer_message', ['msg' => $model]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Massmailer/Service.php b/src/bb-modules/Massmailer/Service.php index 553745bc1..235b93808 100644 --- a/src/bb-modules/Massmailer/Service.php +++ b/src/bb-modules/Massmailer/Service.php @@ -1,6 +1,6 @@ di['mod_service']('extension'); - $extensionService->activateExistingExtension(array('id'=>'queue', 'type'=>'mod')); - - $sql=" + $extensionService->activateExistingExtension(['id' => 'queue', 'type' => 'mod']); + + $sql = ' CREATE TABLE IF NOT EXISTS `mod_massmailer` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `from_email` varchar(255) DEFAULT NULL, @@ -46,116 +45,116 @@ class Service implements \Box\InjectionAwareInterface `updated_at` varchar(35) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; - "; + '; $this->di['db']->exec($sql); - - //default config values - $extensionService->setConfig(array('ext'=>'mod_massmailer', 'limit'=>'2','interval'=>'10', 'test_client_id'=>1)); + + // default config values + $extensionService->setConfig(['ext' => 'mod_massmailer', 'limit' => '2', 'interval' => '10', 'test_client_id' => 1]); } - + public function getSearchQuery($data) { - $sql="SELECT * + $sql = 'SELECT * FROM mod_massmailer - WHERE 1 "; - - $params = array(); - - $search = (isset($data['search']) && !empty($data['search'])) ? $data['search'] : NULL; - $status = $this->di['array_get']($data, 'status', NULL); - - if(NULL !== $status) { + WHERE 1 '; + + $params = []; + + $search = (isset($data['search']) && !empty($data['search'])) ? $data['search'] : null; + $status = $this->di['array_get']($data, 'status', null); + + if (null !== $status) { $sql .= ' AND status = :status'; $params[':status'] = $status; } - - if(NULL !== $search) { + + if (null !== $search) { $sql .= ' AND (subject LIKE :search OR content LIKE :search OR from_email LIKE :search OR from_name LIKE :search)'; $params[':search'] = '%'.$search.'%'; } - + $sql .= ' ORDER BY created_at DESC'; - - return array($sql, $params); + + return [$sql, $params]; } - - public function getMessageReceivers($model, $data = array()) + + public function getMessageReceivers($model, $data = []) { $row = $this->toApiArray($model); $filter = $row['filter']; - - $sql="SELECT c.id, c.first_name, c.last_name + + $sql = 'SELECT c.id, c.first_name, c.last_name FROM client c LEFT JOIN client_order co ON (co.client_id = c.id) WHERE 1 - "; - - $values = array(); - if(!empty($filter)) { - if(isset($filter['client_status']) && !empty($filter['client_status'])) { + '; + + $values = []; + if (!empty($filter)) { + if (isset($filter['client_status']) && !empty($filter['client_status'])) { $sql .= sprintf(" AND c.status IN ('%s')", implode("', '", $filter['client_status'])); } - - if(isset($filter['client_groups']) && !empty($filter['client_groups'])) { + + if (isset($filter['client_groups']) && !empty($filter['client_groups'])) { $sql .= sprintf(" AND c.client_group_id IN ('%s')", implode("', '", $filter['client_groups'])); } - - if(isset($filter['has_order']) && !empty($filter['has_order'])) { + + if (isset($filter['has_order']) && !empty($filter['has_order'])) { $sql .= sprintf(" AND co.product_id IN ('%s')", implode("', '", $filter['has_order'])); } - - if(isset($filter['has_order_with_status']) && !empty($filter['has_order_with_status'])) { + + if (isset($filter['has_order_with_status']) && !empty($filter['has_order_with_status'])) { $sql .= sprintf(" AND co.status IN ('%s')", implode("', '", $filter['has_order_with_status'])); } } - + $sql .= ' ORDER BY c.id DESC'; - - if(isset($data['debug']) && $data['debug']) { - throw new \Exception($sql. ' '. print_r($values, 1)); + + if (isset($data['debug']) && $data['debug']) { + throw new \Exception($sql.' '.print_r($values, 1)); } - + return $this->di['db']->getAll($sql, $values); } - + public function getParsed($model, $client_id) { $clientService = $this->di['mod_service']('client'); $systemService = $this->di['mod_service']('system'); - $client = $clientService->get(array('id'=>$client_id)); + $client = $clientService->get(['id' => $client_id]); $clientArr = $clientService->toApiArray($client, true, null); - $vars = array(); + $vars = []; $vars['c'] = $clientArr; $vars['_tpl'] = $model->subject; $ps = $systemService->renderString($vars['_tpl'], false, $vars); - - $vars = array(); + + $vars = []; $vars['c'] = $clientArr; $vars['_tpl'] = $model->content; $pc = $systemService->renderString($vars['_tpl'], false, $vars); - - return array($ps, $pc); + + return [$ps, $pc]; } public function sendMessage($model, $client_id) { - list($ps, $pc) = $this->getParsed($model, $client_id); + [$ps, $pc] = $this->getParsed($model, $client_id); $clientService = $this->di['mod_service']('client'); - $client = $clientService->get(array('id' => $client_id)); + $client = $clientService->get(['id' => $client_id]); - $data = array( - 'to' => $client->email, - 'to_name' => $client->first_name . ' ' . $client->last_name, - 'from' => $model->from_email, + $data = [ + 'to' => $client->email, + 'to_name' => $client->first_name.' '.$client->last_name, + 'from' => $model->from_email, 'from_name' => $model->from_name, - 'subject' => $ps, - 'content' => $pc, + 'subject' => $ps, + 'content' => $pc, 'client_id' => $client_id, - ); + ]; $mail = $this->di['mail']; $mail->setSubject($data['subject']); @@ -164,58 +163,60 @@ class Service implements \Box\InjectionAwareInterface $mail->addTo($data['to'], $data['to_name']); if (APPLICATION_ENV != 'production') { - if($this->di['config']['debug']) + if ($this->di['config']['debug']) { error_log('Skip email sending. Application ENV: '.APPLICATION_ENV); + } + return true; } - $mod = $this->di['mod']('email'); + $mod = $this->di['mod']('email'); $settings = $mod->getConfig(); if (isset($settings['log_enabled']) && $settings['log_enabled']) { - $activityService = $this->di['mod_service']('activity'); + $activityService = $this->di['mod_service']('activity'); $activityService->logEmail($data['subject'], $client_id, $data['from'], $data['to'], $data['content']); } - + $emailSettings = $this->di['mod_config']('email'); - $transport = $this->di['array_get']($emailSettings, 'mailer', 'sendmail'); + $transport = $this->di['array_get']($emailSettings, 'mailer', 'sendmail'); $mail->send($transport, $emailSettings); return true; } - + public function toApiArray($row) { - if($row instanceof \RedBeanPHP\OODBBean) { + if ($row instanceof \RedBeanPHP\OODBBean) { $row = $row->export(); } - - if($row['filter']) { + + if ($row['filter']) { $row['filter'] = json_decode($row['filter'], 1); } else { - $row['filter'] = array(); + $row['filter'] = []; } - + return $row; } - + public static function onAfterAdminCronRun(\Box_Event $event) { try { $di = $event->getDi(); - $di['api_admin']->queue_execute(array('queue'=>'massmailer')); - } catch(\Exception $e) { + $di['api_admin']->queue_execute(['queue' => 'massmailer']); + } catch (\Exception $e) { error_log('Error executing massmailer queue: '.$e->getMessage()); } } - + public function sendMail($params) { $model = $this->di['db']->load('mod_massmailer', $params['msg_id']); - if(!$model) { + if (!$model) { throw new \Exception('Mass mail message not found'); } $this->sendMessage($model, $params['client_id']); } -} \ No newline at end of file +} diff --git a/src/bb-modules/News/Api/Admin.php b/src/bb-modules/News/Api/Admin.php index 1cc740bc0..22c5f6898 100644 --- a/src/bb-modules/News/Api/Admin.php +++ b/src/bb-modules/News/Api/Admin.php @@ -1,6 +1,6 @@ getService(); - list ($sql, $params) = $service->getSearchQuery($data); + [$sql, $params] = $service->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); + $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $post = $this->di['db']->getExistingModelById('Post', $item['id'], 'Post not found'); + $post = $this->di['db']->getExistingModelById('Post', $item['id'], 'Post not found'); $pager['list'][$key] = $this->getService()->toApiArray($post, 'admin'); } @@ -38,7 +38,7 @@ class Admin extends \Api_Abstract } /** - * Get news item by ID + * Get news item by ID. * * @param int $id - news item ID * @@ -50,7 +50,7 @@ class Admin extends \Api_Abstract throw new \Box_Exception('ID or slug is missing'); } - $id = $this->di['array_get']($data, 'id'); + $id = $this->di['array_get']($data, 'id'); $slug = $this->di['array_get']($data, 'slug'); $model = null; @@ -58,7 +58,7 @@ class Admin extends \Api_Abstract $model = $this->di['db']->load('Post', $id); } else { if (!empty($slug)) { - $model = $this->di['db']->findOne('Post', 'slug = :slug', array('slug' => $slug)); + $model = $this->di['db']->findOne('Post', 'slug = :slug', ['slug' => $slug]); } } @@ -85,23 +85,25 @@ class Admin extends \Api_Abstract public function update($data) { $service = $this->getService(); - $required = array( + $required = [ 'id' => 'Post ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Post', $data['id'], 'News item not found'); $description = $this->di['array_get']($data, 'description', $model->description); - if (empty($description)) $description = $service->generateDescriptionFromContent($this->di['array_get']($data, 'content', $model->content)); + if (empty($description)) { + $description = $service->generateDescriptionFromContent($this->di['array_get']($data, 'content', $model->content)); + } - $model->content = $this->di['array_get']($data, 'content', $model->content); - $model->title = $this->di['array_get']($data, 'title', $model->title); + $model->content = $this->di['array_get']($data, 'content', $model->content); + $model->title = $this->di['array_get']($data, 'title', $model->title); $model->description = $description; - $model->slug = $this->di['array_get']($data, 'slug', $model->slug); - $model->image = $this->di['array_get']($data, 'image', $model->image); - $model->section = $this->di['array_get']($data, 'section', $model->section); - $model->status = $this->di['array_get']($data, 'status', $model->status); + $model->slug = $this->di['array_get']($data, 'slug', $model->slug); + $model->image = $this->di['array_get']($data, 'image', $model->image); + $model->section = $this->di['array_get']($data, 'section', $model->section); + $model->status = $this->di['array_get']($data, 'status', $model->status); $publish_at = $this->di['array_get']($data, 'publish_at', 0); if ($publish_at) { @@ -132,7 +134,7 @@ class Admin extends \Api_Abstract $this->di['logger']->info('Updated news item #%s', $model->id); - return TRUE; + return true; } /** @@ -148,20 +150,20 @@ class Admin extends \Api_Abstract public function create($data) { $service = $this->getService(); - $required = array( + $required = [ 'title' => 'Post title not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $model = $this->di['db']->dispense('Post'); - $model->admin_id = $this->getIdentity()->id; - $model->title = $data['title']; + $model = $this->di['db']->dispense('Post'); + $model->admin_id = $this->getIdentity()->id; + $model->title = $data['title']; $model->description = null; - $model->slug = $this->di['tools']->slug($data['title']); - $model->status = $this->di['array_get']($data, 'status', NULL); - $model->content = $this->di['array_get']($data, 'content', NULL); - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); + $model->slug = $this->di['tools']->slug($data['title']); + $model->status = $this->di['array_get']($data, 'status', null); + $model->content = $this->di['array_get']($data, 'content', null); + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Created news item #%s', $model->id); @@ -170,7 +172,7 @@ class Admin extends \Api_Abstract } /** - * Delete news item by ID + * Delete news item by ID. * * @param int $id - news item ID * @@ -178,13 +180,13 @@ class Admin extends \Api_Abstract */ public function delete($data) { - $required = array( + $required = [ 'id' => 'Post ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Post', $data['id'], 'News item not found'); - $id = $model->id; + $id = $model->id; $this->di['db']->trash($model); $this->di['logger']->info('Removed news item #%s', $id); @@ -192,7 +194,7 @@ class Admin extends \Api_Abstract } /** - * Deletes news items with given IDs + * Deletes news items with given IDs. * * @param array $ids - IDs for deletion * @@ -200,15 +202,15 @@ class Admin extends \Api_Abstract */ public function batch_delete($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->delete(array('id' => $id)); + $this->delete(['id' => $id]); } return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/News/Api/Guest.php b/src/bb-modules/News/Api/Guest.php index a446c3d08..bc03f7fd3 100644 --- a/src/bb-modules/News/Api/Guest.php +++ b/src/bb-modules/News/Api/Guest.php @@ -1,6 +1,6 @@ getService()->getSearchQuery($data); + [$sql, $params] = $this->getService()->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $page = $this->di['array_get']($data, 'page'); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page, $page); foreach ($pager['list'] as $key => $item) { - $post = $this->di['db']->getExistingModelById('Post', $item['id'], 'Post not found'); + $post = $this->di['db']->getExistingModelById('Post', $item['id'], 'Post not found'); $pager['list'][$key] = $this->getService()->toApiArray($post); } @@ -39,31 +39,32 @@ class Guest extends \Api_Abstract } /** - * Get news item by ID or SLUG + * Get news item by ID or SLUG. * - * @param int $id - news item ID. Required only if SLUG is not passed. + * @param int $id - news item ID. Required only if SLUG is not passed. * @param string $slug - news item slug. Required only if ID is not passed. * * @return array */ public function get($data) { - if(!isset($data['id']) && !isset($data['slug'])) { + if (!isset($data['id']) && !isset($data['slug'])) { throw new \Box_Exception('ID or slug is missing'); } - $id = $this->di['array_get']($data, 'id', NULL); - $slug = $this->di['array_get']($data, 'slug', NULL); + $id = $this->di['array_get']($data, 'id', null); + $slug = $this->di['array_get']($data, 'slug', null); - if($id) { + if ($id) { $model = $this->getService()->findOneActiveById($id); } else { $model = $this->getService()->findOneActiveBySlug($slug); } - if(!$model || $model->status !== 'active') { + if (!$model || 'active' !== $model->status) { throw new \Box_Exception('News item not found'); } + return $this->getService()->toApiArray($model); } -} \ No newline at end of file +} diff --git a/src/bb-modules/News/Controller/Admin.php b/src/bb-modules/News/Controller/Admin.php index d6deb3724..169e6b731 100644 --- a/src/bb-modules/News/Controller/Admin.php +++ b/src/bb-modules/News/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'support', - 'index' => 900, + return [ + 'subpages' => [ + [ + 'location' => 'support', + 'index' => 900, 'label' => 'Announcements', - 'uri' => $this->di['url']->adminLink('news'), + 'uri' => $this->di['url']->adminLink('news'), 'class' => '', - ), - ), - ); + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/news', 'get_index', array(), get_class($this)); - $app->get('/news/', 'get_index', array(), get_class($this)); - $app->get('/news/index', 'get_index', array(), get_class($this)); - $app->get('/news/index/', 'get_index', array(), get_class($this)); - $app->get('/news/post/:id', 'get_post', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/news', 'get_index', [], get_class($this)); + $app->get('/news/', 'get_index', [], get_class($this)); + $app->get('/news/index', 'get_index', [], get_class($this)); + $app->get('/news/index/', 'get_index', [], get_class($this)); + $app->get('/news/post/:id', 'get_post', ['id' => '[0-9]+'], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_news_index'); } - + public function get_post(\Box_App $app, $id) { $api = $this->di['api_admin']; - $post = $api->news_get(array('id'=>$id)); - return $app->render('mod_news_post', array('post'=>$post)); + $post = $api->news_get(['id' => $id]); + + return $app->render('mod_news_post', ['post' => $post]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/News/Controller/Client.php b/src/bb-modules/News/Controller/Client.php index f4e3c6c35..efa6886bc 100644 --- a/src/bb-modules/News/Controller/Client.php +++ b/src/bb-modules/News/Controller/Client.php @@ -1,6 +1,6 @@ get('/news', 'get_news', array(), get_class($this)); - $app->get('/news/:slug', 'get_news_item', array('slug' => '[a-z0-9-]+'), get_class($this)); + $app->get('/news', 'get_news', [], get_class($this)); + $app->get('/news/:slug', 'get_news_item', ['slug' => '[a-z0-9-]+'], get_class($this)); } public function get_news(\Box_App $app) @@ -46,8 +45,8 @@ class Client implements \Box\InjectionAwareInterface public function get_news_item(\Box_App $app, $slug) { - $post = $this->di['api_guest']->news_get(array('slug'=>$slug)); - return $app->render('mod_news_post', array('post'=>$post)); - } + $post = $this->di['api_guest']->news_get(['slug' => $slug]); -} \ No newline at end of file + return $app->render('mod_news_post', ['post' => $post]); + } +} diff --git a/src/bb-modules/News/Service.php b/src/bb-modules/News/Service.php index c0131ce0c..729828776 100644 --- a/src/bb-modules/News/Service.php +++ b/src/bb-modules/News/Service.php @@ -1,6 +1,6 @@ di['db']->findOne('Post', 'id = :id AND status = "active"', array('id'=>$id)); + return $this->di['db']->findOne('Post', 'id = :id AND status = "active"', ['id' => $id]); } - + public function findOneActiveBySlug($slug) { - return $this->di['db']->findOne('Post', 'slug = :slug AND status = "active"', array('slug'=>$slug)); + return $this->di['db']->findOne('Post', 'slug = :slug AND status = "active"', ['slug' => $slug]); } /** @@ -46,68 +45,69 @@ class Service { $desc = utf8_encode($content); $desc = strip_tags($desc); - $desc = str_replace(array("\n", "\r", "\t"), ' ', $desc); + $desc = str_replace(["\n", "\r", "\t"], ' ', $desc); $desc = substr($desc, 0, 125); + return $desc; } public function getSearchQuery($data) { - $sql='SELECT * + $sql = 'SELECT * FROM post WHERE 1 '; - $params = array(); + $params = []; - $search = $this->di['array_get']($data, 'search', NULL); - $status = $this->di['array_get']($data, 'status', NULL); + $search = $this->di['array_get']($data, 'search', null); + $status = $this->di['array_get']($data, 'status', null); - if(NULL !== $status) { + if (null !== $status) { $sql .= ' AND status = :status'; $params['status'] = $status; } - if(NULL !== $search) { + if (null !== $search) { $sql .= ' AND (m.title LIKE :search OR m.content LIKE :search)'; $params['search'] = '%'.$search.'%'; } $sql .= ' ORDER BY created_at DESC'; - return array($sql, $params); + return [$sql, $params]; } public function toApiArray($row, $role = 'guest', $deep = true) { - $admin = $this->di['db']->getRow('SELECT name, email FROM admin WHERE id=:id', array('id' => $row->admin_id)); + $admin = $this->di['db']->getRow('SELECT name, email FROM admin WHERE id=:id', ['id' => $row->admin_id]); - $pos = strpos($row->content, ''); + $pos = strpos($row->content, ''); $excerpt = ($pos) ? substr($row->content, 0, $pos) : null; - + // Remove from post content - $content = str_replace("", "", $row->content); + $content = str_replace('', '', $row->content); - $data = array( - 'id' => $row->id, - 'title' => $row->title, - 'description' => $row->description, - 'content' => $content, - 'slug' => $row->slug, - 'image' => $row->image, - 'section' => $row->section, - 'publish_at' => $row->publish_at, + $data = [ + 'id' => $row->id, + 'title' => $row->title, + 'description' => $row->description, + 'content' => $content, + 'slug' => $row->slug, + 'image' => $row->image, + 'section' => $row->section, + 'publish_at' => $row->publish_at, 'published_at' => $row->published_at, - 'expires_at' => $row->expires_at, - 'created_at' => $row->created_at, - 'updated_at' => $row->updated_at, - 'author' => array( - 'name' => $admin['name'], + 'expires_at' => $row->expires_at, + 'created_at' => $row->created_at, + 'updated_at' => $row->updated_at, + 'author' => [ + 'name' => $admin['name'], 'email' => $admin['email'], - ), - 'excerpt' => $excerpt, - ); + ], + 'excerpt' => $excerpt, + ]; - if ($role == 'admin') { + if ('admin' == $role) { $data['status'] = $row->status; } diff --git a/src/bb-modules/Notification/Api/Admin.php b/src/bb-modules/Notification/Api/Admin.php index 78b33b087..0d7c96c0d 100644 --- a/src/bb-modules/Notification/Api/Admin.php +++ b/src/bb-modules/Notification/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getSearchQuery($data); + [$sql, $params] = $this->getService()->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + return $resultSet = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); } /** - * Get notification message + * Get notification message. * * @param int $id - message id + * * @return array + * * @throws Box_Exception */ public function get($data) { - $required = array( + $required = [ 'id' => 'Notification ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $meta = $this->di['db']->load('extension_meta', $data['id']); - if ($meta->extension != 'mod_notification' || $meta->meta_key != 'message') { + if ('mod_notification' != $meta->extension || 'message' != $meta->meta_key) { throw new \Box_Exception('Notification message was not found'); } @@ -58,9 +61,10 @@ class Admin extends \Api_Abstract } /** - * Add new notification message + * Add new notification message. * * @param string $message - message text + * * @return int|false - new message id */ public function add($data) @@ -75,21 +79,23 @@ class Admin extends \Api_Abstract } /** - * Remove notification message + * Remove notification message. * * @param int $id - message id - * @return boolean + * + * @return bool + * * @throws Box_Exception */ public function delete($data) { - $required = array( + $required = [ 'id' => 'Notification ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $meta = $this->di['db']->load('extension_meta', $data['id']); - if ($meta->extension != 'mod_notification' || $meta->meta_key != 'message') { + if ('mod_notification' != $meta->extension || 'message' != $meta->meta_key) { throw new \Box_Exception('Notification message was not found'); } $this->di['db']->trash($meta); @@ -98,9 +104,10 @@ class Admin extends \Api_Abstract } /** - * Remove all notification messages + * Remove all notification messages. + * + * @return bool * - * @return boolean * @throws Box_Exception */ public function delete_all() @@ -113,4 +120,4 @@ class Admin extends \Api_Abstract return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Notification/Controller/Admin.php b/src/bb-modules/Notification/Controller/Admin.php index 5c1f2b368..1a6b9ee23 100644 --- a/src/bb-modules/Notification/Controller/Admin.php +++ b/src/bb-modules/Notification/Controller/Admin.php @@ -1,6 +1,6 @@ get('/notification', 'get_index', array(), get_class($this)); + $app->get('/notification', 'get_index', [], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_notification_index'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Notification/Service.php b/src/bb-modules/Notification/Service.php index 2e6673e20..9f559a3b6 100644 --- a/src/bb-modules/Notification/Service.php +++ b/src/bb-modules/Notification/Service.php @@ -1,6 +1,6 @@ di['db']->dispense('extension_meta'); - $meta->extension = 'mod_notification'; - $meta->rel_type = 'staff'; - $meta->rel_id = 1; - $meta->meta_key = 'message'; + $meta = $this->di['db']->dispense('extension_meta'); + $meta->extension = 'mod_notification'; + $meta->rel_type = 'staff'; + $meta->rel_id = 1; + $meta->meta_key = 'message'; $meta->meta_value = $message; $meta->created_at = date('Y-m-d H:i:s'); $meta->updated_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($meta); + $id = $this->di['db']->store($meta); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminNotificationAdd', 'params' => array('id' => $id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminNotificationAdd', 'params' => ['id' => $id]]); return $id; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Order/Api/Admin.php b/src/bb-modules/Order/Api/Admin.php index 97edf0787..f8f79ddf9 100644 --- a/src/bb-modules/Order/Api/Admin.php +++ b/src/bb-modules/Order/Api/Admin.php @@ -1,6 +1,6 @@ _getOrder($data); return $this->getService()->toApiArray($order, $deep, $this->getIdentity()); } /** - * Return paginated list of orders + * Return paginated list of orders. * * @optional string $date_from - show only order places after this date * @optional string $date_to - show only order places till this date @@ -42,15 +43,15 @@ class Admin extends \Api_Abstract */ public function get_list($data) { - $orderConfig = $this->di['mod']('order')->getConfig(); + $orderConfig = $this->di['mod']('order')->getConfig(); $data['hide_addons'] = (isset($orderConfig['show_addons']) && $orderConfig['show_addons']) ? 0 : 1; - list($sql, $params) = $this->getService()->getSearchQuery($data); + [$sql, $params] = $this->getService()->getSearchQuery($data); $paginator = $this->di['pager']; - $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $resultSet = $paginator->getAdvancedResultSet($sql, $params, $per_page); foreach ($resultSet['list'] as $key => $result) { - $orderObj = $this->di['db']->getExistingModelById('ClientOrder', $result['id'], 'Order not found'); + $orderObj = $this->di['db']->getExistingModelById('ClientOrder', $result['id'], 'Order not found'); $resultSet['list'][$key] = $this->getService()->toApiArray($orderObj, true, $this->getIdentity()); } @@ -60,7 +61,7 @@ class Admin extends \Api_Abstract /** * Place new order for client. Admin is able to order disabled products. * - * @param int $client_id - Client id + * @param int $client_id - Client id * @param int $product_id - Product id to be ordered * * @optional array $config - Depending on product type, you may need to pass product configuration options @@ -78,20 +79,20 @@ class Admin extends \Api_Abstract */ public function create($data) { - $required = array( + $required = [ 'client_id' => 'Client id not passed', 'product_id' => 'Product id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found'); + $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found'); $product = $this->di['db']->getExistingModelById('Product', $data['product_id'], 'Product not found'); return $this->getService()->createOrder($client, $product, $data); } /** - * Update order settings + * Update order settings. * * @param int $id - Order id * @@ -140,7 +141,7 @@ class Admin extends \Api_Abstract { $order = $this->_getOrder($data); - if ($order->status == \Model_ClientOrder::STATUS_PENDING_SETUP || $order->status == \Model_ClientOrder::STATUS_FAILED_SETUP) { + if (\Model_ClientOrder::STATUS_PENDING_SETUP == $order->status || \Model_ClientOrder::STATUS_FAILED_SETUP == $order->status) { return $this->activate($data); } @@ -148,7 +149,7 @@ class Admin extends \Api_Abstract } /** - * Suspend order + * Suspend order. * * @param int $id - Order id * @@ -159,16 +160,16 @@ class Admin extends \Api_Abstract */ public function suspend($data) { - $order = $this->_getOrder($data); - $skip_event = isset($data['skip_event']) ? (bool)$data['skip_event'] : false; + $order = $this->_getOrder($data); + $skip_event = isset($data['skip_event']) ? (bool) $data['skip_event'] : false; - $reason = $this->di['array_get']($data, 'reason', NULL); + $reason = $this->di['array_get']($data, 'reason', null); return $this->getService()->suspendFromOrder($order, $reason, $skip_event); } /** - * Unsuspend suspended order + * Unsuspend suspended order. * * @param int $id - Order id * @@ -177,7 +178,7 @@ class Admin extends \Api_Abstract public function unsuspend($data) { $order = $this->_getOrder($data); - if ($order->status != \Model_ClientOrder::STATUS_SUSPENDED) { + if (\Model_ClientOrder::STATUS_SUSPENDED != $order->status) { throw new \Box_Exception('Only suspended orders can be unsuspended'); } @@ -185,7 +186,7 @@ class Admin extends \Api_Abstract } /** - * Cancel order + * Cancel order. * * @param int $id - Order id * @@ -195,16 +196,16 @@ class Admin extends \Api_Abstract */ public function cancel($data) { - $order = $this->_getOrder($data); - $skip_event = isset($data['skip_event']) ? (bool)$data['skip_event'] : false; + $order = $this->_getOrder($data); + $skip_event = isset($data['skip_event']) ? (bool) $data['skip_event'] : false; - $reason = $this->di['array_get']($data, 'reason', NULL); + $reason = $this->di['array_get']($data, 'reason', null); return $this->getService()->cancelFromOrder($order, $reason, $skip_event); } /** - * Uncancel canceled order + * Uncancel canceled order. * * @param int $id - Order id * @@ -213,7 +214,7 @@ class Admin extends \Api_Abstract public function uncancel($data) { $order = $this->_getOrder($data); - if ($order->status != \Model_ClientOrder::STATUS_CANCELED) { + if (\Model_ClientOrder::STATUS_CANCELED != $order->status) { throw new \Box_Exception('Only canceled orders can be uncanceled'); } @@ -221,7 +222,7 @@ class Admin extends \Api_Abstract } /** - * Delete order + * Delete order. * * @param int $id - Order id * @@ -231,8 +232,8 @@ class Admin extends \Api_Abstract */ public function delete($data) { - $order = $this->_getOrder($data); - $delete_addons = isset($data['delete_addons']) ? (bool)$data['delete_addons'] : false; + $order = $this->_getOrder($data); + $delete_addons = isset($data['delete_addons']) ? (bool) $data['delete_addons'] : false; if ($delete_addons) { $list = $this->getService()->getOrderAddonsList($order); @@ -256,7 +257,7 @@ class Admin extends \Api_Abstract /** * Cancel all suspended orders. - * Configure how many days suspended order should be kept before canceling + * Configure how many days suspended order should be kept before canceling. * * @return bool */ @@ -266,9 +267,9 @@ class Admin extends \Api_Abstract } /** - * Update order config + * Update order config. * - * @param int $id - Order id + * @param int $id - Order id * @param array $config - list of key value pairs of configuration fields * * @return bool @@ -287,7 +288,7 @@ class Admin extends \Api_Abstract } /** - * Get order service data + * Get order service data. * * @param int $id - Order id * @@ -301,7 +302,7 @@ class Admin extends \Api_Abstract } /** - * Get paginated order statuses history list + * Get paginated order statuses history list. * * @param int $id - Order id * @@ -313,16 +314,16 @@ class Admin extends \Api_Abstract $data['client_order_id'] = $order->id; - list($sql, $bindings) = $this->getService()->getOrderStatusSearchQuery($data); + [$sql, $bindings] = $this->getService()->getOrderStatusSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + return $this->di['pager']->getSimpleResultSet($sql, $bindings, $per_page); } - /** - * Add order status history change + * Add order status history change. * - * @param int $id - Order id + * @param int $id - Order id * @param string $status - order status * * @return array @@ -331,9 +332,9 @@ class Admin extends \Api_Abstract { $order = $this->_getOrder($data); - $required = array( + $required = [ 'status' => 'Order status was not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $notes = $this->di['array_get']($data, 'notes', null); @@ -342,7 +343,7 @@ class Admin extends \Api_Abstract } /** - * Remove order status history item + * Remove order status history item. * * @param int $id - History line id * @@ -350,16 +351,16 @@ class Admin extends \Api_Abstract */ public function status_history_delete($data) { - $required = array( + $required = [ 'id' => 'Order history line id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->orderStatusRm($data['id']); } /** - * Return order statuses codes with counter + * Return order statuses codes with counter. * * @return array */ @@ -369,36 +370,36 @@ class Admin extends \Api_Abstract } /** - * Return available invoice options + * Return available invoice options. * * @return array */ public function get_invoice_options($data) { - return array( + return [ 'issue-invoice' => __('Automatically issue renewal invoices'), - 'no-invoice' => __('Issue invoices manually'), - ); + 'no-invoice' => __('Issue invoices manually'), + ]; } /** - * Return order statuses codes with titles + * Return order statuses codes with titles. * * @return array */ public function get_status_pairs($data) { - return array( + return [ \Model_ClientOrder::STATUS_PENDING_SETUP => 'Pending setup', - \Model_ClientOrder::STATUS_FAILED_SETUP => 'Setup failed', - \Model_ClientOrder::STATUS_ACTIVE => 'Active', - \Model_ClientOrder::STATUS_SUSPENDED => 'Suspended', - \Model_ClientOrder::STATUS_CANCELED => 'Canceled', - ); + \Model_ClientOrder::STATUS_FAILED_SETUP => 'Setup failed', + \Model_ClientOrder::STATUS_ACTIVE => 'Active', + \Model_ClientOrder::STATUS_SUSPENDED => 'Suspended', + \Model_ClientOrder::STATUS_CANCELED => 'Canceled', + ]; } /** - * Return order addons list + * Return order addons list. * * @param int $id - Order id * @@ -406,9 +407,9 @@ class Admin extends \Api_Abstract */ public function addons($data) { - $model = $this->_getOrder($data); - $list = $this->getService()->getOrderAddonsList($model); - $result = array(); + $model = $this->_getOrder($data); + $list = $this->getService()->getOrderAddonsList($model); + $result = []; foreach ($list as $order) { $result[] = $this->getService()->toApiArray($order); } @@ -418,16 +419,16 @@ class Admin extends \Api_Abstract protected function _getOrder($data) { - $required = array( + $required = [ 'id' => 'Order id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->di['db']->getExistingModelById('ClientOrder', $data['id'], 'Order not found'); } /** - * Deletes orders with given IDs + * Deletes orders with given IDs. * * @param array $ids - Order ids for deletion * @@ -437,17 +438,17 @@ class Admin extends \Api_Abstract */ public function batch_delete($data) { - $required = array( + $required = [ 'ids' => 'Orders ids not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $delete_addons = isset($data['delete_addons']) ? (bool)$data['delete_addons'] : false; + $delete_addons = isset($data['delete_addons']) ? (bool) $data['delete_addons'] : false; foreach ($data['ids'] as $id) { - $this->delete(array('id' => $id, 'delete_addons' => $delete_addons)); + $this->delete(['id' => $id, 'delete_addons' => $delete_addons]); } return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Order/Api/Client.php b/src/bb-modules/Order/Api/Client.php index 596656dc3..097a4f9c5 100644 --- a/src/bb-modules/Order/Api/Client.php +++ b/src/bb-modules/Order/Api/Client.php @@ -1,6 +1,6 @@ getIdentity(); + $identity = $this->getIdentity(); $data['client_id'] = $identity->id; if (isset($data['expiring'])) { - list($query, $bindings) = $this->getService()->getSoonExpiringActiveOrdersQuery($data); + [$query, $bindings] = $this->getService()->getSoonExpiringActiveOrdersQuery($data); } else { - list($query, $bindings) = $this->getService()->getSearchQuery($data); + [$query, $bindings] = $this->getService()->getSearchQuery($data); } $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getAdvancedResultSet($query, $bindings, $per_page); @@ -39,13 +39,15 @@ class Client extends \Api_Abstract $order = $this->di['db']->getExistingModelById('ClientOrder', $item['id'], 'Client order not found'); $pager['list'][$key] = $this->getService()->toApiArray($order); } + return $pager; } /** - * Get order details + * Get order details. * * @param int $id - order id + * * @return array */ public function get($data) @@ -56,16 +58,17 @@ class Client extends \Api_Abstract } /** - * Get order addons + * Get order addons. * * @param int $id - order id + * * @return array */ public function addons($data) { - $model = $this->_getOrder($data); - $list = $this->getService()->getOrderAddonsList($model); - $result = array(); + $model = $this->_getOrder($data); + $list = $this->getService()->getOrderAddonsList($model); + $result = []; foreach ($list as $order) { $result[] = $this->getService()->toApiArray($order); } @@ -77,37 +80,41 @@ class Client extends \Api_Abstract * Get order service. Order must be activated before service can be retrieved. * * @param int $id - order id + * * @return array */ public function service($data) { $order = $this->_getOrder($data); - return $this->getService()->getOrderServiceData($order, $data['id'], $this->getIdentity());; + return $this->getService()->getOrderServiceData($order, $data['id'], $this->getIdentity()); } /** - * List of product pairs offered as an upgrade + * List of product pairs offered as an upgrade. + * * @param int $id - order id + * * @return array */ public function upgradables($data) { - $model = $this->_getOrder($data); - $product = $this->di['db']->getExistingModelById('Product', $model->product_id); + $model = $this->_getOrder($data); + $product = $this->di['db']->getExistingModelById('Product', $model->product_id); $productService = $this->di['mod_service']('product'); return $productService->getUpgradablePairs($product); } /** - * Can delete only pending setup and failed setup orders + * Can delete only pending setup and failed setup orders. + * * @param int $id - order id */ public function delete($data) { $model = $this->_getOrder($data); - if (!in_array($model->status, array(\Model_ClientOrder::STATUS_PENDING_SETUP, \Model_ClientOrder::STATUS_FAILED_SETUP))) { + if (!in_array($model->status, [\Model_ClientOrder::STATUS_PENDING_SETUP, \Model_ClientOrder::STATUS_FAILED_SETUP])) { throw new \Box_Exception('Only pending and failed setup orders can be deleted.'); } @@ -116,9 +123,9 @@ class Client extends \Api_Abstract protected function _getOrder($data) { - $required = array( + $required = [ 'id' => 'Order id required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $order = $this->getService()->findForClientById($this->getIdentity(), $data['id']); @@ -128,4 +135,4 @@ class Client extends \Api_Abstract return $order; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Order/Controller/Admin.php b/src/bb-modules/Order/Controller/Admin.php index de29503ad..c3d2bfec5 100644 --- a/src/bb-modules/Order/Controller/Admin.php +++ b/src/bb-modules/Order/Controller/Admin.php @@ -1,6 +1,6 @@ array( + return [ + 'group' => [ 'index' => 300, 'location' => 'order', 'label' => 'Orders', 'uri' => $this->di['url']->adminLink('order'), - 'class' => 'orders', + 'class' => 'orders', 'sprite_class' => 'dark-sprite-icon sprite-basket', - ), - 'subpages' => array( - array( - 'location' => 'order', - 'index' => 100, + ], + 'subpages' => [ + [ + 'location' => 'order', + 'index' => 100, 'label' => 'Overview', 'uri' => $this->di['url']->adminLink('order'), - 'class' => '', - ), - array( - 'location' => 'order', - 'index' => 200, + 'class' => '', + ], + [ + 'location' => 'order', + 'index' => 200, 'label' => 'Advanced search', - 'uri' => $this->di['url']->adminLink('order', array('show_filter' => 1)), - 'class' => '', - ), - ), - ); + 'uri' => $this->di['url']->adminLink('order', ['show_filter' => 1]), + 'class' => '', + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/order', 'get_index', array(), get_class($this)); - $app->get('/order/', 'get_index', array(), get_class($this)); - $app->get('/order/index', 'get_index', array(), get_class($this)); - $app->get('/order/manage/:id', 'get_order', array('id'=>'[0-9]+'), get_class($this)); - $app->post('/order/new', 'get_new', array(), get_class($this)); + $app->get('/order', 'get_index', [], get_class($this)); + $app->get('/order/', 'get_index', [], get_class($this)); + $app->get('/order/index', 'get_index', [], get_class($this)); + $app->get('/order/manage/:id', 'get_order', ['id' => '[0-9]+'], get_class($this)); + $app->post('/order/new', 'get_new', [], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_order_index'); } public function get_new(\Box_App $app) { $api = $this->di['api_admin']; - $product = $api->product_get(array('id' => $this->di['request']->getPost('product_id'))); - $client = $api->client_get(array('id' => $this->di['request']->getPost('client_id'))); - return $app->render('mod_order_new', array('product' => $product, 'client' => $client)); + $product = $api->product_get(['id' => $this->di['request']->getPost('product_id')]); + $client = $api->client_get(['id' => $this->di['request']->getPost('client_id')]); + + return $app->render('mod_order_new', ['product' => $product, 'client' => $client]); } - + public function get_order(\Box_App $app, $id) { $api = $this->di['api_admin']; - $data = array( - 'id' => $id, - ); + $data = [ + 'id' => $id, + ]; $order = $api->order_get($data); - $set = array('order'=>$order); - - if(isset($order['plugin']) && !empty($order['plugin'])) { + $set = ['order' => $order]; + + if (isset($order['plugin']) && !empty($order['plugin'])) { $set['plugin'] = 'plugin_'.$order['plugin'].'_manage.phtml'; } - + return $app->render('mod_order_manage', $set); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Order/Controller/Client.php b/src/bb-modules/Order/Controller/Client.php index 8b74311bf..d8b3b3177 100644 --- a/src/bb-modules/Order/Controller/Client.php +++ b/src/bb-modules/Order/Controller/Client.php @@ -1,6 +1,6 @@ get('/order', 'get_products', array(), get_class($this)); - $app->get('/order/service', 'get_orders', array(), get_class($this)); - $app->get('/order/:id', 'get_configure_product', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/order/:slug', 'get_configure_product_by_slug', array('slug' => '[a-z0-9-]+'), get_class($this)); - $app->get('/order/service/manage/:id', 'get_order', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/order', 'get_products', [], get_class($this)); + $app->get('/order/service', 'get_orders', [], get_class($this)); + $app->get('/order/:id', 'get_configure_product', ['id' => '[0-9]+'], get_class($this)); + $app->get('/order/:slug', 'get_configure_product_by_slug', ['slug' => '[a-z0-9-]+'], get_class($this)); + $app->get('/order/service/manage/:id', 'get_order', ['id' => '[0-9]+'], get_class($this)); } - + public function get_products(\Box_App $app) { return $app->render('mod_order_index'); @@ -51,39 +49,42 @@ class Client implements \Box\InjectionAwareInterface public function get_configure_product_by_slug(\Box_App $app, $slug) { $api = $this->di['api_guest']; - $product = $api->product_get(array('slug'=>$slug)); + $product = $api->product_get(['slug' => $slug]); $tpl = 'mod_service'.$product['type'].'_order'; - if($api->system_template_exists(array('file'=>$tpl.'.phtml'))) { - return $app->render($tpl, array('product'=>$product)); + if ($api->system_template_exists(['file' => $tpl.'.phtml'])) { + return $app->render($tpl, ['product' => $product]); } - return $app->render('mod_order_product', array('product'=>$product)); + + return $app->render('mod_order_product', ['product' => $product]); } public function get_configure_product(\Box_App $app, $id) { $api = $this->di['api_guest']; - $product = $api->product_get(array('id'=>$id)); + $product = $api->product_get(['id' => $id]); $tpl = 'mod_service'.$product['type'].'_order'; - if($api->system_template_exists(array('file'=>$tpl.'.phtml'))) { - return $app->render($tpl, array('product'=>$product)); + if ($api->system_template_exists(['file' => $tpl.'.phtml'])) { + return $app->render($tpl, ['product' => $product]); } - return $app->render('mod_order_product', array('product'=>$product)); + + return $app->render('mod_order_product', ['product' => $product]); } - + public function get_orders(\Box_App $app) { $this->di['is_client_logged']; + return $app->render('mod_order_list'); } public function get_order(\Box_App $app, $id) { $api = $this->di['api_client']; - $data = array( - 'id' => $id, - ); + $data = [ + 'id' => $id, + ]; $order = $api->order_get($data); - return $app->render('mod_order_manage', array('order'=>$order)); - } -} \ No newline at end of file + return $app->render('mod_order_manage', ['order' => $order]); + } +} diff --git a/src/bb-modules/Order/Service.php b/src/bb-modules/Order/Service.php index 9249e3797..c54bef73a 100644 --- a/src/bb-modules/Order/Service.php +++ b/src/bb-modules/Order/Service.php @@ -1,6 +1,6 @@ di['db']->getAssoc($sql); - return array( - 'total' => array_sum($data), + return [ + 'total' => array_sum($data), \Model_ClientOrder::STATUS_PENDING_SETUP => $this->di['array_get']($data, \Model_ClientOrder::STATUS_PENDING_SETUP, 0), - \Model_ClientOrder::STATUS_FAILED_SETUP => $this->di['array_get']($data, \Model_ClientOrder::STATUS_FAILED_SETUP, 0), - \Model_ClientOrder::STATUS_ACTIVE => $this->di['array_get']($data, \Model_ClientOrder::STATUS_ACTIVE, 0), - \Model_ClientOrder::STATUS_SUSPENDED => $this->di['array_get']($data, \Model_ClientOrder::STATUS_SUSPENDED, 0), - \Model_ClientOrder::STATUS_CANCELED => $this->di['array_get']($data, \Model_ClientOrder::STATUS_CANCELED, 0), - ); + \Model_ClientOrder::STATUS_FAILED_SETUP => $this->di['array_get']($data, \Model_ClientOrder::STATUS_FAILED_SETUP, 0), + \Model_ClientOrder::STATUS_ACTIVE => $this->di['array_get']($data, \Model_ClientOrder::STATUS_ACTIVE, 0), + \Model_ClientOrder::STATUS_SUSPENDED => $this->di['array_get']($data, \Model_ClientOrder::STATUS_SUSPENDED, 0), + \Model_ClientOrder::STATUS_CANCELED => $this->di['array_get']($data, \Model_ClientOrder::STATUS_CANCELED, 0), + ]; } public static function onAfterAdminOrderActivate(\Box_Event $event) { - $params = $event->getParameters(); + $params = $event->getParameters(); $order_id = $params['id']; $di = $event->getDi(); $service = $di['mod_service']('order'); try { - $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found');; - $s = $service->getOrderServiceData($order); + $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); + $s = $service->getOrderServiceData($order); $orderArr = $service->toApiArray($order, true); - $email = $params; + $email = $params; $email['to_client'] = $order->client_id; - $email['code'] = sprintf('mod_service%s_activated', $orderArr['service_type']); - $email['service'] = $s; - $email['order'] = $orderArr; + $email['code'] = sprintf('mod_service%s_activated', $orderArr['service_type']); + $email['service'] = $s; + $email['order'] = $orderArr; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); @@ -83,22 +82,22 @@ class Service implements InjectionAwareInterface public static function onAfterAdminOrderRenew(\Box_Event $event) { - $params = $event->getParameters(); + $params = $event->getParameters(); $order_id = $params['id']; $di = $event->getDi(); $orderService = $di['mod_service']('order'); try { - $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); + $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); $identity = $di['loggedin_admin']; - $service = $orderService->getOrderServiceData($order, $identity); + $service = $orderService->getOrderServiceData($order, $identity); $orderArr = $orderService->toApiArray($order, true, $identity); - $email = array(); + $email = []; $email['to_client'] = $orderArr['client']['id']; - $email['code'] = sprintf('mod_service%s_renewed', $orderArr['service_type']); - $email['service'] = $service; - $email['order'] = $orderArr; + $email['code'] = sprintf('mod_service%s_renewed', $orderArr['service_type']); + $email['service'] = $service; + $email['order'] = $orderArr; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); @@ -109,22 +108,22 @@ class Service implements InjectionAwareInterface public static function onAfterAdminOrderSuspend(\Box_Event $event) { - $params = $event->getParameters(); + $params = $event->getParameters(); $order_id = $params['id']; $di = $event->getDi(); $service = $di['mod_service']('order'); try { - $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); + $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); $identity = $di['loggedin_admin']; - $s = $service->getOrderServiceData($order, $identity); + $s = $service->getOrderServiceData($order, $identity); $orderArr = $service->toApiArray($order, true, $identity); - $email = array(); + $email = []; $email['to_client'] = $orderArr['client']['id']; - $email['code'] = sprintf('mod_service%s_suspended', $orderArr['service_type']); - $email['service'] = $s; - $email['order'] = $orderArr; + $email['code'] = sprintf('mod_service%s_suspended', $orderArr['service_type']); + $email['service'] = $s; + $email['order'] = $orderArr; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); @@ -135,22 +134,22 @@ class Service implements InjectionAwareInterface public static function onAfterAdminOrderUnsuspend(\Box_Event $event) { - $params = $event->getParameters(); + $params = $event->getParameters(); $order_id = $params['id']; $di = $event->getDi(); $service = $di['mod_service']('order'); try { - $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); + $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); $identity = $di['loggedin_admin']; - $s = $service->getOrderServiceData($order, $identity); + $s = $service->getOrderServiceData($order, $identity); $orderArr = $service->toApiArray($order, true, $identity); - $email = array(); + $email = []; $email['to_client'] = $orderArr['client']['id']; - $email['code'] = sprintf('mod_service%s_unsuspended', $orderArr['service_type']); - $email['service'] = $s; - $email['order'] = $orderArr; + $email['code'] = sprintf('mod_service%s_unsuspended', $orderArr['service_type']); + $email['service'] = $s; + $email['order'] = $orderArr; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); @@ -161,20 +160,20 @@ class Service implements InjectionAwareInterface public static function onAfterAdminOrderCancel(\Box_Event $event) { - $params = $event->getParameters(); + $params = $event->getParameters(); $order_id = $params['id']; $di = $event->getDi(); $service = $di['mod_service']('order'); try { - $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); + $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); $identity = $di['loggedin_admin']; $orderArr = $service->toApiArray($order, true, $identity); - $email = array(); + $email = []; $email['to_client'] = $orderArr['client']['id']; - $email['code'] = sprintf('mod_service%s_canceled', $orderArr['service_type']); - $email['order'] = $orderArr; + $email['code'] = sprintf('mod_service%s_canceled', $orderArr['service_type']); + $email['order'] = $orderArr; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); @@ -185,22 +184,22 @@ class Service implements InjectionAwareInterface public static function onAfterAdminOrderUncancel(\Box_Event $event) { - $params = $event->getParameters(); + $params = $event->getParameters(); $order_id = $params['id']; $di = $event->getDi(); $service = $di['mod_service']('order'); try { - $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); + $order = $di['db']->getExistingModelById('ClientOrder', $order_id, 'Order not found'); $identity = $di['loggedin_admin']; - $s = $service->getOrderServiceData($order, $identity); - $orderArr = $service->toApiArray($order, true, $identity); + $s = $service->getOrderServiceData($order, $identity); + $orderArr = $service->toApiArray($order, true, $identity); - $email = array(); + $email = []; $email['to_client'] = $orderArr['client']['id']; - $email['code'] = sprintf('mod_service%s_renewed', $orderArr['service_type']); - $email['order'] = $orderArr; - $email['service'] = $s; + $email['code'] = sprintf('mod_service%s_renewed', $orderArr['service_type']); + $email['order'] = $orderArr; + $email['service'] = $s; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); @@ -211,48 +210,48 @@ class Service implements InjectionAwareInterface public function getOrderService(\Model_ClientOrder $order) { - if (NULL !== $order->service_id) { - //@deprecated - //@todo remove this when doctrine is removed - $core_services = array( + if (null !== $order->service_id) { + // @deprecated + // @todo remove this when doctrine is removed + $core_services = [ \Model_ProductTable::CUSTOM, \Model_ProductTable::LICENSE, \Model_ProductTable::DOWNLOADABLE, \Model_ProductTable::HOSTING, \Model_ProductTable::MEMBERSHIP, \Model_ProductTable::DOMAIN, - ); + ]; if (in_array($order->service_type, $core_services)) { $repo_class = $this->_getServiceClassName($order); return $this->di['db']->load($repo_class, $order->service_id); } else { - $service = $this->di['db']->findOne('service_' . $order->service_type, + $service = $this->di['db']->findOne('service_'.$order->service_type, 'id = :id', - array(':id' => $order->service_id)); + [':id' => $order->service_id]); return $service; } } - return NULL; + return null; } protected function _getServiceClassName(\Model_ClientOrder $order) { $s = $this->di['tools']->to_camel_case($order->service_type, true); - return 'Service' . ucfirst($s); + return 'Service'.ucfirst($s); } public function getServiceOrder($service) { $type = $this->di['tools']->from_camel_case(str_replace('Model_Service', '', get_class($service))); - $bindings = array( + $bindings = [ 'service_type' => $type, - ':service_id' => $service->id - ); + ':service_id' => $service->id, + ]; return $this->di['db']->findOne('ClientOrder', 'service_type = :service_type AND service_id = :service_id', $bindings); } @@ -264,9 +263,9 @@ class Service implements InjectionAwareInterface public function productHasOrders(\Model_Product $product) { - $order = $this->di['db']->findOne('ClientOrder', 'product_id = :product_id', array(':product_id' => $product->id)); + $order = $this->di['db']->findOne('ClientOrder', 'product_id = :product_id', [':product_id' => $product->id]); - return ($order instanceof \Model_ClientOrder); + return $order instanceof \Model_ClientOrder; } public function getLogger(\Model_ClientOrder $order) @@ -282,69 +281,69 @@ class Service implements InjectionAwareInterface /** * @param string $notes */ - public function saveStatusChange(\Model_ClientOrder $order, $notes = NULL) + public function saveStatusChange(\Model_ClientOrder $order, $notes = null) { - $os = $this->di['db']->dispense('ClientOrderStatus'); + $os = $this->di['db']->dispense('ClientOrderStatus'); $os->client_order_id = $order->id; - $os->status = $order->status; - $os->notes = $notes; - $os->created_at = date('Y-m-d H:i:s'); - $os->updated_at = date('Y-m-d H:i:s'); + $os->status = $order->status; + $os->notes = $notes; + $os->created_at = date('Y-m-d H:i:s'); + $os->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($os); } public function getSoonExpiringActiveOrders() { - list($query, $bindings) = $this->getSoonExpiringActiveOrdersQuery(); + [$query, $bindings] = $this->getSoonExpiringActiveOrdersQuery(); return $this->di['db']->getAll($query, $bindings); } - public function getSoonExpiringActiveOrdersQuery($data = array()) + public function getSoonExpiringActiveOrdersQuery($data = []) { - $systemService = $this->di['mod_service']('system'); + $systemService = $this->di['mod_service']('system'); $days_until_expiration = $systemService->getParamValue('invoice_issue_days_before_expire', 14); - $client_id = $this->di['array_get']($data, 'client_id', NULL); + $client_id = $this->di['array_get']($data, 'client_id', null); - $query = "SELECT * + $query = 'SELECT * FROM client_order WHERE status = :status AND invoice_option = :invoice_option AND period IS NOT NULL AND expires_at IS NOT NULL - AND unpaid_invoice_id IS NULL"; + AND unpaid_invoice_id IS NULL'; - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; - if (NULL !== $client_id) { - $where[] = 'client_id = :client_id'; + if (null !== $client_id) { + $where[] = 'client_id = :client_id'; $bindings[':client_id'] = $client_id; } if (!empty($where)) { - $query = $query . ' AND '. implode(' AND ', $where); + $query = $query.' AND '.implode(' AND ', $where); } - $query .= " HAVING DATEDIFF(expires_at, NOW()) <= :days_until_expiration ORDER BY client_id DESC"; - $bindings[':status'] = \Model_ClientOrder::STATUS_ACTIVE; - $bindings[':invoice_option'] = 'issue-invoice'; + $query .= ' HAVING DATEDIFF(expires_at, NOW()) <= :days_until_expiration ORDER BY client_id DESC'; + $bindings[':status'] = \Model_ClientOrder::STATUS_ACTIVE; + $bindings[':invoice_option'] = 'issue-invoice'; $bindings[':days_until_expiration'] = $days_until_expiration; - return array($query, $bindings); + return [$query, $bindings]; } public function toApiArray(\Model_ClientOrder $model, $deep = true, $identity = null) { - $clientService = $this->di['mod_service']('client'); + $clientService = $this->di['mod_service']('client'); $supportService = $this->di['mod_service']('support'); - $data = $this->di['db']->toArray($model); - $data['config'] = json_decode($model->config, 1); - $data['total'] = $this->getTotal($model); - $data['title'] = $model->title; - $data['meta'] = $this->di['db']->getAssoc('SELECT name, value FROM client_order_meta WHERE client_order_id = :id', array(':id' => $model->id)); + $data = $this->di['db']->toArray($model); + $data['config'] = json_decode($model->config, 1); + $data['total'] = $this->getTotal($model); + $data['title'] = $model->title; + $data['meta'] = $this->di['db']->getAssoc('SELECT name, value FROM client_order_meta WHERE client_order_id = :id', [':id' => $model->id]); $data['active_tickets'] = $supportService->getActiveTicketsCountForOrder($model); $client = $this->di['db']->getExistingModelById('Client', $model->client_id, 'Client not found'); $data['client'] = $clientService->toApiArray($client, false); @@ -352,9 +351,9 @@ class Service implements InjectionAwareInterface if ($identity instanceof \Model_Admin) { $data['config'] = $this->getConfig($model); $productModel = $this->di['db']->load('Product', $model->product_id); - if ($productModel instanceof \Model_Product){ + if ($productModel instanceof \Model_Product) { $data['plugin'] = $productModel->plugin; - }else{ + } else { $data['plugin'] = null; } } @@ -367,122 +366,122 @@ class Service implements InjectionAwareInterface public function getSearchQuery($data) { - $query = "SELECT co.* from client_order co + $query = 'SELECT co.* from client_order co LEFT JOIN client c ON c.id = co.client_id - LEFT JOIN client_order_meta meta ON meta.client_order_id = co.id"; + LEFT JOIN client_order_meta meta ON meta.client_order_id = co.id'; - $search = $this->di['array_get']($data, 'search', FALSE); - $hide_addons = $this->di['array_get']($data, 'hide_addons', NULL); - $id = $this->di['array_get']($data, 'id', NULL); - $product_id = $this->di['array_get']($data, 'product_id', NULL); - $status = $this->di['array_get']($data, 'status', NULL); - $title = $this->di['array_get']($data, 'title', NULL); - $period = $this->di['array_get']($data, 'period', NULL); - $type = $this->di['array_get']($data, 'type', NULL); - $created_at = $this->di['array_get']($data, 'created_at', NULL); - $date_from = $this->di['array_get']($data, 'date_from', NULL); - $date_to = $this->di['array_get']($data, 'date_to', NULL); - $ids = (isset($data['ids']) && is_array($data['ids'])) ? $data['ids'] : null; - $meta = (isset($data['meta']) && is_array($data['meta'])) ? $data['meta'] : null; + $search = $this->di['array_get']($data, 'search', false); + $hide_addons = $this->di['array_get']($data, 'hide_addons', null); + $id = $this->di['array_get']($data, 'id', null); + $product_id = $this->di['array_get']($data, 'product_id', null); + $status = $this->di['array_get']($data, 'status', null); + $title = $this->di['array_get']($data, 'title', null); + $period = $this->di['array_get']($data, 'period', null); + $type = $this->di['array_get']($data, 'type', null); + $created_at = $this->di['array_get']($data, 'created_at', null); + $date_from = $this->di['array_get']($data, 'date_from', null); + $date_to = $this->di['array_get']($data, 'date_to', null); + $ids = (isset($data['ids']) && is_array($data['ids'])) ? $data['ids'] : null; + $meta = (isset($data['meta']) && is_array($data['meta'])) ? $data['meta'] : null; - $client_id = $this->di['array_get']($data, 'client_id', NULL); - $invoice_option = $this->di['array_get']($data, 'invoice_option', NULL); + $client_id = $this->di['array_get']($data, 'client_id', null); + $invoice_option = $this->di['array_get']($data, 'invoice_option', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; if ($client_id) { - $where[] = "co.client_id = :client_id"; + $where[] = 'co.client_id = :client_id'; $bindings[':client_id'] = $client_id; } if ($invoice_option) { - $where[] = "co.invoice_option = :invoice_option"; + $where[] = 'co.invoice_option = :invoice_option'; $bindings[':invoice_option'] = $invoice_option; } if ($id) { - $where[] = "co.id = :id"; + $where[] = 'co.id = :id'; $bindings[':id'] = $id; } if ($status) { - $where[] = "co.status = :status"; + $where[] = 'co.status = :status'; $bindings[':status'] = $status; } if ($product_id) { - $where[] = "co.product_id = :product_id"; + $where[] = 'co.product_id = :product_id'; $bindings[':product_id'] = $product_id; } if ($type) { - $where[] = "co.service_type = :service_type"; + $where[] = 'co.service_type = :service_type'; $bindings[':service_type'] = $type; } if ($title) { - $where[] = "co.title LIKE :title"; - $bindings[':title'] = '%' . $title . '%'; + $where[] = 'co.title LIKE :title'; + $bindings[':title'] = '%'.$title.'%'; } if ($period) { - $where[] = "co.period = :period"; + $where[] = 'co.period = :period'; $bindings[':period'] = $period; } if ($hide_addons) { - $where[] = "co.group_master = 1"; + $where[] = 'co.group_master = 1'; } if ($created_at) { - $where[] = "DATE_FORMAT(co.created_at, '%Y-%m-%d') = :created_at"; + $where[] = "DATE_FORMAT(co.created_at, '%Y-%m-%d') = :created_at"; $bindings[':created_at'] = date('Y-m-d', strtotime($created_at)); } if ($date_from) { - $where[] = "UNIX_TIMESTAMP(co.created_at) >= :date_from"; + $where[] = 'UNIX_TIMESTAMP(co.created_at) >= :date_from'; $bindings[':date_from'] = strtotime($date_from); } if ($date_to) { - $where[] = "UNIX_TIMESTAMP(co.created_at) <= :date_to"; + $where[] = 'UNIX_TIMESTAMP(co.created_at) <= :date_to'; $bindings[':date_to'] = strtotime($date_to); } - //smartSearch + // smartSearch if ($search) { if (is_numeric($search)) { - $where[] = "co.id = :search"; + $where[] = 'co.id = :search'; $bindings[':search'] = $search; } else { - $where[] = "(c.first_name LIKE :first_name OR c.last_name LIKE :last_name OR co.title LIKE :title)"; + $where[] = '(c.first_name LIKE :first_name OR c.last_name LIKE :last_name OR co.title LIKE :title)'; $bindings[':first_name'] = "%$search%"; - $bindings[':last_name'] = "%$search%"; - $bindings[':title'] = "%$search%"; + $bindings[':last_name'] = "%$search%"; + $bindings[':title'] = "%$search%"; } } if ($ids) { - $where[] = "co.id IN (:ids)"; - $bindings[':ids'] = implode(', ',$ids); + $where[] = 'co.id IN (:ids)'; + $bindings[':ids'] = implode(', ', $ids); } if ($meta) { $i = 1; foreach ($meta as $k => $v) { - $where[] = "(meta.name = :meta_name$i AND meta.value LIKE :meta_value$i)"; - $bindings[':meta_name' . $i] = $k; - $bindings[':meta_value' . $i] = $v . '%'; - $i++; + $where[] = "(meta.name = :meta_name$i AND meta.value LIKE :meta_value$i)"; + $bindings[':meta_name'.$i] = $k; + $bindings[':meta_value'.$i] = $v.'%'; + ++$i; } } if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); + $query = $query.' WHERE '.implode(' AND ', $where); } - $query .= " ORDER BY co.id DESC"; + $query .= ' ORDER BY co.id DESC'; - return array($query, $bindings); + return [$query, $bindings]; } public function createOrder(\Model_Client $client, \Model_Product $product, array $data) @@ -499,24 +498,24 @@ class Service implements InjectionAwareInterface throw new \Box_Exception('Currency could not be determined for order'); } - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderCreate', 'params' => $data, 'subject' => $product->type)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderCreate', 'params' => $data, 'subject' => $product->type]); - $period = (isset($data['period']) && !empty($data['period'])) ? $data['period'] : NULL; - $qty = $this->di['array_get']($data, 'quantity', 1); - $config = (isset($data['config']) && is_array($data['config'])) ? $data['config'] : array(); - $group_id = $this->di['array_get']($data, 'group_id'); - $activate = (bool) $this->di['array_get']($data, 'activate', false); - $invoiceOption = $this->di['array_get']($data, 'invoice_option', 'no-invoice'); + $period = (isset($data['period']) && !empty($data['period'])) ? $data['period'] : null; + $qty = $this->di['array_get']($data, 'quantity', 1); + $config = (isset($data['config']) && is_array($data['config'])) ? $data['config'] : []; + $group_id = $this->di['array_get']($data, 'group_id'); + $activate = (bool) $this->di['array_get']($data, 'activate', false); + $invoiceOption = $this->di['array_get']($data, 'invoice_option', 'no-invoice'); $skipValidation = (bool) $this->di['array_get']($data, 'skip_validation', false); $cartService = $this->di['mod_service']('cart'); // check stock if (!$cartService->isStockAvailable($product, $qty)) { - throw new \Box_Exception("Product :id is out of stock.", array(':id' => $product->id), 831); + throw new \Box_Exception('Product :id is out of stock.', [':id' => $product->id], 831); } // Addons must have defined master order - $parent_order = FALSE; + $parent_order = false; if ($product->is_addon && empty($group_id)) { throw new \Box_Exception('Group ID parameter is missing for addon product order', null, 832); } @@ -524,46 +523,48 @@ class Service implements InjectionAwareInterface if (!empty($group_id)) { $parent_order = $this->getMasterOrderForClient($client, $group_id); if (!$parent_order instanceof \Model_ClientOrder) { - throw new \Box_Exception('Parent order :group_id was not found', array(':group_id' => $group_id)); + throw new \Box_Exception('Parent order :group_id was not found', [':group_id' => $group_id]); } } - //validate order config data + // validate order config data if ($period) { $config['period'] = $period; } - $se = $this->di['mod_service']('service' . $product->type); - //@deprecated logic + $se = $this->di['mod_service']('service'.$product->type); + // @deprecated logic if (method_exists($se, 'prependOrderConfig')) { $config = $se->prependOrderConfig($product, $config); } - //@migration script - $se = $this->di['mod_service']('service' . $product->type); + // @migration script + $se = $this->di['mod_service']('service'.$product->type); if (method_exists($se, 'attachOrderConfig')) { $config = $se->attachOrderConfig($product, $config); } if (method_exists($se, 'validateOrderData')) { - if (!$skipValidation) $se->validateOrderData($config); + if (!$skipValidation) { + $se->validateOrderData($config); + } } - $order = $this->di['db']->dispense('ClientOrder'); - $order->client_id = $client->id; - $order->product_id = $product->id; - $order->group_id = ($parent_order) ? $parent_order->group_id : uniqid(); - $order->group_master = ($parent_order) ? 0 : 1; - $order->title = isset($data['title']) ? $data['title'] : $product->title; - $order->currency = $currency->code; - $order->quantity = $qty; - $order->service_type = $product->type; - $order->unit = $product->unit; - $order->status = \Model_ClientOrder::STATUS_PENDING_SETUP; - $order->config = json_encode($config); + $order = $this->di['db']->dispense('ClientOrder'); + $order->client_id = $client->id; + $order->product_id = $product->id; + $order->group_id = ($parent_order) ? $parent_order->group_id : uniqid(); + $order->group_master = ($parent_order) ? 0 : 1; + $order->title = $data['title'] ?? $product->title; + $order->currency = $currency->code; + $order->quantity = $qty; + $order->service_type = $product->type; + $order->unit = $product->unit; + $order->status = \Model_ClientOrder::STATUS_PENDING_SETUP; + $order->config = json_encode($config); $order->invoice_option = $invoiceOption; if ($period) { - $bp = $this->di['period']($data['period']); + $bp = $this->di['period']($data['period']); $order->period = $bp->getCode(); } @@ -571,7 +572,7 @@ class Service implements InjectionAwareInterface $order->price = $data['price']; } else { $repo = $product->getTable($product->type); - $rate = $currencyService->getRateByCode($currency->code); + $rate = $currencyService->getRateByCode($currency->code); $order->price = $repo->getProductPrice($product, $config) * $rate; } @@ -592,29 +593,29 @@ class Service implements InjectionAwareInterface if (isset($data['meta']) && is_array($data['meta'])) { foreach ($data['meta'] as $k => $v) { - $mm = $this->di['db']->findOne('client_order_meta', 'client_order_id = :id AND name = :n', array(':id' => $order->id, ':n' => $k)); + $mm = $this->di['db']->findOne('client_order_meta', 'client_order_id = :id AND name = :n', [':id' => $order->id, ':n' => $k]); if (!$mm) { - $mm = $this->di['db']->dispense('ClientOrderMeta'); + $mm = $this->di['db']->dispense('ClientOrderMeta'); $mm->client_order_id = $id; - $mm->name = $k; - $mm->created_at = date('Y-m-d H:i:s'); + $mm->name = $k; + $mm->created_at = date('Y-m-d H:i:s'); } - $mm->value = $v; + $mm->value = $v; $mm->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($mm); } } - $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderCreate', 'params' => array('id' => $order->id), 'subject' => $product->type)); + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderCreate', 'params' => ['id' => $order->id], 'subject' => $product->type]); $this->di['logger']->info('Created order #%s', $id); // invoice options - if ($invoiceOption == 'issue-invoice' && $order->price > 0) { + if ('issue-invoice' == $invoiceOption && $order->price > 0) { $invoiceService = $this->di['mod_service']('invoice'); - $invoice = $invoiceService->generateForOrder($order); + $invoice = $invoiceService->generateForOrder($order); - $invoiceService->approveInvoice($invoice, array('id' => $invoice->id, 'use_credits' => true)); + $invoiceService->approveInvoice($invoice, ['id' => $invoice->id, 'use_credits' => true]); } // activate imediately if say so @@ -631,16 +632,17 @@ class Service implements InjectionAwareInterface public function getMasterOrderForClient(\Model_Client $client, $group_id) { - $bindings = array( - ':group_id' => $group_id, - ':client_id' => $client->id - ); + $bindings = [ + ':group_id' => $group_id, + ':client_id' => $client->id, + ]; return $this->di['db']->findOne('ClientOrder', 'group_id = :group_id AND group_master = 1 AND client_id = :client_id', $bindings); } /** - * activate all addons on initial activation + * activate all addons on initial activation. + * * @see https://github.com/boxbilling/BoxBilling/issues/54 */ public function activateOrderAddons(\Model_ClientOrder $order) @@ -652,53 +654,54 @@ class Service implements InjectionAwareInterface $list = $this->getOrderAddonsList($order); foreach ($list as $addon) { try { - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderActivate', 'params' => array('id' => $addon->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderActivate', 'params' => ['id' => $addon->id]]); $this->createFromOrder($addon); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderActivate', 'params' => array('id' => $addon->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderActivate', 'params' => ['id' => $addon->id]]); } catch (\Exception $e) { error_log($e->getMessage()); } } + return true; } - public function activateOrder(\Model_ClientOrder $order, $data = array()) + public function activateOrder(\Model_ClientOrder $order, $data = []) { - $statues = array( + $statues = [ \Model_ClientOrder::STATUS_PENDING_SETUP, \Model_ClientOrder::STATUS_FAILED_SETUP, - ); - if (!in_array($order->status, $statues)){ + ]; + if (!in_array($order->status, $statues)) { if (!isset($data['force']) || !$data['force']) { throw new \Box_Exception('Only pending setup or failed orders can be activated'); } } - $event_params = array('id' => $order->id); - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderActivate', 'params' => $event_params)); + $event_params = ['id' => $order->id]; + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderActivate', 'params' => $event_params]); $result = $this->createFromOrder($order); if (is_array($result)) { $event_params = array_merge($event_params, $result); } - $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderActivate', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderActivate', 'params' => $event_params]); $this->activateOrderAddons($order); $this->di['logger']->info('Activated order #%s', $order->id); - return TRUE; + return true; } public function createFromOrder(\Model_ClientOrder $order) { $service = $this->getOrderService($order); if (!is_object($service)) { - $mod = $this->di['mod']('service' . $order->service_type); - $s = $mod->getService(); + $mod = $this->di['mod']('service'.$order->service_type); + $s = $mod->getService(); if (method_exists($s, 'create') || method_exists($s, 'action_create')) { $service = $this->_callOnService($order, \Model_ClientOrder::ACTION_CREATE); if (!is_object($service)) { - throw new \Box_Exception('Error creating ' . $order->service_type . ' service for order ' . $order->id); + throw new \Box_Exception('Error creating '.$order->service_type.' service for order '.$order->id); } $order->service_id = $service->id; @@ -720,21 +723,21 @@ class Service implements InjectionAwareInterface // set automatic order expiration if (!empty($order->period)) { - $from_time = (NULL === $order->expires_at) ? time() : strtotime($order->expires_at); + $from_time = (null === $order->expires_at) ? time() : strtotime($order->expires_at); - $period = $this->di['period']($order->period); + $period = $this->di['period']($order->period); $order->expires_at = date('Y-m-d H:i:s', $period->getExpirationTime($from_time)); } - $order->status = \Model_ClientOrder::STATUS_ACTIVE; + $order->status = \Model_ClientOrder::STATUS_ACTIVE; $order->activated_at = date('Y-m-d H:i:s'); - $order->suspended_at = NULL; - $order->canceled_at = NULL; - $order->updated_at = date('Y-m-d H:i:s'); + $order->suspended_at = null; + $order->canceled_at = null; + $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); $productModel = $this->di['db']->load('Product', $order->product_id); - if($productModel instanceof \Model_Product) { + if ($productModel instanceof \Model_Product) { $this->stockSale($productModel, $order->quantity); } else { error_log(sprintf('Order without product ID detected Order #%s', $order->id)); @@ -747,41 +750,41 @@ class Service implements InjectionAwareInterface public function getOrderAddonsList(\Model_ClientOrder $order) { - return $this->di['db']->find('ClientOrder', 'group_id = :group_id AND client_id = :client_id and (group_master = 0 OR group_master IS NULL)', array(':group_id' => $order->group_id, ':client_id' => $order->client_id)); + return $this->di['db']->find('ClientOrder', 'group_id = :group_id AND client_id = :client_id and (group_master = 0 OR group_master IS NULL)', [':group_id' => $order->group_id, ':client_id' => $order->client_id]); } protected function _callOnService(\Model_ClientOrder $order, $action) { - $repo = $this->di['mod_service']('service' . $order->service_type); - //@deprecated - //@todo remove this when doctrine is removed - $core_services = array( + $repo = $this->di['mod_service']('service'.$order->service_type); + // @deprecated + // @todo remove this when doctrine is removed + $core_services = [ \Model_ProductTable::CUSTOM, \Model_ProductTable::LICENSE, \Model_ProductTable::DOWNLOADABLE, \Model_ProductTable::HOSTING, \Model_ProductTable::MEMBERSHIP, \Model_ProductTable::DOMAIN, - ); + ]; if (in_array($order->service_type, $core_services)) { - $m = 'action_' . $action; - if (!method_exists($repo, $m) || !is_callable(array($repo, $m))) { - throw new \Box_Exception('Service ' . $order->service_type . ' do not support ' . $m); + $m = 'action_'.$action; + if (!method_exists($repo, $m) || !is_callable([$repo, $m])) { + throw new \Box_Exception('Service '.$order->service_type.' do not support '.$m); } return $repo->$m($order); } else { - //@new logic for services - $o = $this->di['db']->findOne('client_order', + // @new logic for services + $o = $this->di['db']->findOne('client_order', 'id = :id', - array(':id' => $order->id)); - $service = NULL; - $sdbname = 'service_' . $order->service_type; + [':id' => $order->id]); + $service = null; + $sdbname = 'service_'.$order->service_type; if ($order->service_id) { $service = $this->di['db']->load($sdbname, $order->service_id); } - if (method_exists($repo, $action) && is_callable(array($repo, $action))) { + if (method_exists($repo, $action) && is_callable([$repo, $action])) { return $repo->$action($o, $service); } } @@ -794,34 +797,35 @@ class Service implements InjectionAwareInterface { if ($product->stock_control) { $product->quantity_in_stock = $product->quantity_in_stock - $qty; - $product->updated_at = date('Y-m-d H:i:s'); + $product->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($product); } - return TRUE; + return true; } /** - * @param \Model_ClientOrder $order * @return int */ public function updatePeriod(\Model_ClientOrder $order, $period) { if (!empty($period)) { - $period = $this->di['period']($period); + $period = $this->di['period']($period); $order->period = $period->getCode(); + return 1; } if (!is_null($period)) { - $order->period = NULL; + $order->period = null; + return 2; } + return 0; } /** - * @param \Model_ClientOrder $order * @return int */ public function updateOrderMeta(\Model_ClientOrder $order, $meta) @@ -831,27 +835,29 @@ class Service implements InjectionAwareInterface } if (empty($meta)) { - $this->di['db']->exec('DELETE FROM client_order_meta WHERE client_order_id = :id;', array(':id' => $order->id)); + $this->di['db']->exec('DELETE FROM client_order_meta WHERE client_order_id = :id;', [':id' => $order->id]); + return 1; } foreach ($meta as $k => $v) { - $mm = $this->di['db']->findOne('ClientOrderMeta', 'client_order_id = :id AND name = :n', array(':id' => $order->id, ':n' => $k)); + $mm = $this->di['db']->findOne('ClientOrderMeta', 'client_order_id = :id AND name = :n', [':id' => $order->id, ':n' => $k]); if (!$mm) { - $mm = $this->di['db']->dispense('ClientOrderMeta'); + $mm = $this->di['db']->dispense('ClientOrderMeta'); $mm->client_order_id = $order->id; - $mm->name = $k; - $mm->created_at = date('Y-m-d H:i:s'); + $mm->name = $k; + $mm->created_at = date('Y-m-d H:i:s'); } - $mm->value = $v; + $mm->value = $v; $mm->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($mm); } + return 2; } public function updateOrder(\Model_ClientOrder $order, array $data) { - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderUpdate', 'params' => $data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderUpdate', 'params' => $data]); $this->updatePeriod($order, $this->di['array_get']($data, 'period', null)); $created_at = $this->di['array_get']($data, 'created_at', ''); @@ -869,37 +875,37 @@ class Service implements InjectionAwareInterface $order->expires_at = date('Y-m-d H:i:s', strtotime($expires_at)); } if (empty($expires_at) && !is_null($expires_at)) { - $order->expires_at = NULL; + $order->expires_at = null; } $order->invoice_option = $this->di['array_get']($data, 'invoice_option', $order->invoice_option); - $order->title = $this->di['array_get']($data, 'title', $order->title); - $order->price = $this->di['array_get']($data, 'price', $order->price); - $order->status = $this->di['array_get']($data, 'status', $order->status); - $order->notes = $this->di['array_get']($data, 'notes', $order->notes); - $order->reason = $this->di['array_get']($data, 'reason', $order->reason); + $order->title = $this->di['array_get']($data, 'title', $order->title); + $order->price = $this->di['array_get']($data, 'price', $order->price); + $order->status = $this->di['array_get']($data, 'status', $order->status); + $order->notes = $this->di['array_get']($data, 'notes', $order->notes); + $order->reason = $this->di['array_get']($data, 'reason', $order->reason); $this->updateOrderMeta($order, $this->di['array_get']($data, 'meta', null)); $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderUpdate', 'params' => array('id' => $order->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderUpdate', 'params' => ['id' => $order->id]]); $this->di['logger']->info('Update order #%s', $order->id); - return TRUE; + return true; } public function renewOrder(\Model_ClientOrder $order) { - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderRenew', 'params' => array('id' => $order->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderRenew', 'params' => ['id' => $order->id]]); $this->renewFromOrder($order); // activate all addons on initial activation // @see https://github.com/boxbilling/BoxBilling/issues/54 - if ($order->group_master && $order->status == \Model_ClientOrder::STATUS_PENDING_SETUP) { + if ($order->group_master && \Model_ClientOrder::STATUS_PENDING_SETUP == $order->status) { $list = $this->getOrderAddonsList($order); foreach ($list as $addon) { try { @@ -910,10 +916,10 @@ class Service implements InjectionAwareInterface } } - $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderRenew', 'params' => array('id' => $order->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderRenew', 'params' => ['id' => $order->id]]); $this->di['logger']->info('Renewed order #%s', $order->id); - return TRUE; + return true; } public function renewFromOrder(\Model_ClientOrder $order) @@ -922,29 +928,29 @@ class Service implements InjectionAwareInterface // set automatic order expiration if (!empty($order->period)) { - $from_time = (NULL === $order->expires_at) ? time() : strtotime($order->expires_at); // from expiration date + $from_time = (null === $order->expires_at) ? time() : strtotime($order->expires_at); // from expiration date $config = $this->di['mod_config']('order'); - $logic = $this->di['array_get']($config, 'order_renewal_logic', ''); + $logic = $this->di['array_get']($config, 'order_renewal_logic', ''); - if ($logic == 'from_today') { - $from_time = time(); //renew order from the date renewal occured - } elseif ($logic == 'from_greater') { + if ('from_today' == $logic) { + $from_time = time(); // renew order from the date renewal occured + } elseif ('from_greater' == $logic) { if (strtotime($order->expires_at) > time()) { $from_time = strtotime($order->expires_at); } else { $from_time = time(); } } - $period = $this->di['period']($order->period); + $period = $this->di['period']($order->period); $order->expires_at = date('Y-m-d H:i:s', $period->getExpirationTime($from_time)); } - $order->status = \Model_ClientOrder::STATUS_ACTIVE; - $order->suspended_at = NULL; - $order->unsuspended_at = NULL; - $order->canceled_at = NULL; - $order->updated_at = date('Y-m-d H:i:s'); + $order->status = \Model_ClientOrder::STATUS_ACTIVE; + $order->suspended_at = null; + $order->unsuspended_at = null; + $order->canceled_at = null; + $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); $this->saveStatusChange($order, 'Order renewed'); @@ -952,130 +958,137 @@ class Service implements InjectionAwareInterface public function suspendFromOrder(\Model_ClientOrder $order, $reason = null, $skipEvent = false) { - if (!$skipEvent) $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderSuspend', 'params' => array('id' => $order->id))); + if (!$skipEvent) { + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderSuspend', 'params' => ['id' => $order->id]]); + } - if ($order->status != \Model_ClientOrder::STATUS_ACTIVE) { + if (\Model_ClientOrder::STATUS_ACTIVE != $order->status) { throw new \Box_Exception('Only active orders can be suspended'); } $this->_callOnService($order, \Model_ClientOrder::ACTION_SUSPEND); - $order->status = \Model_ClientOrder::STATUS_SUSPENDED; - $order->reason = $reason; + $order->status = \Model_ClientOrder::STATUS_SUSPENDED; + $order->reason = $reason; $order->suspended_at = date('Y-m-d H:i:s'); - $order->updated_at = date('Y-m-d H:i:s'); + $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); - $note = (NULL === $reason) ? "Order suspeded" : 'Order suspended for ' . $reason; + $note = (null === $reason) ? 'Order suspeded' : 'Order suspended for '.$reason; $this->saveStatusChange($order, $note); - if (!$skipEvent) $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderSuspend', 'params' => array('id' => $order->id))); + if (!$skipEvent) { + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderSuspend', 'params' => ['id' => $order->id]]); + } $this->di['logger']->info('Suspended order #%s', $order->id); - return TRUE; + return true; } public function unsuspendFromOrder(\Model_ClientOrder $order) { - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderUnsuspend', 'params' => array('id' => $order->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderUnsuspend', 'params' => ['id' => $order->id]]); $this->_callOnService($order, \Model_ClientOrder::ACTION_UNSUSPEND); - $order->status = \Model_ClientOrder::STATUS_ACTIVE; - $order->reason = NULL; - $order->suspended_at = NULL; + $order->status = \Model_ClientOrder::STATUS_ACTIVE; + $order->reason = null; + $order->suspended_at = null; $order->unsuspended_at = date('Y-m-d H:i:s'); - $order->updated_at = date('Y-m-d H:i:s'); + $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); $this->saveStatusChange($order, 'Order unsuspended'); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderUnsuspend', 'params' => array('id' => $order->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderUnsuspend', 'params' => ['id' => $order->id]]); $this->di['logger']->info('Unsuspended order #%s', $order->id); - return TRUE; + return true; } public function cancelFromOrder(\Model_ClientOrder $order, $reason = null, $skipEvent = false) { - if (!$skipEvent) $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderCancel', 'params' => array('id' => $order->id))); + if (!$skipEvent) { + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderCancel', 'params' => ['id' => $order->id]]); + } - if (in_array($order->status, array(\Model_ClientOrder::STATUS_CANCELED, \Model_ClientOrder::STATUS_PENDING_SETUP, \Model_ClientOrder::STATUS_FAILED_SETUP))) { - throw new \Box_Exception('Can not cancel ' . $order->status . ' order'); + if (in_array($order->status, [\Model_ClientOrder::STATUS_CANCELED, \Model_ClientOrder::STATUS_PENDING_SETUP, \Model_ClientOrder::STATUS_FAILED_SETUP])) { + throw new \Box_Exception('Can not cancel '.$order->status.' order'); } $this->_callOnService($order, \Model_ClientOrder::ACTION_CANCEL); - $order->status = \Model_ClientOrder::STATUS_CANCELED; - $order->reason = $reason; - $order->canceled_at = date('Y-m-d H:i:s'); - $order->expires_at = NULL; - $order->suspended_at = NULL; - $order->updated_at = date('Y-m-d H:i:s'); + $order->status = \Model_ClientOrder::STATUS_CANCELED; + $order->reason = $reason; + $order->canceled_at = date('Y-m-d H:i:s'); + $order->expires_at = null; + $order->suspended_at = null; + $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); - $note = (NULL === $reason) ? "Order canceled" : 'Canceled order for ' . $reason; + $note = (null === $reason) ? 'Order canceled' : 'Canceled order for '.$reason; $this->saveStatusChange($order, $note); - if (!$skipEvent) $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderCancel', 'params' => array('id' => $order->id))); + if (!$skipEvent) { + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderCancel', 'params' => ['id' => $order->id]]); + } $this->di['logger']->info('Canceled order #%s', $order->id); - return TRUE; + return true; } public function uncancelFromOrder(\Model_ClientOrder $order) { - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderUncancel', 'params' => array('id' => $order->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderUncancel', 'params' => ['id' => $order->id]]); $this->_callOnService($order, \Model_ClientOrder::ACTION_UNCANCEL); - $expires_at = NULL; + $expires_at = null; if ($order->period) { - $period = $this->di['period']($order->period); + $period = $this->di['period']($order->period); $expires_at = $period->getExpirationTime(time()); $expires_at = date('Y-m-d H:i:s', $expires_at); } - $order->status = \Model_ClientOrder::STATUS_ACTIVE; - $order->reason = NULL; + $order->status = \Model_ClientOrder::STATUS_ACTIVE; + $order->reason = null; $order->activated_at = date('Y-m-d H:i:s'); - $order->expires_at = $expires_at; - $order->suspended_at = NULL; - $order->canceled_at = NULL; - $order->updated_at = date('Y-m-d H:i:s'); + $order->expires_at = $expires_at; + $order->suspended_at = null; + $order->canceled_at = null; + $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); $this->saveStatusChange($order, 'Activated canceled order'); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderUncancel', 'params' => array('id' => $order->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderUncancel', 'params' => ['id' => $order->id]]); $this->di['logger']->info('Uncanceled order #%s', $order->id); - return TRUE; + return true; } public function rmInvoiceItemByOrder(\Model_ClientOrder $order) { - $bindings = array( + $bindings = [ ':rel_id' => $order->id, - ':status' => \Model_InvoiceItem::STATUS_PENDING_PAYMENT - ); + ':status' => \Model_InvoiceItem::STATUS_PENDING_PAYMENT, + ]; $items = $this->di['db']->find('InvoiceItem', 'rel_id = :rel_id AND status = :status', $bindings); - foreach($items as $item){ - if ($item instanceof \Model_InvoiceItem) { - $this->di['db']->trash($item); + foreach ($items as $item) { + if ($item instanceof \Model_InvoiceItem) { + $this->di['db']->trash($item); } } } - public function rmClientOrderStatusByOrder(\Model_ClientOrder $order) { - $this->di['db']->exec('Delete FROM client_order_status WHERE client_order_id = :client_order_id', array(':client_order_id' => $order->id)); + $this->di['db']->exec('Delete FROM client_order_status WHERE client_order_id = :client_order_id', [':client_order_id' => $order->id]); } public function rmOrder(\Model_ClientOrder $model) @@ -1085,7 +1098,7 @@ class Service implements InjectionAwareInterface $list = $this->getOrderAddonsList($model); foreach ($list as $addon) { $addon->group_master = 1; - $addon->group_id = 0; + $addon->group_id = 0; $this->di['db']->store($addon); } } @@ -1094,9 +1107,9 @@ class Service implements InjectionAwareInterface public function deleteFromOrder(\Model_ClientOrder $order) { - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOrderDelete', 'params' => array('id' => $order->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOrderDelete', 'params' => ['id' => $order->id]]); - if ($order->status == \Model_ClientOrder::STATUS_PENDING_SETUP) { + if (\Model_ClientOrder::STATUS_PENDING_SETUP == $order->status) { $this->rmInvoiceItemByOrder($order); } @@ -1105,29 +1118,29 @@ class Service implements InjectionAwareInterface $this->rmClientOrderStatusByOrder($order); $this->rmOrder($order); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminOrderDelete', 'params' => array('id' => $id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminOrderDelete', 'params' => ['id' => $id]]); $this->di['logger']->info('Deleted order #%s', $id); - return TRUE; + return true; } public function getExpiredOrders() { - $bindings = array( + $bindings = [ ':status' => \Model_ClientOrder::STATUS_ACTIVE, - ); + ]; return $this->di['db']->find('ClientOrder', 'status = :status AND expires_at IS NOT NULL AND DATEDIFF(NOW(), expires_at) >= 1 ORDER BY id', $bindings); } public function batchSuspendExpired() { - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminBatchSuspendOrders')); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminBatchSuspendOrders']); $mod = $this->di['mod']('order'); - $c = $mod->getConfig(); + $c = $mod->getConfig(); - $reason = $this->di['array_get']($c, 'batch_suspend_reason', null); + $reason = $this->di['array_get']($c, 'batch_suspend_reason', null); $list = $this->getExpiredOrders(); @@ -1139,25 +1152,25 @@ class Service implements InjectionAwareInterface } } - $this->di['events_manager']->fire(array('event' => 'onAfterAdminBatchSuspendOrders')); + $this->di['events_manager']->fire(['event' => 'onAfterAdminBatchSuspendOrders']); $this->di['logger']->info('Executed action to suspend expired orders'); - return TRUE; + return true; } public function batchCancelSuspended() { - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminBatchCancelSuspendedOrders')); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminBatchCancelSuspendedOrders']); - $mod = $this->di['mod']('order'); + $mod = $this->di['mod']('order'); $config = $mod->getConfig(); if (!isset($config['batch_cancel_suspended']) || !$config['batch_cancel_suspended']) { return false; } - $reason = $this->di['array_get']($config, 'batch_cancel_suspended_reason', null); - $days = isset($config['batch_cancel_suspended_after_days']) ? (int)$config['batch_cancel_suspended_after_days'] : 7; + $reason = $this->di['array_get']($config, 'batch_cancel_suspended_reason', null); + $days = isset($config['batch_cancel_suspended_after_days']) ? (int) $config['batch_cancel_suspended_after_days'] : 7; if ($days < 0) { $days = 7; @@ -1171,7 +1184,7 @@ class Service implements InjectionAwareInterface ORDER BY id DESC "; - $orders = $this->di['db']->getAll($sql, array(':days' => $days)); + $orders = $this->di['db']->getAll($sql, [':days' => $days]); foreach ($orders as $orderArr) { try { @@ -1182,59 +1195,59 @@ class Service implements InjectionAwareInterface } } - $this->di['events_manager']->fire(array('event' => 'onAfterAdminBatchCancelSuspendedOrders')); + $this->di['events_manager']->fire(['event' => 'onAfterAdminBatchCancelSuspendedOrders']); $this->di['logger']->info('Executed action to cancel suspended orders'); - return TRUE; + return true; } public function updateOrderConfig(\Model_ClientOrder $order, array $config) { $oldConfig = $order->config; - $order->config = json_encode($config); + $order->config = json_encode($config); $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); $this->di['logger']->info(sprintf("Order #%s config changes:\n%s\n%s", $order->id, $oldConfig, $order->config)); - return TRUE; + return true; } public function getOrderStatusSearchQuery($data) { - $query = "SELECT * FROM client_order_status"; + $query = 'SELECT * FROM client_order_status'; - $oid = $this->di['array_get']($data, 'client_order_id', NULL); + $oid = $this->di['array_get']($data, 'client_order_id', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; - if (NULL !== $oid) { - $where[] = "client_order_id = :client_order_id"; + if (null !== $oid) { + $where[] = 'client_order_id = :client_order_id'; $bindings[':client_order_id'] = $oid; } if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); + $query = $query.' WHERE '.implode(' AND ', $where); } - $query .= " ORDER BY id DESC"; + $query .= ' ORDER BY id DESC'; - return array($query, $bindings); + return [$query, $bindings]; } public function orderStatusAdd(\Model_ClientOrder $order, $status, $notes = null) { - $bean = $this->di['db']->dispense('ClientOrderStatus'); + $bean = $this->di['db']->dispense('ClientOrderStatus'); $bean->client_order_id = $order->id; - $bean->status = $status; - $bean->notes = $notes; - $bean->created_at = date('Y-m-d H:i:s'); - $bean->updated_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($bean); + $bean->status = $status; + $bean->notes = $notes; + $bean->created_at = date('Y-m-d H:i:s'); + $bean->updated_at = date('Y-m-d H:i:s'); + $id = $this->di['db']->store($bean); $this->di['logger']->info('Added order status history message to order #%s', $id); @@ -1254,10 +1267,11 @@ class Service implements InjectionAwareInterface public function findForClientById(\Model_Client $client, $id) { - $bindings = array( - ':id' => $id, - ':client_id' => $client->id - ); + $bindings = [ + ':id' => $id, + ':client_id' => $client->id, + ]; + return $this->di['db']->findOne('ClientOrder', 'id = :id AND client_id = :client_id', $bindings); } @@ -1270,7 +1284,7 @@ class Service implements InjectionAwareInterface return null; } - $srepo = $this->di['mod_service']('service' . $order->service_type); + $srepo = $this->di['mod_service']('service'.$order->service_type); if (!method_exists($srepo, 'toApiArray')) { error_log(sprintf('service #%s method toApiArray is missing', $order->service_type)); @@ -1280,10 +1294,9 @@ class Service implements InjectionAwareInterface return $srepo->toApiArray($service, true, $identity); } - public function getTotal(\Model_ClientOrder $model) { - return ($model->price * $model->quantity); + return $model->price * $model->quantity; } public function setUnpaidInvoice(\Model_ClientOrder $order, \Model_Invoice $proforma) @@ -1295,17 +1308,17 @@ class Service implements InjectionAwareInterface public function unsetUnpaidInvoice(\Model_ClientOrder $order) { - $order->unpaid_invoice_id = NULL; + $order->unpaid_invoice_id = null; $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); } public function getRelatedOrderIdByType(\Model_ClientOrder $order, $type) { - $bindings = array( - ':group_id' => $order->group_id, - ':service_type' => $type - ); + $bindings = [ + ':group_id' => $order->group_id, + ':service_type' => $type, + ]; $o = $this->di['db']->findOne('ClientOrder', 'group_id = :group_id AND service_type = :service_type', $bindings); @@ -1313,7 +1326,7 @@ class Service implements InjectionAwareInterface return $o->id; } - return NULL; + return null; } public function rmByClient(\Model_Client $client) @@ -1322,7 +1335,6 @@ class Service implements InjectionAwareInterface $pdo = $this->di['pdo']; $stmt = $pdo->prepare($sql); - $stmt->execute(array('id'=>$client->id)); + $stmt->execute(['id' => $client->id]); } - } diff --git a/src/bb-modules/Orderbutton/Controller/Client.php b/src/bb-modules/Orderbutton/Controller/Client.php index e0bfde32b..8654a8058 100644 --- a/src/bb-modules/Orderbutton/Controller/Client.php +++ b/src/bb-modules/Orderbutton/Controller/Client.php @@ -1,6 +1,6 @@ get('/orderbutton', 'get_index', array(), get_class($this)); - $app->get('/orderbutton/js', 'get_js', array(), get_class($this)); + $app->get('/orderbutton', 'get_index', [], get_class($this)); + $app->get('/orderbutton/js', 'get_js', [], get_class($this)); } public function get_index(\Box_App $app) @@ -46,7 +45,8 @@ class Client implements \Box\InjectionAwareInterface public function get_js(\Box_App $app) { - header("Content-Type: application/javascript"); + header('Content-Type: application/javascript'); + return $app->render('mod_orderbutton_js'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Page/Api/Admin.php b/src/bb-modules/Page/Api/Admin.php index 1eb7f69e0..bf1214da1 100644 --- a/src/bb-modules/Page/Api/Admin.php +++ b/src/bb-modules/Page/Api/Admin.php @@ -1,6 +1,6 @@ getService(); + return $service->getPairs(); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Page/Service.php b/src/bb-modules/Page/Service.php index 814de24ab..7ed02c07e 100644 --- a/src/bb-modules/Page/Service.php +++ b/src/bb-modules/Page/Service.php @@ -1,6 +1,6 @@ di['mod_service']('theme'); $code = $themeService->getCurrentClientAreaThemeCode(); - $paths = array( - BB_PATH_THEMES . DIRECTORY_SEPARATOR . $code . DIRECTORY_SEPARATOR . 'html' . DIRECTORY_SEPARATOR, - BB_PATH_MODS . DIRECTORY_SEPARATOR . 'mod_page' . DIRECTORY_SEPARATOR . 'html_client' . DIRECTORY_SEPARATOR, - ); + $paths = [ + BB_PATH_THEMES.DIRECTORY_SEPARATOR.$code.DIRECTORY_SEPARATOR.'html'.DIRECTORY_SEPARATOR, + BB_PATH_MODS.DIRECTORY_SEPARATOR.'mod_page'.DIRECTORY_SEPARATOR.'html_client'.DIRECTORY_SEPARATOR, + ]; - $list = array(); - foreach($paths as $path) { - foreach(glob($path.'mod_page_*.phtml') as $file) { + $list = []; + foreach ($paths as $path) { + foreach (glob($path.'mod_page_*.phtml') as $file) { $file = str_replace('mod_page_', '', pathinfo($file, PATHINFO_FILENAME)); - $list[$file] = ucwords(strtr($file, array('-'=>' ', '_'=>' '))); + $list[$file] = ucwords(strtr($file, ['-' => ' ', '_' => ' '])); } } return $list; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Paidsupport/Service.php b/src/bb-modules/Paidsupport/Service.php index 33b5768b8..78669fbcb 100644 --- a/src/bb-modules/Paidsupport/Service.php +++ b/src/bb-modules/Paidsupport/Service.php @@ -1,6 +1,6 @@ hasHelpdeskPaidSupport($params['support_helpdesk_id'])) { $paidSupportService->enoughInBalanceToOpenTicket($client); } + return true; } /** - * @param \Box_Event $event * @return bool */ public static function onAfterClientOpenTicket(\Box_Event $event) @@ -84,10 +83,10 @@ class Service implements InjectionAwareInterface $clientBalanceService->setDi($di); $message = sprintf('Paid support ticket#%d "%s" opened', $supportTicket->id, $supportTicket->subject); - $extra = array( + $extra = [ 'rel_id' => $supportTicket->id, 'type' => 'supportticket', - ); + ]; $clientBalanceService->deductFunds($client, $paidSupportService->getTicketPrice(), $message, $extra); return true; @@ -99,10 +98,12 @@ class Service implements InjectionAwareInterface public function getTicketPrice() { $config = $this->di['mod_config']('Paidsupport'); - if (!isset($config['ticket_price'])){ + if (!isset($config['ticket_price'])) { error_log('Paid Support ticket price is not set'); + return (float) 0; } + return (float) $config['ticket_price']; } @@ -113,13 +114,15 @@ class Service implements InjectionAwareInterface { $config = $this->di['mod_config']('Paidsupport'); $errorMessage = $this->di['array_get']($config, 'error_msg', ''); + return strlen(trim($errorMessage)) > 0 ? $errorMessage : 'Configure paid support module!'; } public function getPaidHelpdeskConfig() { $config = $this->di['mod_config']('Paidsupport'); - return isset($config['helpdesk']) ? $config['helpdesk'] : array(); + + return $config['helpdesk'] ?? []; } public function enoughInBalanceToOpenTicket(\Model_Client $client) @@ -127,7 +130,7 @@ class Service implements InjectionAwareInterface $clientBalanceService = $this->di['mod_service']('Client', 'Balance'); $clientBalance = $clientBalanceService->getClientBalance($client); - if ($this->getTicketPrice() > $clientBalance){ + if ($this->getTicketPrice() > $clientBalance) { throw new \Box_Exception($this->getErrorMessage()); } @@ -136,37 +139,40 @@ class Service implements InjectionAwareInterface /** * @param $id + * * @return bool */ public function hasHelpdeskPaidSupport($id) { $helpdeskConfig = $this->getPaidHelpdeskConfig(); - if (isset($helpdeskConfig[$id]) && $helpdeskConfig[$id] == 1){ + if (isset($helpdeskConfig[$id]) && 1 == $helpdeskConfig[$id]) { return true; } + return false; } public function uninstall() { $model = $this->di['db']->findOne('ExtensionMeta', 'extension = :ext AND meta_key = :key', - array(':ext'=>'mod_paidsupport', ':key'=>'config')); + [':ext' => 'mod_paidsupport', ':key' => 'config']); if ($model instanceof \Model_ExtensionMeta) { $this->di['db']->trash($model); } + return true; } public function install() { $extensionService = $this->di['mod_service']('Extension'); - $defaultConfig = array( + $defaultConfig = [ 'ext' => 'mod_paidsupport', - 'error_msg' => 'Insufficient funds' - ); + 'error_msg' => 'Insufficient funds', + ]; $extensionService->setConfig($defaultConfig); + return true; } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Product/Api/Admin.php b/src/bb-modules/Product/Api/Admin.php index 582ae8270..1f3a9dd45 100644 --- a/src/bb-modules/Product/Api/Admin.php +++ b/src/bb-modules/Product/Api/Admin.php @@ -1,6 +1,6 @@ getService(); - list($sql, $params) = $service->getProductSearchQuery($data); + [$sql, $params] = $service->getProductSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $model = $this->di['db']->getExistingModelById('Product', $item['id'], 'Post not found'); + $model = $this->di['db']->getExistingModelById('Product', $item['id'], 'Post not found'); $pager['list'][$key] = $this->getService()->toApiArray($model, false, $this->getIdentity()); } @@ -39,82 +39,86 @@ class Admin extends \Api_Abstract } /** - * Get product pair. Id -> title values - * + * Get product pair. Id -> title values. + * * @return array */ public function get_pairs($data) { $service = $this->getService(); + return $service->getPairs($data); } - + /** - * Get product details - * + * Get product details. + * * @param int $id - product id - * @return type + * + * @return type */ public function get($data) { $model = $this->_getProduct($data); $service = $this->getService(); + return $service->toApiArray($model, true, $this->getIdentity()); } - + /** - * Get installed product types - * - * @return array + * Get installed product types. + * + * @return array */ public function get_types() { return $this->getService()->getTypes(); } - + /** - * Create new product. Set default values depending on type - * + * Create new product. Set default values depending on type. + * * @param string $title - product title - * @param string $type - product type + * @param string $type - product type * * @optional string $product_category_id - category id * * @return int - new product id - * @throws Box_Exception + * + * @throws Box_Exception */ public function prepare($data) { - $required = array( + $required = [ 'title' => 'Notification is required', 'type' => 'Type is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); - //allow having only one domain product - if($data['type'] == 'domain') { + // allow having only one domain product + if ('domain' == $data['type']) { $model = $service->getMainDomainProduct(); - if($model instanceof \Model_Product) { + if ($model instanceof \Model_Product) { throw new \Box_Exception('You have already created domain product.', null, 413); } } $types = $service->getTypes(); - if(!array_key_exists($data['type'], $types)) { - throw new \Box_Exception('Product type :type is not registered', array(':type'=>$data['type']), 413); + if (!array_key_exists($data['type'], $types)) { + throw new \Box_Exception('Product type :type is not registered', [':type' => $data['type']], 413); } $categoryId = $this->di['array_get']($data, 'product_category_id', null); return (int) $service->createProduct($data['title'], $data['type'], $categoryId); } - + /** * Update prodcut settings. - * + * * @param int $id - product id - * + * * @optional array $pricing - product pricing configuration * @optional array $config - product configuration options depending on type * @optional array $upgrades - array of upgradable products @@ -127,59 +131,65 @@ class Admin extends \Api_Abstract * @optional string $slug - product slug. Used to create unique link to order page * @optional string $setup - product setup option. Define when order must be activated. * @optional bool $hidden - product visibility flag - * + * * @optional bool $stock_control - product stock control flag. * @optional bool $allow_quantity_select - client can select product quantity on order form flag * @optional bool $quantity_in_stock - quantity available for sale. When out of stock, new order can not be placed. - * - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function update($data) { $model = $this->_getProduct($data); $service = $this->getService(); + return $service->updateProduct($model, $data); } /** - * Change products sorting order - * + * Change products sorting order. + * * @param array $priority - id => number key value pairs to define sort order for all products - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function update_priority($data) { - if(!isset($data['priority']) || !is_array($data['priority'])) { + if (!isset($data['priority']) || !is_array($data['priority'])) { throw new \Box_Exception('priority params is missing'); } $service = $this->getService(); + return $service->updatePriority($data); } /** - * Convenience method to update product config only - * + * Convenience method to update product config only. + * * @param int $id - product id - * + * * @optional array $config - product config key value array - * - * @return boolean + * + * @return bool */ public function update_config($data) { $model = $this->_getProduct($data); - + $service = $this->getService(); + return $service->updateConfig($model, $data); } /** - * Get available addons - * - * @return array + * Get available addons. + * + * @return array */ public function addon_get_pairs($data) { @@ -187,47 +197,50 @@ class Admin extends \Api_Abstract } /** - * Create new addon - * + * Create new addon. + * * @param string $title - addon title - * + * * @return int - new addon id - * @throws Box_Exception + * + * @throws Box_Exception */ public function addon_create($data) { - $required = array( + $required = [ 'title' => 'Notification is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $title = $data['title']; + $title = $data['title']; $status = $this->di['array_get']($data, 'status', null); - $setup = $this->di['array_get']($data, 'setup', null); + $setup = $this->di['array_get']($data, 'setup', null); $iconUrl = $this->di['array_get']($data, 'icon_url', null); $description = $this->di['array_get']($data, 'description', null); $service = $this->getService(); + return $service->createAddon($title, $description, $setup, $status, $iconUrl); } /** - * Get addon details - * + * Get addon details. + * * @param int $id - addon id - * + * * @return array - * @throws Box_Exception + * + * @throws Box_Exception */ public function addon_get($data) { - $required = array( + $required = [ 'id' => 'Addon ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->load('Product', $data['id']); - if(!$model instanceof \Model_Product || !$model->is_addon) { + if (!$model instanceof \Model_Product || !$model->is_addon) { throw new \Box_Exception('Addon not found'); } $service = $this->getService(); @@ -236,10 +249,10 @@ class Admin extends \Api_Abstract } /** - * Addon update - * + * Addon update. + * * @param int $id - addon id - * + * * @optional array $pricing - product pricing configuration * @optional array $config - product configuration options depending on type * @optional array $upgrades - array of upgradable products @@ -252,35 +265,37 @@ class Admin extends \Api_Abstract * @optional string $slug - product slug. Used to create unique link to order page * @optional string $setup - product setup option. Define when order must be activated. * @optional bool $hidden - product visibility flag - * + * * @optional bool $stock_control - product stock control flag. * @optional bool $allow_quantity_select - client can select product quantity on order form flag * @optional bool $quantity_in_stock - quantity available for sale. When out of stock, new order can not be placed. - * + * * @return bool - * @throws Box_Exception + * + * @throws Box_Exception */ public function addon_update($data) { - $required = array( + $required = [ 'id' => 'Addon ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->load('Product', $data['id']); - if(!$model instanceof \Model_Product || !$model->is_addon) { + if (!$model instanceof \Model_Product || !$model->is_addon) { throw new \Box_Exception('Addon not found'); } $this->di['logger']->info('Updated addon #%s', $model->id); + return $this->update($data); } /** - * Remove addon - * + * Remove addon. + * * @param int $id - addon id - * - * @return bool + * + * @return bool */ public function addon_delete($data) { @@ -288,93 +303,97 @@ class Admin extends \Api_Abstract } /** - * Remove product - * + * Remove product. + * * @param int $id - addon id - * - * @return bool + * + * @return bool */ public function delete($data) { $model = $this->_getProduct($data); $service = $this->getService(); + return $service->deleteProduct($model); } - + /** - * Get product category pairs - * + * Get product category pairs. + * * @return array */ public function category_get_pairs($data) { return $this->getService()->getProductCategoryPairs($data); } - + /** - * Method to update category - * + * Method to update category. + * * @param int $id - category id - * + * * @optional string $title - category title * @optional string $icon_url - icon url * @optional string $description - description - * - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function category_update($data) { - $required = array( + $required = [ 'id' => 'Category ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found'); - $title = $this->di['array_get']($data, 'title', null); - $description = $this->di['array_get']($data, 'description', null); - $icon_url = $this->di['array_get']($data, 'icon_url', null); + $title = $this->di['array_get']($data, 'title', null); + $description = $this->di['array_get']($data, 'description', null); + $icon_url = $this->di['array_get']($data, 'icon_url', null); $service = $this->getService(); - return $service->updateCategory($model, $title, $description, $icon_url); + return $service->updateCategory($model, $title, $description, $icon_url); } /** - * Get category details - * + * Get category details. + * * @return array - * @throws Box_Exception + * + * @throws Box_Exception */ public function category_get($data) { - $required = array( + $required = [ 'id' => 'Category ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found'); + return $this->getService()->toProductCategoryApiArray($model); } /** - * Create new product category - * + * Create new product category. + * * @param string $title - new category title - * + * * @optional string $icon_url - icon url * @optional string $description - description - * + * * @return int - new category id - * - * @throws Box_Exception + * + * @throws Box_Exception */ public function category_create($data) { - $required = array( + $required = [ 'title' => 'Category title is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); @@ -384,54 +403,56 @@ class Admin extends \Api_Abstract $icon_url = $this->di['array_get']($data, 'icon_url', null); return (int) $service->createCategory($title, $description, $icon_url); - } /** - * Remove product category - * + * Remove product category. + * * @param int $id - category id - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function category_delete($data) { - $required = array( + $required = [ 'id' => 'Category ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ProductCategory', $data['id'], 'Category not found'); $service = $this->getService(); + return $service->removeProductCategory($model); } /** - * Get product promo codes list - * + * Get product promo codes list. + * * @return array */ public function promo_get_list($data) { $service = $this->getService(); - list($sql, $params) = $service->getPromoSearchQuery($data); + [$sql, $params] = $service->getPromoSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $model = $this->di['db']->getExistingModelById('Promo', $item['id'], 'Promo not found'); + $model = $this->di['db']->getExistingModelById('Promo', $item['id'], 'Promo not found'); $pager['list'][$key] = $this->getService()->toPromoApiArray($model); } return $pager; } - + /** - * Create new promo code - * - * @param string $code - promo code - * @param string $type - promo code type: percentage|absolute + * Create new promo code. + * + * @param string $code - promo code + * @param string $type - promo code type: percentage|absolute * @param string $value - promo code value. Percents or discount amount in currency - * + * * @optional array $products - list of product ids for which this promo code applies * @optional array $periods - list of period codes * @optional bool $active - flag to enable/disable promo code @@ -441,65 +462,68 @@ class Admin extends \Api_Abstract * @optional int $maxuses - how many times this promo code can be used * @optional string $start_at - date (Y-m-d) when will this promo code be active * @optional string $end_at - date (Y-m-d) when this promo code expires - * + * * @return int - new promo code id - * @throws Box_Exception + * + * @throws Box_Exception */ public function promo_create($data) { - $required = array( - 'code' => 'Promo code is missing', - 'type' => 'Promo type is missing', + $required = [ + 'code' => 'Promo code is missing', + 'type' => 'Promo type is missing', 'value' => 'Promo value is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - - $products = array(); - if(isset($data['products']) && is_array($data['products'])) { + + $products = []; + if (isset($data['products']) && is_array($data['products'])) { $products = $data['products']; } - $periods = array(); - if(isset($data['periods']) && is_array($data['periods'])) { + $periods = []; + if (isset($data['periods']) && is_array($data['periods'])) { $periods = $data['periods']; } - $clientGroups = array(); - if(isset($data['client_groups']) && is_array($data['client_groups'])) { + $clientGroups = []; + if (isset($data['client_groups']) && is_array($data['client_groups'])) { $clientGroups = $data['client_groups']; } $service = $this->getService(); + return (int) $service->createPromo($data['code'], $data['type'], $data['value'], $products, $periods, $clientGroups, $data); } - + /** - * Get promo code details - * + * Get promo code details. + * * @param int $id - promo code id - * + * * @return array - * @throws Box_Exception + * + * @throws Box_Exception */ public function promo_get($data) { - $required = array( + $required = [ 'id' => 'Promo ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $model = $this->di['db']->getExistingModelById('Promo', $data['id'], 'Promo not found'); return $this->getService()->toPromoApiArray($model, true, $this->getIdentity()); } /** - * Promo code update - * + * Promo code update. + * * @param int $id - promo code id - * + * * @optional string $code - promo code * @optional string $type - promo code type: percentage|absolute * @optional string $value - promo code value. Percents or discount amount in currency - * + * * @optional array $products - list of product ids for which this promo code applies * @optional array $periods - list of period codes * @optional bool $active - flag to enable/disable promo code @@ -509,52 +533,57 @@ class Admin extends \Api_Abstract * @optional int $maxuses - how many times this promo code can be used * @optional string $start_at - date (Y-m-d) when will this promo code be active * @optional string $end_at - date (Y-m-d) when this promo code expires - * + * * @optional int $used - how many times this promo code was already used - * - * @return boolean - * @throws Box_Exception + * + * @return bool + * + * @throws Box_Exception */ public function promo_update($data) { - $required = array( + $required = [ 'id' => 'Promo ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Promo', $data['id'], 'Promo not found'); $service = $this->getService(); + return $service->updatePromo($model, $data); } - + /** - * Delete promo code - * + * Delete promo code. + * * @param int $id - promo code id - * + * * @return bool - * @throws Box_Exception + * + * @throws Box_Exception */ public function promo_delete($data) { - $required = array( + $required = [ 'id' => 'Promo ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Promo', $data['id'], 'Promo not found'); + return $this->getService()->deletePromo($model); } - + private function _getProduct($data) { - $required = array( + $required = [ 'id' => 'Product ID not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Product', $data['id'], 'Product not found'); + return $model; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Product/Api/Guest.php b/src/bb-modules/Product/Api/Guest.php index 059918b9c..511cb2a74 100644 --- a/src/bb-modules/Product/Api/Guest.php +++ b/src/bb-modules/Product/Api/Guest.php @@ -1,6 +1,6 @@ getService()->getProductSearchQuery($data); + [$sql, $params] = $this->getService()->getProductSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $model = $this->di['db']->getExistingModelById('Product', $item['id'], 'Post not found'); + $model = $this->di['db']->getExistingModelById('Product', $item['id'], 'Post not found'); $pager['list'][$key] = $this->getService()->toApiArray($model, false, $this->getIdentity()); } return $pager; } - + /** - * Get products pairs. Product id -> title values - * + * Get products pairs. Product id -> title values. + * * @return array */ public function get_pairs($data) @@ -52,61 +53,65 @@ class Guest extends \Api_Abstract $data['products_only'] = true; $data['active_only'] = true; $service = $this->getService(); + return $service->getPairs($data); } /** - * Get product by ID - * + * Get product by ID. + * * @param int $id - product id - * + * * @return array - * - * @throws Box_Exception + * + * @throws Box_Exception */ public function get($data) { - if(!isset($data['id']) && !isset($data['slug'])) { + if (!isset($data['id']) && !isset($data['slug'])) { throw new \Box_Exception('Product ID or slug is missing'); } - $id = $this->di['array_get']($data, 'id', NULL); - $slug = $this->di['array_get']($data, 'slug', NULL); + $id = $this->di['array_get']($data, 'id', null); + $slug = $this->di['array_get']($data, 'slug', null); $service = $this->getService(); - if($id) { + if ($id) { $model = $service->findOneActiveById($id); } else { $model = $service->findOneActiveBySlug($slug); } - if(!$model instanceof \Model_Product) { + if (!$model instanceof \Model_Product) { throw new \Box_Exception('Product not found'); } + return $service->toApiArray($model); } - + /** - * Get paginated list of product categories - * + * Get paginated list of product categories. + * * @return array */ public function category_get_list($data) { $data['status'] = 'enabled'; $service = $this->getService(); - list($sql, $params) = $service->getProductCategorySearchQuery($data); + [$sql, $params] = $service->getProductCategorySearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getAdvancedResultSet($sql, $params, $per_page); - foreach($pager['list'] as $key => $item){ + foreach ($pager['list'] as $key => $item) { $category = $this->di['db']->getExistingModelById('ProductCategory', $item['id'], 'Product category not found'); $pager['list'][$key] = $this->getService()->toProductCategoryApiArray($category, true, $this->getIdentity()); } + return $pager; } /** - * Get pairs of product categories + * Get pairs of product categories. + * * @return array */ public function category_get_pairs($data) @@ -117,42 +122,44 @@ class Guest extends \Api_Abstract /** * Return slider data for product types. * Products are grouped by type. You can pass parameter to select product type for slider - * Product configuration must have slider_%s keys - * + * Product configuration must have slider_%s keys. + * * @optional string $type - product type for slider - default = hosting * @optional string $format - return format. Default is array . You can choose json format, to directly inject to javascript + * * @return mixed */ public function get_slider($data) { $format = $this->di['array_get']($data, 'format', null); $type = $this->di['array_get']($data, 'type', 'hosting'); - - $products = $this->di['db']->find('Product', 'type = :type', array(':type' => $type)); - if(count($products) <= 0) { - return array(); + + $products = $this->di['db']->find('Product', 'type = :type', [':type' => $type]); + if (count($products) <= 0) { + return []; } - $slider = array(); + $slider = []; foreach ($products as $productModel) { $product = $this->getService()->toApiArray($productModel); $pc = $product['config']; - $s = array( - 'product_id' => $product['id'], - 'slug' => $product['slug'], - 'title' => $product['title'], - 'pricing' => $product['pricing'], - ); - foreach($pc as $k=>$v) { - if(strpos($k, 'slider_') !== false) { + $s = [ + 'product_id' => $product['id'], + 'slug' => $product['slug'], + 'title' => $product['title'], + 'pricing' => $product['pricing'], + ]; + foreach ($pc as $k => $v) { + if (false !== strpos($k, 'slider_')) { $s[substr($k, strlen('slider_'))] = $v; } } $slider[] = $s; } - if($format == 'json') { + if ('json' == $format) { return json_encode($slider); } + return $slider; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Product/Controller/Admin.php b/src/bb-modules/Product/Controller/Admin.php index 7ab6d22e8..2108df783 100644 --- a/src/bb-modules/Product/Controller/Admin.php +++ b/src/bb-modules/Product/Controller/Admin.php @@ -1,6 +1,6 @@ array( + return [ + 'group' => [ 'index' => 401, 'location' => 'products', 'label' => 'Products', 'uri' => $this->di['url']->adminLink('products'), 'class' => 'pic', 'sprite_class' => 'dark-sprite-icon sprite-blocks', - ), - 'subpages' => array( - array( - 'location' => 'products', - 'index' => 110, + ], + 'subpages' => [ + [ + 'location' => 'products', + 'index' => 110, 'label' => 'Products / Services', - 'uri' => $this->di['url']->adminLink('product'), + 'uri' => $this->di['url']->adminLink('product'), 'class' => '', - ), - array( - 'location' => 'products', - 'index' => 120, + ], + [ + 'location' => 'products', + 'index' => 120, 'label' => 'Product addons', - 'uri' => $this->di['url']->adminLink('product/addons'), + 'uri' => $this->di['url']->adminLink('product/addons'), 'class' => '', - ), - array( - 'location' => 'products', - 'index' => 130, + ], + [ + 'location' => 'products', + 'index' => 130, 'label' => 'Product promotions', - 'uri' => $this->di['url']->adminLink('product/promos'), + 'uri' => $this->di['url']->adminLink('product/promos'), 'class' => '', - ), - ), - ); + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/product', 'get_index', array(), get_class($this)); - $app->get('/product/promos', 'get_promos', array(), get_class($this)); - $app->get('/product/promo/:id', 'get_promo', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/product/manage/:id', 'get_manage', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/product/addons', 'get_addons', array(), get_class($this)); - $app->get('/product/addon/:id', 'get_addon_manage', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/product/category/:id', 'get_cat_manage', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/product', 'get_index', [], get_class($this)); + $app->get('/product/promos', 'get_promos', [], get_class($this)); + $app->get('/product/promo/:id', 'get_promo', ['id' => '[0-9]+'], get_class($this)); + $app->get('/product/manage/:id', 'get_manage', ['id' => '[0-9]+'], get_class($this)); + $app->get('/product/addons', 'get_addons', [], get_class($this)); + $app->get('/product/addon/:id', 'get_addon_manage', ['id' => '[0-9]+'], get_class($this)); + $app->get('/product/category/:id', 'get_cat_manage', ['id' => '[0-9]+'], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_product_index'); } - + public function get_addons(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_product_addons'); } public function get_addon_manage(\Box_App $app, $id) { $api = $this->di['api_admin']; - $addon= $api->product_addon_get(array('id'=>$id)); - return $app->render('mod_product_addon_manage', array('addon'=>$addon, 'product'=>$addon)); + $addon = $api->product_addon_get(['id' => $id]); + + return $app->render('mod_product_addon_manage', ['addon' => $addon, 'product' => $addon]); } public function get_cat_manage(\Box_App $app, $id) { $api = $this->di['api_admin']; - $cat= $api->product_category_get(array('id'=>$id)); - return $app->render('mod_product_category', array('category'=>$cat)); + $cat = $api->product_category_get(['id' => $id]); + + return $app->render('mod_product_category', ['category' => $cat]); } public function get_manage(\Box_App $app, $id) { $api = $this->di['api_admin']; - $product= $api->product_get(array('id'=>$id)); + $product = $api->product_get(['id' => $id]); - $addons = array(); + $addons = []; foreach ($product['addons'] as $addon) { $addons[] = $addon['id']; } - return $app->render('mod_product_manage', array('product'=>$product, 'assigned_addons'=>$addons)); + return $app->render('mod_product_manage', ['product' => $product, 'assigned_addons' => $addons]); } - + public function get_promo(\Box_App $app, $id) { $api = $this->di['api_admin']; - $promo= $api->product_promo_get(array('id'=>$id)); - return $app->render('mod_product_promo', array('promo'=>$promo)); + $promo = $api->product_promo_get(['id' => $id]); + + return $app->render('mod_product_promo', ['promo' => $promo]); } public function get_promos(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_product_promos'); } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Product/Service.php b/src/bb-modules/Product/Service.php index 03de35b14..5eafc1383 100644 --- a/src/bb-modules/Product/Service.php +++ b/src/bb-modules/Product/Service.php @@ -1,6 +1,6 @@ di['array_get']($data, 'type', null); + $type = $this->di['array_get']($data, 'type', null); $products_only = $this->di['array_get']($data, 'products_only', true); - $active_only = $this->di['array_get']($data, 'active_only', true); + $active_only = $this->di['array_get']($data, 'active_only', true); - $params = array(); + $params = []; if ($products_only) { $sql .= ' AND is_addon = 0'; } @@ -75,8 +74,8 @@ class Service implements InjectionAwareInterface $params['type'] = $type; } - $rows = $this->di['db']->getAll($sql, $params); - $result = array(); + $rows = $this->di['db']->getAll($sql, $params); + $result = []; foreach ($rows as $record) { $result[$record['id']] = $record['title']; } @@ -86,48 +85,48 @@ class Service implements InjectionAwareInterface public function toApiArray(\Model_Product $model, $deep = true, $identity = null) { - $repo = $model->getTable(); - $addons = $this->getAddonsApiArray($model); - $config = $this->di['tools']->decodeJ($model->config, 1); - $pricing = $repo->getPricingArray($model); + $repo = $model->getTable(); + $addons = $this->getAddonsApiArray($model); + $config = $this->di['tools']->decodeJ($model->config, 1); + $pricing = $repo->getPricingArray($model); $starting_from = $this->getStartingFromPrice($model); - $result = array( - 'id' => $model->id, - 'product_category_id' => $model->product_category_id, - 'type' => $model->type, - 'title' => $model->title, - 'form_id' => $model->form_id, - 'slug' => $model->slug, - 'description' => $model->description, - 'unit' => $model->unit, - 'priority' => $model->priority, - 'created_at' => $model->created_at, - 'updated_at' => $model->updated_at, - 'pricing' => $pricing, - 'config' => $config, - 'addons' => $addons, + $result = [ + 'id' => $model->id, + 'product_category_id' => $model->product_category_id, + 'type' => $model->type, + 'title' => $model->title, + 'form_id' => $model->form_id, + 'slug' => $model->slug, + 'description' => $model->description, + 'unit' => $model->unit, + 'priority' => $model->priority, + 'created_at' => $model->created_at, + 'updated_at' => $model->updated_at, + 'pricing' => $pricing, + 'config' => $config, + 'addons' => $addons, - 'price_starting_from' => $starting_from, - 'icon_url' => $model->icon_url, + 'price_starting_from' => $starting_from, + 'icon_url' => $model->icon_url, - //stock control + // stock control 'allow_quantity_select' => $model->allow_quantity_select, - 'quantity_in_stock' => $model->quantity_in_stock, - 'stock_control' => $model->stock_control, - ); + 'quantity_in_stock' => $model->quantity_in_stock, + 'stock_control' => $model->stock_control, + ]; if ($identity instanceof \Model_Admin) { $result['upgrades'] = $this->getUpgradablePairs($model); - $result['status'] = $model->status; - $result['hidden'] = $model->hidden; - $result['setup'] = $model->setup; + $result['status'] = $model->status; + $result['hidden'] = $model->hidden; + $result['setup'] = $model->setup; if ($model->product_category_id) { - $productCategory = $this->di['db']->load('ProductCategory', $model->product_category_id); - $result['category'] = array( - 'id' => $productCategory->id, + $productCategory = $this->di['db']->load('ProductCategory', $model->product_category_id); + $result['category'] = [ + 'id' => $productCategory->id, 'title' => $productCategory->title, - ); + ]; } } @@ -136,20 +135,20 @@ class Service implements InjectionAwareInterface public function getTypes() { - $data = array( - self::CUSTOM => 'Custom', - self::LICENSE => 'License', + $data = [ + self::CUSTOM => 'Custom', + self::LICENSE => 'License', self::DOWNLOADABLE => 'Downloadable', - self::HOSTING => 'Hosting', - self::DOMAIN => 'Domain', - ); + self::HOSTING => 'Hosting', + self::DOMAIN => 'Domain', + ]; // attach service modules $extensionService = $this->di['mod_service']('extension'); - $list = $extensionService->getInstalledMods(); + $list = $extensionService->getInstalledMods(); foreach ($list as $mod) { - if (substr($mod, 0, strlen('service')) == 'service') { - $n = substr($mod, strlen('service')); + if ('service' == substr($mod, 0, strlen('service'))) { + $n = substr($mod, strlen('service')); $data[$n] = ucfirst($n); } } @@ -159,38 +158,38 @@ class Service implements InjectionAwareInterface public function getMainDomainProduct() { - return $this->di['db']->findOne('Product', 'type = ?', array(self::DOMAIN)); + return $this->di['db']->findOne('Product', 'type = ?', [self::DOMAIN]); } public function getPaymentTypes() { - return array( - \Model_ProductPayment::FREE => 'Free', - \Model_ProductPayment::ONCE => 'One time', + return [ + \Model_ProductPayment::FREE => 'Free', + \Model_ProductPayment::ONCE => 'One time', \Model_ProductPayment::RECURRENT => 'Recurrent', - ); + ]; } public function createProduct($title, $type, $categoryId = null) { $systemService = $this->di['mod_service']('system'); $systemService->checkLimits('Model_Product', 5); - $sql = "SELECT MAX(priority) FROM product LIMIT 1"; + $sql = 'SELECT MAX(priority) FROM product LIMIT 1'; $priority = $this->di['db']->getCell($sql); - $modelPayment = $this->di['db']->dispense('ProductPayment'); + $modelPayment = $this->di['db']->dispense('ProductPayment'); $modelPayment->type = \Model_ProductPayment::FREE; - $paymentId = $this->di['db']->store($modelPayment); + $paymentId = $this->di['db']->store($modelPayment); - $model = $this->di['db']->dispense('Product'); - $model->product_payment_id = $paymentId; + $model = $this->di['db']->dispense('Product'); + $model->product_payment_id = $paymentId; $model->product_category_id = $categoryId; - $model->status = \Model_Product::STATUS_DISABLED; - $model->title = $title; - $model->slug = $this->di['tools']->slug($title); - $model->type = $type; - $model->setup = self::SETUP_AFTER_PAYMENT; - $model->priority = $priority + 10; + $model->status = \Model_Product::STATUS_DISABLED; + $model->title = $title; + $model->slug = $this->di['tools']->slug($title); + $model->type = $type; + $model->setup = self::SETUP_AFTER_PAYMENT; + $model->priority = $priority + 10; $model->updated_at = date('Y-m-d H:i:s'); $model->created_at = date('Y-m-d H:i:s'); @@ -199,18 +198,18 @@ class Service implements InjectionAwareInterface try { $productId = $this->di['db']->store($model); } catch (\Exception $e) { - $model->slug = $this->di['tools']->slug($title) . '-' . rand(1, 9999); + $model->slug = $this->di['tools']->slug($title).'-'.rand(1, 9999); } $productId = $this->di['db']->store($model); $this->di['logger']->info('Created new product #%s', $model->id); - return (int)$productId; + return (int) $productId; } public function updateProduct(\Model_Product $model, $data) { - //pricing + // pricing if (isset($data['pricing'])) { $types = $this->getPaymentTypes(); @@ -219,105 +218,103 @@ class Service implements InjectionAwareInterface } $productPayment = $this->di['db']->getExistingModelById('ProductPayment', $model->product_payment_id, 'Product payment not found'); - $pricing = $data['pricing']; + $pricing = $data['pricing']; $productPayment->type = $data['pricing']['type']; - if ($data['pricing']['type'] == \Model_ProductPayment::ONCE) { - $productPayment->once_setup_price = (float)$data['pricing']['once']['setup']; - $productPayment->once_price = (float)$data['pricing']['once']['price']; + if (\Model_ProductPayment::ONCE == $data['pricing']['type']) { + $productPayment->once_setup_price = (float) $data['pricing']['once']['setup']; + $productPayment->once_price = (float) $data['pricing']['once']['price']; } - if ($data['pricing']['type'] == \Model_ProductPayment::RECURRENT) { - + if (\Model_ProductPayment::RECURRENT == $data['pricing']['type']) { if (isset($pricing['recurrent']['1W'])) { $productPayment->w_setup_price = $pricing['recurrent']['1W']['setup']; - $productPayment->w_price = $pricing['recurrent']['1W']['price']; - $productPayment->w_enabled = $pricing['recurrent']['1W']['enabled']; + $productPayment->w_price = $pricing['recurrent']['1W']['price']; + $productPayment->w_enabled = $pricing['recurrent']['1W']['enabled']; } if (isset($pricing['recurrent']['1M'])) { $productPayment->m_setup_price = $pricing['recurrent']['1M']['setup']; - $productPayment->m_price = $pricing['recurrent']['1M']['price']; - $productPayment->m_enabled = $pricing['recurrent']['1M']['enabled']; + $productPayment->m_price = $pricing['recurrent']['1M']['price']; + $productPayment->m_enabled = $pricing['recurrent']['1M']['enabled']; } if (isset($pricing['recurrent']['3M'])) { $productPayment->q_setup_price = $pricing['recurrent']['3M']['setup']; - $productPayment->q_price = $pricing['recurrent']['3M']['price']; - $productPayment->q_enabled = $pricing['recurrent']['3M']['enabled']; + $productPayment->q_price = $pricing['recurrent']['3M']['price']; + $productPayment->q_enabled = $pricing['recurrent']['3M']['enabled']; } if (isset($pricing['recurrent']['6M'])) { $productPayment->b_setup_price = $pricing['recurrent']['6M']['setup']; - $productPayment->b_price = $pricing['recurrent']['6M']['price']; - $productPayment->b_enabled = $pricing['recurrent']['6M']['enabled']; + $productPayment->b_price = $pricing['recurrent']['6M']['price']; + $productPayment->b_enabled = $pricing['recurrent']['6M']['enabled']; } if (isset($pricing['recurrent']['1Y'])) { $productPayment->a_setup_price = $pricing['recurrent']['1Y']['setup']; - $productPayment->a_price = $pricing['recurrent']['1Y']['price']; - $productPayment->a_enabled = $pricing['recurrent']['1Y']['enabled']; + $productPayment->a_price = $pricing['recurrent']['1Y']['price']; + $productPayment->a_enabled = $pricing['recurrent']['1Y']['enabled']; } if (isset($pricing['recurrent']['2Y'])) { $productPayment->bia_setup_price = $pricing['recurrent']['2Y']['setup']; - $productPayment->bia_price = $pricing['recurrent']['2Y']['price']; - $productPayment->bia_enabled = $pricing['recurrent']['2Y']['enabled']; + $productPayment->bia_price = $pricing['recurrent']['2Y']['price']; + $productPayment->bia_enabled = $pricing['recurrent']['2Y']['enabled']; } if (isset($pricing['recurrent']['3Y'])) { $productPayment->tria_setup_price = $pricing['recurrent']['3Y']['setup']; - $productPayment->tria_price = $pricing['recurrent']['3Y']['price']; - $productPayment->tria_enabled = $pricing['recurrent']['3Y']['enabled']; + $productPayment->tria_price = $pricing['recurrent']['3Y']['price']; + $productPayment->tria_enabled = $pricing['recurrent']['3Y']['enabled']; } } $this->di['db']->store($productPayment); - } if (isset($data['config']) && is_array($data['config'])) { - $current = $this->di['tools']->decodeJ($model->config); - $c = array_merge($current, $data['config']); + $current = $this->di['tools']->decodeJ($model->config); + $c = array_merge($current, $data['config']); $model->config = json_encode($c); } $form_id = $this->di['array_get']($data, 'form_id', $model->form_id); $model->product_category_id = $this->di['array_get']($data, 'product_category_id', $model->product_category_id); - $model->form_id = empty($form_id) ? null : $form_id; - $model->icon_url = $this->di['array_get']($data, 'icon_url', $model->icon_url); - $model->status = $this->di['array_get']($data, 'status', $model->status); - $model->hidden = (int)$this->di['array_get']($data, 'hidden', $model->hidden); - $model->slug = $this->di['array_get']($data, 'slug', $model->slug); - $model->setup = $this->di['array_get']($data, 'setup', $model->setup); + $model->form_id = empty($form_id) ? null : $form_id; + $model->icon_url = $this->di['array_get']($data, 'icon_url', $model->icon_url); + $model->status = $this->di['array_get']($data, 'status', $model->status); + $model->hidden = (int) $this->di['array_get']($data, 'hidden', $model->hidden); + $model->slug = $this->di['array_get']($data, 'slug', $model->slug); + $model->setup = $this->di['array_get']($data, 'setup', $model->setup); if (isset($data['upgrades']) && is_array($data['upgrades'])) { $model->upgrades = json_encode($data['upgrades']); } elseif (isset($data['upgrades']) && empty($data['upgrades'])) { - $model->upgrades = NULL; + $model->upgrades = null; } if (isset($data['addons']) && is_array($data['addons'])) { - $addons = array(); + $addons = []; foreach ($data['addons'] as $addon => $on) { if ($on) { $addons[] = $addon; } } - if (empty ($addons)) { - $model->addons = NULL; + if (empty($addons)) { + $model->addons = null; } else { $model->addons = json_encode($addons); } } - $model->title = $this->di['array_get']($data, 'title', $model->title); - $model->stock_control = $this->di['array_get']($data, 'stock_control', $model->stock_control); + $model->title = $this->di['array_get']($data, 'title', $model->title); + $model->stock_control = $this->di['array_get']($data, 'stock_control', $model->stock_control); $model->allow_quantity_select = $this->di['array_get']($data, 'allow_quantity_select', $model->allow_quantity_select); - $model->quantity_in_stock = $this->di['array_get']($data, 'quantity_in_stock', $model->quantity_in_stock); - $model->description = $this->di['array_get']($data, 'description', $model->description); - $model->plugin = $this->di['array_get']($data, 'plugin', $model->plugin); - $model->updated_at = date('Y-m-d H:i:s'); + $model->quantity_in_stock = $this->di['array_get']($data, 'quantity_in_stock', $model->quantity_in_stock); + $model->description = $this->di['array_get']($data, 'description', $model->description); + $model->plugin = $this->di['array_get']($data, 'plugin', $model->plugin); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); @@ -331,7 +328,7 @@ class Service implements InjectionAwareInterface foreach ($data['priority'] as $id => $p) { $model = $this->di['db']->load('Product', $id); if ($model instanceof \Model_Product) { - $model->priority = $p; + $model->priority = $p; $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); } @@ -348,11 +345,11 @@ class Service implements InjectionAwareInterface $config = json_decode($model->config, true); if (isset($data['config']) && is_array($data['config'])) { - $config = array_intersect_key((array)$config, $data['config']); + $config = array_intersect_key((array) $config, $data['config']); foreach ($data['config'] as $key => $val) { $config[$key] = $val; if (isset($config[$key]) && empty($val) && !is_numeric($val)) { - unset ($config[$key]); + unset($config[$key]); } } } @@ -362,11 +359,10 @@ class Service implements InjectionAwareInterface !empty($data['new_config_name']) && !empty($data['new_config_value']) ) { - $config[$data['new_config_name']] = $data['new_config_value']; } - $model->config = json_encode($config); + $model->config = json_encode($config); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); @@ -377,13 +373,13 @@ class Service implements InjectionAwareInterface public function getAddons() { - $sql = 'SELECT id, title + $sql = 'SELECT id, title FROM product WHERE is_addon =1 ORDER by id asc'; $addons = $this->di['db']->getAll($sql); - $result = array(); + $result = []; foreach ($addons as $addon) { $result[$addon['id']] = $addon['title']; } @@ -393,21 +389,21 @@ class Service implements InjectionAwareInterface public function createAddon($title, $description = null, $setup = null, $status = null, $iconUrl = null) { - $modelPayment = $this->di['db']->dispense('ProductPayment'); + $modelPayment = $this->di['db']->dispense('ProductPayment'); $modelPayment->type = \Model_ProductPayment::FREE; - $paymentId = $this->di['db']->store($modelPayment); + $paymentId = $this->di['db']->store($modelPayment); - $model = $this->di['db']->dispense('Product'); - $model->product_payment_id = $paymentId; - $model->product_category_id = NULL; - $model->status = (isset($status)) ? $status : \Model_Product::STATUS_DISABLED; - $model->title = $title; - $model->slug = $this->di['tools']->slug($title); - $model->type = self::CUSTOM; - $model->setup = (isset($setup)) ? $setup : self::SETUP_AFTER_PAYMENT; - $model->is_addon = 1; + $model = $this->di['db']->dispense('Product'); + $model->product_payment_id = $paymentId; + $model->product_category_id = null; + $model->status = (isset($status)) ? $status : \Model_Product::STATUS_DISABLED; + $model->title = $title; + $model->slug = $this->di['tools']->slug($title); + $model->type = self::CUSTOM; + $model->setup = (isset($setup)) ? $setup : self::SETUP_AFTER_PAYMENT; + $model->is_addon = 1; - $model->icon_url = $iconUrl; + $model->icon_url = $iconUrl; $model->description = $description; $model->updated_at = date('Y-m-d H:i:s'); @@ -417,8 +413,8 @@ class Service implements InjectionAwareInterface try { $productId = $this->di['db']->store($model); } catch (\Exception $e) { - $model->slug = $this->di['tools']->slug($title) . '-' . rand(1, 9999); - $productId = $this->di['db']->store($model); + $model->slug = $this->di['tools']->slug($title).'-'.rand(1, 9999); + $productId = $this->di['db']->store($model); } $this->di['logger']->info('Created new addon #%s', $productId); @@ -444,8 +440,8 @@ class Service implements InjectionAwareInterface $sql = 'SELECT id, title FROM product_category'; - $rows = $this->di['db']->getAll($sql); - $result = array(); + $rows = $this->di['db']->getAll($sql); + $result = []; foreach ($rows as $record) { $result[$record['id']] = $record['title']; } @@ -455,8 +451,8 @@ class Service implements InjectionAwareInterface public function updateCategory(\Model_ProductCategory $productCategory, $title = null, $description = null, $icon_url = null) { - $productCategory->title = $title; - $productCategory->icon_url = $icon_url; + $productCategory->title = $title; + $productCategory->icon_url = $icon_url; $productCategory->description = $description; $productCategory->updated_at = date('Y-m-d H:i:s'); @@ -472,13 +468,13 @@ class Service implements InjectionAwareInterface $systemService = $this->di['mod_service']('system'); $systemService->checkLimits('Model_ProductCategory', 2); - $model = $this->di['db']->dispense('ProductCategory'); - $model->title = $title; + $model = $this->di['db']->dispense('ProductCategory'); + $model->title = $title; $model->description = $description; - $model->icon_url = $icon_url; - $model->updated_at = date('Y-m-d H:i:s'); - $model->created_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $model->icon_url = $icon_url; + $model->updated_at = date('Y-m-d H:i:s'); + $model->created_at = date('Y-m-d H:i:s'); + $id = $this->di['db']->store($model); $this->di['logger']->info('Created new product category #%s', $id); @@ -487,7 +483,7 @@ class Service implements InjectionAwareInterface public function removeProductCategory(\Model_ProductCategory $category) { - $model = $this->di['db']->findOne('Product', 'product_category_id = :category_id', array(':category_id' => $category->id)); + $model = $this->di['db']->findOne('Product', 'product_category_id = :category_id', [':category_id' => $category->id]); if ($model instanceof \Model_Product) { throw new \Box_Exception('Can not remove product category with products'); } @@ -506,10 +502,10 @@ class Service implements InjectionAwareInterface WHERE 1'; $search = $this->di['array_get']($data, 'search', null); - $id = $this->di['array_get']($data, 'id', null); + $id = $this->di['array_get']($data, 'id', null); $status = $this->di['array_get']($data, 'status', null); - $params = array(); + $params = []; if ($id) { $sql .= ' AND id = :id'; $params['id'] = $id; @@ -524,7 +520,7 @@ class Service implements InjectionAwareInterface case 'active': $sql .= ' AND start_at <= :start_at AND end_at >= :end_at'; $params['start_at'] = time(); - $params['end_at'] = time(); + $params['end_at'] = time(); break; case 'not-started': $sql .= ' AND start_at <= :start_at'; @@ -538,40 +534,40 @@ class Service implements InjectionAwareInterface $sql .= ' ORDER BY id asc'; - return array($sql, $params); + return [$sql, $params]; } public function createPromo($code, $type, $value, $products, $periods, $clientGroups, $data) { - if ($this->di['db']->findOne('Promo', 'code = :code', array(':code' => $code))) { + if ($this->di['db']->findOne('Promo', 'code = :code', [':code' => $code])) { throw new \Box_Exception('This promo code already exists.'); } $systemService = $this->di['mod_service']('system'); $systemService->checkLimits('Model_Promo', 2); - $model = $this->di['db']->dispense('Promo'); - $model->code = $code; - $model->type = $type; - $model->value = $value; - $model->active = $this->di['array_get']($data, 'active', 0); - $model->freesetup = $this->di['array_get']($data, 'freesetup', 0); - $model->once_per_client = (bool)$this->di['array_get']($data, 'once_per_client', 0); - $model->recurring = (bool)$this->di['array_get']($data, 'recurring', 0); - $model->maxuses = $this->di['array_get']($data, 'maxuses'); + $model = $this->di['db']->dispense('Promo'); + $model->code = $code; + $model->type = $type; + $model->value = $value; + $model->active = $this->di['array_get']($data, 'active', 0); + $model->freesetup = $this->di['array_get']($data, 'freesetup', 0); + $model->once_per_client = (bool) $this->di['array_get']($data, 'once_per_client', 0); + $model->recurring = (bool) $this->di['array_get']($data, 'recurring', 0); + $model->maxuses = $this->di['array_get']($data, 'maxuses'); - $start_at = $this->di['array_get']($data, 'start_at'); - $model->start_at = !empty($start_at) ? date('Y-m-d H:i:s', strtotime($start_at)) : NULL; - $end_at = $this->di['array_get']($data, 'end_at'); - $model->end_at = (!empty($end_at)) ? date('Y-m-d H:i:s', strtotime($end_at)) : NULL; + $start_at = $this->di['array_get']($data, 'start_at'); + $model->start_at = !empty($start_at) ? date('Y-m-d H:i:s', strtotime($start_at)) : null; + $end_at = $this->di['array_get']($data, 'end_at'); + $model->end_at = (!empty($end_at)) ? date('Y-m-d H:i:s', strtotime($end_at)) : null; - $model->products = json_encode($products); - $model->periods = json_encode($periods); + $model->products = json_encode($products); + $model->periods = json_encode($periods); $model->client_groups = json_encode($clientGroups); $model->updated_at = date('Y-m-d H:i:s'); $model->created_at = date('Y-m-d H:i:s'); - $promoId = $this->di['db']->store($model); + $promoId = $this->di['db']->store($model); $this->di['logger']->info('Created new promo code %s', $model->code); @@ -586,51 +582,51 @@ class Service implements InjectionAwareInterface $clientGroups = json_decode($model->client_groups, 1); $clientGroups = $this->di['tools']->getPairsForTableByIds('client_group', $clientGroups); - $result = $this->di['db']->toArray($model); - $result['applies_to'] = $products; - $result['cgroups'] = $clientGroups; - $result['products'] = json_decode($model->products, 1); - $result['periods'] = json_decode($model->periods, 1); + $result = $this->di['db']->toArray($model); + $result['applies_to'] = $products; + $result['cgroups'] = $clientGroups; + $result['products'] = json_decode($model->products, 1); + $result['periods'] = json_decode($model->periods, 1); $result['client_groups'] = json_decode($model->client_groups, 1); return $result; } - public function updatePromo(\Model_Promo $model, array $data = array()) + public function updatePromo(\Model_Promo $model, array $data = []) { - $model->code = $this->di['array_get']($data, 'code', $model->code); - $model->type = $this->di['array_get']($data, 'type', $model->type); - $model->value = $this->di['array_get']($data, 'value', $model->value); - $model->active = $this->di['array_get']($data, 'active', $model->active); - $model->freesetup = $this->di['array_get']($data, 'freesetup', $model->freesetup); + $model->code = $this->di['array_get']($data, 'code', $model->code); + $model->type = $this->di['array_get']($data, 'type', $model->type); + $model->value = $this->di['array_get']($data, 'value', $model->value); + $model->active = $this->di['array_get']($data, 'active', $model->active); + $model->freesetup = $this->di['array_get']($data, 'freesetup', $model->freesetup); $model->once_per_client = $this->di['array_get']($data, 'once_per_client', $model->once_per_client); - $model->recurring = $this->di['array_get']($data, 'recurring', $model->recurring); - $model->used = $this->di['array_get']($data, 'used', $model->used); + $model->recurring = $this->di['array_get']($data, 'recurring', $model->recurring); + $model->used = $this->di['array_get']($data, 'used', $model->used); $start_at = $this->di['array_get']($data, 'start_at'); - if (empty ($start_at) && !is_null($start_at)) { - $model->start_at = NULL; + if (empty($start_at) && !is_null($start_at)) { + $model->start_at = null; } else { $model->start_at = date('Y-m-d H:i:s', strtotime($start_at)); } $end_at = $this->di['array_get']($data, 'end_at'); - if (empty ($end_at) && !is_null($end_at)) { - $model->end_at = NULL; + if (empty($end_at) && !is_null($end_at)) { + $model->end_at = null; } else { $model->end_at = date('Y-m-d H:i:s', strtotime($end_at)); } $products = $this->di['array_get']($data, 'products'); if (empty($products) && !is_null($products)) { - $model->products = NULL; + $model->products = null; } else { $model->products = json_encode($products); } $client_groups = $this->di['array_get']($data, 'client_groups'); if (empty($client_groups) && !is_null($client_groups)) { - $model->client_groups = NULL; + $model->client_groups = null; } else { $model->client_groups = json_encode($client_groups); } @@ -651,7 +647,7 @@ class Service implements InjectionAwareInterface public function deletePromo(\Model_Promo $model) { $sql = 'UPDATE client_order SET promo_id = NULL WHERE promo_id = :id'; - $this->di['db']->exec($sql, array(':id' => $model->id)); + $this->di['db']->exec($sql, [':id' => $model->id]); $id = $model->code; $this->di['db']->trash($model); @@ -668,12 +664,12 @@ class Service implements InjectionAwareInterface LEFT JOIN product_payment as pp on m.product_payment_id = pp.id WHERE m.is_addon = 0'; - $type = $this->di['array_get']($data, 'type', null); - $search = $this->di['array_get']($data, 'search', null); - $status = $this->di['array_get']($data, 'status', null); + $type = $this->di['array_get']($data, 'type', null); + $search = $this->di['array_get']($data, 'search', null); + $status = $this->di['array_get']($data, 'status', null); $show_hidden = $this->di['array_get']($data, 'show_hidden', true); - $params = array(); + $params = []; if ($type) { $sql .= ' AND m.type = :type'; $params[':type'] = $type; @@ -695,23 +691,23 @@ class Service implements InjectionAwareInterface $sql .= ' ORDER BY m.priority ASC'; - return array($sql, $params); + return [$sql, $params]; } public function toProductCategoryApiArray(\Model_ProductCategory $model, $deep = true) { $min_price = 0; - $products = array(); - $pr = $this->getCategoryProducts($model); + $products = []; + $pr = $this->getCategoryProducts($model); - $type = null; //identified by first product in category + $type = null; // identified by first product in category foreach ($pr as $p) { $pa = $this->toApiArray($p, false); if (reset($pr) == $p) { $type = $p->type; } - $products[] = $pa; - $startingPrice = $this->di['array_get']($pa, 'price_starting_from', 0);; + $products[] = $pa; + $startingPrice = $this->di['array_get']($pa, 'price_starting_from', 0); if (0 == $min_price) { $min_price = $startingPrice; @@ -720,34 +716,35 @@ class Service implements InjectionAwareInterface } } - $data = $this->di['db']->toArray($model); + $data = $this->di['db']->toArray($model); $data['price_starting_from'] = $min_price; - $data['icon_url'] = $model->icon_url; - $data['type'] = $type; - $data['products'] = $products; + $data['icon_url'] = $model->icon_url; + $data['type'] = $type; + $data['products'] = $products; return $data; } /** * @param int $id + * * @return \Model_Product */ public function findOneActiveById($id) { - return $this->di['db']->findOne('Product', "id = ? and active = 1 and status = 'enabled' and is_addon = 0", array($id)); + return $this->di['db']->findOne('Product', "id = ? and active = 1 and status = 'enabled' and is_addon = 0", [$id]); } /** * @param string $slug + * * @return \Model_Product */ public function findOneActiveBySlug($slug) { - return $this->di['db']->findOne('Product', "slug = ? and active = 1 and status = 'enabled' and is_addon = 0", array($slug)); + return $this->di['db']->findOne('Product', "slug = ? and active = 1 and status = 'enabled' and is_addon = 0", [$slug]); } - public function getProductCategorySearchQuery($data) { $sql = 'SELECT m.id, @@ -770,14 +767,14 @@ class Service implements InjectionAwareInterface m.updated_at ORDER BY MaxPrio ASC;'; - $params = array(); + $params = []; - return array($sql, $params); + return [$sql, $params]; } public function getStartingFromPrice(\Model_Product $model) { - if ($model->type == self::DOMAIN){ + if (self::DOMAIN == $model->type) { return $this->getStartingDomainPrice(); } @@ -787,19 +784,18 @@ class Service implements InjectionAwareInterface return $this->getStartingPrice($productPaymentModel); } - return NULL; + return null; } public function getUpgradablePairs(\Model_Product $model) { - $ids = json_decode($model->upgrades, 1); + $ids = json_decode($model->upgrades, 1); $pids = $this->getProductTitlesByIds($ids); unset($pids[$model->id]); return $pids; } - public function canUpgradeTo(\Model_Product $model, \Model_Product $new) { if ($model->id == $new->id) { @@ -813,15 +809,15 @@ class Service implements InjectionAwareInterface public function getProductTitlesByIds($ids) { - if (empty ($ids)) { - return array(); + if (empty($ids)) { + return []; } - $slots = (count($ids)) ? implode(',', array_fill(0, count($ids), '?')) : ''; //same as RedBean genSlots() method + $slots = (count($ids)) ? implode(',', array_fill(0, count($ids), '?')) : ''; // same as RedBean genSlots() method - $rows = $this->di['db']->getAll('SELECT id, title FROM product WHERE id in (' . $slots . ')', $ids); + $rows = $this->di['db']->getAll('SELECT id, title FROM product WHERE id in ('.$slots.')', $ids); - $result = array(); + $result = []; foreach ($rows as $record) { $result[$record['id']] = $record['title']; } @@ -831,27 +827,26 @@ class Service implements InjectionAwareInterface public function getCategoryProducts(\Model_ProductCategory $model) { - return $this->di['db']->find('Product', 'is_addon = 0 and status="enabled" and hidden = 0 and product_category_id = ?', array($model->id)); - + return $this->di['db']->find('Product', 'is_addon = 0 and status="enabled" and hidden = 0 and product_category_id = ?', [$model->id]); } public function toProductPaymentApiArray(\Model_ProductPayment $model) { - $periods = array(); - $periods['1W'] = array('price' => $model->w_price, 'setup' => $model->w_setup_price, 'enabled' => $model->w_enabled); - $periods['1M'] = array('price' => $model->m_price, 'setup' => $model->m_setup_price, 'enabled' => $model->m_enabled); - $periods['3M'] = array('price' => $model->q_price, 'setup' => $model->q_setup_price, 'enabled' => $model->q_enabled); - $periods['6M'] = array('price' => $model->b_price, 'setup' => $model->b_setup_price, 'enabled' => $model->b_enabled); - $periods['1Y'] = array('price' => $model->a_price, 'setup' => $model->a_setup_price, 'enabled' => $model->a_enabled); - $periods['2Y'] = array('price' => $model->bia_price, 'setup' => $model->bia_setup_price, 'enabled' => $model->bia_enabled); - $periods['3Y'] = array('price' => $model->tria_price, 'setup' => $model->tria_setup_price, 'enabled' => $model->tria_enabled); + $periods = []; + $periods['1W'] = ['price' => $model->w_price, 'setup' => $model->w_setup_price, 'enabled' => $model->w_enabled]; + $periods['1M'] = ['price' => $model->m_price, 'setup' => $model->m_setup_price, 'enabled' => $model->m_enabled]; + $periods['3M'] = ['price' => $model->q_price, 'setup' => $model->q_setup_price, 'enabled' => $model->q_enabled]; + $periods['6M'] = ['price' => $model->b_price, 'setup' => $model->b_setup_price, 'enabled' => $model->b_enabled]; + $periods['1Y'] = ['price' => $model->a_price, 'setup' => $model->a_setup_price, 'enabled' => $model->a_enabled]; + $periods['2Y'] = ['price' => $model->bia_price, 'setup' => $model->bia_setup_price, 'enabled' => $model->bia_enabled]; + $periods['3Y'] = ['price' => $model->tria_price, 'setup' => $model->tria_setup_price, 'enabled' => $model->tria_enabled]; - return array( - 'type' => $model->type, - \Model_ProductPayment::FREE => array('price' => 0, 'setup' => 0), - \Model_ProductPayment::ONCE => array('price' => $model->once_price, 'setup' => $model->once_setup_price), + return [ + 'type' => $model->type, + \Model_ProductPayment::FREE => ['price' => 0, 'setup' => 0], + \Model_ProductPayment::ONCE => ['price' => $model->once_price, 'setup' => $model->once_setup_price], \Model_ProductPayment::RECURRENT => $periods, - ); + ]; } public function getStartingDomainPrice() @@ -860,21 +855,21 @@ class Service implements InjectionAwareInterface FROM tld WHERE active = 1'; - return (double) $this->di['db']->getCell($sql); + return (float) $this->di['db']->getCell($sql); } public function getStartingPrice(\Model_ProductPayment $model) { - if ($model->type == 'free') { + if ('free' == $model->type) { return 0; } - if ($model->type == 'once') { + if ('once' == $model->type) { return $model->once_price; } - if ($model->type == 'recurrent') { - $p = array(); + if ('recurrent' == $model->type) { + $p = []; if ($model->w_enabled) { $p[] = $model->w_price; @@ -886,7 +881,6 @@ class Service implements InjectionAwareInterface if ($model->q_enabled) { $p[] = $model->q_price; - } if ($model->b_enabled) { @@ -908,12 +902,12 @@ class Service implements InjectionAwareInterface return min($p); } - return NULL; + return null; } public function getSavePath($filename = null) { - $path = $this->di['config']['path_data'] . '/uploads/'; + $path = $this->di['config']['path_data'].'/uploads/'; if (null !== $filename) { $path .= md5($filename); } @@ -937,7 +931,7 @@ class Service implements InjectionAwareInterface public function getAddonById($id) { - return $this->di['db']->findOne('Product', "type = 'custom' and is_addon = 1 and id = ?", array($id)); + return $this->di['db']->findOne('Product', "type = 'custom' and is_addon = 1 and id = ?", [$id]); } public function getProductDiscount(\Model_Product $product, \Model_Promo $promo, array $config = null) @@ -954,10 +948,10 @@ class Service implements InjectionAwareInterface } } - $repo = $product->getTable(); + $repo = $product->getTable(); $price = $repo->getProductPrice($product, $config); - if ($price == 0) { + if (0 == $price) { return 0; } @@ -970,11 +964,10 @@ class Service implements InjectionAwareInterface break; case \Model_Promo::PERCENTAGE: - - if(isset($config['quantity']) && is_numeric($config['quantity'])){ + if (isset($config['quantity']) && is_numeric($config['quantity'])) { $quantity = $config['quantity']; } - + $discount += round(($price * $quantity * $promo->value / 100), 2); break; @@ -1022,9 +1015,9 @@ class Service implements InjectionAwareInterface private function getAddonsApiArray(\Model_Product $model) { - $addons = array(); + $addons = []; foreach ($this->getProductAddons($model) as $addon) { - $d = $this->toAddonArray($addon); + $d = $this->toAddonArray($addon); $addons[] = $d; } @@ -1035,38 +1028,37 @@ class Service implements InjectionAwareInterface { $ids = $this->di['tools']->decodeJ($model->addons); if (empty($ids)) { - return array(); + return []; } - $slots = (count($ids)) ? implode(',', array_fill(0, count($ids), '?')) : ''; //same as RedBean genSlots() method - array_unshift($ids, (int)$model->id); //adding product ID as first param in array + $slots = (count($ids)) ? implode(',', array_fill(0, count($ids), '?')) : ''; // same as RedBean genSlots() method + array_unshift($ids, (int) $model->id); // adding product ID as first param in array - return $this->di['db']->find('Product', 'type = "custom" and is_addon= 1 and id != ? and id IN (' . $slots . ')', $ids); + return $this->di['db']->find('Product', 'type = "custom" and is_addon= 1 and id != ? and id IN ('.$slots.')', $ids); } public function toAddonArray(\Model_Product $model, $deep = true) { $productPayment = $this->di['db']->load('ProductPayment', $model->product_payment_id); - $pricing = $this->toProductPaymentApiArray($productPayment); + $pricing = $this->toProductPaymentApiArray($productPayment); $config = $this->di['tools']->decodeJ($model->config); - return array( - 'id' => $model->id, - 'type' => $model->type, - 'title' => $model->title, - 'slug' => $model->slug, - 'description' => $model->description, - 'unit' => $model->unit, - 'plugin' => $model->plugin, + return [ + 'id' => $model->id, + 'type' => $model->type, + 'title' => $model->title, + 'slug' => $model->slug, + 'description' => $model->description, + 'unit' => $model->unit, + 'plugin' => $model->plugin, 'allow_quantity_select' => $model->allow_quantity_select, - 'created_at' => $model->created_at, - 'updated_at' => $model->updated_at, - 'icon_url' => $model->icon_url, + 'created_at' => $model->created_at, + 'updated_at' => $model->updated_at, + 'icon_url' => $model->icon_url, - 'pricing' => $pricing, - 'config' => $config, - ); + 'pricing' => $pricing, + 'config' => $config, + ]; } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Profile/Api/Admin.php b/src/bb-modules/Profile/Api/Admin.php index 8f5ad0cdf..93d133357 100644 --- a/src/bb-modules/Profile/Api/Admin.php +++ b/src/bb-modules/Profile/Api/Admin.php @@ -1,6 +1,6 @@ * Array - * ( + * ( * [id] => 1 * [role] => staff * [admin_group_id] => 1 @@ -38,8 +38,8 @@ class Admin extends \Api_Abstract * [api_token] => 29baba87f1c120f1b7fc6b0139167003 * [created_at] => 1310024416 * [updated_at] => 1310024416 - * ) - * + * ) + * */ public function get() { @@ -47,27 +47,29 @@ class Admin extends \Api_Abstract } /** - * Clear session data and logout from system - * - * @return boolean + * Clear session data and logout from system. + * + * @return bool */ public function logout() { $this->di['cookie']->delete('BOXADMR'); $this->di['session']->delete('admin'); $this->di['logger']->info('Admin logged out'); + return true; } /** - * Update currently logged in staff member details - * + * Update currently logged in staff member details. + * * @optional string $email - new email * @optional string $name - new name * @optional string $signature - new signature - * - * @return boolean - * @throws Exception + * + * @return bool + * + * @throws Exception */ public function update($data) { @@ -75,9 +77,9 @@ class Admin extends \Api_Abstract } /** - * Generates new API token for currently logged in staff member - * - * @return boolean + * Generates new API token for currently logged in staff member. + * + * @return bool */ public function generate_api_key($data) { @@ -85,24 +87,26 @@ class Admin extends \Api_Abstract } /** - * Change password for currently logged in staff member - * - * @param string $password - new password + * Change password for currently logged in staff member. + * + * @param string $password - new password * @param string $password_confirm - repeat new password - * @return boolean - * @throws Exception + * + * @return bool + * + * @throws Exception */ public function change_password($data) { - if(!isset($data['password'])) { + if (!isset($data['password'])) { throw new \Exception('Password required'); } - if(!isset($data['password_confirm'])) { + if (!isset($data['password_confirm'])) { throw new \Exception('Password confirmation required'); } - if($data['password'] != $data['password_confirm']) { + if ($data['password'] != $data['password_confirm']) { throw new \Exception('Passwords do not match'); } @@ -110,4 +114,4 @@ class Admin extends \Api_Abstract return $this->getService()->changeAdminPassword($this->getIdentity(), $data['password']); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Profile/Api/Client.php b/src/bb-modules/Profile/Api/Client.php index 7831f3bcc..8f48f011a 100644 --- a/src/bb-modules/Profile/Api/Client.php +++ b/src/bb-modules/Profile/Api/Client.php @@ -1,6 +1,6 @@ di['mod_service']('client'); + return $clientService->toApiArray($this->getIdentity(), true, $this->getIdentity()); } /** - * Update currencty logged in client details - * + * Update currencty logged in client details. + * * @optional string $email - new client email. Must not exist on system * @optional string $last_name - last name * @optional string $aid - Alternative id. Usually used by import tools. @@ -61,26 +62,28 @@ class Client extends \Api_Abstract * @optional string $custom_8 - Custom field 8 * @optional string $custom_9 - Custom field 9 * @optional string $custom_10 - Custom field 10 - * - * @return boolean - * @throws Exception + * + * @return bool + * + * @throws Exception */ public function update($data) { return $this->getService()->updateClient($this->getIdentity(), $data); } - + /** - * Retrieve current API key + * Retrieve current API key. */ public function api_key_get($data) { $client = $this->getIdentity(); + return $client->api_token; } - + /** - * Generate new API key + * Generate new API key. */ public function api_key_reset($data) { @@ -88,14 +91,14 @@ class Client extends \Api_Abstract } /** - * Change client area password + * Change client area password. */ public function change_password($data) { - $required = array( - 'password' => 'Password required', + $required = [ + 'password' => 'Password required', 'password_confirm' => 'Password confirmation required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); if ($data['password'] != $data['password_confirm']) { @@ -106,11 +109,12 @@ class Client extends \Api_Abstract } /** - * Clear session and logout - * @return boolean + * Clear session and logout. + * + * @return bool */ public function logout() { return $this->getService()->logoutClient(); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Profile/Service.php b/src/bb-modules/Profile/Service.php index 4dc35430c..32e254453 100644 --- a/src/bb-modules/Profile/Service.php +++ b/src/bb-modules/Profile/Service.php @@ -1,6 +1,6 @@ id; - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminStaffProfilePasswordChange', 'params' => $event_params)); + $event_params['id'] = $admin->id; + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffProfilePasswordChange', 'params' => $event_params]); - $admin->pass = $this->di['password']->hashIt($new_password); + $admin->pass = $this->di['password']->hashIt($new_password); $admin->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($admin); - $event_params = array(); + $event_params = []; $event_params['id'] = $admin->id; - $this->di['events_manager']->fire(array('event' => 'onAfterAdminStaffProfilePasswordChange', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffProfilePasswordChange', 'params' => $event_params]); $this->di['logger']->info('Changed profile password'); @@ -51,15 +50,15 @@ class Service implements InjectionAwareInterface public function generateNewApiKey(\Model_Admin $admin) { - $event_params = array(); + $event_params = []; $event_params['id'] = $admin->id; - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminStaffApiKeyChange', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffApiKeyChange', 'params' => $event_params]); - $admin->api_token = $this->di['tools']->generatePassword(32); + $admin->api_token = $this->di['tools']->generatePassword(32); $admin->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($admin); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminStaffApiKeyChange', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffApiKeyChange', 'params' => $event_params]); $this->di['logger']->info('Generated new API key'); @@ -68,9 +67,9 @@ class Service implements InjectionAwareInterface public function updateAdmin(\Model_Admin $admin, array $data) { - $event_params = $data; + $event_params = $data; $event_params['id'] = $admin->id; - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminStaffProfileUpdate', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffProfileUpdate', 'params' => $event_params]); $admin->email = $this->di['array_get']($data, 'email', $admin->email); $admin->name = $this->di['array_get']($data, 'name', $admin->name); @@ -78,9 +77,9 @@ class Service implements InjectionAwareInterface $admin->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($admin); - $event_params = array(); + $event_params = []; $event_params['id'] = $admin->id; - $this->di['events_manager']->fire(array('event' => 'onAfterAdminStaffProfileUpdate', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffProfileUpdate', 'params' => $event_params]); $this->di['logger']->info('Updated profile'); @@ -89,27 +88,27 @@ class Service implements InjectionAwareInterface public function getAdminIdentityArray(\Model_Admin $identity) { - return array( - 'id' => $identity->id, - 'role' => $identity->role, + return [ + 'id' => $identity->id, + 'role' => $identity->role, 'admin_group_id' => $identity->admin_group_id, - 'email' => $identity->email, - 'name' => $identity->name, - 'signature' => $identity->signature, - 'status' => $identity->status, - 'api_token' => $identity->api_token, - 'created_at' => $identity->created_at, - 'updated_at' => $identity->updated_at, - ); + 'email' => $identity->email, + 'name' => $identity->name, + 'signature' => $identity->signature, + 'status' => $identity->status, + 'api_token' => $identity->api_token, + 'created_at' => $identity->created_at, + 'updated_at' => $identity->updated_at, + ]; } - public function updateClient(\Model_Client $client, array $data = array()) + public function updateClient(\Model_Client $client, array $data = []) { - $event_params = $data; + $event_params = $data; $event_params['id'] = $client->id; - $this->di['events_manager']->fire(array('event' => 'onBeforeClientProfileUpdate', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onBeforeClientProfileUpdate', 'params' => $event_params]); - $mod = $this->di['mod']('client'); + $mod = $this->di['mod']('client'); $config = $mod->getConfig(); $email = $this->di['array_get']($data, 'email', ''); if ($client->email != $email @@ -132,51 +131,51 @@ class Service implements InjectionAwareInterface } $client->first_name = $this->di['array_get']($data, 'first_name', $client->first_name); - $client->last_name = $this->di['array_get']($data, 'last_name', $client->last_name); - $client->gender = $this->di['array_get']($data, 'gender', $client->gender); + $client->last_name = $this->di['array_get']($data, 'last_name', $client->last_name); + $client->gender = $this->di['array_get']($data, 'gender', $client->gender); $birthday = $this->di['array_get']($data, 'birthday'); - if (strlen(trim($birthday)) > 0 && strtotime($birthday) === false) { + if (strlen(trim($birthday)) > 0 && false === strtotime($birthday)) { throw new \Box_Exception('Invalid birth date value'); } $client->birthday = $birthday; - $client->company = $this->di['array_get']($data, 'company', $client->company); - $client->company_vat = $this->di['array_get']($data, 'company_vat', $client->company_vat); + $client->company = $this->di['array_get']($data, 'company', $client->company); + $client->company_vat = $this->di['array_get']($data, 'company_vat', $client->company_vat); $client->company_number = $this->di['array_get']($data, 'company_number', $client->company_number); - $client->type = $this->di['array_get']($data, 'type', $client->type); - $client->address_1 = $this->di['array_get']($data, 'address_1', $client->address_1); - $client->address_2 = $this->di['array_get']($data, 'address_2', $client->address_2); - $client->phone_cc = $this->di['array_get']($data, 'phone_cc', $client->phone_cc); - $client->phone = $this->di['array_get']($data, 'phone', $client->phone); - $client->country = $this->di['array_get']($data, 'country', $client->country); - $client->postcode = $this->di['array_get']($data, 'postcode', $client->postcode); - $client->city = $this->di['array_get']($data, 'city', $client->city); - $client->state = $this->di['array_get']($data, 'state', $client->state); - $client->document_type = $this->di['array_get']($data, 'document_type', $client->document_type); - $client->document_nr = $this->di['array_get']($data, 'document_nr', $client->document_nr); + $client->type = $this->di['array_get']($data, 'type', $client->type); + $client->address_1 = $this->di['array_get']($data, 'address_1', $client->address_1); + $client->address_2 = $this->di['array_get']($data, 'address_2', $client->address_2); + $client->phone_cc = $this->di['array_get']($data, 'phone_cc', $client->phone_cc); + $client->phone = $this->di['array_get']($data, 'phone', $client->phone); + $client->country = $this->di['array_get']($data, 'country', $client->country); + $client->postcode = $this->di['array_get']($data, 'postcode', $client->postcode); + $client->city = $this->di['array_get']($data, 'city', $client->city); + $client->state = $this->di['array_get']($data, 'state', $client->state); + $client->document_type = $this->di['array_get']($data, 'document_type', $client->document_type); + $client->document_nr = $this->di['array_get']($data, 'document_nr', $client->document_nr); if (isset($client->document_nr)) { $client->document_type = $this->di['array_get']($data, 'document_type ', 'passport'); } - $client->lang = $this->di['array_get']($data, 'lang', $client->lang); - $client->notes = $this->di['array_get']($data, 'notes', $client->notes); - $client->custom_1 = $this->di['array_get']($data, 'custom_1', $client->custom_1); - $client->custom_2 = $this->di['array_get']($data, 'custom_2', $client->custom_2); - $client->custom_3 = $this->di['array_get']($data, 'custom_3', $client->custom_3); - $client->custom_4 = $this->di['array_get']($data, 'custom_4', $client->custom_4); - $client->custom_5 = $this->di['array_get']($data, 'custom_5', $client->custom_5); - $client->custom_6 = $this->di['array_get']($data, 'custom_6', $client->custom_6); - $client->custom_7 = $this->di['array_get']($data, 'custom_7', $client->custom_7); - $client->custom_8 = $this->di['array_get']($data, 'custom_8', $client->custom_8); - $client->custom_9 = $this->di['array_get']($data, 'custom_9', $client->custom_9); + $client->lang = $this->di['array_get']($data, 'lang', $client->lang); + $client->notes = $this->di['array_get']($data, 'notes', $client->notes); + $client->custom_1 = $this->di['array_get']($data, 'custom_1', $client->custom_1); + $client->custom_2 = $this->di['array_get']($data, 'custom_2', $client->custom_2); + $client->custom_3 = $this->di['array_get']($data, 'custom_3', $client->custom_3); + $client->custom_4 = $this->di['array_get']($data, 'custom_4', $client->custom_4); + $client->custom_5 = $this->di['array_get']($data, 'custom_5', $client->custom_5); + $client->custom_6 = $this->di['array_get']($data, 'custom_6', $client->custom_6); + $client->custom_7 = $this->di['array_get']($data, 'custom_7', $client->custom_7); + $client->custom_8 = $this->di['array_get']($data, 'custom_8', $client->custom_8); + $client->custom_9 = $this->di['array_get']($data, 'custom_9', $client->custom_9); $client->custom_10 = $this->di['array_get']($data, 'custom_10', $client->custom_10); $client->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($client); - $this->di['events_manager']->fire(array('event' => 'onAfterClientProfileUpdate', 'params' => array('id' => $client->id))); + $this->di['events_manager']->fire(['event' => 'onAfterClientProfileUpdate', 'params' => ['id' => $client->id]]); $this->di['logger']->info('Updated profile'); @@ -185,7 +184,7 @@ class Service implements InjectionAwareInterface public function resetApiKey(\Model_Client $client) { - $client->api_token = $this->di['tools']->generatePassword(32); + $client->api_token = $this->di['tools']->generatePassword(32); $client->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($client); @@ -197,30 +196,32 @@ class Service implements InjectionAwareInterface public function changeClientPassword(\Model_Client $client, $password) { - $event_params = array(); + $event_params = []; $event_params['password'] = $password; - $event_params['id'] = $client->id; - $this->di['events_manager']->fire(array('event' => 'onBeforeClientProfilePasswordChange', 'params' => $event_params)); + $event_params['id'] = $client->id; + $this->di['events_manager']->fire(['event' => 'onBeforeClientProfilePasswordChange', 'params' => $event_params]); $this->di['validator']->isPasswordStrong($password); $client->pass = $this->di['password']->hashIt($password); $this->di['db']->store($client); - $this->di['events_manager']->fire(array('event' => 'onAfterClientProfilePasswordChange', 'params' => array('id' => $client->id))); + $this->di['events_manager']->fire(['event' => 'onAfterClientProfilePasswordChange', 'params' => ['id' => $client->id]]); $this->di['logger']->info('Changed profile password'); return true; } - public function logoutClient(){ - if($_COOKIE) { // testing env fix - $this->di['cookie']->set('BOXCLR', "", time() - 3600, '/'); + public function logoutClient() + { + if ($_COOKIE) { // testing env fix + $this->di['cookie']->set('BOXCLR', '', time() - 3600, '/'); } $this->di['session']->delete('client'); $this->di['session']->delete('client_id'); $this->di['logger']->info('Logged out'); + return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Queue/Api/Admin.php b/src/bb-modules/Queue/Api/Admin.php index f95819e38..5f1adf10a 100644 --- a/src/bb-modules/Queue/Api/Admin.php +++ b/src/bb-modules/Queue/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getSearchQuery($data); + [$sql, $params] = $this->getService()->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { @@ -37,87 +37,89 @@ class Admin extends \Api_Abstract return $pager; } - + /** - * Get queue details - * - * @param string $queue - queue name, ie: massemails - * + * Get queue details. + * + * @param string $queue - queue name, ie: massemails + * * @return array */ public function get($data) { $q = $this->_getQueue($data); $service = $this->getService(); + return $service->toApiArray($q); } - + /** - * Remove message from queue - * + * Remove message from queue. + * * @param type $int - message id - * + * * @return bool */ public function message_delete($data) { - $required = array( + $required = [ 'id' => 'Queue message ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $msg = $this->di['db']->getExistingModelById('queue_message', $data['id'], 'Queue message not found'); - + $this->di['db']->trash($msg); + return true; } - + /** - * Add message to queue to be executed later - * - * @param string $queue - unique queue name, ie: massemails - * @param string $mod - module name, ie: massmailer - * + * Add message to queue to be executed later. + * + * @param string $queue - unique queue name, ie: massemails + * @param string $mod - module name, ie: massmailer + * * @optional string $execute_at - Message execution time. Schedule message to be executed later, ie: 2022-12-29 14:53:51 * @optional mixed $params - queue message params. Any serializable param * @optional string $handler - function handler. Static function name in extensions service class - default $queue name * @optional int $interval - Interval to execute messages in the queue. Default 30 * @optional int $max - Maximum amount of messages to be executed per interval. Default 25 - * + * * @return int - message id */ public function message_add($data) { - $required = array( + $required = [ 'queue' => 'Queue name not provided', - 'mod' => 'Module name not provided', - ); + 'mod' => 'Module name not provided', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $mod = $this->di['mod']($data['mod']); $service = $mod->getService(); - $handler = isset($data['handler']) ? $data['handler'] : $data['queue']; - if(!method_exists($service, $handler)) { - throw new \Box_Exception('Message handler function :method does not exists', array(':ext'=>$data['mod'], ':method'=> get_class($service).':'.$handler)); + $handler = $data['handler'] ?? $data['queue']; + if (!method_exists($service, $handler)) { + throw new \Box_Exception('Message handler function :method does not exists', [':ext' => $data['mod'], ':method' => get_class($service).':'.$handler]); } - - $interval = isset($data['interval']) ? (int)$data['interval'] : 30; - $max = isset($data['max']) ? (int)$data['max'] : 25; - $q = $this->di['db']->findOne('queue', 'name = :name', array('name'=>$data['queue'])); - if(!$q) { + + $interval = isset($data['interval']) ? (int) $data['interval'] : 30; + $max = isset($data['max']) ? (int) $data['max'] : 25; + $q = $this->di['db']->findOne('queue', 'name = :name', ['name' => $data['queue']]); + if (!$q) { $q = $this->di['db']->dispense('queue'); - $q->name = $data['queue']; - $q->module = $data['mod']; - $q->created_at = date('Y-m-d H:i:s'); + $q->name = $data['queue']; + $q->module = $data['mod']; + $q->created_at = date('Y-m-d H:i:s'); } $q->timeout = $interval; $q->iteration = $max; $q->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($q); - + $params = $this->di['array_get']($data, 'params', null); - $body = base64_encode(json_encode($params)); - + $body = base64_encode(json_encode($params)); + $msg = $this->di['db']->dispense('queue_message'); $msg->queue_id = $q->id; $msg->handler = $handler; @@ -125,72 +127,72 @@ class Admin extends \Api_Abstract $msg->hash = md5($body); $msg->created_at = date('Y-m-d H:i:s'); $msg->updated_at = date('Y-m-d H:i:s'); - - if(isset($data['execute_at'])) { + + if (isset($data['execute_at'])) { $msg->execute_at = date('Y-m-d H:i:s', strtotime($data['execute_at'])); } - + $this->di['db']->store($msg); - return (int)$msg->id; + return (int) $msg->id; } - + /** * Execute queue. * For example: Send 25 emails every 30 seconds until complete * Executing queue is locked until finished. - * + * * @param string $queue - queue name to be executed - * + * * @optional int $max - Maximum amount of messages to be executed per interval. Default is queue max amount * @optional int $interval - interval in seconds for message to be executed. Default is queue timeout * @optional bool $until_complete - Execute until all messages in queue are executed. Default true - * + * * @return bool - returns true when queue finihed executing */ public function execute($data) { - $required = array( + $required = [ 'queue' => 'Queue name not provided', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - - $q = $this->di['db']->findOne('queue', 'name = :name', array('name'=>$data['queue'])); - if(!$q) { + + $q = $this->di['db']->findOne('queue', 'name = :name', ['name' => $data['queue']]); + if (!$q) { throw new \Exception('Queue not found'); } $lock_file = BB_PATH_LOG.'/queue_'.$q->id.'.lock'; touch($lock_file); $file_handle = fopen($lock_file, 'r+'); - if(!flock($file_handle, LOCK_EX | LOCK_NB)) { + if (!flock($file_handle, LOCK_EX | LOCK_NB)) { $this->di['logger']->info(sprintf('Queue %s is being executed by other process.', $q->id)); throw new \Exception('This queue is being executed by other process.'); } $this->di['logger']->info('Locked queue: '.$q->id); - - $max = isset($data['max']) ? (int)$data['max'] : $q->iteration; - $interval = isset($data['interval']) ? (int)$data['interval'] : $q->timeout; - $until_complete = isset($data['until_complete']) ? (bool)$data['until_complete'] : true; - + + $max = isset($data['max']) ? (int) $data['max'] : $q->iteration; + $interval = isset($data['interval']) ? (int) $data['interval'] : $q->timeout; + $until_complete = isset($data['until_complete']) ? (bool) $data['until_complete'] : true; + $this->di['logger']->info(sprintf('Started executing %s queue by selecting %s messages every %s seconds', $q->name, $max, $interval)); - + $iterate = true; - while($iterate) { - $start = (float) array_sum(explode(' ',microtime())); + while ($iterate) { + $start = (float) array_sum(explode(' ', microtime())); $r = $this->_execute($q, $max, $interval); - $end = (float) array_sum(explode(' ',microtime())); - - $wait_for = $interval - ($end-$start); - - if($wait_for > 0.000001) { + $end = (float) array_sum(explode(' ', microtime())); + + $wait_for = $interval - ($end - $start); + + if ($wait_for > 0.000001) { $this->di['logger']->info('Waiting for '.$wait_for.' seconds to continue iteration'); - if(APPLICATION_ENV != 'testing') { + if (APPLICATION_ENV != 'testing') { sleep($wait_for); } } - - if(!$until_complete) { + + if (!$until_complete) { $iterate = false; } else { $iterate = !empty($r); @@ -199,105 +201,108 @@ class Admin extends \Api_Abstract fclose($file_handle); $this->di['logger']->info('Unlocked queue: '.$q->id); unlink($lock_file); - + $this->di['logger']->info(sprintf('Finished executing queue %s', $q->name)); + return true; } - + private function _execute($q, $max, $interval) { - $lsql = "UPDATE queue_message SET log = :log, updated_at = :u WHERE id = :id;"; - $dsql = "DELETE FROM queue_message WHERE id = :id;"; + $lsql = 'UPDATE queue_message SET log = :log, updated_at = :u WHERE id = :id;'; + $dsql = 'DELETE FROM queue_message WHERE id = :id;'; $mod = $this->di['mod']($q->module); $service = $mod->getService(); - + $msgs = $this->receiveQueueMessages($q->id, $max, $interval); - $result = array(); - foreach($msgs as $msg) { + $result = []; + foreach ($msgs as $msg) { try { $this->di['logger']->info(sprintf('Executing %s queue message #%s with handler %s(%s)', $q->name, $msg['id'], get_class($service).':'.$msg['handler'], $msg['json'])); - call_user_func(array($service, $msg['handler']), $msg['params']); - $this->di['db']->exec($dsql, array('id'=>$msg['id'])); - $result[$msg['id']] = array('status'=> 'executed', 'error'=>null); - } catch(\Exception $e) { - $this->di['db']->exec($lsql, array('log'=>$e->getMessage(). ' '. $e->getCode(), 'id'=>$msg['id'], 'u'=>date('Y-m-d H:i:s'))); + call_user_func([$service, $msg['handler']], $msg['params']); + $this->di['db']->exec($dsql, ['id' => $msg['id']]); + $result[$msg['id']] = ['status' => 'executed', 'error' => null]; + } catch (\Exception $e) { + $this->di['db']->exec($lsql, ['log' => $e->getMessage().' '.$e->getCode(), 'id' => $msg['id'], 'u' => date('Y-m-d H:i:s')]); $this->di['logger']->info(sprintf('Error executing queue %s message #%s %s', $q->name, $msg['id'], $e->getMessage())); - $result[$msg['id']] = array('status'=> 'fail', 'error' => $e->getMessage()); + $result[$msg['id']] = ['status' => 'fail', 'error' => $e->getMessage()]; } } - + return $result; } - + private function _getQueue($data) { - $required = array( + $required = [ 'queue' => 'Queue name not provided', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - - $q = $this->di['db']->findOne('queue', 'name = :name', array('name'=>$data['queue'])); - if(!$q) { + + $q = $this->di['db']->findOne('queue', 'name = :name', ['name' => $data['queue']]); + if (!$q) { throw new \Exception('Queue not found'); } + return $q; } - + /** - * Select unselected messages from queue - * + * Select unselected messages from queue. + * * @param Queue $queue - * @param int $max - * @param int $timeout + * @param int $max + * @param int $timeout + * * @return array */ private function receiveQueueMessages($qid, $max, $timeout) { // start transaction handling - if ( $max < 0 ) { - return array(); + if ($max < 0) { + return []; } - - $qid = (int)$qid; - $max = (int)$max; - $msgs = array(); + + $qid = (int) $qid; + $max = (int) $max; + $msgs = []; $microtime = microtime(true); // cache microtime - $db = $this->di['pdo']; + $db = $this->di['pdo']; $sql = "SELECT id, handler, body FROM queue_message WHERE queue_id = $qid - AND (handle IS NULL OR timeout+" . (int)$timeout . " < " . (int)$microtime .") + AND (handle IS NULL OR timeout+".(int) $timeout.' < '.(int) $microtime.") AND (execute_at IS NULL OR UNIX_TIMESTAMP(execute_at) > UNIX_TIMESTAMP() ) LIMIT $max"; - - $sql2= "UPDATE queue_message + + $sql2 = 'UPDATE queue_message SET handle = :handle, timeout = :timeout WHERE id = :id AND - (handle IS NULL OR timeout+" . (int)$timeout . " < " . (int)$microtime.')'; - + (handle IS NULL OR timeout+'.(int) $timeout.' < '.(int) $microtime.')'; + $stmt1 = $db->prepare($sql); $stmt1->execute(); - + foreach ($stmt1->fetchAll() as $data) { $stmt = $db->prepare($sql2); $stmt->bindValue('handle', md5(random_bytes(23)), \PDO::PARAM_STR); $stmt->bindValue('id', $data['id'], \PDO::PARAM_INT); $stmt->bindValue('timeout', $microtime); if ($stmt->execute()) { - $msgs[] = array( - 'id' => $data['id'], - 'handler' => $data['handler'], - 'json' => base64_decode($data['body']), - 'params' => json_decode(base64_decode($data['body']), 1), - ); + $msgs[] = [ + 'id' => $data['id'], + 'handler' => $data['handler'], + 'json' => base64_decode($data['body']), + 'params' => json_decode(base64_decode($data['body']), 1), + ]; } } return $msgs; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Queue/Service.php b/src/bb-modules/Queue/Service.php index 5eb81dcf5..976fd20ae 100644 --- a/src/bb-modules/Queue/Service.php +++ b/src/bb-modules/Queue/Service.php @@ -1,6 +1,6 @@ di['db']->exec('DROP TABLE queue;'); $this->di['db']->exec('DROP TABLE queue_message;'); } - + public function install() { - $sql=" + $sql = ' CREATE TABLE IF NOT EXISTS `queue` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL, @@ -52,10 +51,10 @@ class Service implements \Box\InjectionAwareInterface `updated_at` varchar(35) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; - "; + '; $this->di['db']->exec($sql); - - $sql=" + + $sql = ' CREATE TABLE IF NOT EXISTS `queue_message` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `queue_id` bigint(20) DEFAULT NULL, @@ -71,74 +70,75 @@ class Service implements \Box\InjectionAwareInterface PRIMARY KEY (`id`), KEY `queue_id_idx` (`queue_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; - "; - + '; + $this->di['db']->exec($sql); $columns = $this->di['db']->getColumns('queue'); - if(!array_key_exists('module', $columns)) { + if (!array_key_exists('module', $columns)) { $this->di['db']->exec('ALTER TABLE `queue` ADD `module` VARCHAR( 255 ) NULL AFTER `name`;'); } - - if(!array_key_exists('iteration', $columns)) { + + if (!array_key_exists('iteration', $columns)) { $this->di['db']->exec('ALTER TABLE `queue` ADD `iteration` VARCHAR( 255 ) NULL AFTER `timeout`;'); } - + $columns = $this->di['db']->getColumns('queue_message'); - if(!array_key_exists('handler', $columns)) { + if (!array_key_exists('handler', $columns)) { $this->di['db']->exec('ALTER TABLE `queue_message` ADD `handler` VARCHAR( 255 ) NULL AFTER `handle`;'); } - - if(!array_key_exists('execute_at', $columns)) { + + if (!array_key_exists('execute_at', $columns)) { $this->di['db']->exec('ALTER TABLE `queue_message` ADD `execute_at` VARCHAR( 255 ) NULL AFTER `log`;'); } } - + public function getSearchQuery($data) { - $sql="SELECT * + $sql = 'SELECT * FROM queue - WHERE 1 "; - - $params = array(); - - $search = $this->di['array_get']($data, 'search', NULL); - $name = $this->di['array_get']($data, 'name', NULL); - $mod = $this->di['array_get']($data, 'mod', NULL); - - if($mod) { - $sql .= " AND mod = :mod "; + WHERE 1 '; + + $params = []; + + $search = $this->di['array_get']($data, 'search', null); + $name = $this->di['array_get']($data, 'name', null); + $mod = $this->di['array_get']($data, 'mod', null); + + if ($mod) { + $sql .= ' AND mod = :mod '; $params['mod'] = $mod; } - - if($name) { - $sql .= " AND name = :name "; + + if ($name) { + $sql .= ' AND name = :name '; $params['name'] = $name; } - - if($search) { - $sql .= " AND (name LIKE :search)"; + + if ($search) { + $sql .= ' AND (name LIKE :search)'; $params['search'] = '%'.$search.'%'; } - + $sql .= ' ORDER BY id DESC'; - return array($sql, $params); + + return [$sql, $params]; } public function toApiArray($row) { - if($row instanceof \RedBeanPHP\OODBBean) { + if ($row instanceof \RedBeanPHP\OODBBean) { $row = $row->export(); } - - $sql="SELECT COUNT(id) FROM queue_message WHERE queue_id = :id GROUP BY queue_id"; - $count = $this->di['db']->getCell($sql, array('id'=>$row['id'])); + + $sql = 'SELECT COUNT(id) FROM queue_message WHERE queue_id = :id GROUP BY queue_id'; + $count = $this->di['db']->getCell($sql, ['id' => $row['id']]); $row['messages_count'] = ($count) ? $count : 0; - + return $row; } - + public static function dummy($params) { throw new \Exception('Received params: '.var_export($params, 1)); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Redirect/Api/Admin.php b/src/bb-modules/Redirect/Api/Admin.php index 02273d411..740131c5b 100644 --- a/src/bb-modules/Redirect/Api/Admin.php +++ b/src/bb-modules/Redirect/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getRedirects(); } - + /** - * Get redirect by id - * + * Get redirect by id. + * * @param int $id - int - * + * * @return array */ public function get($data) { - $required = array( + $required = [ 'id' => 'Redirect ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $bean = $this->_getRedirect($data['id']); - return array( - 'id' => $bean->id, - 'path' => $bean->meta_key, - 'target' => $bean->meta_value, - ); + + return [ + 'id' => $bean->id, + 'path' => $bean->meta_key, + 'target' => $bean->meta_value, + ]; } - + /** - * Create new redirect - * - * @param string $path - redirect path + * Create new redirect. + * + * @param string $path - redirect path * @param string $target - redirect target - * + * * @return int redirect id */ public function create($data) { - $required = array( - 'path' => 'Redirect path not passed', + $required = [ + 'path' => 'Redirect path not passed', 'target' => 'Redirect target not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $bean = $this->di['db']->dispense('extension_meta'); $bean->extension = 'mod_redirect'; $bean->meta_key = trim(htmlspecialchars($data['path'], ENT_QUOTES | ENT_HTML5, 'UTF-8'), '/'); @@ -73,71 +73,75 @@ class Admin extends \Api_Abstract $bean->created_at = date('Y-m-d H:i:s'); $bean->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($bean); - + $id = $bean->id; - + $this->di['logger']->info('Created new redirect #%s', $id); - return (int)$id; + + return (int) $id; } - + /** - * Update redirect - * + * Update redirect. + * * @param int $id - redirect id - * + * * @optional string $path - redirect path * @optional string $target - redirect target - * + * * @return true */ public function update($data) { - $required = array( + $required = [ 'id' => 'Redirect ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $bean = $this->_getRedirect($data['id']); - + $bean->meta_key = trim(htmlspecialchars($this->di['array_get']($data, 'path', $bean->meta_key), ENT_QUOTES | ENT_HTML5, 'UTF-8'), '/'); $bean->meta_value = trim(htmlspecialchars($this->di['array_get']($data, 'target', $bean->meta_value), ENT_QUOTES | ENT_HTML5, 'UTF-8'), '/'); $bean->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($bean); - + $this->di['logger']->info('Updated redirect #%s', $data['id']); + return true; } - + /** - * Delete redirect - * + * Delete redirect. + * * @param int $id - redirect id + * * @return true */ public function delete($data) { - $required = array( + $required = [ 'id' => 'Redirect ID is required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $bean = $this->_getRedirect($data['id']); $this->di['db']->trash($bean); - + $this->di['logger']->info('Removed redirect #%s', $data['id']); + return true; } - + private function _getRedirect($id) { $sql = " extension = 'mod_redirect' AND id = :id"; - $values = array('id'=>$id); - $bean = $this->di['db']->findOne('extension_meta',$sql, $values); - - if(!$bean) { + $values = ['id' => $id]; + $bean = $this->di['db']->findOne('extension_meta', $sql, $values); + + if (!$bean) { throw new \Box_Exception('Redirect not found'); } - + return $bean; } } diff --git a/src/bb-modules/Redirect/Controller/Client.php b/src/bb-modules/Redirect/Controller/Client.php index cb895d9c6..c3e488564 100644 --- a/src/bb-modules/Redirect/Controller/Client.php +++ b/src/bb-modules/Redirect/Controller/Client.php @@ -1,6 +1,6 @@ get('/me', 'get_profile', array(), '\Box\Mod\Client\Controller\Client'); - $app->get('/balance', 'get_balance', array(), '\Box\Mod\Client\Controller\Client'); - $app->get('/reset-password-confirm/:hash', 'get_reset_password_confirm', array('hash'=>'[a-z0-9]+'), '\Box\Mod\Client\Controller\Client'); - $app->get('/emails', 'get_emails', array(), '\Box\Mod\Email\Controller\Client'); - $app->get('/banklink/:hash/:id', 'get_banklink', array('id'=>'[0-9]+', 'hash'=>'[a-z0-9]+'), '\Box\Mod\Invoice\Controller\Client'); - $app->get('/blog', 'get_news', array(), '\Box\Mod\News\Controller\Client'); - $app->get('/blog/:slug', 'get_news_item', array('slug' => '[a-z0-9-]+'), '\Box\Mod\News\Controller\Client'); - $app->get('/service', 'get_orders', array(), '\Box\Mod\Order\Controller\Client'); - $app->get('/service/manage/:id', 'get_order', array('id'=>'[0-9]+'), '\Box\Mod\Order\Controller\Client'); - $app->get('/contact-us', 'get_contact_us', array(), '\Box\Mod\Support\Controller\Client'); - $app->get('/contact-us/conversation/:hash', 'get_contact_us_conversation', array('hash'=>'[a-z0-9]+'), '\Box\Mod\Support\Controller\Client'); - + $app->get('/me', 'get_profile', [], '\Box\Mod\Client\Controller\Client'); + $app->get('/balance', 'get_balance', [], '\Box\Mod\Client\Controller\Client'); + $app->get('/reset-password-confirm/:hash', 'get_reset_password_confirm', ['hash' => '[a-z0-9]+'], '\Box\Mod\Client\Controller\Client'); + $app->get('/emails', 'get_emails', [], '\Box\Mod\Email\Controller\Client'); + $app->get('/banklink/:hash/:id', 'get_banklink', ['id' => '[0-9]+', 'hash' => '[a-z0-9]+'], '\Box\Mod\Invoice\Controller\Client'); + $app->get('/blog', 'get_news', [], '\Box\Mod\News\Controller\Client'); + $app->get('/blog/:slug', 'get_news_item', ['slug' => '[a-z0-9-]+'], '\Box\Mod\News\Controller\Client'); + $app->get('/service', 'get_orders', [], '\Box\Mod\Order\Controller\Client'); + $app->get('/service/manage/:id', 'get_order', ['id' => '[0-9]+'], '\Box\Mod\Order\Controller\Client'); + $app->get('/contact-us', 'get_contact_us', [], '\Box\Mod\Support\Controller\Client'); + $app->get('/contact-us/conversation/:hash', 'get_contact_us_conversation', ['hash' => '[a-z0-9]+'], '\Box\Mod\Support\Controller\Client'); + $service = $this->di['mod_service']('redirect'); $redirects = $service->getRedirects(); - foreach($redirects as $redirect) { - $app->get('/'.$redirect['path'], 'do_redirect', array(), get_class($this)); + foreach ($redirects as $redirect) { + $app->get('/'.$redirect['path'], 'do_redirect', [], get_class($this)); } } @@ -57,8 +57,8 @@ class Client implements \Box\InjectionAwareInterface { $service = $this->di['mod_service']('redirect'); $target = $service->getRedirectByPath($app->uri); - Header( "HTTP/1.1 301 Moved Permanently" ); - Header( "Location: ".$target ); + header('HTTP/1.1 301 Moved Permanently'); + header('Location: '.$target); exit; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Redirect/Service.php b/src/bb-modules/Redirect/Service.php index 2a348316f..31628c318 100644 --- a/src/bb-modules/Redirect/Service.php +++ b/src/bb-modules/Redirect/Service.php @@ -1,6 +1,6 @@ di['db']->getAll($sql); } - public function getRedirectByPath($path){ - $sql=' + public function getRedirectByPath($path) + { + $sql = ' SELECT meta_value FROM extension_meta WHERE extension = "mod_redirect" AND meta_key = :path LIMIT 1 '; - return $this->di['db']->getCell($sql, array('path'=>$path)); + + return $this->di['db']->getCell($sql, ['path' => $path]); } } diff --git a/src/bb-modules/Seo/Service.php b/src/bb-modules/Seo/Service.php index ab6aa9737..54e25d7eb 100644 --- a/src/bb-modules/Seo/Service.php +++ b/src/bb-modules/Seo/Service.php @@ -1,6 +1,6 @@ di['mod_service']('system'); - $key = 'mod_seo_last_sitemap_submit'; + $key = 'mod_seo_last_sitemap_submit'; $last_time = $systemService->getParamValue($key); if ($last_time && (time() - strtotime($last_time)) < 86400) { return false; } - $url = urldecode(BB_URL . 'sitemap.xml'); + $url = urldecode(BB_URL.'sitemap.xml'); if (isset($config['sitemap_google']) && $config['sitemap_google']) { - try{ - $link = "http://www.google.com/ping?sitemap=" . $url; - $this->di['guzzle_client']->get($link); - error_log('Submitted sitemap to Google'); - }catch (\Exception $e){ - error_log('Exception :('); - } + try { + $link = 'http://www.google.com/ping?sitemap='.$url; + $this->di['guzzle_client']->get($link); + error_log('Submitted sitemap to Google'); + } catch (\Exception $e) { + error_log('Exception :('); + } } if (isset($config['sitemap_bing']) && $config['sitemap_bing']) { - $link = "http://www.bing.com/ping?sitemap=" . $url; + $link = 'http://www.bing.com/ping?sitemap='.$url; $this->di['guzzle_client']->get($link); error_log('Submitted sitemap to Bing'); } - $systemService->updateParams(array($key => date('Y-m-d H:i:s'))); + $systemService->updateParams([$key => date('Y-m-d H:i:s')]); return true; } public function pingRss($config) { - //@todo + // @todo return false; - $rss = ''; - $title = ''; + $rss = ''; + $title = ''; $homepage = BB_URL; - $rss = urldecode($rss); - $title = urldecode($title); + $rss = urldecode($rss); + $title = urldecode($title); $homepage = urldecode($homepage); - $fp = @fopen("http://rpc.weblogs.com/pingSiteForm?name=$title&url=" . $rss, "r"); + $fp = @fopen("http://rpc.weblogs.com/pingSiteForm?name=$title&url=".$rss, 'r'); @fclose($fp); - $fp = @fopen("http://pingomatic.com/ping/?title=$title&blogurl=$homepage&rssurl=" . $rss . "&chk_weblogscom=on&chk_blogs=on&chk_feedburner=on&chk_syndic8=on&chk_newsgator=on&chk_myyahoo=on&chk_pubsubcom=on&chk_blogdigger=on&chk_blogstreet=on&chk_moreover=on&chk_weblogalot=on&chk_icerocket=on&chk_newsisfree=on&chk_topicexchange=on&chk_google=on&chk_tailrank=on&chk_postrank=on&chk_skygrid=on&chk_collecta=on&chk_superfeedr=on&chk_audioweblogs=on&chk_rubhub=on&chk_geourl=on&chk_a2b=on&chk_blogshares=on", "r"); + $fp = @fopen("http://pingomatic.com/ping/?title=$title&blogurl=$homepage&rssurl=".$rss.'&chk_weblogscom=on&chk_blogs=on&chk_feedburner=on&chk_syndic8=on&chk_newsgator=on&chk_myyahoo=on&chk_pubsubcom=on&chk_blogdigger=on&chk_blogstreet=on&chk_moreover=on&chk_weblogalot=on&chk_icerocket=on&chk_newsisfree=on&chk_topicexchange=on&chk_google=on&chk_tailrank=on&chk_postrank=on&chk_skygrid=on&chk_collecta=on&chk_superfeedr=on&chk_audioweblogs=on&chk_rubhub=on&chk_geourl=on&chk_a2b=on&chk_blogshares=on', 'r'); @fclose($fp); return true; @@ -92,12 +92,12 @@ class Service implements InjectionAwareInterface { $di = $event->getDi(); $extensionService = $di['mod_service']('extension'); - $config = $extensionService->getConfig("mod_seo"); + $config = $extensionService->getConfig('mod_seo'); try { $seoService = $di['mod_service']('seo'); $seoService->setDi($di); - $seoService->pingSitemap( $config); + $seoService->pingSitemap($config); $seoService->pingRss($config); } catch (\Exception $e) { error_log($e->getMessage()); @@ -105,4 +105,4 @@ class Service implements InjectionAwareInterface return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicecentovacast/Api/Admin.php b/src/bb-modules/Servicecentovacast/Api/Admin.php index 48a03c9d8..ae1614170 100644 --- a/src/bb-modules/Servicecentovacast/Api/Admin.php +++ b/src/bb-modules/Servicecentovacast/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getServers(); } - + /** - * Get server pairs - * + * Get server pairs. + * * @return array */ public function server_pairs() { $servers = $this->getService()->getServers(); - $result = array(); - foreach($servers as $server) { + $result = []; + foreach ($servers as $server) { $result[$server['id']] = $server['hostname']; } + return $result; } - + /** - * Add new centovacast server - * + * Add new centovacast server. + * * @param type $data - * @return int - server id + * + * @return int - server id */ public function server_add($data) { @@ -57,190 +59,207 @@ class Admin extends \Api_Abstract $bean->created_at = date('Y-m-d H:i:s'); $bean->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($bean); - + $this->di['logger']->info('Added new CentovaCast server %s', $bean->id); + return $bean->id; } - + /** - * Get server - * + * Get server. + * * @param int $id - server id + * * @return type - * @throws Exception + * + * @throws Exception */ public function server_get($data) { - if(!isset($data['id'])) { + if (!isset($data['id'])) { throw new \Exception('Server id not passed'); } + return $this->getService()->getServer($data['id']); } - + /** - * Update server - * + * Update server. + * * @param int $id - server id + * * @return bool - * @throws Exception + * + * @throws Exception */ public function server_update($data) { $server = $this->server_get($data); - $bean = $this->di['db']->findOne('extension_meta', 'id = :id', array('id'=>$server['id'])); + $bean = $this->di['db']->findOne('extension_meta', 'id = :id', ['id' => $server['id']]); $bean->meta_value = json_encode($data); $bean->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($bean); - + $this->di['logger']->info('Updated CentovaCast server %s', $server['id']); + return true; } - + /** - * Remove server - * + * Remove server. + * * @param int $id - server id + * * @return type - * @throws Exception + * + * @throws Exception */ public function server_delete($data) { $server = $this->server_get($data); - - $sql="SELECT id FROM service_centovacast WHERE server_id = :sid LIMIT 1"; - $exists = $this->di['db']->getCell($sql, array('sid'=>$server['id'])); - if($exists) { + + $sql = 'SELECT id FROM service_centovacast WHERE server_id = :sid LIMIT 1'; + $exists = $this->di['db']->getCell($sql, ['sid' => $server['id']]); + if ($exists) { throw new \Exception('Server is used for active order. It can not be removed.'); } - - $sql="DELETE FROM extension_meta WHERE id = :id"; - $this->di['db']->exec($sql, array('id'=>$server['id'])); + + $sql = 'DELETE FROM extension_meta WHERE id = :id'; + $this->di['db']->exec($sql, ['id' => $server['id']]); $this->di['logger']->info('Removed CentovaCast server %s', $server['id']); + return true; } - + /** - * Test connection to server - * + * Test connection to server. + * * @param int $id - server id - * @return boolean - * @throws Exception + * + * @return bool + * + * @throws Exception */ public function server_connection($data) { $server = $this->server_get($data); + return $this->getService()->apiConnection($server); } - + /** - * Update existing order service - * - * @return boolean + * Update existing order service. + * + * @return bool */ public function update($data) { - list($order, $s) = $this->_getService($data); - + [$order, $s] = $this->_getService($data); + $s->username = $this->di['array_get']($data, 'username', $s->username); - if(isset($data['pass'])) { + if (isset($data['pass'])) { $s->pass = $this->getService()->encryptPass($data['pass']); } - + $s->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($s); - + $this->di['logger']->info('Updated CentovaCast service %s details', $s->id); + return true; } - + /** - * Retrieves the configuration for a CentovaCast client account. - * If server-side streaming source support is enabled, + * Retrieves the configuration for a CentovaCast client account. + * If server-side streaming source support is enabled, * the configuration for the streaming source is returned as well. - * + * * @param int $order_id - order id * @optional bool $try - do not throw an exception, return error message as a result - * + * * @return array */ public function getaccount($data) { try { - list($order, $model) = $this->_getService($data); + [$order, $model] = $this->_getService($data); $result = $this->getService()->getaccount($model); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); - $result = array(); - if(!isset($data['try']) || !$data['try']) { + $result = []; + if (!isset($data['try']) || !$data['try']) { throw $e; } } - + return $result; } - - /** - * Returns the state (up or down) of one or more CentovaCast streaming - * server accounts. This can be used to monitor streams to see if any - * have crashed. (Note that CentovaCast's cron job automatically monitors - * and restarts crashed streaming servers as well.) + /** + * Returns the state (up or down) of one or more CentovaCast streaming + * server accounts. This can be used to monitor streams to see if any + * have crashed. (Note that CentovaCast's cron job automatically monitors + * and restarts crashed streaming servers as well.). + * * @param int $order_id - order id * @optional bool $try - do not throw an exception, return error message as a result - * - * @return boolean + * + * @return bool */ public function info($data) { - list($order, $model) = $this->_getService($data); - + [$order, $model] = $this->_getService($data); + try { $result = $this->getService()->info($model); - } catch(\Exception $e) { + } catch (\Exception $e) { $result = $e->getMessage(); - if(!isset($data['try']) || !$data['try']) { + if (!isset($data['try']) || !$data['try']) { throw $e; } } - + return $result; } - + /** - * Updates the settings for an existing client streaming server + * Updates the settings for an existing client streaming server * account in CentovaCast. - * + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function reconfigure($data) { - list($order, $model) = $this->_getService($data); + [$order, $model] = $this->_getService($data); + return $this->getService()->reconfigure($model, $data); } - + private function _getService($data) { - if(!isset($data['order_id'])) { + if (!isset($data['order_id'])) { throw new \Box_Exception('Order id is required'); } - + $order = $this->di['db']->findOne('client_order', "id=:id AND service_type = 'centovacast' - ", - array('id'=>$data['order_id'])); - - if(!$order) { + ", + ['id' => $data['order_id']]); + + if (!$order) { throw new \Box_Exception('Centova Cast order not found'); } - + $s = $this->di['db']->findOne('service_centovacast', 'id=:id', - array('id'=>$order->service_id)); - if(!$s) { - throw new \Box_Exception('Order :id is not activated', array(':id'=>$order->id)); + ['id' => $order->service_id]); + if (!$s) { + throw new \Box_Exception('Order :id is not activated', [':id' => $order->id]); } - return array($order, $s); + + return [$order, $s]; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicecentovacast/Api/Client.php b/src/bb-modules/Servicecentovacast/Api/Client.php index d7826f279..6189bb02e 100644 --- a/src/bb-modules/Servicecentovacast/Api/Client.php +++ b/src/bb-modules/Servicecentovacast/Api/Client.php @@ -1,6 +1,6 @@ di['db']->findOne('client_order', "id=:id AND client_id = :cid AND service_type = 'centovacast' - ", - array('id'=>$data['order_id'], 'cid'=>$this->getIdentity()->id)); - - if(!$order) { + ", + ['id' => $data['order_id'], 'cid' => $this->getIdentity()->id]); + + if (!$order) { throw new \Box_Exception('Centova Cast order not found'); } - + $s = $this->di['db']->findOne('service_centovacast', 'id=:id AND client_id = :cid', - array('id'=>$order->service_id, 'cid'=>$this->getIdentity()->id)); - if(!$s) { - throw new \Box_Exception('Order :id is not activated', array(':id'=>$order->id)); + ['id' => $order->service_id, 'cid' => $this->getIdentity()->id]); + if (!$s) { + throw new \Box_Exception('Order :id is not activated', [':id' => $order->id]); } - return array($order, $s); + + return [$order, $s]; } - + /** - * Return control panel url for order - * + * Return control panel url for order. + * * @param int $order_id - order id + * * @return string */ public function control_panel_url($data) { try { - list($order, $model) = $this->_getService($data); + [$order, $model] = $this->_getService($data); $result = $this->getService()->cpanelUrl($model); - } catch(\Exception $e) { + } catch (\Exception $e) { $result = $e->getMessage(); - if(!isset($data['try']) || !$data['try']) { + if (!isset($data['try']) || !$data['try']) { throw $e; } } + return $result; } - + /** - * Starts a streaming server for a CentovaCast client account. - * If server-side streaming source support is enabled, + * Starts a streaming server for a CentovaCast client account. + * If server-side streaming source support is enabled, * the streaming source is started as well. - * + * * @param int $order_id - order id - * @return boolean + * + * @return bool */ public function start($data) { - list($order, $model) = $this->_getService($data); + [$order, $model] = $this->_getService($data); $this->getService()->start($model); $this->di['logger']->info('Started server %s', $order->id); + return true; } - + /** - * Stops a streaming server for a CentovaCast client account. - * If server-side streaming source support is enabled, + * Stops a streaming server for a CentovaCast client account. + * If server-side streaming source support is enabled, * the streaming source is stopped as well. - * + * * @param int $order_id - order id - * @return boolean + * + * @return bool */ public function stop($data) { - list($order, $model) = $this->_getService($data); + [$order, $model] = $this->_getService($data); $this->getService()->stop($model); $this->di['logger']->info('Stoped server %s', $order->id); + return true; } - + /** * Stops, then re-starts a streaming server for a CentovaCast client account. - * If server-side streaming source support is enabled, the streaming + * If server-side streaming source support is enabled, the streaming * source is restarted as well. - * + * * @param int $order_id - order id - * @return boolean + * + * @return bool */ public function restart($data) { - list($order, $model) = $this->_getService($data); + [$order, $model] = $this->_getService($data); $this->getService()->restart($model); $this->di['logger']->info('Restarted server %s', $order->id); + return true; } - + /** - * Reloads the streaming server configuration for a CentovaCast client account. - * If server-side streaming source support is enabled, - * the configuration and playlist for the streaming source + * Reloads the streaming server configuration for a CentovaCast client account. + * If server-side streaming source support is enabled, + * the configuration and playlist for the streaming source * is reloaded as well. - * + * * @param int $order_id - order id - * @return boolean + * + * @return bool */ public function reload($data) { - list($order, $model) = $this->_getService($data); + [$order, $model] = $this->_getService($data); $this->getService()->reload($model); $this->di['logger']->info('Reloaded server %s', $order->id); + return true; } - + /** - * Retrieves the configuration for a CentovaCast client account. - * If server-side streaming source support is enabled, + * Retrieves the configuration for a CentovaCast client account. + * If server-side streaming source support is enabled, * the configuration for the streaming source is returned as well. - * + * * @param int $order_id - order id * @optional bool $try - do not throw an exception, return error message as a result - * - * @return boolean + * + * @return bool */ public function getaccount($data) { - list($order, $model) = $this->_getService($data); - + [$order, $model] = $this->_getService($data); + try { $result = $this->getService()->getaccount($model); - } catch(\Exception $e) { + } catch (\Exception $e) { $result = $e->getMessage(); - if(!isset($data['try']) || !$data['try']) { + if (!isset($data['try']) || !$data['try']) { throw $e; } } - + return $result; } - + /** - * Retrieves status information from the streaming server for a + * Retrieves status information from the streaming server for a * CentovaCast client account. - * + * * @param int $order_id - order id * @optional bool $try - do not throw an exception, return error message as a result - * - * @return boolean + * + * @return bool */ public function getstatus($data) { - list($order, $model) = $this->_getService($data); - + [$order, $model] = $this->_getService($data); + try { $result = $this->getService()->getstatus($model); - } catch(\Exception $e) { + } catch (\Exception $e) { $result = $e->getMessage(); - if(!isset($data['try']) || !$data['try']) { + if (!isset($data['try']) || !$data['try']) { throw $e; } } - + return $result; } - + /** - * Retrieves a list of tracks that were recently broadcasted on a + * Retrieves a list of tracks that were recently broadcasted on a * given CentovaCast client's streaming server. - * + * * @param int $order_id - order id * @optional bool $try - do not throw an exception, return error message as a result - * - * @return boolean + * + * @return bool */ public function getsongs($data) { - list($order, $model) = $this->_getService($data); - + [$order, $model] = $this->_getService($data); + try { $result = $this->getService()->getsongs($model); - } catch(\Exception $e) { + } catch (\Exception $e) { $result = $e->getMessage(); - if(!isset($data['try']) || !$data['try']) { + if (!isset($data['try']) || !$data['try']) { throw $e; } } - + return $result; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicecentovacast/Service.php b/src/bb-modules/Servicecentovacast/Service.php index 375a8d35b..e1f33ac42 100644 --- a/src/bb-modules/Servicecentovacast/Service.php +++ b/src/bb-modules/Servicecentovacast/Service.php @@ -1,6 +1,6 @@ di; } - + public function install() { - $sql=" + $sql = ' CREATE TABLE IF NOT EXISTS `service_centovacast` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `client_id` bigint(20) DEFAULT NULL, @@ -43,338 +43,364 @@ class Service implements \Box\InjectionAwareInterface UNIQUE KEY `username` (`username`), KEY `client_id_idx` (`client_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; - "; + '; $this->di['db']->exec($sql); } - + public function toApiArray($row) { - if($row instanceof \RedBeanPHP\OODBBean) { + if ($row instanceof \RedBeanPHP\OODBBean) { $row = $row->export(); } - + $row['pass'] = $this->di['crypt']->decrypt($row['pass'], $this->_salt); + return $row; } - + public function getServers() { - $sql="SELECT id, meta_value + $sql = "SELECT id, meta_value FROM extension_meta WHERE extension = 'mod_servicecentovacast' AND meta_key = 'server' ORDER BY id DESC "; $result = $this->di['db']->getAll($sql); - $servers = array(); - foreach($result as $s) { - $d = array(); + $servers = []; + foreach ($result as $s) { + $d = []; $d['id'] = $s['id']; $d = array_merge($d, json_decode($s['meta_value'], 1)); $servers[$s['id']] = $d; } + return $servers; } - + public function getServer($id) { $servers = $this->getServers(); - if(!isset($servers[$id])) { + if (!isset($servers[$id])) { throw new \Exception('Centova Cast Server not found'); } - - if(APPLICATION_ENV == 'testing') { - $config = array(); - $config['url'] = 'http://castdemo.centova.com:2199'; - $config['secret'] = 'example'; - $config['ip'] = '123.123.123.123'; + + if (APPLICATION_ENV == 'testing') { + $config = []; + $config['url'] = 'http://castdemo.centova.com:2199'; + $config['secret'] = 'example'; + $config['ip'] = '123.123.123.123'; $config['hostname'] = 'castdemo.centova.com'; + return $config; } - + return $servers[$id]; } - + /** * @param $order + * * @return \RedBeanPHP\OODBBean */ public function create($order) { $model = $this->di['db']->dispense('service_centovacast'); - $model->client_id = $order->client_id; - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); + $model->client_id = $order->client_id; + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return $model; } /** * @param $order + * * @return array + * * @see http://www.centova.com/docs/cast/centovacast_xml_api.php?manual=1 */ public function activate($order, $model) { - if(!is_object($model)) { + if (!is_object($model)) { throw new \Box_Exception('Could not activate order. Service was not created', null, 7456); } - + $oc = json_decode($order->config, 1); - + $api = $this->di['api_admin']; - $client = $api->client_get(array('id'=>$order->client_id)); - $product = $api->product_get(array('id'=>$order->product_id)); + $client = $api->client_get(['id' => $order->client_id]); + $product = $api->product_get(['id' => $order->product_id]); $pc = $product['config']; - $required = array( - 'server_id' => 'CentovaCast product is not configured properly. Field server_id is missing', - 'maxclients' => 'CentovaCast product is not configured properly. Field maxclients is missing', - 'maxbitrate' => 'CentovaCast product is not configured properly. Field maxbitrate is missing', + $required = [ + 'server_id' => 'CentovaCast product is not configured properly. Field server_id is missing', + 'maxclients' => 'CentovaCast product is not configured properly. Field maxclients is missing', + 'maxbitrate' => 'CentovaCast product is not configured properly. Field maxbitrate is missing', 'transferlimit' => 'CentovaCast product is not configured properly. Field transferlimit is missing', - 'diskquota' => 'CentovaCast product is not configured properly. Field diskquota is missing', - 'template' => 'CentovaCast product is not configured properly. Field template is missing', - 'autostart' => 'CentovaCast product is not configured properly. Field autostart is missing', - ); + 'diskquota' => 'CentovaCast product is not configured properly. Field diskquota is missing', + 'template' => 'CentovaCast product is not configured properly. Field template is missing', + 'autostart' => 'CentovaCast product is not configured properly. Field autostart is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $pc); - - $server = $this->getServer($pc['server_id']); - $username = ( isset($oc['username']) && !empty($oc['username']) ) ? $oc['username'] : $this->_genUsername($client); - $password = ( isset($oc['password']) && !empty($oc['password']) ) ? $oc['password'] : $this->di['tools']->generatePassword(); + + $server = $this->getServer($pc['server_id']); + $username = (isset($oc['username']) && !empty($oc['username'])) ? $oc['username'] : $this->_genUsername($client); + $password = (isset($oc['password']) && !empty($oc['password'])) ? $oc['password'] : $this->di['tools']->generatePassword(); $sourcepassword = $this->di['tools']->generatePassword(); - - $params = array( - 'hostname' => $server['hostname'], - 'ipaddress' => $server['ip'], - 'port' => 'auto', - 'maxclients' => $pc['maxclients'], - 'username' => $username, - 'adminpassword' => $password, - 'sourcepassword' => $sourcepassword, - 'maxbitrate' => $pc['maxbitrate'], - 'transferlimit' => $pc['transferlimit'], - 'diskquota' => $pc['diskquota'], - 'title' => $client['company'], - 'organization' => $client['company'], - 'genre' => $client['company'], - 'email' => $client['email'], - 'url' => BB_URL, - 'usesource' => '1', - 'introfile' => '', - 'fallbackfile' => '', - 'autorebuildlist' => '0', - 'autostart' => (bool)$pc['autostart'], - 'timezone' => 'auto', - 'allowproxy' => '0', - 'charset' => 'ISO-8859-1', - 'servertype' => $pc['servertype'], - 'sourcetype' => $pc['sourcetype'], - 'template' => $pc['template'], - ); - + + $params = [ + 'hostname' => $server['hostname'], + 'ipaddress' => $server['ip'], + 'port' => 'auto', + 'maxclients' => $pc['maxclients'], + 'username' => $username, + 'adminpassword' => $password, + 'sourcepassword' => $sourcepassword, + 'maxbitrate' => $pc['maxbitrate'], + 'transferlimit' => $pc['transferlimit'], + 'diskquota' => $pc['diskquota'], + 'title' => $client['company'], + 'organization' => $client['company'], + 'genre' => $client['company'], + 'email' => $client['email'], + 'url' => BB_URL, + 'usesource' => '1', + 'introfile' => '', + 'fallbackfile' => '', + 'autorebuildlist' => '0', + 'autostart' => (bool) $pc['autostart'], + 'timezone' => 'auto', + 'allowproxy' => '0', + 'charset' => 'ISO-8859-1', + 'servertype' => $pc['servertype'], + 'sourcetype' => $pc['sourcetype'], + 'template' => $pc['template'], + ]; + // call api if not import action - if(!isset($oc['import']) || !$oc['import']) { + if (!isset($oc['import']) || !$oc['import']) { $this->_apiSystemCall($server, 'provision', $params); } - - $model->server_id = $pc['server_id']; - $model->username = $username; - $model->pass = $this->encryptPass($password); - $model->updated_at = date('Y-m-d H:i:s'); + + $model->server_id = $pc['server_id']; + $model->username = $username; + $model->pass = $this->encryptPass($password); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); - - return array_merge($params, array('server'=>$server)); + + return array_merge($params, ['server' => $server]); } private function _genUsername($client) { $u = preg_replace('/([^@]*).*/', '$1', $client['email']); - $u = str_replace('.', "", $u); - $sql="SELECT id FROM service_centovacast WHERE username = :u"; - $exists = $this->di['db']->getCell($sql, array('u'=>$u)); - if($exists) { - $u = $u. rand(1, 100); + $u = str_replace('.', '', $u); + $sql = 'SELECT id FROM service_centovacast WHERE username = :u'; + $exists = $this->di['db']->getCell($sql, ['u' => $u]); + if ($exists) { + $u = $u.rand(1, 100); } + return $u; } - + /** - * Suspend order - * + * Suspend order. + * * @param $order - * @return boolean + * + * @return bool */ public function suspend($order, $model) { - if(!is_object($model)) { + if (!is_object($model)) { throw new \Box_Exception('Could not suspend order. Service was not created', null, 7456); } $server = $this->getServer($model->server_id); - $params = array( - 'username' => $model->username, - 'status' => 'disabled', - ); + $params = [ + 'username' => $model->username, + 'status' => 'disabled', + ]; $this->_apiSystemCall($server, 'setstatus', $params); - + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return true; } /** * @param $order - * @return boolean + * + * @return bool */ public function unsuspend($order, $model) { - if(!is_object($model)) { + if (!is_object($model)) { throw new \Box_Exception('Could not unsuspend order. Service was not created', null, 7456); } - + $server = $this->getServer($model->server_id); - $params = array( - 'username' => $model->username, - 'status' => 'enabled', - ); + $params = [ + 'username' => $model->username, + 'status' => 'enabled', + ]; $this->_apiSystemCall($server, 'setstatus', $params); - + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return true; } /** * @param $order - * @return boolean + * + * @return bool */ public function cancel($order, $model) { return $this->suspend($order, $model); } - + /** * @param $order - * @return boolean + * + * @return bool */ public function uncancel($order, $model) { return $this->unsuspend($order, $model); } - + /** * @param $order - * @return boolean + * + * @return bool */ public function delete($order, $model) { - if(is_object($model)) { + if (is_object($model)) { try { $server = $this->getServer($model->server_id); - $params = array( - 'username' => $model->username, - ); + $params = [ + 'username' => $model->username, + ]; $this->_apiSystemCall($server, 'terminate', $params); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); } - + $this->di['db']->trash($model); } + return true; } - + public function start($model) { $this->_apiServerCall($model, 'start'); + return true; } - + public function stop($model) { $this->_apiServerCall($model, 'stop'); + return true; } - + public function restart($model) { $this->_apiServerCall($model, 'restart'); + return true; } - + public function reload($model) { $this->_apiServerCall($model, 'reload'); + return true; } - + public function getaccount($model) { $res = $this->_apiServerCall($model, 'getaccount'); + return $res['account']; } - + public function getstatus($model) { $res = $this->_apiServerCall($model, 'getstatus'); + return $res['status']; } - + public function getsongs($model) { $res = $this->_apiServerCall($model, 'getsongs'); - return isset($res['songs']['row']) ? $res['songs']['row'] : array(); + + return $res['songs']['row'] ?? []; } - + public function reconfigure($model, $params) { return $this->_apiServerCall($model, 'reconfigure', $params, true); } - + public function info($model) { $server = $this->getServer($model->server_id); - $params = array( - 'username' => $model->username, - ); - $res = $this->_apiSystemCall($server, 'info', $params); + $params = [ + 'username' => $model->username, + ]; + $res = $this->_apiSystemCall($server, 'info', $params); + return $res['row']; } - + public function version($server) { - return $this->_apiSystemCall($server, 'version'); + return $this->_apiSystemCall($server, 'version'); } - + public function apiConnection($server) { - $params = array( - 'username' => 'all', - ); - return $this->_apiSystemCall($server, 'info', $params); + $params = [ + 'username' => 'all', + ]; + + return $this->_apiSystemCall($server, 'info', $params); } - + public function cpanelUrl($model) { $server = $this->getServer($model->server_id); + return $server['url']; } - + /** * @param string $method */ - private function _apiServerCall($model, $method, $arguments = array(), $admin = false) + private function _apiServerCall($model, $method, $arguments = [], $admin = false) { $account_username = $model->username; $account_password = $this->di['crypt']->decrypt($model->pass, $this->_salt); - $server = $this->getServer($model->server_id); - - $centovacast_url = $server['url']; - - if($admin) { + $server = $this->getServer($model->server_id); + + $centovacast_url = $server['url']; + + if ($admin) { $account_password = 'admin|'.$server['secret']; } - - require_once(dirname(__FILE__).'/ccapiclient/ccapiclient.php'); + + require_once dirname(__FILE__).'/ccapiclient/ccapiclient.php'; $server = new CCServerAPIClient($centovacast_url); $server->cc_initialize($centovacast_url); $server->call($method, $account_username, $account_password, $arguments); @@ -382,29 +408,29 @@ class Service implements \Box\InjectionAwareInterface if (!$server->success) { throw new \Exception($server->error); } - + return $server->bb_data; } - + /** * @param string $method */ - private function _apiSystemCall($server, $method, $params = array()) + private function _apiSystemCall($server, $method, $params = []) { - require_once(dirname(__FILE__).'/ccapiclient.php'); - $centovacast_url = $server['url']; - $admin_password = $server['secret']; + require_once dirname(__FILE__).'/ccapiclient.php'; + $centovacast_url = $server['url']; + $admin_password = $server['secret']; $system = new CCSystemAPIClient($centovacast_url); $system->cc_initialize($centovacast_url); $system->call($method, $admin_password, $params); - + if (!$system->success) { throw new \Exception($system->error); } - + return $system->bb_data; } - + public function encryptPass($password) { return $this->di['crypt']->encrypt($password, $this->_salt); diff --git a/src/bb-modules/Servicecentovacast/ccapiclient.php b/src/bb-modules/Servicecentovacast/ccapiclient.php index 7fb2897e0..50bd11589 100644 --- a/src/bb-modules/Servicecentovacast/ccapiclient.php +++ b/src/bb-modules/Servicecentovacast/ccapiclient.php @@ -12,307 +12,335 @@ * calls to what would be the public methods of each class. * */ + namespace Box\Mod\Servicecentovacast; -require_once(dirname(__FILE__) . '/class_HTTPRetriever.php'); +require_once dirname(__FILE__).'/class_HTTPRetriever.php'; // This library was originally designed to support object overloading, but // PHP's support for this appears to be flaky and prone to segfaulting // (particularly in 4.x) so it's disabled by default. -define('CCAPI_NO_OVERLOAD',true); +define('CCAPI_NO_OVERLOAD', true); /* CCBaseAPIClient * * Base class for all CentovaCast API classes */ -class CCBaseAPIClient { - - var $debug = false; - var $debugconsole = false; - var $encoding = 'UTF-8'; - - /** - * @param string $payload - */ - function build_request_packet($methodname,$payload) { - return sprintf( - 'encoding.'"?'.'>' . - '' . - '' . - '%s' . - '' . - '', - htmlentities($this->classname), - htmlentities($methodname), - ($this->debug ? ' debug="enabled"' : '') . - ($this->debugconsole ? ' debugconsole="'.htmlentities($this->debugconsole).'"' : ''), - $payload - ); - } - - function cc_initialize($ccurl) { - $this->ccurl = $ccurl; - $this->http = new HTTPRetriever(); - $this->http->HTTPRetriever(); - $this->http->headers["User-Agent"] = 'CentovaCast PHP API Client'; - } - - function build_argument_payload($functionargs) { - return $this->build_argument_xml($functionargs[0]); - } - - function build_argument_xml($args) { - $payload = ''; - foreach ($args as $name=>$value) { - $payload .= sprintf('<%s>%s',$name,htmlentities($value),$name); - } - - return $payload; - } - - function parse_data($data) { - if (!preg_match('/]*?>([\s\S]+)<\/data>/i',$data,$matches)) return false; - list(,$rowxml) = $matches; - - $rows = array(); - if (!preg_match_all('/]*?>([\s\S]*?)<\/row>/i',$rowxml,$rowmatches,PREG_SET_ORDER)) return $rows; +class CCBaseAPIClient +{ + public $debug = false; + public $debugconsole = false; + public $encoding = 'UTF-8'; - foreach ($rowmatches as $k=>$rowmatch) { - $fields = array(); - list(,$fieldxml) = $rowmatch; - - if (preg_match_all('/]*?>([\s\S]*?)<\/field>/i',$fieldxml,$fieldmatches,PREG_SET_ORDER)) { - foreach ($fieldmatches as $k=>$fieldmatch) { - list(,$fieldname,$fieldvalue) = $fieldmatch; - if (strlen($fieldname)) { - $fields[ $fieldname ] = $fieldvalue; - } else { - $fields[] = $fieldvalue; - } - } - } - - $rows[] = $fields; - - } + /** + * @param string $payload + */ + public function build_request_packet($methodname, $payload) + { + return sprintf( + 'encoding.'"?'.'>'. + ''. + ''. + '%s'. + ''. + '', + htmlentities($this->classname), + htmlentities($methodname), + ($this->debug ? ' debug="enabled"' : ''). + ($this->debugconsole ? ' debugconsole="'.htmlentities($this->debugconsole).'"' : ''), + $payload + ); + } - return $rows; - } - - function parse_response_packet($packet) { - $this->raw_response = $packet; - - if (!preg_match('/]+)>([\s\S]+)<\/centovacast>/i',$packet,$matches)) { - return $this->set_error('Invalid response packet received from API server'); - } - $cctags = $matches[1]; - if (preg_match('/version="([^\"]+)"/i',$cctags,$tagmatches)) { - $this->remote_version = $tagmatches[1]; - } else { - $this->remote_version = false; - } + public function cc_initialize($ccurl) + { + $this->ccurl = $ccurl; + $this->http = new HTTPRetriever(); + $this->http->HTTPRetriever(); + $this->http->headers['User-Agent'] = 'CentovaCast PHP API Client'; + } - list(,,$payload) = $matches; - if (!preg_match('/]*>([\s\S]+)<\/response>/i',$payload,$matches)) { - return $this->set_error('Empty or unrecognized response packet received from API server'); - } - - list(,$type,$data) = $matches; - if (preg_match('/]*>([\s\S]+)<\/message>/i',$data,$matches)) { - $this->message = $matches[1]; - } else { - $this->message = '(Message not provided by API server)'; - } - - switch(strtolower($type)) { - case 'error': - return $this->set_error($this->message); - case 'success': - $this->data = $this->parse_data($data); - $this->bb_data = $this->bb_data($packet); - $this->success = true; - - return; - default: - return $this->set_error('Invalid response type received from API server'); - } - } - - /** - * @param string $packet - */ - function api_request($packet) { - $url = $this->ccurl; - $apiscript = 'api.php'; - if (substr($url,-strlen($apiscript)-1)!='/'.$apiscript) { - if (substr($url,-1)!='/') $url .= '/'; - $url .= $apiscript; - } - - $this->success = false; - - $postdata = $packet; - if (!$this->http->post($url,$postdata)) { - $this->set_error('Error contacting server: '.$this->http->get_error()); - return; - } - - $this->parse_response_packet($this->http->response); - - $this->raw_request = $packet; - $this->raw_response = $this->http->raw_response; - } - - /** - * @param string $msg - */ - function set_error($msg) { - $this->success = false; - $this->error = $msg; - - return false; - } - - /* Overloaded method handler; simply passes the request to - * the _call() method. - * - */ - function __call($name,$args) { - return $this->_call($name,$args); - } - - /* For use when object overloading is not available. - * - * Usage: $obj->call('methodname',$arg1,$arg2,...) - */ - function call() { - $args = func_get_args(); - $name = array_shift($args); - $this->_call($name,$args); - - return true; - } - - - /* Private dispatch method for API calls. Used by __call() (for - * overloaded method calls) and call() (for direct calls). - * - */ - function _call($name,$args) { - $this->methodname = $name; - - $payload = $this->build_argument_payload($args); - $packet = $this->build_request_packet($name,$payload); + public function build_argument_payload($functionargs) + { + return $this->build_argument_xml($functionargs[0]); + } - $this->api_request($packet); - } - - function bb_data($packet) + public function build_argument_xml($args) + { + $payload = ''; + foreach ($args as $name => $value) { + $payload .= sprintf('<%s>%s', $name, htmlentities($value), $name); + } + + return $payload; + } + + public function parse_data($data) + { + if (!preg_match('/]*?>([\s\S]+)<\/data>/i', $data, $matches)) { + return false; + } + [, $rowxml] = $matches; + + $rows = []; + if (!preg_match_all('/]*?>([\s\S]*?)<\/row>/i', $rowxml, $rowmatches, PREG_SET_ORDER)) { + return $rows; + } + + foreach ($rowmatches as $k => $rowmatch) { + $fields = []; + [, $fieldxml] = $rowmatch; + + if (preg_match_all('/]*?>([\s\S]*?)<\/field>/i', $fieldxml, $fieldmatches, PREG_SET_ORDER)) { + foreach ($fieldmatches as $k => $fieldmatch) { + [, $fieldname, $fieldvalue] = $fieldmatch; + if (strlen($fieldname)) { + $fields[$fieldname] = $fieldvalue; + } else { + $fields[] = $fieldvalue; + } + } + } + + $rows[] = $fields; + } + + return $rows; + } + + public function parse_response_packet($packet) + { + $this->raw_response = $packet; + + if (!preg_match('/]+)>([\s\S]+)<\/centovacast>/i', $packet, $matches)) { + return $this->set_error('Invalid response packet received from API server'); + } + $cctags = $matches[1]; + if (preg_match('/version="([^\"]+)"/i', $cctags, $tagmatches)) { + $this->remote_version = $tagmatches[1]; + } else { + $this->remote_version = false; + } + + [, , $payload] = $matches; + if (!preg_match('/]*>([\s\S]+)<\/response>/i', $payload, $matches)) { + return $this->set_error('Empty or unrecognized response packet received from API server'); + } + + [, $type, $data] = $matches; + if (preg_match('/]*>([\s\S]+)<\/message>/i', $data, $matches)) { + $this->message = $matches[1]; + } else { + $this->message = '(Message not provided by API server)'; + } + + switch (strtolower($type)) { + case 'error': + return $this->set_error($this->message); + case 'success': + $this->data = $this->parse_data($data); + $this->bb_data = $this->bb_data($packet); + $this->success = true; + + return; + default: + return $this->set_error('Invalid response type received from API server'); + } + } + + /** + * @param string $packet + */ + public function api_request($packet) + { + $url = $this->ccurl; + $apiscript = 'api.php'; + if (substr($url, -strlen($apiscript) - 1) != '/'.$apiscript) { + if ('/' != substr($url, -1)) { + $url .= '/'; + } + $url .= $apiscript; + } + + $this->success = false; + + $postdata = $packet; + if (!$this->http->post($url, $postdata)) { + $this->set_error('Error contacting server: '.$this->http->get_error()); + + return; + } + + $this->parse_response_packet($this->http->response); + + $this->raw_request = $packet; + $this->raw_response = $this->http->raw_response; + } + + /** + * @param string $msg + */ + public function set_error($msg) + { + $this->success = false; + $this->error = $msg; + + return false; + } + + /* Overloaded method handler; simply passes the request to + * the _call() method. + * + */ + public function __call($name, $args) + { + return $this->_call($name, $args); + } + + /* For use when object overloading is not available. + * + * Usage: $obj->call('methodname',$arg1,$arg2,...) + */ + public function call() + { + $args = func_get_args(); + $name = array_shift($args); + $this->_call($name, $args); + + return true; + } + + /* Private dispatch method for API calls. Used by __call() (for + * overloaded method calls) and call() (for direct calls). + * + */ + public function _call($name, $args) + { + $this->methodname = $name; + + $payload = $this->build_argument_payload($args); + $packet = $this->build_request_packet($name, $payload); + + $this->api_request($packet); + } + + public function bb_data($packet) { $array = $this->xmlstr_to_array($packet); - - if(isset($array['response']['data'])) { + + if (isset($array['response']['data'])) { return $array['response']['data']; } - - if(isset($array['response']['@attributes']['type']) && $array['response']['@attributes']['type'] == 'success') { + + if (isset($array['response']['@attributes']['type']) && 'success' == $array['response']['@attributes']['type']) { return true; } - + return $array; } - + /** - * convert xml string to php array - useful to get a serializable value - * - * @param string $xmlstr - * @return array - * @author Adrien aka Gaarf - */ - function xmlstr_to_array($xmlstr) { + * convert xml string to php array - useful to get a serializable value. + * + * @param string $xmlstr + * + * @return array + * + * @author Adrien aka Gaarf + */ + public function xmlstr_to_array($xmlstr) + { $doc = new \DOMDocument(); $doc->loadXML($xmlstr); + return $this->domnode_to_array($doc->documentElement); } /** * @param DOMElement $node */ - function domnode_to_array($node) { - $output = array(); + public function domnode_to_array($node) + { + $output = []; switch ($node->nodeType) { case XML_CDATA_SECTION_NODE: case XML_TEXT_NODE: $output = trim($node->textContent); break; case XML_ELEMENT_NODE: - for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) { - $child = $node->childNodes->item($i); - $v = $this->domnode_to_array($child); - if(isset($child->tagName)) { - $t = $child->tagName; - if(!isset($output[$t])) { - $output[$t] = array(); - } - $output[$t][] = $v; - } - elseif($v) { - $output = (string) $v; - } - } - if(is_array($output)) { - if($node->attributes->length) { - $a = array(); - foreach($node->attributes as $attrName => $attrNode) { - $a[$attrName] = (string) $attrNode->value; - } - $output['@attributes'] = $a; - } - foreach ($output as $t => $v) { - if(is_array($v) && count($v)==1 && $t!='@attributes') { - $output[$t] = $v[0]; - } + for ($i = 0, $m = $node->childNodes->length; $i < $m; ++$i) { + $child = $node->childNodes->item($i); + $v = $this->domnode_to_array($child); + if (isset($child->tagName)) { + $t = $child->tagName; + if (!isset($output[$t])) { + $output[$t] = []; + } + $output[$t][] = $v; + } elseif ($v) { + $output = (string) $v; + } } + if (is_array($output)) { + if ($node->attributes->length) { + $a = []; + foreach ($node->attributes as $attrName => $attrNode) { + $a[$attrName] = (string) $attrNode->value; + } + $output['@attributes'] = $a; + } + foreach ($output as $t => $v) { + if (is_array($v) && 1 == count($v) && '@attributes' != $t) { + $output[$t] = $v[0]; + } + } } break; } - if(empty($output)) { - $output = NULL; + if (empty($output)) { + $output = null; } + return $output; } - } /* CCServerAPIClient * * Provides an interface to the Server class of the CentovaCast XML API. */ -class CCServerAPIClient extends CCBaseAPIClient { - var $classname = 'server'; - - function CCServerAPIClient($ccurl) { - $this->cc_initialize($ccurl); - } +class CCServerAPIClient extends CCBaseAPIClient +{ + public $classname = 'server'; - function build_argument_payload($functionargs) { - if (count($functionargs)<3) trigger_error(sprintf('Function %s requires a minimum of 3 arguments, %d given',$this->methodname,count($functionargs)),E_USER_WARNING); - - $username = $functionargs[0]; - $password = $functionargs[1]; - $arguments = $functionargs[2]; - if (!is_array($arguments)) $arguments = array(); - - $arguments = array_merge( - array( - 'username'=>$username, - 'password'=>$password - ), - $arguments - ); - - return $this->build_argument_xml($arguments); - } + public function CCServerAPIClient($ccurl) + { + $this->cc_initialize($ccurl); + } + + public function build_argument_payload($functionargs) + { + if (count($functionargs) < 3) { + trigger_error(sprintf('Function %s requires a minimum of 3 arguments, %d given', $this->methodname, count($functionargs)), E_USER_WARNING); + } + + $username = $functionargs[0]; + $password = $functionargs[1]; + $arguments = $functionargs[2]; + if (!is_array($arguments)) { + $arguments = []; + } + + $arguments = array_merge( + [ + 'username' => $username, + 'password' => $password, + ], + $arguments + ); + + return $this->build_argument_xml($arguments); + } } /* CCSystemAPIClient @@ -320,35 +348,41 @@ class CCServerAPIClient extends CCBaseAPIClient { * Provides an interface to the System class of the CentovaCast XML API. */ -class CCSystemAPIClient extends CCBaseAPIClient { - var $classname = 'system'; +class CCSystemAPIClient extends CCBaseAPIClient +{ + public $classname = 'system'; - function CCSystemAPIClient($ccurl) { - $this->cc_initialize($ccurl); - } + public function CCSystemAPIClient($ccurl) + { + $this->cc_initialize($ccurl); + } - function build_argument_payload($functionargs) { - if (count($functionargs)<2) trigger_error(sprintf('Function %s requires a minimum of 2 arguments, %d given',$this->methodname,count($functionargs)),E_USER_WARNING); - - $adminpassword = $functionargs[0]; - $arguments = $functionargs[1]; - if (!is_array($arguments)) $arguments = array(); - - $arguments = array_merge( - array('password'=>$adminpassword), - $arguments - ); - - return $this->build_argument_xml($arguments); - } + public function build_argument_payload($functionargs) + { + if (count($functionargs) < 2) { + trigger_error(sprintf('Function %s requires a minimum of 2 arguments, %d given', $this->methodname, count($functionargs)), E_USER_WARNING); + } + + $adminpassword = $functionargs[0]; + $arguments = $functionargs[1]; + if (!is_array($arguments)) { + $arguments = []; + } + + $arguments = array_merge( + ['password' => $adminpassword], + $arguments + ); + + return $this->build_argument_xml($arguments); + } } if (!defined('CCAPI_NO_OVERLOAD')) { - if ( function_exists('overload') ) { - overload('CCSystemAPIClient'); - overload('CCServerAPIClient'); - } elseif (version_compare(PHP_VERSION,'5.0.0','<')) { - die('The CentovaCast PHP API client requires that object overloading support is built into PHP.'); - } + if (function_exists('overload')) { + overload('CCSystemAPIClient'); + overload('CCServerAPIClient'); + } elseif (version_compare(PHP_VERSION, '5.0.0', '<')) { + exit('The CentovaCast PHP API client requires that object overloading support is built into PHP.'); + } } -?> diff --git a/src/bb-modules/Servicecentovacast/class_HTTPRetriever.php b/src/bb-modules/Servicecentovacast/class_HTTPRetriever.php index 6a567a281..06fde0f21 100644 --- a/src/bb-modules/Servicecentovacast/class_HTTPRetriever.php +++ b/src/bb-modules/Servicecentovacast/class_HTTPRetriever.php @@ -1,5 +1,7 @@

";
  * var_dump($http->response_headers);
  * echo "

"; - * + * * echo "Page content:
";
  * echo $http->response;
  * echo "
"; * // ---------------------------------------------------------------------------- - * + * * * // Example POST request: * // ---------------------------------------------------------------------------- @@ -130,7 +132,7 @@ namespace Box\Mod\Servicecentovacast; * echo "HTTP response headers:
";
  * var_dump($http->response_headers);
  * echo "

"; - * + * * echo "Page content:
";
  * echo $http->response;
  * echo "
"; @@ -148,1165 +150,1337 @@ namespace Box\Mod\Servicecentovacast; * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. - * + * * You should have received a copy of the GNU General Public License along * with this script; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // define user agent ID's -define("UA_EXPLORER",0); -define("UA_MOZILLA",1); -define("UA_FIREFOX",2); -define("UA_OPERA",3); +define('UA_EXPLORER', 0); +define('UA_MOZILLA', 1); +define('UA_FIREFOX', 2); +define('UA_OPERA', 3); // define progress message severity levels -define('HRP_DEBUG',0); -define('HRP_INFO',1); -define('HRP_ERROR',2); +define('HRP_DEBUG', 0); +define('HRP_INFO', 1); +define('HRP_ERROR', 2); -if (!defined("CURL_PATH")) define("CURL_PATH","/usr/bin/curl"); +if (!defined('CURL_PATH')) { + define('CURL_PATH', '/usr/bin/curl'); +} // if the CURL extension is not loaded, but the CURL Emulation Library is found, try // to load it -if (!extension_loaded("curl") && !defined('HTTPR_NO_REDECLARE_CURL') ) { - foreach (array(dirname(__FILE__)."/",dirname(__FILE__)."/libcurlemu/") as $k=>$libcurlemupath) { - $libcurlemuinc = $libcurlemupath.'libcurlemu.inc.php'; - if (is_readable($libcurlemuinc)) require_once($libcurlemuinc); - } +if (!extension_loaded('curl') && !defined('HTTPR_NO_REDECLARE_CURL')) { + foreach ([dirname(__FILE__).'/', dirname(__FILE__).'/libcurlemu/'] as $k => $libcurlemupath) { + $libcurlemuinc = $libcurlemupath.'libcurlemu.inc.php'; + if (is_readable($libcurlemuinc)) { + require_once $libcurlemuinc; + } + } } -class HTTPRetriever { - - var $class_version = '1.1.11'; - - // Constructor - function HTTPRetriever() { - // default HTTP headers to send with all requests - $this->headers = array( - "Referer"=>"", - "User-Agent"=>"HTTPRetriever/".$this->class_version, - "Connection"=>"close" - ); - - // HTTP version (has no effect if using CURL) - $this->version = "1.1"; - - // Normally, CURL is only used for HTTPS requests; setting this to - // TRUE will force CURL for HTTP requests as well. Not recommended. - $this->force_curl = false; - - // If you don't want to use CURL at all, set this to TRUE. - $this->disable_curl = false; - - // If HTTPS request return an error message about SSL certificates in - // $this->error and you don't care about security, set this to TRUE - $this->insecure_ssl = false; - - // Set the maximum time to wait for a connection - $this->connect_timeout = 15; - - // Set the maximum time to allow a transfer to run, or 0 to disable. - $this->max_time = 0; - - // Set the maximum time for a socket read/write operation, or 0 to disable. - $this->stream_timeout = 0; - - // If you're making an HTTPS request to a host whose SSL certificate - // doesn't match its domain name, AND YOU FULLY UNDERSTAND THE - // SECURITY IMPLICATIONS OF IGNORING THIS PROBLEM, set this to TRUE. - $this->ignore_ssl_hostname = false; - - // If TRUE, the get() and post() methods will close the connection - // and return immediately after receiving the HTTP result code - $this->result_close = false; - - // If set to a positive integer value, retrieved pages will be cached - // for this number of seconds. Any subsequent calls within the cache - // period will return the cached page, without contacting the remote - // server. - $this->caching = false; - - // If TRUE and $this->caching is not false, retrieved pages/files will be - // cached only if they appear to be static. - $this->caching_intelligent = false; - - // If TRUE, cached files will be stored in subdirectories corresponding - // to the first 2 letters of the hash filename - $this->caching_highvolume = false; +class HTTPRetriever +{ + public $class_version = '1.1.11'; - // If $this->caching is enabled, this specifies the folder under which - // cached pages are saved. - $this->cache_path = '/tmp/'; - - // Set these to perform basic HTTP authentication - $this->auth_username = ''; - $this->auth_password = ''; + // Constructor + public function HTTPRetriever() + { + // default HTTP headers to send with all requests + $this->headers = [ + 'Referer' => '', + 'User-Agent' => 'HTTPRetriever/'.$this->class_version, + 'Connection' => 'close', + ]; - // Optionally set this to a valid callback method to have HTTPRetriever - // provide page preprocessing capabilities to your script. If set, this - // method should accept two arguments: an object representing an instance - // of HTTPRetriever, and a string containing the page contents - $this->page_preprocessor = null; - - // Optionally set this to a valid callback method to have HTTPRetriever - // provide progress messages. Your callback must accept 2 parameters: - // an integer representing the severity (0=debug, 1=information, 2=error), - // and a string representing the progress message - $this->progress_callback = null; - - // Optionally set this to a valid callback method to have HTTPRetriever - // provide bytes-transferred messages. Your callbcak must accept 2 - // parameters: an integer representing the number of bytes transferred, - // and an integer representing the total number of bytes expected (or - // -1 if unknown). - $this->transfer_callback = null; - - // Set this to TRUE to have HTTPRetriever transparently follow HTTP - // redirects (code 301, 302, 303, and 307). Optionally set this to a - // numeric value to limit the maximum number of redirects to the specified - // value. (Redirection loops are detected automatically.) - // Note that non-GET/HEAD requests will NOT be redirected except on code - // 303, as per HTTP standards. - $this->follow_redirects = false; - - // Set this to TRUE to have HTTPRetriever automatically follow HTTP - // code 301 and 302 redirects received in response to HTTP POST requests, - // and treat them like a code 303. This is technically contrary to the - // RFCs but all common browsers do it anyway, so it's necessary for usable - // browser emulation. - $this->redirect_on_post = true; - - // Set this to TRUE to have HTTPRetriever automatically manage cookies - // for each request, simulating the behavior of an actual browser. When - // this is used, the $cookies parameter to the get(), and post() methods - // is ignored and cookies can only be set by the remote web server. - $this->manage_cookies = false; - $this->managed_cookies = array(); - } - - // Send an HTTP GET request to $url; if $ipaddress is specified, the - // connection will be made to the selected IP instead of resolving the - // hostname in $url. - // - // If $cookies is set, it should be an array in one of two formats. - // - // Either: $cookies[ 'cookiename' ] = array ( - // '/path/'=>array( - // 'expires'=>time(), - // 'domain'=>'yourdomain.com', - // 'value'=>'cookievalue' - // ) - // ); - // - // Or, a more simplified format: - // $cookies[ 'cookiename' ] = 'value'; - // - // The former format will automatically check to make sure that the path, domain, - // and expiration values match the HTTP request, and will only send the cookie if - // they do match. The latter will force the cookie to be set for the HTTP request - // unconditionally. - // - function get($url,$ipaddress = false,$cookies = false) { - $this->method = "GET"; - $this->post_data = ""; - $this->connect_ip = $ipaddress; - return $this->_execute_request($url,$cookies); - } - - // Send an HTTP POST request to $url containing the POST data $data. See ::get() - // for a description of the remaining arguments. - function post($url,$data="",$ipaddress = false,$cookies = false) { - $this->method = "POST"; - $this->post_data = $data; - $this->connect_ip = $ipaddress; - return $this->_execute_request($url,$cookies); - } - - // Send an HTTP HEAD request to $url. See ::get() for a description of the arguments. - function head($url,$ipaddress = false,$cookies = false) { - $this->method = "HEAD"; - $this->post_data = ""; - $this->connect_ip = $ipaddress; - return $this->_execute_request($url,$cookies); - } - - // send an alternate (non-GET/POST) HTTP request to $url - function custom($method,$url,$data="",$ipaddress = false,$cookies = false) { - $this->method = $method; - $this->post_data = $data; - $this->connect_ip = $ipaddress; - return $this->_execute_request($url,$cookies); - } - - /** - * @param string $arrayname - */ - function array_to_query($arrayname,$arraycontents) { - $output = ""; - foreach ($arraycontents as $key=>$value) { - if (is_array($value)) { - $output .= $this->array_to_query(sprintf('%s[%s]',$arrayname,urlencode($key)),$value); - } else { - $output .= sprintf('%s[%s]=%s&',$arrayname,urlencode($key),urlencode($value)); - } - } - return $output; - } - - // builds a query string from the associative array array $data; - // returns a string that can be passed to $this->post() - function make_query_string($data) { - $output = ""; - if (is_array($data)) { - foreach ($data as $name=>$value) { - if (is_array($value)) { - $output .= $this->array_to_query(urlencode($name),$value); - } elseif (is_scalar($value)) { - $output .= urlencode($name)."=".urlencode($value)."&"; - } else { - $output .= urlencode($name)."=".urlencode(serialize($value)).'&'; - } - } - } - return substr($output,0,strlen($output)-1); - } + // HTTP version (has no effect if using CURL) + $this->version = '1.1'; - - // this is pretty limited... but really, if you're going to spoof you UA, you'll probably - // want to use a Windows OS for the spoof anyway - // - // if you want to set the user agent to a custom string, just assign your string to - // $this->headers["User-Agent"] directly - function set_user_agent($agenttype,$agentversion,$windowsversion) { - $useragents = array( - "Mozilla/4.0 (compatible; MSIE %agent%; Windows NT %os%%ie7osstuff%)", // IE - "Mozilla/5.0 (Windows; U; Windows NT %os%; en-US; rv:%agent%) Gecko/20040514", // Moz - "Mozilla/5.0 (Windows; U; Windows NT %os%; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/%agent%", // FFox - "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT %os%) Opera %agent% [en]", // Opera - ); - - $agent = $useragents[$agenttype]; + // Normally, CURL is only used for HTTPS requests; setting this to + // TRUE will force CURL for HTTP requests as well. Not recommended. + $this->force_curl = false; - if ( ($agenttype==UA_EXPLORER) && (substr($agentversion,0,1)=='7') ) { - // cheeky, yes? - $agent = str_replace('%ie7osstuff%','; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022',$agent); - } + // If you don't want to use CURL at all, set this to TRUE. + $this->disable_curl = false; - $this->headers["User-Agent"] = str_replace(array("%agent%","%os%"),array($agentversion,$windowsversion),$agent); - } - - // this isn't presently used as it's now handled inline by the request parser - function remove_chunkiness() { - $remaining = $this->response; - $this->response = ""; - - while ($remaining) { - $hexlen = strpos($remaining,"\r"); - $chunksize = substr($remaining,0,$hexlen); - $argstart = strpos($chunksize,';'); - if ($argstart!==false) $chunksize = substr($chunksize,0,$argstart); - $chunksize = (int) @hexdec($chunksize); + // If HTTPS request return an error message about SSL certificates in + // $this->error and you don't care about security, set this to TRUE + $this->insecure_ssl = false; - $this->response .= substr($remaining,$hexlen+2,$chunksize); - $remaining = substr($remaining,$hexlen+2+$chunksize+2); + // Set the maximum time to wait for a connection + $this->connect_timeout = 15; - if (!$chunksize) { - // either we're done, or something's borked... exit - $this->response .= $remaining; - return; - } - } - } - - // (internal) store a page in the cache + // Set the maximum time to allow a transfer to run, or 0 to disable. + $this->max_time = 0; - /** - * @param string $token - */ - function _cache_store($token,$url) { + // Set the maximum time for a socket read/write operation, or 0 to disable. + $this->stream_timeout = 0; - if ($this->caching_intelligent) { - $urlinfo = @parse_url($url); - if ($this->method=='POST') { - $this->progress(HRP_DEBUG,"POST request; not caching"); - return; - } else if (strlen($urlinfo['query'])) { - $this->progress(HRP_DEBUG,"Request used query string; not caching"); - return; - } else { - $this->progress(HRP_DEBUG,"Request appears to be static and cacheable"); - } - } + // If you're making an HTTPS request to a host whose SSL certificate + // doesn't match its domain name, AND YOU FULLY UNDERSTAND THE + // SECURITY IMPLICATIONS OF IGNORING THIS PROBLEM, set this to TRUE. + $this->ignore_ssl_hostname = false; - $values = array( - "stats"=>$this->stats, - "result_code"=>$this->result_code, - "result_text"=>$this->result_text, - "version"=>$this->version, - "response"=>$this->response, - "response_headers"=>$this->response_headers, - "response_cookies"=>$this->response_cookies, - "raw_response"=>$this->raw_response, - ); - $values = serialize($values); + // If TRUE, the get() and post() methods will close the connection + // and return immediately after receiving the HTTP result code + $this->result_close = false; - $cache_dir = $this->cache_path; - if (substr($cache_dir,-1)!='/') $cache_dir .= '/'; - - if ($this->caching_highvolume) { - $cache_dir .= substr($token,0,2) . '/'; - if (!is_dir($cache_dir)) @mkdir($cache_dir); - } - - $filename = $cache_dir.$token.'.tmp'; + // If set to a positive integer value, retrieved pages will be cached + // for this number of seconds. Any subsequent calls within the cache + // period will return the cached page, without contacting the remote + // server. + $this->caching = false; - $fp = @fopen($filename,"w"); - if (!$fp) { - $this->progress(HRP_DEBUG,"Unable to create cache file"); - return false; - } - fwrite($fp,$values); - fclose($fp); + // If TRUE and $this->caching is not false, retrieved pages/files will be + // cached only if they appear to be static. + $this->caching_intelligent = false; - $this->progress(HRP_DEBUG,"HTTP response stored to cache"); - } - - // (internal) fetch a page from the cache + // If TRUE, cached files will be stored in subdirectories corresponding + // to the first 2 letters of the hash filename + $this->caching_highvolume = false; - /** - * @param string $token - */ - function _cache_fetch($token) { - $this->cache_hit = false; - $this->progress(HRP_DEBUG,"Checking for cached page value"); + // If $this->caching is enabled, this specifies the folder under which + // cached pages are saved. + $this->cache_path = '/tmp/'; - $cache_dir = $this->cache_path; - if (substr($cache_dir,-1)!='/') $cache_dir .= '/'; - - if ($this->caching_highvolume) $cache_dir .= substr($token,0,2) . '/'; - - $filename = $cache_dir.$token.'.tmp'; - if (!file_exists($filename)) { - $this->progress(HRP_DEBUG,"Page not available in cache"); - return false; - } - - if (time()-filemtime($filename)>$this->caching) { - $this->progress(HRP_DEBUG,"Page in cache is expired"); - @unlink($filename); - return false; - } - - if ($values = file_get_contents($filename)) { - $values = unserialize($values); - if (!$values) { - $this->progress(HRP_DEBUG,"Invalid cache contents"); - return false; - } - - $this->stats = $values["stats"]; - $this->result_code = $values["result_code"]; - $this->result_text = $values["result_text"]; - $this->version = $values["version"]; - $this->response = $values["response"]; - $this->response_headers = $values["response_headers"]; - $this->response_cookies = $values["response_cookies"]; - $this->raw_response = $values["raw_response"]; - - $this->progress(HRP_DEBUG,"Page loaded from cache"); - $this->cache_hit = true; - return true; - } else { - $this->progress(HRP_DEBUG,"Error reading cache file"); - return false; - } - } - - function parent_path($path) { - if (substr($path,0,1)=='/') $path = substr($path,1); - if (substr($path,-1)=='/') $path = substr($path,0,strlen($path)-1); - $path = explode('/',$path); - array_pop($path); - return count($path) ? ('/' . implode('/',$path)) : ''; - } - - // $cookies should be an array in one of two formats. - // - // Either: $cookies[ 'cookiename' ] = array ( - // '/path/'=>array( - // 'expires'=>time(), - // 'domain'=>'yourdomain.com', - // 'value'=>'cookievalue' - // ) - // ); - // - // Or, a more simplified format: - // $cookies[ 'cookiename' ] = 'value'; - // - // The former format will automatically check to make sure that the path, domain, - // and expiration values match the HTTP request, and will only send the cookie if - // they do match. The latter will force the cookie to be set for the HTTP request - // unconditionally. - // - function response_to_request_cookies($cookies,$urlinfo) { - if (!is_array($cookies)) return; - - // check for simplified cookie format (name=value) - $cookiekeys = array_keys($cookies); - if (!count($cookiekeys)) return; - - $testkey = array_pop($cookiekeys); - if (!is_array($cookies[ $testkey ])) { - foreach ($cookies as $k=>$v) $this->request_cookies[$k] = $v; - return; - } - - // must not be simplified format, so parse as complex format: - foreach ($cookies as $name=>$paths) { - foreach ($paths as $path=>$values) { - // make sure the cookie isn't expired - if ( isset($values['expires']) && ($values['expires']request_cookies[$name]); - continue; - } - - $cookiehost = $values['domain']; - $requesthost = $urlinfo['host']; - // make sure the cookie is valid for this host - $domain_match = ( - ($requesthost==$cookiehost) || - (substr($requesthost,-(strlen($cookiehost)+1))=='.'.$cookiehost) - ); - - // make sure the cookie is valid for this path - $cookiepath = $path; if (substr($cookiepath,-1)!='/') $cookiepath .= '/'; - $requestpath = $urlinfo['path']; if (substr($requestpath,-1)!='/') $requestpath .= '/'; - if (substr($requestpath,0,strlen($cookiepath))!=$cookiepath) continue; - - $this->request_cookies[$name] = $values['value']; - } - } - } - - // Execute the request for a particular URL, and transparently follow - // HTTP redirects if enabled. If $cookies is specified, it is assumed - // to be an array received from $this->response_cookies and will be - // processed to determine which cookies are valid for this host/URL. - function _execute_request($url,$cookies = false) { - // valid codes for which we transparently follow a redirect - $redirect_codes = array(301,302,303,307); - // valid methods for which we transparently follow a redirect - $redirect_methods = array('GET','HEAD'); - - if ($this->redirect_on_post) $redirect_methods[] = 'POST'; + // Set these to perform basic HTTP authentication + $this->auth_username = ''; + $this->auth_password = ''; - $request_result = false; - - $this->followed_redirect = false; - $this->response_cookies = array(); - $this->cookie_headers = ''; + // Optionally set this to a valid callback method to have HTTPRetriever + // provide page preprocessing capabilities to your script. If set, this + // method should accept two arguments: an object representing an instance + // of HTTPRetriever, and a string containing the page contents + $this->page_preprocessor = null; - $previous_redirects = array(); - do { - // send the request - $request_result = $this->_send_request($url,$cookies); - - $lasturl = $url; - $url = false; + // Optionally set this to a valid callback method to have HTTPRetriever + // provide progress messages. Your callback must accept 2 parameters: + // an integer representing the severity (0=debug, 1=information, 2=error), + // and a string representing the progress message + $this->progress_callback = null; - // see if a redirect code was received - if ($this->follow_redirects && in_array($this->result_code,$redirect_codes)) { - // only redirect on a code 303 or if the method was GET/HEAD - if ( ($this->result_code==303) || in_array($this->method,$redirect_methods) ) { - // parse the information from the OLD URL so that we can handle - // relative links - $oldurlinfo = @parse_url($lasturl); - - $url = $this->response_headers['Location']; - - // parse the information in the new URL, and fill in any blanks - // using values from the old URL - $urlinfo = @parse_url($url); - foreach ($oldurlinfo as $k=>$v) { - if (!$urlinfo[$k]) $urlinfo[$k] = $v; - } - - // create an absolute path - if (substr($urlinfo['path'],0,1)!='/') { - $baseurl = $oldurlinfo['path']; - if (substr($baseurl,-1)!='/') $baseurl = $this->parent_path($url) . '/'; - $urlinfo['path'] = $baseurl . $urlinfo['path']; - } - - // rebuild the URL - $url = $this->rebuild_url($urlinfo); + // Optionally set this to a valid callback method to have HTTPRetriever + // provide bytes-transferred messages. Your callbcak must accept 2 + // parameters: an integer representing the number of bytes transferred, + // and an integer representing the total number of bytes expected (or + // -1 if unknown). + $this->transfer_callback = null; - $this->method = "GET"; - $this->post_data = ""; - - $this->progress(HRP_INFO,'Redirected to '.$url); - } - } - - if ( $url && strlen($url) ) { - - if (isset($previous_redirects[$url])) { - $this->error = "Infinite redirection loop"; - $request_result = false; - break; - } - if ( is_numeric($this->follow_redirects) && (count($previous_redirects)>$this->follow_redirects) ) { - $this->error = "Exceeded redirection limit"; - $request_result = false; - break; - } + // Set this to TRUE to have HTTPRetriever transparently follow HTTP + // redirects (code 301, 302, 303, and 307). Optionally set this to a + // numeric value to limit the maximum number of redirects to the specified + // value. (Redirection loops are detected automatically.) + // Note that non-GET/HEAD requests will NOT be redirected except on code + // 303, as per HTTP standards. + $this->follow_redirects = false; - $previous_redirects[$url] = true; - } + // Set this to TRUE to have HTTPRetriever automatically follow HTTP + // code 301 and 302 redirects received in response to HTTP POST requests, + // and treat them like a code 303. This is technically contrary to the + // RFCs but all common browsers do it anyway, so it's necessary for usable + // browser emulation. + $this->redirect_on_post = true; - } while ($url && strlen($url)); + // Set this to TRUE to have HTTPRetriever automatically manage cookies + // for each request, simulating the behavior of an actual browser. When + // this is used, the $cookies parameter to the get(), and post() methods + // is ignored and cookies can only be set by the remote web server. + $this->manage_cookies = false; + $this->managed_cookies = []; + } - // clear headers that shouldn't persist across multiple requests - $per_request_headers = array('Host','Content-Length'); - foreach ($per_request_headers as $k=>$v) unset($this->headers[$v]); - - if (count($previous_redirects)>1) $this->followed_redirect = array_keys($previous_redirects); - - return $request_result; - } - - // private - sends an HTTP request to $url - function _send_request($url,$cookies = false) { - $this->progress(HRP_INFO,"Initiating {$this->method} request for $url"); - if ($this->caching) { - $cachetoken = md5($url.'|'.$this->post_data); - if ($this->_cache_fetch($cachetoken)) return true; - } - - $time_request_start = $this->getmicrotime(); - - $urldata = @parse_url($url); - $this->urldata = &$urldata; - $http_host = $urldata['host'] . (isset($urldata['port']) ? ':'.$urldata['port'] : ''); - - if (!isset($urldata["port"]) || !$urldata["port"]) $urldata["port"] = ($urldata["scheme"]=="https") ? 443 : 80; - if (!isset($urldata["path"]) || !$urldata["path"]) $urldata["path"] = '/'; - - if (!empty($urldata['user'])) $this->auth_username = $urldata['user']; - if (!empty($urldata['pass'])) $this->auth_password = $urldata['pass']; - - //echo "Sending HTTP/{$this->version} {$this->method} request for ".$urldata["host"].":".$urldata["port"]." page ".$urldata["path"]."
"; - - if ($this->version>"1.0") $this->headers["Host"] = $http_host; - if ($this->method=="POST") { - $this->headers["Content-Length"] = strlen($this->post_data); - if (!isset($this->headers["Content-Type"])) $this->headers["Content-Type"] = "application/x-www-form-urlencoded"; - } - - if ( !empty($this->auth_username) || !empty($this->auth_password) ) { - $this->headers['Authorization'] = 'Basic '.base64_encode($this->auth_username.':'.$this->auth_password); - } else { - unset($this->headers['Authorization']); - } - - if (is_array($cookies)) $this->response_to_request_cookies($cookies,$urldata); + // Send an HTTP GET request to $url; if $ipaddress is specified, the + // connection will be made to the selected IP instead of resolving the + // hostname in $url. + // + // If $cookies is set, it should be an array in one of two formats. + // + // Either: $cookies[ 'cookiename' ] = array ( + // '/path/'=>array( + // 'expires'=>time(), + // 'domain'=>'yourdomain.com', + // 'value'=>'cookievalue' + // ) + // ); + // + // Or, a more simplified format: + // $cookies[ 'cookiename' ] = 'value'; + // + // The former format will automatically check to make sure that the path, domain, + // and expiration values match the HTTP request, and will only send the cookie if + // they do match. The latter will force the cookie to be set for the HTTP request + // unconditionally. + // + public function get($url, $ipaddress = false, $cookies = false) + { + $this->method = 'GET'; + $this->post_data = ''; + $this->connect_ip = $ipaddress; - if ($this->manage_cookies) $this->response_to_request_cookies($this->managed_cookies[ $urldata['host'] ],$urldata); - - if (!empty($urldata["query"])) $urldata["path"] .= "?".$urldata["query"]; - $request = $this->method." ".$urldata["path"]." HTTP/".$this->version."\r\n"; - $request .= $this->build_headers(); - $request .= $this->post_data; - - $this->response = ""; - - // clear headers that shouldn't persist across multiple requests - // (we can do this here as we've already built the request, including headers, above) - $per_request_headers = array('Host','Content-Length'); - foreach ($per_request_headers as $k=>$v) unset($this->headers[$v]); - - // Native SSL support requires the OpenSSL extension, and was introduced in PHP 4.3.0 - $php_ssl_support = extension_loaded("openssl") && version_compare(phpversion(),"4.3.0")>=0; - - // if this is a plain HTTP request, or if it's an HTTPS request and OpenSSL support is available, - // natively perform the HTTP request - if ( ( ($urldata["scheme"]=="http") || ($php_ssl_support && ($urldata["scheme"]=="https")) ) && (!$this->force_curl) ) { - $curl_mode = false; + return $this->_execute_request($url, $cookies); + } - $hostname = $this->connect_ip ? $this->connect_ip : $urldata['host']; - if ($urldata["scheme"]=="https") $hostname = 'ssl://'.$hostname; - - $time_connect_start = $this->getmicrotime(); + // Send an HTTP POST request to $url containing the POST data $data. See ::get() + // for a description of the remaining arguments. + public function post($url, $data = '', $ipaddress = false, $cookies = false) + { + $this->method = 'POST'; + $this->post_data = $data; + $this->connect_ip = $ipaddress; - $this->progress(HRP_INFO,'Opening socket connection to '.$hostname.' port '.$urldata['port']); + return $this->_execute_request($url, $cookies); + } - $this->expected_bytes = -1; - $this->received_bytes = 0; - - $fp = @fsockopen ($hostname,$urldata["port"],$errno,$errstr,$this->connect_timeout); - $time_connected = $this->getmicrotime(); - $connect_time = $time_connected - $time_connect_start; - if ($fp) { - if ($this->stream_timeout) stream_set_timeout($fp,$this->stream_timeout); - $this->progress(HRP_INFO,"Connected; sending request"); - - $this->progress(HRP_DEBUG,$request); - fputs ($fp, $request); - $this->raw_request = $request; - - if ($this->stream_timeout) { - $meta = socket_get_status($fp); - if ($meta['timed_out']) { - $this->error = "Exceeded socket write timeout of ".$this->stream_timeout." seconds"; - $this->progress(HRP_ERROR,$this->error); - return false; - } - } - - $this->progress(HRP_INFO,"Request sent; awaiting reply"); - - $headers_received = false; - $data_length = false; - $chunked = false; - $iterations = 0; - while (!feof($fp)) { - if ($data_length>0) { - $line = fread($fp,$data_length); - $this->progress(HRP_DEBUG,"[DL] Got a line: [{$line}] " . gettype($line)); + // Send an HTTP HEAD request to $url. See ::get() for a description of the arguments. + public function head($url, $ipaddress = false, $cookies = false) + { + $this->method = 'HEAD'; + $this->post_data = ''; + $this->connect_ip = $ipaddress; - if ($line!==false) $data_length -= strlen($line); - } else { - $line = @fgets($fp,10240); - $this->progress(HRP_DEBUG,"[NDL] Got a line: [{$line}] " . gettype($line)); - - if ( ($chunked) && ($line!==false) ) { - $line = trim($line); - if (!strlen($line)) continue; - - list($data_length,) = explode(';',$line,2); - $data_length = (int) hexdec(trim($data_length)); - - if ($data_length==0) { - $this->progress(HRP_DEBUG,"Done"); - // end of chunked data - break; - } - $this->progress(HRP_DEBUG,"Chunk length $data_length (0x$line)"); - continue; - } - } - - if ($line===false) { - $meta = socket_get_status($fp); - if ($meta['timed_out']) { - if ($this->stream_timeout) { - $this->error = "Exceeded socket read timeout of ".$this->stream_timeout." seconds"; - } else { - $this->error = "Exceeded default socket read timeout"; - } - $this->progress(HRP_ERROR,$this->error); - return false; - } else { - $this->progress(HRP_ERROR,'No data but not timed out'); - } - continue; - } + return $this->_execute_request($url, $cookies); + } - // check time limits if requested - if ($this->max_time>0) { - if ($this->getmicrotime() - $time_request_start > $this->max_time) { - $this->error = "Exceeded maximum transfer time of ".$this->max_time." seconds"; - $this->progress(HRP_ERROR,$this->error); - return false; - } - } + // send an alternate (non-GET/POST) HTTP request to $url + public function custom($method, $url, $data = '', $ipaddress = false, $cookies = false) + { + $this->method = $method; + $this->post_data = $data; + $this->connect_ip = $ipaddress; - $this->response .= $line; - - $iterations++; - if ($headers_received) { - if ($time_connected>0) { - $time_firstdata = $this->getmicrotime(); - $process_time = $time_firstdata - $time_connected; - $time_connected = 0; - } - $this->received_bytes += strlen($line); - if ($iterations % 20 == 0) { - $this->update_transfer_counters(); - } - } + return $this->_execute_request($url, $cookies); + } - - // some dumbass webservers don't respect Connection: close and just - // leave the connection open, so we have to be diligent about - // calculating the content length so we can disconnect at the end of - // the response - if ( (!$headers_received) && (trim($line)=="") ) { - $headers_received = true; - $this->progress(HRP_DEBUG,"Got headers: {$this->response}"); + /** + * @param string $arrayname + */ + public function array_to_query($arrayname, $arraycontents) + { + $output = ''; + foreach ($arraycontents as $key => $value) { + if (is_array($value)) { + $output .= $this->array_to_query(sprintf('%s[%s]', $arrayname, urlencode($key)), $value); + } else { + $output .= sprintf('%s[%s]=%s&', $arrayname, urlencode($key), urlencode($value)); + } + } - if (preg_match('/^Content-Length: ([0-9]+)/im',$this->response,$matches)) { - $data_length = (int) $matches[1]; - $this->progress(HRP_DEBUG,"Content length is $data_length"); - $this->expected_bytes = $data_length; - $this->update_transfer_counters(); - } else { - $this->progress(HRP_DEBUG,"No data length specified"); - } - if (preg_match("/^Transfer-Encoding: chunked/im",$this->response,$matches)) { - $chunked = true; - $this->progress(HRP_DEBUG,"Chunked transfer encoding requested"); - } else { - $this->progress(HRP_DEBUG,"CTE not requested"); - } - - if (preg_match_all("/^Set-Cookie: ((.*?)\=(.*?)(?:;\s*(.*))?)$/im",$this->response,$cookielist,PREG_SET_ORDER)) { - foreach ($cookielist as $k=>$cookie) $this->cookie_headers .= $cookie[0]."\n"; - - // get the path for which cookies will be valid if no path is specified - $cookiepath = preg_replace('/\/{2,}/','',$urldata['path']); - if (substr($cookiepath,-1)!='/') { - $cookiepath = explode('/',$cookiepath); - array_pop($cookiepath); - $cookiepath = implode('/',$cookiepath) . '/'; - } - // process each cookie - foreach ($cookielist as $k=>$cookiedata) { - list(,$rawcookie,$name,$value,$attributedata) = $cookiedata; - $attributedata = explode(';',trim($attributedata)); - $attributes = array(); + return $output; + } - $cookie = array( - 'value'=>$value, - 'raw'=>trim($rawcookie), - ); - foreach ($attributedata as $k=>$attribute) { - list($attrname,$attrvalue) = explode('=',trim($attribute)); - $cookie[$attrname] = $attrvalue; - } + // builds a query string from the associative array array $data; + // returns a string that can be passed to $this->post() + public function make_query_string($data) + { + $output = ''; + if (is_array($data)) { + foreach ($data as $name => $value) { + if (is_array($value)) { + $output .= $this->array_to_query(urlencode($name), $value); + } elseif (is_scalar($value)) { + $output .= urlencode($name).'='.urlencode($value).'&'; + } else { + $output .= urlencode($name).'='.urlencode(serialize($value)).'&'; + } + } + } - if (!isset($cookie['domain']) || !$cookie['domain']) $cookie['domain'] = $urldata['host']; - if (!isset($cookie['path']) || !$cookie['path']) $cookie['path'] = $cookiepath; - if (isset($cookie['expires']) && $cookie['expires']) $cookie['expires'] = strtotime($cookie['expires']); - - if (!$this->validate_response_cookie($cookie,$urldata['host'])) continue; - - // do not store expired cookies; if one exists, unset it - if ( isset($cookie['expires']) && ($cookie['expires']response_cookies[ $name ][ $cookie['path'] ]); - if ($this->manage_cookies) unset($this->managed_cookies[ $urldata['host'] ][ $name ][ $cookie['path'] ]); - continue; - } - - $this->response_cookies[ $name ][ $cookie['path'] ] = $cookie; - if ($this->manage_cookies) $this->managed_cookies[ $urldata['host'] ][ $name ][ $cookie['path'] ] = $cookie; - } - } - } - - if ($this->result_close) { - if (preg_match_all("/HTTP\/([0-9\.]+) ([0-9]+) (.*?)[\r\n]/",$this->response,$matches)) { - $resultcodes = $matches[2]; - foreach ($resultcodes as $k=>$code) { - if ($code!=100) { - $this->progress(HRP_INFO,'HTTP result code received; closing connection'); + return substr($output, 0, strlen($output) - 1); + } - $this->result_code = $code; - $this->result_text = $matches[3][$k]; - fclose($fp); - - return ($this->result_code==200); - } - } - } - } - } - if (feof($fp)) $this->progress(HRP_DEBUG,'EOF on socket'); - @fclose ($fp); - - $this->update_transfer_counters(); - - if (is_array($this->response_cookies)) { - // make sure paths are sorted in the order in which they should be applied - // when setting response cookies - foreach ($this->response_cookies as $name=>$paths) { - ksort($this->response_cookies[$name]); - } - } - if ($this->manage_cookies && is_array($this->managed_cookies[ $urldata['host'] ]) ) { - // make sure paths are sorted in the order in which they should be applied - // when setting response cookies - foreach ($this->managed_cookies[ $urldata['host'] ] as $name=>$paths) { - ksort($this->managed_cookies[ $urldata['host'] ][$name]); - } - } - - $this->progress(HRP_INFO,'Request complete'); - } else { - $this->error = strtoupper($urldata["scheme"])." connection to ".$hostname." port ".$urldata["port"]." failed"; - $this->progress(HRP_ERROR,$this->error); - return false; - } + // this is pretty limited... but really, if you're going to spoof you UA, you'll probably + // want to use a Windows OS for the spoof anyway + // + // if you want to set the user agent to a custom string, just assign your string to + // $this->headers["User-Agent"] directly + public function set_user_agent($agenttype, $agentversion, $windowsversion) + { + $useragents = [ + 'Mozilla/4.0 (compatible; MSIE %agent%; Windows NT %os%%ie7osstuff%)', // IE + 'Mozilla/5.0 (Windows; U; Windows NT %os%; en-US; rv:%agent%) Gecko/20040514', // Moz + 'Mozilla/5.0 (Windows; U; Windows NT %os%; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/%agent%', // FFox + 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT %os%) Opera %agent% [en]', // Opera + ]; - // perform an HTTP/HTTPS request using CURL - } elseif ( !$this->disable_curl && ( ($urldata["scheme"]=="https") || ($this->force_curl) ) ) { - $this->progress(HRP_INFO,'Passing HTTP request for $url to CURL'); - $curl_mode = true; - if (!$this->_curl_request($url)) return false; - - // unknown protocol - } else { - $this->error = "Unsupported protocol: ".$urldata["scheme"]; - $this->progress(HRP_ERROR,$this->error); - return false; - } - - $this->raw_response = $this->response; + $agent = $useragents[$agenttype]; - $totallength = strlen($this->response); - - do { - $headerlength = strpos($this->response,"\r\n\r\n"); + if ((UA_EXPLORER == $agenttype) && ('7' == substr($agentversion, 0, 1))) { + // cheeky, yes? + $agent = str_replace('%ie7osstuff%', '; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022', $agent); + } - $response_headers = explode("\r\n",substr($this->response,0,$headerlength)); - $http_status = trim(array_shift($response_headers)); - foreach ($response_headers as $line) { - list($k,$v) = explode(":",$line,2); - $this->response_headers[trim($k)] = trim($v); - } - $this->response = substr($this->response,$headerlength+4); - - /* // Handled in-transfer now - if (($this->response_headers['Transfer-Encoding']=="chunked") && (!$curl_mode)) { - $this->remove_chunkiness(); - } - */ - - if (!preg_match("/^HTTP\/([0-9\.]+) ([0-9]+) (.*?)$/",$http_status,$matches)) { - $matches = array("",$this->version,0,"HTTP request error"); - } - list (,$response_version,$this->result_code,$this->result_text) = $matches; + $this->headers['User-Agent'] = str_replace(['%agent%', '%os%'], [$agentversion, $windowsversion], $agent); + } - // skip HTTP result code 100 (Continue) responses - } while (($this->result_code==100) && ($headerlength)); - - // record some statistics, roughly compatible with CURL's curl_getinfo() - if (!$curl_mode) { - $total_time = $this->getmicrotime() - $time_request_start; - $transfer_time = $total_time - $connect_time; - $this->stats = array( - "total_time"=>$total_time, - "connect_time"=>$connect_time, // time between connection request and connection established - "process_time"=>$process_time, // time between HTTP request and first data (non-headers) received - "url"=>$url, - "content_type"=>$this->response_headers["Content-Type"], - "http_code"=>$this->result_code, - "header_size"=>$headerlength, - "request_size"=>$totallength, - "filetime"=>isset($this->response_headers["Date"]) ? strtotime($this->response_headers["Date"]) : time(), - "pretransfer_time"=>$connect_time, - "size_download"=>$totallength, - "speed_download"=>$transfer_time > 0 ? round($totallength / $transfer_time) : 0, - "download_content_length"=>$totallength, - "upload_content_length"=>0, - "starttransfer_time"=>$connect_time, - ); - } + // this isn't presently used as it's now handled inline by the request parser + public function remove_chunkiness() + { + $remaining = $this->response; + $this->response = ''; - $ok = ($this->result_code==200); - if ($ok) { - // if a page preprocessor is defined, call it to process the page contents - if (is_callable($this->page_preprocessor)) $this->response = call_user_func($this->page_preprocessor,$this,$this->response); - - // if caching is enabled, save the page - if ($this->caching) $this->_cache_store($cachetoken,$url); - } + while ($remaining) { + $hexlen = strpos($remaining, "\r"); + $chunksize = substr($remaining, 0, $hexlen); + $argstart = strpos($chunksize, ';'); + if (false !== $argstart) { + $chunksize = substr($chunksize, 0, $argstart); + } + $chunksize = (int) @hexdec($chunksize); - return $ok; - } - - function validate_response_cookie($cookie,$actual_hostname) { - // make sure the cookie can't be set for a TLD, eg: '.com' - $cookiehost = $cookie['domain']; - $p = strrpos($cookiehost,'.'); - if ($p===false) return false; - - $tld = strtolower(substr($cookiehost,$p+1)); - $special_domains = array("com", "edu", "net", "org", "gov", "mil", "int"); - $periods_required = in_array($tld,$special_domains) ? 1 : 2; - - $periods = substr_count($cookiehost,'.'); - if ($periods<$periods_required) return false; - - if (substr($actual_hostname,0,1)!='.') $actual_hostname = '.'.$actual_hostname; - if (substr($cookiehost,0,1)!='.') $cookiehost = '.'.$cookiehost; - $domain_match = ( - ($actual_hostname==$cookiehost) || - (substr($actual_hostname,-strlen($cookiehost))==$cookiehost) - ); - - return $domain_match; + $this->response .= substr($remaining, $hexlen + 2, $chunksize); + $remaining = substr($remaining, $hexlen + 2 + $chunksize + 2); - } - - function build_headers() { - $headers = ""; - foreach ($this->headers as $name=>$value) { - $value = trim($value); - if (empty($value)) continue; - $headers .= "{$name}: {$value}\r\n"; - } + if (!$chunksize) { + // either we're done, or something's borked... exit + $this->response .= $remaining; - if (isset($this->request_cookies) && is_array($this->request_cookies)) { - $cookielist = array(); - foreach ($this->request_cookies as $name=>$value) { - $cookielist[] = "{$name}={$value}"; - } - if (count($cookielist)) $headers .= "Cookie: ".implode('; ',$cookielist)."\r\n"; - } - - - $headers .= "\r\n"; - - return $headers; - } - - // opposite of parse_url() - function rebuild_url($urlinfo) { - $url = $urlinfo['scheme'].'://'; - - if ($urlinfo['user'] || $urlinfo['pass']) { - $url .= $urlinfo['user']; - if ($urlinfo['pass']) { - if ($urlinfo['user']) $url .= ':'; - $url .= $urlinfo['pass']; - } - $url .= '@'; - } - - $url .= $urlinfo['host']; - if ($urlinfo['port']) $url .= ':'.$urlinfo['port']; - - $url .= $urlinfo['path']; - - if ($urlinfo['query']) $url .= '?'.$urlinfo['query']; - if ($urlinfo['fragment']) $url .= '#'.$urlinfo['fragment']; - - return $url; - } - - function _replace_hostname(&$url,$new_hostname) { - $parts = @parse_url($url); - $old_hostname = $parts['host']; - - $parts['host'] = $new_hostname; - - $url = $this->rebuild_url($parts); - - return $old_hostname; - } - - function _curl_request($url) { - $this->error = false; + return; + } + } + } - // if a direct connection IP address was specified, replace the hostname - // in the URL with the IP address, and set the Host: header to the - // original hostname - if ($this->connect_ip) { - $old_hostname = $this->_replace_hostname($url,$this->connect_ip); - $this->headers["Host"] = $old_hostname; - } - + // (internal) store a page in the cache - unset($this->headers["Content-Length"]); - $headers = explode("\n",$this->build_headers()); - - $ch = curl_init(); - curl_setopt($ch,CURLOPT_URL, $url); - curl_setopt($ch,CURLOPT_USERAGENT, $this->headers["User-Agent"]); - curl_setopt($ch,CURLOPT_HEADER, 1); - curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); -// curl_setopt($ch,CURLOPT_FOLLOWLOCATION, 1); // native method doesn't support this yet, so it's disabled for consistency - curl_setopt($ch,CURLOPT_TIMEOUT, 10); - if ($this->curl_proxy) { - curl_setopt($ch,CURLOPT_PROXY,$this->curl_proxy); - } - curl_setopt($ch,CURLOPT_HTTPHEADER, $headers); - - if ($this->method=="POST") { - curl_setopt($ch,CURLOPT_POST,1); - curl_setopt($ch,CURLOPT_POSTFIELDS,$this->post_data); - } - if ($this->insecure_ssl) { - curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0); - } - if ($this->ignore_ssl_hostname) { - curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1); - } - - $this->response = curl_exec ($ch); - if (curl_errno($ch)!=0) { - $this->error = "CURL error #".curl_errno($ch).": ".curl_error($ch); - } - - $this->stats = curl_getinfo($ch); - curl_close($ch); - - return ($this->error === false); - } - - /** - * @param integer $level - */ - function progress($level,$msg) { - if (is_callable($this->progress_callback)) call_user_func($this->progress_callback,$level,$msg); - } - - // Gets any available HTTPRetriever error message (including both internal - // errors and HTTP errors) - function get_error() { - return $this->error ? $this->error : 'HTTP ' . $this->result_code.': '.$this->result_text; - } - - function get_content_type() { - if (!$ctype = $this->response_headers['Content-Type']) { - $ctype = $this->response_headers['Content-type']; - } - list($ctype,) = explode(';',$ctype); - - return strtolower($ctype); - } - - function update_transfer_counters() { - if (is_callable($this->transfer_callback)) call_user_func($this->transfer_callback,$this->received_bytes,$this->expected_bytes); - } + /** + * @param string $token + */ + public function _cache_store($token, $url) + { + if ($this->caching_intelligent) { + $urlinfo = @parse_url($url); + if ('POST' == $this->method) { + $this->progress(HRP_DEBUG, 'POST request; not caching'); - function set_transfer_display($enabled = true) { - if ($enabled) { - $this->transfer_callback = array(&$this,'default_transfer_callback'); - } else { - unset($this->transfer_callback); - } - } - - function set_progress_display($enabled = true) { - if ($enabled) { - $this->progress_callback = array(&$this,'default_progress_callback'); - } else { - unset($this->progress_callback); - } - } - - function default_progress_callback($severity,$message) { - $severities = array( - HRP_DEBUG=>'debug', - HRP_INFO=>'info', - HRP_ERROR=>'error', - ); - - echo date('Y-m-d H:i:sa').' ['.$severities[$severity].'] '.$message."\n"; - flush(); - } + return; + } elseif (strlen($urlinfo['query'])) { + $this->progress(HRP_DEBUG, 'Request used query string; not caching'); - function default_transfer_callback($transferred,$expected) { - $msg = "Transferred " . round($transferred/1024,1); - if ($expected>=0) $msg .= "/" . round($expected/1024,1); - $msg .= "KB"; - if ($expected>0) $msg .= " (".round($transferred*100/$expected,1)."%)"; - echo date('Y-m-d H:i:sa')." $msg\n"; - flush(); - } - - function getmicrotime() { - list($usec, $sec) = explode(" ",microtime()); - return ((float)$usec + (float)$sec); - } - - function parse_page_form($formindex = false, $formid = false,$formattrsearch = false) { - - if (!preg_match_all('|([\s\S]*?)|',$this->response,$matches,PREG_SET_ORDER)) { - $this->error = 'HTTP response did not include an HTML login form'; - return false; - } - - $matchingform = false; - - if ($formindex!==false) { - $matchingform = $matches[ $formindex ]; - } elseif ($formid!==false) { - foreach ($matches as $k=>$match) { - $formdata = $this->get_element_attributes($match[1]); - if ($formdata['id']==$formid) { - $matchingform = $match; - break; - } - } - } elseif (is_array($formattrsearch)) { - list($key,$value) = $formattrsearch; - $value = strtolower($value); - foreach ($matches as $k=>$match) { - $formdata = $this->get_element_attributes($match[1]); - if (strpos(strtolower($formdata[$key]),$value)!==false) { - $matchingform = $match; - break; - } - } - } else { - $matchingform = array_shift($matches); - } - - if (!is_array($matchingform)) { - $this->error = 'Could not find a matching HTML form'; - return false; - } - - $form = $matchingform[0]; - $formdata = $this->get_element_attributes($matchingform[1]); - - $inputtypes = array('input','select','textarea'); - - $fields = array(); - foreach ($inputtypes as $k=>$inputtype) { - if (!preg_match_all('|<'.$inputtype.'([\s\S]*?)/?>|',$form,$matches)) continue; - - foreach ($matches[1] as $k=>$match) { - $fielddata = $this->get_element_attributes($match); - $fields[ $fielddata['name'] ] = $fielddata; - } - } - - return array($formdata,$fields); - - } - - function get_element_attributes($element) { - $regex = '/' . - '([a-z0-9_-]+)\s*?=\s*?[\"\']*\s*?' . // [src=][src='][src = '][src="][src = "] / etc. - '([^\s\"\'>]*)' . // [all characters up to a space, ", ', or >] - '/i'; - if (!preg_match_all($regex,$element,$matches,PREG_SET_ORDER)) return false; - - $output = array(); - foreach ($matches as $k=>$match) { - $output[ $match[1] ] = $match[2]; - } - - return $output; - } - - function form_fields_to_request_fields($fields) { - $output = array(); - foreach ($fields as $name=>$field) { - if ($field['type']=='image') { - $output[$name.'.x'] = rand(2,64); - $output[$name.'.y'] = rand(2,16); - } else { - $output[$name] = is_scalar($field['value']) ? $field['value'] : ''; - } - } - return $output; - } + return; + } else { + $this->progress(HRP_DEBUG, 'Request appears to be static and cacheable'); + } + } + $values = [ + 'stats' => $this->stats, + 'result_code' => $this->result_code, + 'result_text' => $this->result_text, + 'version' => $this->version, + 'response' => $this->response, + 'response_headers' => $this->response_headers, + 'response_cookies' => $this->response_cookies, + 'raw_response' => $this->raw_response, + ]; + $values = serialize($values); + + $cache_dir = $this->cache_path; + if ('/' != substr($cache_dir, -1)) { + $cache_dir .= '/'; + } + + if ($this->caching_highvolume) { + $cache_dir .= substr($token, 0, 2).'/'; + if (!is_dir($cache_dir)) { + @mkdir($cache_dir); + } + } + + $filename = $cache_dir.$token.'.tmp'; + + $fp = @fopen($filename, 'w'); + if (!$fp) { + $this->progress(HRP_DEBUG, 'Unable to create cache file'); + + return false; + } + fwrite($fp, $values); + fclose($fp); + + $this->progress(HRP_DEBUG, 'HTTP response stored to cache'); + } + + // (internal) fetch a page from the cache + + /** + * @param string $token + */ + public function _cache_fetch($token) + { + $this->cache_hit = false; + $this->progress(HRP_DEBUG, 'Checking for cached page value'); + + $cache_dir = $this->cache_path; + if ('/' != substr($cache_dir, -1)) { + $cache_dir .= '/'; + } + + if ($this->caching_highvolume) { + $cache_dir .= substr($token, 0, 2).'/'; + } + + $filename = $cache_dir.$token.'.tmp'; + if (!file_exists($filename)) { + $this->progress(HRP_DEBUG, 'Page not available in cache'); + + return false; + } + + if (time() - filemtime($filename) > $this->caching) { + $this->progress(HRP_DEBUG, 'Page in cache is expired'); + @unlink($filename); + + return false; + } + + if ($values = file_get_contents($filename)) { + $values = unserialize($values); + if (!$values) { + $this->progress(HRP_DEBUG, 'Invalid cache contents'); + + return false; + } + + $this->stats = $values['stats']; + $this->result_code = $values['result_code']; + $this->result_text = $values['result_text']; + $this->version = $values['version']; + $this->response = $values['response']; + $this->response_headers = $values['response_headers']; + $this->response_cookies = $values['response_cookies']; + $this->raw_response = $values['raw_response']; + + $this->progress(HRP_DEBUG, 'Page loaded from cache'); + $this->cache_hit = true; + + return true; + } else { + $this->progress(HRP_DEBUG, 'Error reading cache file'); + + return false; + } + } + + public function parent_path($path) + { + if ('/' == substr($path, 0, 1)) { + $path = substr($path, 1); + } + if ('/' == substr($path, -1)) { + $path = substr($path, 0, strlen($path) - 1); + } + $path = explode('/', $path); + array_pop($path); + + return count($path) ? ('/'.implode('/', $path)) : ''; + } + + // $cookies should be an array in one of two formats. + // + // Either: $cookies[ 'cookiename' ] = array ( + // '/path/'=>array( + // 'expires'=>time(), + // 'domain'=>'yourdomain.com', + // 'value'=>'cookievalue' + // ) + // ); + // + // Or, a more simplified format: + // $cookies[ 'cookiename' ] = 'value'; + // + // The former format will automatically check to make sure that the path, domain, + // and expiration values match the HTTP request, and will only send the cookie if + // they do match. The latter will force the cookie to be set for the HTTP request + // unconditionally. + // + public function response_to_request_cookies($cookies, $urlinfo) + { + if (!is_array($cookies)) { + return; + } + + // check for simplified cookie format (name=value) + $cookiekeys = array_keys($cookies); + if (!count($cookiekeys)) { + return; + } + + $testkey = array_pop($cookiekeys); + if (!is_array($cookies[$testkey])) { + foreach ($cookies as $k => $v) { + $this->request_cookies[$k] = $v; + } + + return; + } + + // must not be simplified format, so parse as complex format: + foreach ($cookies as $name => $paths) { + foreach ($paths as $path => $values) { + // make sure the cookie isn't expired + if (isset($values['expires']) && ($values['expires'] < time())) { + unset($this->request_cookies[$name]); + continue; + } + + $cookiehost = $values['domain']; + $requesthost = $urlinfo['host']; + // make sure the cookie is valid for this host + $domain_match = ( + ($requesthost == $cookiehost) || + (substr($requesthost, -(strlen($cookiehost) + 1)) == '.'.$cookiehost) + ); + + // make sure the cookie is valid for this path + $cookiepath = $path; + if ('/' != substr($cookiepath, -1)) { + $cookiepath .= '/'; + } + $requestpath = $urlinfo['path']; + if ('/' != substr($requestpath, -1)) { + $requestpath .= '/'; + } + if (substr($requestpath, 0, strlen($cookiepath)) != $cookiepath) { + continue; + } + + $this->request_cookies[$name] = $values['value']; + } + } + } + + // Execute the request for a particular URL, and transparently follow + // HTTP redirects if enabled. If $cookies is specified, it is assumed + // to be an array received from $this->response_cookies and will be + // processed to determine which cookies are valid for this host/URL. + public function _execute_request($url, $cookies = false) + { + // valid codes for which we transparently follow a redirect + $redirect_codes = [301, 302, 303, 307]; + // valid methods for which we transparently follow a redirect + $redirect_methods = ['GET', 'HEAD']; + + if ($this->redirect_on_post) { + $redirect_methods[] = 'POST'; + } + + $request_result = false; + + $this->followed_redirect = false; + $this->response_cookies = []; + $this->cookie_headers = ''; + + $previous_redirects = []; + do { + // send the request + $request_result = $this->_send_request($url, $cookies); + + $lasturl = $url; + $url = false; + + // see if a redirect code was received + if ($this->follow_redirects && in_array($this->result_code, $redirect_codes)) { + // only redirect on a code 303 or if the method was GET/HEAD + if ((303 == $this->result_code) || in_array($this->method, $redirect_methods)) { + // parse the information from the OLD URL so that we can handle + // relative links + $oldurlinfo = @parse_url($lasturl); + + $url = $this->response_headers['Location']; + + // parse the information in the new URL, and fill in any blanks + // using values from the old URL + $urlinfo = @parse_url($url); + foreach ($oldurlinfo as $k => $v) { + if (!$urlinfo[$k]) { + $urlinfo[$k] = $v; + } + } + + // create an absolute path + if ('/' != substr($urlinfo['path'], 0, 1)) { + $baseurl = $oldurlinfo['path']; + if ('/' != substr($baseurl, -1)) { + $baseurl = $this->parent_path($url).'/'; + } + $urlinfo['path'] = $baseurl.$urlinfo['path']; + } + + // rebuild the URL + $url = $this->rebuild_url($urlinfo); + + $this->method = 'GET'; + $this->post_data = ''; + + $this->progress(HRP_INFO, 'Redirected to '.$url); + } + } + + if ($url && strlen($url)) { + if (isset($previous_redirects[$url])) { + $this->error = 'Infinite redirection loop'; + $request_result = false; + break; + } + if (is_numeric($this->follow_redirects) && (count($previous_redirects) > $this->follow_redirects)) { + $this->error = 'Exceeded redirection limit'; + $request_result = false; + break; + } + + $previous_redirects[$url] = true; + } + } while ($url && strlen($url)); + + // clear headers that shouldn't persist across multiple requests + $per_request_headers = ['Host', 'Content-Length']; + foreach ($per_request_headers as $k => $v) { + unset($this->headers[$v]); + } + + if (count($previous_redirects) > 1) { + $this->followed_redirect = array_keys($previous_redirects); + } + + return $request_result; + } + + // private - sends an HTTP request to $url + public function _send_request($url, $cookies = false) + { + $this->progress(HRP_INFO, "Initiating {$this->method} request for $url"); + if ($this->caching) { + $cachetoken = md5($url.'|'.$this->post_data); + if ($this->_cache_fetch($cachetoken)) { + return true; + } + } + + $time_request_start = $this->getmicrotime(); + + $urldata = @parse_url($url); + $this->urldata = &$urldata; + $http_host = $urldata['host'].(isset($urldata['port']) ? ':'.$urldata['port'] : ''); + + if (!isset($urldata['port']) || !$urldata['port']) { + $urldata['port'] = ('https' == $urldata['scheme']) ? 443 : 80; + } + if (!isset($urldata['path']) || !$urldata['path']) { + $urldata['path'] = '/'; + } + + if (!empty($urldata['user'])) { + $this->auth_username = $urldata['user']; + } + if (!empty($urldata['pass'])) { + $this->auth_password = $urldata['pass']; + } + + // echo "Sending HTTP/{$this->version} {$this->method} request for ".$urldata["host"].":".$urldata["port"]." page ".$urldata["path"]."
"; + + if ($this->version > '1.0') { + $this->headers['Host'] = $http_host; + } + if ('POST' == $this->method) { + $this->headers['Content-Length'] = strlen($this->post_data); + if (!isset($this->headers['Content-Type'])) { + $this->headers['Content-Type'] = 'application/x-www-form-urlencoded'; + } + } + + if (!empty($this->auth_username) || !empty($this->auth_password)) { + $this->headers['Authorization'] = 'Basic '.base64_encode($this->auth_username.':'.$this->auth_password); + } else { + unset($this->headers['Authorization']); + } + + if (is_array($cookies)) { + $this->response_to_request_cookies($cookies, $urldata); + } + + if ($this->manage_cookies) { + $this->response_to_request_cookies($this->managed_cookies[$urldata['host']], $urldata); + } + + if (!empty($urldata['query'])) { + $urldata['path'] .= '?'.$urldata['query']; + } + $request = $this->method.' '.$urldata['path'].' HTTP/'.$this->version."\r\n"; + $request .= $this->build_headers(); + $request .= $this->post_data; + + $this->response = ''; + + // clear headers that shouldn't persist across multiple requests + // (we can do this here as we've already built the request, including headers, above) + $per_request_headers = ['Host', 'Content-Length']; + foreach ($per_request_headers as $k => $v) { + unset($this->headers[$v]); + } + + // Native SSL support requires the OpenSSL extension, and was introduced in PHP 4.3.0 + $php_ssl_support = extension_loaded('openssl') && version_compare(phpversion(), '4.3.0') >= 0; + + // if this is a plain HTTP request, or if it's an HTTPS request and OpenSSL support is available, + // natively perform the HTTP request + if ((('http' == $urldata['scheme']) || ($php_ssl_support && ('https' == $urldata['scheme']))) && (!$this->force_curl)) { + $curl_mode = false; + + $hostname = $this->connect_ip ? $this->connect_ip : $urldata['host']; + if ('https' == $urldata['scheme']) { + $hostname = 'ssl://'.$hostname; + } + + $time_connect_start = $this->getmicrotime(); + + $this->progress(HRP_INFO, 'Opening socket connection to '.$hostname.' port '.$urldata['port']); + + $this->expected_bytes = -1; + $this->received_bytes = 0; + + $fp = @fsockopen($hostname, $urldata['port'], $errno, $errstr, $this->connect_timeout); + $time_connected = $this->getmicrotime(); + $connect_time = $time_connected - $time_connect_start; + if ($fp) { + if ($this->stream_timeout) { + stream_set_timeout($fp, $this->stream_timeout); + } + $this->progress(HRP_INFO, 'Connected; sending request'); + + $this->progress(HRP_DEBUG, $request); + fputs($fp, $request); + $this->raw_request = $request; + + if ($this->stream_timeout) { + $meta = socket_get_status($fp); + if ($meta['timed_out']) { + $this->error = 'Exceeded socket write timeout of '.$this->stream_timeout.' seconds'; + $this->progress(HRP_ERROR, $this->error); + + return false; + } + } + + $this->progress(HRP_INFO, 'Request sent; awaiting reply'); + + $headers_received = false; + $data_length = false; + $chunked = false; + $iterations = 0; + while (!feof($fp)) { + if ($data_length > 0) { + $line = fread($fp, $data_length); + $this->progress(HRP_DEBUG, "[DL] Got a line: [{$line}] ".gettype($line)); + + if (false !== $line) { + $data_length -= strlen($line); + } + } else { + $line = @fgets($fp, 10240); + $this->progress(HRP_DEBUG, "[NDL] Got a line: [{$line}] ".gettype($line)); + + if (($chunked) && (false !== $line)) { + $line = trim($line); + if (!strlen($line)) { + continue; + } + + [$data_length] = explode(';', $line, 2); + $data_length = (int) hexdec(trim($data_length)); + + if (0 == $data_length) { + $this->progress(HRP_DEBUG, 'Done'); + // end of chunked data + break; + } + $this->progress(HRP_DEBUG, "Chunk length $data_length (0x$line)"); + continue; + } + } + + if (false === $line) { + $meta = socket_get_status($fp); + if ($meta['timed_out']) { + if ($this->stream_timeout) { + $this->error = 'Exceeded socket read timeout of '.$this->stream_timeout.' seconds'; + } else { + $this->error = 'Exceeded default socket read timeout'; + } + $this->progress(HRP_ERROR, $this->error); + + return false; + } else { + $this->progress(HRP_ERROR, 'No data but not timed out'); + } + continue; + } + + // check time limits if requested + if ($this->max_time > 0) { + if ($this->getmicrotime() - $time_request_start > $this->max_time) { + $this->error = 'Exceeded maximum transfer time of '.$this->max_time.' seconds'; + $this->progress(HRP_ERROR, $this->error); + + return false; + } + } + + $this->response .= $line; + + ++$iterations; + if ($headers_received) { + if ($time_connected > 0) { + $time_firstdata = $this->getmicrotime(); + $process_time = $time_firstdata - $time_connected; + $time_connected = 0; + } + $this->received_bytes += strlen($line); + if (0 == $iterations % 20) { + $this->update_transfer_counters(); + } + } + + // some dumbass webservers don't respect Connection: close and just + // leave the connection open, so we have to be diligent about + // calculating the content length so we can disconnect at the end of + // the response + if ((!$headers_received) && ('' == trim($line))) { + $headers_received = true; + $this->progress(HRP_DEBUG, "Got headers: {$this->response}"); + + if (preg_match('/^Content-Length: ([0-9]+)/im', $this->response, $matches)) { + $data_length = (int) $matches[1]; + $this->progress(HRP_DEBUG, "Content length is $data_length"); + $this->expected_bytes = $data_length; + $this->update_transfer_counters(); + } else { + $this->progress(HRP_DEBUG, 'No data length specified'); + } + if (preg_match('/^Transfer-Encoding: chunked/im', $this->response, $matches)) { + $chunked = true; + $this->progress(HRP_DEBUG, 'Chunked transfer encoding requested'); + } else { + $this->progress(HRP_DEBUG, 'CTE not requested'); + } + + if (preg_match_all("/^Set-Cookie: ((.*?)\=(.*?)(?:;\s*(.*))?)$/im", $this->response, $cookielist, PREG_SET_ORDER)) { + foreach ($cookielist as $k => $cookie) { + $this->cookie_headers .= $cookie[0]."\n"; + } + + // get the path for which cookies will be valid if no path is specified + $cookiepath = preg_replace('/\/{2,}/', '', $urldata['path']); + if ('/' != substr($cookiepath, -1)) { + $cookiepath = explode('/', $cookiepath); + array_pop($cookiepath); + $cookiepath = implode('/', $cookiepath).'/'; + } + // process each cookie + foreach ($cookielist as $k => $cookiedata) { + [, $rawcookie, $name, $value, $attributedata] = $cookiedata; + $attributedata = explode(';', trim($attributedata)); + $attributes = []; + + $cookie = [ + 'value' => $value, + 'raw' => trim($rawcookie), + ]; + foreach ($attributedata as $k => $attribute) { + [$attrname, $attrvalue] = explode('=', trim($attribute)); + $cookie[$attrname] = $attrvalue; + } + + if (!isset($cookie['domain']) || !$cookie['domain']) { + $cookie['domain'] = $urldata['host']; + } + if (!isset($cookie['path']) || !$cookie['path']) { + $cookie['path'] = $cookiepath; + } + if (isset($cookie['expires']) && $cookie['expires']) { + $cookie['expires'] = strtotime($cookie['expires']); + } + + if (!$this->validate_response_cookie($cookie, $urldata['host'])) { + continue; + } + + // do not store expired cookies; if one exists, unset it + if (isset($cookie['expires']) && ($cookie['expires'] < time())) { + unset($this->response_cookies[$name][$cookie['path']]); + if ($this->manage_cookies) { + unset($this->managed_cookies[$urldata['host']][$name][$cookie['path']]); + } + continue; + } + + $this->response_cookies[$name][$cookie['path']] = $cookie; + if ($this->manage_cookies) { + $this->managed_cookies[$urldata['host']][$name][$cookie['path']] = $cookie; + } + } + } + } + + if ($this->result_close) { + if (preg_match_all("/HTTP\/([0-9\.]+) ([0-9]+) (.*?)[\r\n]/", $this->response, $matches)) { + $resultcodes = $matches[2]; + foreach ($resultcodes as $k => $code) { + if (100 != $code) { + $this->progress(HRP_INFO, 'HTTP result code received; closing connection'); + + $this->result_code = $code; + $this->result_text = $matches[3][$k]; + fclose($fp); + + return 200 == $this->result_code; + } + } + } + } + } + if (feof($fp)) { + $this->progress(HRP_DEBUG, 'EOF on socket'); + } + @fclose($fp); + + $this->update_transfer_counters(); + + if (is_array($this->response_cookies)) { + // make sure paths are sorted in the order in which they should be applied + // when setting response cookies + foreach ($this->response_cookies as $name => $paths) { + ksort($this->response_cookies[$name]); + } + } + if ($this->manage_cookies && is_array($this->managed_cookies[$urldata['host']])) { + // make sure paths are sorted in the order in which they should be applied + // when setting response cookies + foreach ($this->managed_cookies[$urldata['host']] as $name => $paths) { + ksort($this->managed_cookies[$urldata['host']][$name]); + } + } + + $this->progress(HRP_INFO, 'Request complete'); + } else { + $this->error = strtoupper($urldata['scheme']).' connection to '.$hostname.' port '.$urldata['port'].' failed'; + $this->progress(HRP_ERROR, $this->error); + + return false; + } + + // perform an HTTP/HTTPS request using CURL + } elseif (!$this->disable_curl && (('https' == $urldata['scheme']) || ($this->force_curl))) { + $this->progress(HRP_INFO, 'Passing HTTP request for $url to CURL'); + $curl_mode = true; + if (!$this->_curl_request($url)) { + return false; + } + + // unknown protocol + } else { + $this->error = 'Unsupported protocol: '.$urldata['scheme']; + $this->progress(HRP_ERROR, $this->error); + + return false; + } + + $this->raw_response = $this->response; + + $totallength = strlen($this->response); + + do { + $headerlength = strpos($this->response, "\r\n\r\n"); + + $response_headers = explode("\r\n", substr($this->response, 0, $headerlength)); + $http_status = trim(array_shift($response_headers)); + foreach ($response_headers as $line) { + [$k, $v] = explode(':', $line, 2); + $this->response_headers[trim($k)] = trim($v); + } + $this->response = substr($this->response, $headerlength + 4); + + /* // Handled in-transfer now + if (($this->response_headers['Transfer-Encoding']=="chunked") && (!$curl_mode)) { + $this->remove_chunkiness(); + } + */ + + if (!preg_match("/^HTTP\/([0-9\.]+) ([0-9]+) (.*?)$/", $http_status, $matches)) { + $matches = ['', $this->version, 0, 'HTTP request error']; + } + [, $response_version, $this->result_code, $this->result_text] = $matches; + + // skip HTTP result code 100 (Continue) responses + } while ((100 == $this->result_code) && ($headerlength)); + + // record some statistics, roughly compatible with CURL's curl_getinfo() + if (!$curl_mode) { + $total_time = $this->getmicrotime() - $time_request_start; + $transfer_time = $total_time - $connect_time; + $this->stats = [ + 'total_time' => $total_time, + 'connect_time' => $connect_time, // time between connection request and connection established + 'process_time' => $process_time, // time between HTTP request and first data (non-headers) received + 'url' => $url, + 'content_type' => $this->response_headers['Content-Type'], + 'http_code' => $this->result_code, + 'header_size' => $headerlength, + 'request_size' => $totallength, + 'filetime' => isset($this->response_headers['Date']) ? strtotime($this->response_headers['Date']) : time(), + 'pretransfer_time' => $connect_time, + 'size_download' => $totallength, + 'speed_download' => $transfer_time > 0 ? round($totallength / $transfer_time) : 0, + 'download_content_length' => $totallength, + 'upload_content_length' => 0, + 'starttransfer_time' => $connect_time, + ]; + } + + $ok = (200 == $this->result_code); + if ($ok) { + // if a page preprocessor is defined, call it to process the page contents + if (is_callable($this->page_preprocessor)) { + $this->response = call_user_func($this->page_preprocessor, $this, $this->response); + } + + // if caching is enabled, save the page + if ($this->caching) { + $this->_cache_store($cachetoken, $url); + } + } + + return $ok; + } + + public function validate_response_cookie($cookie, $actual_hostname) + { + // make sure the cookie can't be set for a TLD, eg: '.com' + $cookiehost = $cookie['domain']; + $p = strrpos($cookiehost, '.'); + if (false === $p) { + return false; + } + + $tld = strtolower(substr($cookiehost, $p + 1)); + $special_domains = ['com', 'edu', 'net', 'org', 'gov', 'mil', 'int']; + $periods_required = in_array($tld, $special_domains) ? 1 : 2; + + $periods = substr_count($cookiehost, '.'); + if ($periods < $periods_required) { + return false; + } + + if ('.' != substr($actual_hostname, 0, 1)) { + $actual_hostname = '.'.$actual_hostname; + } + if ('.' != substr($cookiehost, 0, 1)) { + $cookiehost = '.'.$cookiehost; + } + $domain_match = ( + ($actual_hostname == $cookiehost) || + (substr($actual_hostname, -strlen($cookiehost)) == $cookiehost) + ); + + return $domain_match; + } + + public function build_headers() + { + $headers = ''; + foreach ($this->headers as $name => $value) { + $value = trim($value); + if (empty($value)) { + continue; + } + $headers .= "{$name}: {$value}\r\n"; + } + + if (isset($this->request_cookies) && is_array($this->request_cookies)) { + $cookielist = []; + foreach ($this->request_cookies as $name => $value) { + $cookielist[] = "{$name}={$value}"; + } + if (count($cookielist)) { + $headers .= 'Cookie: '.implode('; ', $cookielist)."\r\n"; + } + } + + $headers .= "\r\n"; + + return $headers; + } + + // opposite of parse_url() + public function rebuild_url($urlinfo) + { + $url = $urlinfo['scheme'].'://'; + + if ($urlinfo['user'] || $urlinfo['pass']) { + $url .= $urlinfo['user']; + if ($urlinfo['pass']) { + if ($urlinfo['user']) { + $url .= ':'; + } + $url .= $urlinfo['pass']; + } + $url .= '@'; + } + + $url .= $urlinfo['host']; + if ($urlinfo['port']) { + $url .= ':'.$urlinfo['port']; + } + + $url .= $urlinfo['path']; + + if ($urlinfo['query']) { + $url .= '?'.$urlinfo['query']; + } + if ($urlinfo['fragment']) { + $url .= '#'.$urlinfo['fragment']; + } + + return $url; + } + + public function _replace_hostname(&$url, $new_hostname) + { + $parts = @parse_url($url); + $old_hostname = $parts['host']; + + $parts['host'] = $new_hostname; + + $url = $this->rebuild_url($parts); + + return $old_hostname; + } + + public function _curl_request($url) + { + $this->error = false; + + // if a direct connection IP address was specified, replace the hostname + // in the URL with the IP address, and set the Host: header to the + // original hostname + if ($this->connect_ip) { + $old_hostname = $this->_replace_hostname($url, $this->connect_ip); + $this->headers['Host'] = $old_hostname; + } + + unset($this->headers['Content-Length']); + $headers = explode("\n", $this->build_headers()); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_USERAGENT, $this->headers['User-Agent']); + curl_setopt($ch, CURLOPT_HEADER, 1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + // curl_setopt($ch,CURLOPT_FOLLOWLOCATION, 1); // native method doesn't support this yet, so it's disabled for consistency + curl_setopt($ch, CURLOPT_TIMEOUT, 10); + if ($this->curl_proxy) { + curl_setopt($ch, CURLOPT_PROXY, $this->curl_proxy); + } + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + + if ('POST' == $this->method) { + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $this->post_data); + } + if ($this->insecure_ssl) { + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + } + if ($this->ignore_ssl_hostname) { + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); + } + + $this->response = curl_exec($ch); + if (0 != curl_errno($ch)) { + $this->error = 'CURL error #'.curl_errno($ch).': '.curl_error($ch); + } + + $this->stats = curl_getinfo($ch); + curl_close($ch); + + return false === $this->error; + } + + /** + * @param int $level + */ + public function progress($level, $msg) + { + if (is_callable($this->progress_callback)) { + call_user_func($this->progress_callback, $level, $msg); + } + } + + // Gets any available HTTPRetriever error message (including both internal + // errors and HTTP errors) + public function get_error() + { + return $this->error ? $this->error : 'HTTP '.$this->result_code.': '.$this->result_text; + } + + public function get_content_type() + { + if (!$ctype = $this->response_headers['Content-Type']) { + $ctype = $this->response_headers['Content-type']; + } + [$ctype] = explode(';', $ctype); + + return strtolower($ctype); + } + + public function update_transfer_counters() + { + if (is_callable($this->transfer_callback)) { + call_user_func($this->transfer_callback, $this->received_bytes, $this->expected_bytes); + } + } + + public function set_transfer_display($enabled = true) + { + if ($enabled) { + $this->transfer_callback = [&$this, 'default_transfer_callback']; + } else { + unset($this->transfer_callback); + } + } + + public function set_progress_display($enabled = true) + { + if ($enabled) { + $this->progress_callback = [&$this, 'default_progress_callback']; + } else { + unset($this->progress_callback); + } + } + + public function default_progress_callback($severity, $message) + { + $severities = [ + HRP_DEBUG => 'debug', + HRP_INFO => 'info', + HRP_ERROR => 'error', + ]; + + echo date('Y-m-d H:i:sa').' ['.$severities[$severity].'] '.$message."\n"; + flush(); + } + + public function default_transfer_callback($transferred, $expected) + { + $msg = 'Transferred '.round($transferred / 1024, 1); + if ($expected >= 0) { + $msg .= '/'.round($expected / 1024, 1); + } + $msg .= 'KB'; + if ($expected > 0) { + $msg .= ' ('.round($transferred * 100 / $expected, 1).'%)'; + } + echo date('Y-m-d H:i:sa')." $msg\n"; + flush(); + } + + public function getmicrotime() + { + [$usec, $sec] = explode(' ', microtime()); + + return (float) $usec + (float) $sec; + } + + public function parse_page_form($formindex = false, $formid = false, $formattrsearch = false) + { + if (!preg_match_all('|([\s\S]*?)|', $this->response, $matches, PREG_SET_ORDER)) { + $this->error = 'HTTP response did not include an HTML login form'; + + return false; + } + + $matchingform = false; + + if (false !== $formindex) { + $matchingform = $matches[$formindex]; + } elseif (false !== $formid) { + foreach ($matches as $k => $match) { + $formdata = $this->get_element_attributes($match[1]); + if ($formdata['id'] == $formid) { + $matchingform = $match; + break; + } + } + } elseif (is_array($formattrsearch)) { + [$key, $value] = $formattrsearch; + $value = strtolower($value); + foreach ($matches as $k => $match) { + $formdata = $this->get_element_attributes($match[1]); + if (false !== strpos(strtolower($formdata[$key]), $value)) { + $matchingform = $match; + break; + } + } + } else { + $matchingform = array_shift($matches); + } + + if (!is_array($matchingform)) { + $this->error = 'Could not find a matching HTML form'; + + return false; + } + + $form = $matchingform[0]; + $formdata = $this->get_element_attributes($matchingform[1]); + + $inputtypes = ['input', 'select', 'textarea']; + + $fields = []; + foreach ($inputtypes as $k => $inputtype) { + if (!preg_match_all('|<'.$inputtype.'([\s\S]*?)/?>|', $form, $matches)) { + continue; + } + + foreach ($matches[1] as $k => $match) { + $fielddata = $this->get_element_attributes($match); + $fields[$fielddata['name']] = $fielddata; + } + } + + return [$formdata, $fields]; + } + + public function get_element_attributes($element) + { + $regex = '/'. + '([a-z0-9_-]+)\s*?=\s*?[\"\']*\s*?'. // [src=][src='][src = '][src="][src = "] / etc. + '([^\s\"\'>]*)'. // [all characters up to a space, ", ', or >] + '/i'; + if (!preg_match_all($regex, $element, $matches, PREG_SET_ORDER)) { + return false; + } + + $output = []; + foreach ($matches as $k => $match) { + $output[$match[1]] = $match[2]; + } + + return $output; + } + + public function form_fields_to_request_fields($fields) + { + $output = []; + foreach ($fields as $name => $field) { + if ('image' == $field['type']) { + $output[$name.'.x'] = rand(2, 64); + $output[$name.'.y'] = rand(2, 16); + } else { + $output[$name] = is_scalar($field['value']) ? $field['value'] : ''; + } + } + + return $output; + } } -?> \ No newline at end of file diff --git a/src/bb-modules/Servicecustom/Api/Admin.php b/src/bb-modules/Servicecustom/Api/Admin.php index ca839f341..dad2a38d4 100644 --- a/src/bb-modules/Servicecustom/Api/Admin.php +++ b/src/bb-modules/Servicecustom/Api/Admin.php @@ -1,6 +1,6 @@ getService()->updateConfig($data['order_id'], $data['config']); } - return TRUE; + return true; } /** * Universal method to call method from plugin - * Pass any other params and they will be passed to plugin + * Pass any other params and they will be passed to plugin. * * @param int $order_id - ID of the order * @@ -58,6 +58,4 @@ class Admin extends \Api_Abstract return $this->getService()->customCall($model, $name, $data); } - - -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicecustom/Api/Client.php b/src/bb-modules/Servicecustom/Api/Client.php index 8a04cbf08..9abb4dc56 100644 --- a/src/bb-modules/Servicecustom/Api/Client.php +++ b/src/bb-modules/Servicecustom/Api/Client.php @@ -1,6 +1,6 @@ getService()->customCall($model, $name, $data); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicecustom/Service.php b/src/bb-modules/Servicecustom/Service.php index 6f95f1942..61bfc4854 100644 --- a/src/bb-modules/Servicecustom/Service.php +++ b/src/bb-modules/Servicecustom/Service.php @@ -1,6 +1,6 @@ di['mod_service']('formbuilder'); - $form = $formbuilderService->getForm($product['form_id']); + $form = $formbuilderService->getForm($product['form_id']); foreach ($form['fields'] as $field) { - if ($field['required'] == 1) { + if (1 == $field['required']) { $field_name = $field['name']; if (!isset($data[$field_name]) || empty($data[$field_name])) { - throw new \Box_Exception("You must fill in all required fields. " . $field['label'] . " is missing", null, 9684); + throw new \Box_Exception('You must fill in all required fields. '.$field['label'].' is missing', null, 9684); } } - if ($field['readonly'] == 1) { + if (1 == $field['readonly']) { $field_name = $field['name']; if ($data[$field_name] != $field['default_value']) { - throw new \Box_Exception("Field " . $field['label'] . " is read only. You can not change its value", null, 5468); + throw new \Box_Exception('Field '.$field['label'].' is read only. You can not change its value', null, 5468); } } } } - } /** - * @param \Model_ClientOrder $order * @return void */ public function action_create(\Model_ClientOrder $order) { $product = $this->di['db']->getExistingModelById('Product', $order->product_id, 'Product not found'); - $model = $this->di['db']->dispense('ServiceCustom'); - $model->client_id = $order->client_id; - $model->plugin = $product->plugin; + $model = $this->di['db']->dispense('ServiceCustom'); + $model->client_id = $order->client_id; + $model->plugin = $product->plugin; $model->plugin_config = $product->plugin_config; - $model->config = $order->config; - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); + $model->config = $order->config; + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); return $model; } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_activate(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); - $model = $orderService->getOrderService($order); + $model = $orderService->getOrderService($order); if (!$model instanceof \RedBeanPHP\SimpleModel) { throw new \Box_Exception('Could not activate order. Service was not created', null, 7456); } @@ -95,8 +91,7 @@ class Service implements \Box\InjectionAwareInterface } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_renew(\Model_ClientOrder $order) { @@ -112,8 +107,7 @@ class Service implements \Box\InjectionAwareInterface } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_suspend(\Model_ClientOrder $order) { @@ -130,8 +124,7 @@ class Service implements \Box\InjectionAwareInterface } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_unsuspend(\Model_ClientOrder $order) { @@ -148,8 +141,7 @@ class Service implements \Box\InjectionAwareInterface } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_cancel(\Model_ClientOrder $order) { @@ -166,8 +158,7 @@ class Service implements \Box\InjectionAwareInterface } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_uncancel(\Model_ClientOrder $order) { @@ -184,15 +175,15 @@ class Service implements \Box\InjectionAwareInterface } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_delete(\Model_ClientOrder $order) { try { $model = $this->_getOrderService($order); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e); + return true; } @@ -209,19 +200,19 @@ class Service implements \Box\InjectionAwareInterface public function toApiArray(\Model_ServiceCustom $model) { - $data = $this->getConfig($model); - $data['id'] = $model->id; - $data['client_id'] = $model->client_id; - $data['plugin'] = $model->plugin; + $data = $this->getConfig($model); + $data['id'] = $model->id; + $data['client_id'] = $model->client_id; + $data['plugin'] = $model->plugin; $data['updated_at'] = $model->updated_at; $data['created_at'] = $model->created_at; return $data; } - public function customCall(\Model_ServiceCustom $model, $method, $params = array()) + public function customCall(\Model_ServiceCustom $model, $method, $params = []) { - $forbidden_methods = array( + $forbidden_methods = [ 'delete', 'cancel', 'uncancel', @@ -229,9 +220,9 @@ class Service implements \Box\InjectionAwareInterface 'unsuspend', 'renew', 'activate', - ); + ]; if (in_array($method, $forbidden_methods)) { - throw new \Box_Exception('Custom plugin method :method is forbidden', array(':method' => $method), 403); + throw new \Box_Exception('Custom plugin method :method is forbidden', [':method' => $method], 403); } return $this->callOnAdapter($model, $method, $params); @@ -239,12 +230,12 @@ class Service implements \Box\InjectionAwareInterface public function updateConfig($orderId, $config) { - if (!is_array($config)){ + if (!is_array($config)) { throw new \Box_Exception('Config must be an array'); } - $model = $this->getServiceCustomByOrderId($orderId); - $model->config = json_encode($config); + $model = $this->getServiceCustomByOrderId($orderId); + $model->config = json_encode($config); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); @@ -259,42 +250,45 @@ class Service implements \Box\InjectionAwareInterface $orderService = $this->di['mod_service']('order'); $s = $orderService->getOrderService($order); - if(!$s instanceof \Model_ServiceCustom) { + if (!$s instanceof \Model_ServiceCustom) { throw new \Box_Exception('Order is not activated'); } + return $s; } - private function callOnAdapter(\Model_ServiceCustom $model, $method, $params = array()) + private function callOnAdapter(\Model_ServiceCustom $model, $method, $params = []) { $plugin = $model->plugin; if (empty($plugin)) { - //error_log('Plugin is not used for this custom service'); + // error_log('Plugin is not used for this custom service'); return null; } // check if plugin exists. If plugin does not exist, do not throw error. Simply add to log $file = sprintf('Plugin/%s/%s.php', $plugin, $plugin); - if (APPLICATION_ENV != 'testing' && !file_exists(BB_PATH_LIBRARY . DIRECTORY_SEPARATOR . $file)) { - $e = new \Box_Exception('Plugin class file :file was not found', array(':file' => $file), 3124); - if (BB_DEBUG) error_log($e->getMessage()); + if (APPLICATION_ENV != 'testing' && !file_exists(BB_PATH_LIBRARY.DIRECTORY_SEPARATOR.$file)) { + $e = new \Box_Exception('Plugin class file :file was not found', [':file' => $file], 3124); + if (BB_DEBUG) { + error_log($e->getMessage()); + } return null; } require_once $file; - $config = $this->di['tools']->decodeJ($model->plugin_config); + $config = $this->di['tools']->decodeJ($model->plugin_config); $adapter = new $plugin($config); if (!method_exists($adapter, $method)) { - throw new \Box_Exception('Plugin :plugin does not support action :action', array(':plugin' => $plugin, ':action' => $method), 3125); + throw new \Box_Exception('Plugin :plugin does not support action :action', [':plugin' => $plugin, ':action' => $method], 3125); } $orderService = $this->di['mod_service']('order'); - $order = $orderService->getServiceOrder($model); - $order_data = $orderService->toApiArray($order); - $data = $this->toApiArray($model); + $order = $orderService->getServiceOrder($model); + $order_data = $orderService->toApiArray($order); + $data = $this->toApiArray($model); return $adapter->$method($data, $order_data, $params); } @@ -302,11 +296,11 @@ class Service implements \Box\InjectionAwareInterface private function _getOrderService(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); - $model = $orderService->getOrderService($order); + $model = $orderService->getOrderService($order); if (!$model instanceof \RedBeanPHP\SimpleModel) { - throw new \Box_Exception('Order :id has no active service', array(':id' => $order->id)); + throw new \Box_Exception('Order :id has no active service', [':id' => $order->id]); } return $model; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicedomain/Api/Admin.php b/src/bb-modules/Servicedomain/Api/Admin.php index 277a4cd61..4819b06c0 100644 --- a/src/bb-modules/Servicedomain/Api/Admin.php +++ b/src/bb-modules/Servicedomain/Api/Admin.php @@ -1,6 +1,6 @@ _getService($data); - return $this->getService()->lock($s);; + return $this->getService()->lock($s); } /** - * Unlock domain + * Unlock domain. * * @param int $order_id - domain order id * - * @return boolean + * @return bool */ public function unlock($data) { $s = $this->_getService($data); - return $this->getService()->unlock($s);; + return $this->getService()->unlock($s); } /** - * Get paginated top level domains list + * Get paginated top level domains list. + * * @return array */ public function tld_get_list($data) { - list($sql, $params) = $this->getService()->tldGetSearchQuery($data); + [$sql, $params] = $this->getService()->tldGetSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); + $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $tldArr) { - $tld = $this->di['db']->getExistingModelById('Tld', $tldArr['id'], sprintf('Tld #%s not found', $tldArr['id'])); + $tld = $this->di['db']->getExistingModelById('Tld', $tldArr['id'], sprintf('Tld #%s not found', $tldArr['id'])); $pager['list'][$key] = $this->getService()->tldToApiArray($tld); } @@ -165,23 +165,24 @@ class Admin extends \Api_Abstract } /** - * Get top level domain details + * Get top level domain details. * * @param string $tld - top level domain, ie: .com * * @return array + * * @throws Box_Exception */ public function tld_get($data) { - $required = array( + $required = [ 'tld' => 'TLD is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $tld = $data['tld']; - if ($tld[0] != '.') { - $tld = '.' . $tld; + if ('.' != $tld[0]) { + $tld = '.'.$tld; } $model = $this->getService()->tldFindOneByTld($tld); @@ -193,18 +194,19 @@ class Admin extends \Api_Abstract } /** - * Delete top level domain + * Delete top level domain. * * @param string $tld - top level domain, ie: .com * * @return bool + * * @throws Box_Exception */ public function tld_delete($data) { - $required = array( + $required = [ 'tld' => 'TLD is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->getService()->tldFindOneByTld($data['tld']); @@ -217,26 +219,27 @@ class Admin extends \Api_Abstract } /** - * Add new top level domain + * Add new top level domain. * - * @param string $tld - top level domain, ie: .com - * @param int $tld_registrar_id - domain registrar id - * @param float $price_registration - registration price - * @param float $price_renew - renewal price - * @param float $price_transfer - transfer price + * @param string $tld - top level domain, ie: .com + * @param int $tld_registrar_id - domain registrar id + * @param float $price_registration - registration price + * @param float $price_renew - renewal price + * @param float $price_transfer - transfer price * * @return bool + * * @throws Box_Exception */ public function tld_create($data) { - $required = array( - 'tld' => 'TLD is missing', - 'tld_registrar_id' => 'TLD registrar id is missing', + $required = [ + 'tld' => 'TLD is missing', + 'tld_registrar_id' => 'TLD registrar id is missing', 'price_registration' => 'Registration price is missing', - 'price_renew' => 'Renewal price is missing', - 'price_transfer' => 'Transfer price is missing', - ); + 'price_renew' => 'Renewal price is missing', + 'price_transfer' => 'Transfer price is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); if ($this->getService()->tldAlreadyRegistered($data['tld'])) { @@ -247,7 +250,7 @@ class Admin extends \Api_Abstract } /** - * Update top level domain + * Update top level domain. * * @param string $tld - top level domain, ie: .com * @@ -257,13 +260,14 @@ class Admin extends \Api_Abstract * @optional float $price_transfer - transfer price * * @return bool + * * @throws Box_Exception */ public function tld_update($data) { - $required = array( + $required = [ 'tld' => 'TLD is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->getService()->tldFindOneByTld($data['tld']); @@ -275,19 +279,19 @@ class Admin extends \Api_Abstract } /** - * Get paginated registrars list + * Get paginated registrars list. * * @return array */ public function registrar_get_list($data) { - list($sql, $params) = $this->getService()->registrarGetSearchQuery($data); + [$sql, $params] = $this->getService()->registrarGetSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); + $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); $registrars = $this->di['db']->find('TldRegistrar', 'ORDER By name ASC'); - $registrarsArr = array(); + $registrarsArr = []; foreach ($registrars as $registrar) { $registrarsArr[] = $this->getService()->registrarToApiArray($registrar); } @@ -298,7 +302,7 @@ class Admin extends \Api_Abstract } /** - * Get registrars pairs + * Get registrars pairs. * * @return array */ @@ -308,7 +312,7 @@ class Admin extends \Api_Abstract } /** - * Get available registrars for install + * Get available registrars for install. * * @return type */ @@ -318,7 +322,7 @@ class Admin extends \Api_Abstract } /** - * Install domain registrar + * Install domain registrar. * * @param string $code - registrar code * @@ -326,9 +330,9 @@ class Admin extends \Api_Abstract */ public function registrar_install($data) { - $required = array( + $required = [ 'code' => 'registrar code is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $code = $data['code']; @@ -340,7 +344,7 @@ class Admin extends \Api_Abstract } /** - * Uninstall domain registrar + * Uninstall domain registrar. * * @param int $id - registrar id * @@ -348,9 +352,9 @@ class Admin extends \Api_Abstract */ public function registrar_delete($data) { - $required = array( + $required = [ 'id' => 'Registrar ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found'); @@ -359,7 +363,7 @@ class Admin extends \Api_Abstract } /** - * Copy domain registrar + * Copy domain registrar. * * @param int $id - registrar id * @@ -367,9 +371,9 @@ class Admin extends \Api_Abstract */ public function registrar_copy($data) { - $required = array( + $required = [ 'id' => 'Registrar ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found'); @@ -378,7 +382,7 @@ class Admin extends \Api_Abstract } /** - * Get domain registrar details + * Get domain registrar details. * * @param int $id - registrar id * @@ -386,9 +390,9 @@ class Admin extends \Api_Abstract */ public function registrar_get($data) { - $required = array( + $required = [ 'id' => 'Registrar ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $registrar = $this->di['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found'); @@ -398,7 +402,8 @@ class Admin extends \Api_Abstract /** * Sync domain expiration dates with registrars. - * This action is run once a month + * This action is run once a month. + * * @return bool */ public function batch_sync_expiration_dates($data) @@ -407,7 +412,7 @@ class Admin extends \Api_Abstract } /** - * Update domain registrar + * Update domain registrar. * * @param int $id - registrar id * @@ -418,9 +423,9 @@ class Admin extends \Api_Abstract */ public function registrar_update($data) { - $required = array( + $required = [ 'id' => 'Registrar ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('TldRegistrar', $data['id'], 'Registrar not found'); @@ -430,9 +435,9 @@ class Admin extends \Api_Abstract protected function _getService($data) { - $required = array( + $required = [ 'order_id' => 'Order ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $orderId = $data['order_id']; @@ -440,7 +445,7 @@ class Admin extends \Api_Abstract $order = $this->di['db']->getExistingModelById('ClientOrder', $orderId, 'Order not found'); $orderService = $this->di['mod_service']('order'); - $s = $orderService->getOrderService($order); + $s = $orderService->getOrderService($order); if (!$s instanceof \Model_ServiceDomain) { throw new \Box_Exception('Domain order is not activated'); @@ -448,4 +453,4 @@ class Admin extends \Api_Abstract return $s; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicedomain/Api/Client.php b/src/bb-modules/Servicedomain/Api/Client.php index 07a7512b6..b263651c2 100644 --- a/src/bb-modules/Servicedomain/Api/Client.php +++ b/src/bb-modules/Servicedomain/Api/Client.php @@ -1,6 +1,6 @@ _getService($data); - $this->di['events_manager']->fire(array('event' => 'onBeforeClientChangeNameservers', 'params' => $data)); + $this->di['events_manager']->fire(['event' => 'onBeforeClientChangeNameservers', 'params' => $data]); $this->getService()->updateNameservers($s, $data); - $this->di['events_manager']->fire(array('event' => 'onAfterClientChangeNameservers', 'params' => $data)); + $this->di['events_manager']->fire(['event' => 'onAfterClientChangeNameservers', 'params' => $data]); return true; } @@ -46,8 +45,8 @@ class Client extends \Api_Abstract /** * Change domain WHOIS contact details. Method sends action to registrar. * - * @param int $order_id - domain order id - * @param array $contact - Contact array must contain these fields: first_name, last_name, email, company, address1, address2, country, city, state, postcode, phone_cc, phone + * @param int $order_id - domain order id + * @param array $contact - Contact array must contain these fields: first_name, last_name, email, company, address1, address2, country, city, state, postcode, phone_cc, phone * * @return true */ @@ -89,7 +88,7 @@ class Client extends \Api_Abstract } /** - * Retireve domain transfer code + * Retireve domain transfer code. * * @param int $order_id - domain order id * @@ -103,7 +102,7 @@ class Client extends \Api_Abstract } /** - * Lock domain + * Lock domain. * * @param int $order_id - domain order id * @@ -117,7 +116,7 @@ class Client extends \Api_Abstract } /** - * Unlock domain + * Unlock domain. * * @param int $order_id - domain order id * @@ -149,4 +148,4 @@ class Client extends \Api_Abstract return $s; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicedomain/Api/Guest.php b/src/bb-modules/Servicedomain/Api/Guest.php index 9520ddd14..065d6ea02 100644 --- a/src/bb-modules/Servicedomain/Api/Guest.php +++ b/src/bb-modules/Servicedomain/Api/Guest.php @@ -1,6 +1,6 @@ di['array_get']($data, 'allow_register'); $allow_transfer = $this->di['array_get']($data, 'allow_transfer'); - $where = array(); - $where[] = "active = 1"; + $where = []; + $where[] = 'active = 1'; - if (NULL !== $allow_register) { - $where[] = "allow_register = 1"; + if (null !== $allow_register) { + $where[] = 'allow_register = 1'; } - if (NULL !== $allow_transfer) { - $where[] = "allow_transfer = 1"; + if (null !== $allow_transfer) { + $where[] = 'allow_transfer = 1'; } if (!empty($where)) { $query = implode(' AND ', $where); } - $tlds = $this->di['db']->find('Tld', $query, array()); - $result = array(); + $tlds = $this->di['db']->find('Tld', $query, []); + $result = []; foreach ($tlds as $model) { $result[] = $this->getService()->tldToApiArray($model); } @@ -56,7 +55,7 @@ class Guest extends \Api_Abstract } /** - * Get TLD pricing information + * Get TLD pricing information. * * @param string $tld - Top level domain, ie: .com * @@ -64,9 +63,9 @@ class Guest extends \Api_Abstract */ public function pricing($data) { - $required = array( + $required = [ 'tld' => 'TLD is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->getService()->tldFindOneByTld($data['tld']); @@ -88,16 +87,16 @@ class Guest extends \Api_Abstract */ public function check($data) { - $required = array( + $required = [ 'tld' => 'TLD is missing', 'sld' => 'SLD is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $sld = htmlspecialchars($data['sld'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); + $sld = htmlspecialchars($data['sld'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); $validator = $this->di['validator']; if (!$validator->isSldValid($sld)) { - throw new \Box_Exception('Domain :domain is not valid', array(':domain' => $sld)); + throw new \Box_Exception('Domain :domain is not valid', [':domain' => $sld]); } $tld = $this->getService()->tldFindOneByTld($data['tld']); @@ -109,7 +108,7 @@ class Guest extends \Api_Abstract throw new \Box_Exception('Domain is not available.'); } - return TRUE; + return true; } /** @@ -123,10 +122,10 @@ class Guest extends \Api_Abstract */ public function can_be_transferred($data) { - $required = array( + $required = [ 'tld' => 'TLD is missing', 'sld' => 'SLD is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $tld = $this->getService()->tldFindOneByTld($data['tld']); @@ -137,6 +136,6 @@ class Guest extends \Api_Abstract throw new \Box_Exception('Domain can not be transferred.'); } - return TRUE; + return true; } } diff --git a/src/bb-modules/Servicedomain/Controller/Admin.php b/src/bb-modules/Servicedomain/Controller/Admin.php index 23a66868f..5632459a8 100644 --- a/src/bb-modules/Servicedomain/Controller/Admin.php +++ b/src/bb-modules/Servicedomain/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'system', - 'index' => 150, + return [ + 'subpages' => [ + [ + 'location' => 'system', + 'index' => 150, 'label' => 'Domain registration', - 'uri' => $this->di['url']->adminLink('servicedomain'), + 'uri' => $this->di['url']->adminLink('servicedomain'), 'class' => '', - ), - ), - ); + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/servicedomain', 'get_index', null, get_class($this)); - $app->get('/servicedomain/tld/:tld', 'get_tld', array('tld'=>'[/.a-z0-9]+'), get_class($this)); - $app->get('/servicedomain/registrar/:id', 'get_registrar', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/servicedomain', 'get_index', null, get_class($this)); + $app->get('/servicedomain/tld/:tld', 'get_tld', ['tld' => '[/.a-z0-9]+'], get_class($this)); + $app->get('/servicedomain/registrar/:id', 'get_registrar', ['id' => '[0-9]+'], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_servicedomain_index'); } public function get_tld(\Box_App $app, $tld) { $api = $this->di['api_admin']; - $m = $api->servicedomain_tld_get(array('tld'=>$tld)); - return $app->render('mod_servicedomain_tld', array('tld'=>$m)); + $m = $api->servicedomain_tld_get(['tld' => $tld]); + + return $app->render('mod_servicedomain_tld', ['tld' => $m]); } public function get_registrar(\Box_App $app, $id) { $api = $this->di['api_admin']; - $registrar = $api->servicedomain_registrar_get(array('id'=>$id)); - return $app->render('mod_servicedomain_registrar', array('registrar'=>$registrar)); + $registrar = $api->servicedomain_registrar_get(['id' => $id]); + + return $app->render('mod_servicedomain_registrar', ['registrar' => $registrar]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicedomain/Service.php b/src/bb-modules/Servicedomain/Service.php index b4d539568..ab571f1d8 100644 --- a/src/bb-modules/Servicedomain/Service.php +++ b/src/bb-modules/Servicedomain/Service.php @@ -1,6 +1,6 @@ $data['register_sld'] . $data['register_tld'])); + return __('Domain :domain registration', [':domain' => $data['register_sld'].$data['register_tld']]); } - if (isset($data['action']) && $data['action'] == 'transfer' && + if (isset($data['action']) && 'transfer' == $data['action'] && isset($data['transfer_tld']) && isset($data['transfer_sld']) ) { - return __('Domain :domain transfer', array(':domain' => $data['transfer_sld'] . $data['transfer_tld'])); + return __('Domain :domain transfer', [':domain' => $data['transfer_sld'].$data['transfer_tld']]); } return $product->title; @@ -53,47 +53,47 @@ class Service implements \Box\InjectionAwareInterface { $validator = $this->di['validator']; - $required = array( + $required = [ 'action' => 'Are you registering new domain or transferring existing? Action parameter missing', - ); + ]; $validator->checkRequiredParamsForArray($required, $data); $action = $data['action']; - if (!in_array($action, array('register', 'transfer', 'owndomain'))) { + if (!in_array($action, ['register', 'transfer', 'owndomain'])) { throw new \Box_Exception('Invalid domain action.'); } - if ($action == 'owndomain') { + if ('owndomain' == $action) { if (!isset($data['owndomain_sld'])) { - throw new \Box_Exception('Order data must contain :field configuration field', array(':field' => 'owndomain_sld')); + throw new \Box_Exception('Order data must contain :field configuration field', [':field' => 'owndomain_sld']); } if (!$validator->isSldValid($data['owndomain_sld'])) { $safe_dom = htmlspecialchars($data['owndomain_sld'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); - throw new \Box_Exception('Domain name :domain is not valid', array(':domain' => $safe_dom)); + throw new \Box_Exception('Domain name :domain is not valid', [':domain' => $safe_dom]); } - $required = array( + $required = [ 'owndomain_tld' => 'Domain TLD is not valid.', 'owndomain_sld' => 'Domain name is required.', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); } - if ($action == 'transfer') { + if ('transfer' == $action) { if (!isset($data['transfer_sld'])) { - throw new \Box_Exception('Order data must contain :field configuration field', array(':field' => 'transfer_sld')); + throw new \Box_Exception('Order data must contain :field configuration field', [':field' => 'transfer_sld']); } if (!$validator->isSldValid($data['transfer_sld'])) { $safe_dom = htmlspecialchars($data['transfer_sld'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); - throw new \Box_Exception('Domain name :domain is not valid', array(':domain' => $safe_dom)); + throw new \Box_Exception('Domain name :domain is not valid', [':domain' => $safe_dom]); } - $required = array( + $required = [ 'transfer_tld' => 'Transfer domain type (TLD) is required.', 'transfer_sld' => 'Transfer domain name (SLD) is required.', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $tld = $this->tldFindOneByTld($data['transfer_tld']); @@ -101,31 +101,31 @@ class Service implements \Box\InjectionAwareInterface throw new \Box_Exception('TLD not found'); } - $domain = $data['transfer_sld'] . $tld->tld; + $domain = $data['transfer_sld'].$tld->tld; if (!$this->canBeTransfered($tld, $data['transfer_sld'])) { - throw new \Box_Exception(':domain can not be transferred!', array(':domain' => $domain)); + throw new \Box_Exception(':domain can not be transferred!', [':domain' => $domain]); } // return by reference - $data['period'] = '1Y'; + $data['period'] = '1Y'; $data['quantity'] = 1; } - if ($action == 'register') { + if ('register' == $action) { if (!isset($data['register_sld'])) { - throw new \Box_Exception('Order data must contain :field configuration field', array(':field' => 'register_sld')); + throw new \Box_Exception('Order data must contain :field configuration field', [':field' => 'register_sld']); } if (!$validator->isSldValid($data['register_sld'])) { $safe_dom = htmlspecialchars($data['register_sld'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); - throw new \Box_Exception('Domain name :domain is not valid', array(':domain' => $safe_dom)); + throw new \Box_Exception('Domain name :domain is not valid', [':domain' => $safe_dom]); } - $required = array( - 'register_tld' => 'Domain registration tld parameter missing.', - 'register_sld' => 'Domain registration sld parameter missing.', + $required = [ + 'register_tld' => 'Domain registration tld parameter missing.', + 'register_sld' => 'Domain registration sld parameter missing.', 'register_years' => 'Years parameter is missing for domain configuration.', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $tld = $this->tldFindOneByTld($data['register_tld']); @@ -133,75 +133,74 @@ class Service implements \Box\InjectionAwareInterface throw new \Box_Exception('TLD not found'); } - $years = (int)$data['register_years']; + $years = (int) $data['register_years']; if ($years < $tld->min_years) { - throw new \Box_Exception(':tld can be registered for at least :years years', array(':tld' => $tld->tld, ':years' => $tld->min_years)); + throw new \Box_Exception(':tld can be registered for at least :years years', [':tld' => $tld->tld, ':years' => $tld->min_years]); } - $domain = $data['register_sld'] . $tld->tld; + $domain = $data['register_sld'].$tld->tld; if (!$this->isDomainAvailable($tld, $data['register_sld'])) { - throw new \Box_Exception(':domain is already registered!', array(':domain' => $domain)); + throw new \Box_Exception(':domain is already registered!', [':domain' => $domain]); } // return by reference - $data['period'] = $years . 'Y'; + $data['period'] = $years.'Y'; $data['quantity'] = $years; } } /** - * Creates domain service object from order + * Creates domain service object from order. * - * @param \Model_ClientOrder $order * @return \Model_ServiceDomain */ public function action_create(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); - $c = $orderService->getConfig($order); + $c = $orderService->getConfig($order); $this->validateOrderData($c); - list($sld, $tld) = $this->_getTuple($c); - $years = isset($c['register_years']) ? $c['register_years'] : 1; + [$sld, $tld] = $this->_getTuple($c); + $years = $c['register_years'] ?? 1; - //@todo ? + // @todo ? $systemService = $this->di['mod_service']('system'); - $ns = $systemService->getNameservers(); + $ns = $systemService->getNameservers(); if (empty($ns)) { throw new \Box_Exception('Default domain nameservers are not configured'); } $tldModel = $this->tldFindOneByTld($tld); - $model = $this->di['db']->dispense('ServiceDomain'); - $model->client_id = $order->client_id; + $model = $this->di['db']->dispense('ServiceDomain'); + $model->client_id = $order->client_id; $model->tld_registrar_id = $tldModel->tld_registrar_id; - $model->sld = $sld; - $model->tld = $tld; - $model->period = $years; - $model->transfer_code = $this->di['array_get']($c, 'transfer_code', NULL); - $model->privacy = FALSE; - $model->action = $c['action']; - $model->ns1 = (isset($c['ns1']) && !empty($c['ns1'])) ? $c['ns1'] : $ns['nameserver_1']; - $model->ns2 = (isset($c['ns2']) && !empty($c['ns1'])) ? $c['ns2'] : $ns['nameserver_2']; - $model->ns3 = (isset($c['ns3']) && !empty($c['ns1'])) ? $c['ns3'] : $ns['nameserver_3']; - $model->ns4 = (isset($c['ns4']) && !empty($c['ns1'])) ? $c['ns4'] : $ns['nameserver_4']; + $model->sld = $sld; + $model->tld = $tld; + $model->period = $years; + $model->transfer_code = $this->di['array_get']($c, 'transfer_code', null); + $model->privacy = false; + $model->action = $c['action']; + $model->ns1 = (isset($c['ns1']) && !empty($c['ns1'])) ? $c['ns1'] : $ns['nameserver_1']; + $model->ns2 = (isset($c['ns2']) && !empty($c['ns1'])) ? $c['ns2'] : $ns['nameserver_2']; + $model->ns3 = (isset($c['ns3']) && !empty($c['ns1'])) ? $c['ns3'] : $ns['nameserver_3']; + $model->ns4 = (isset($c['ns4']) && !empty($c['ns1'])) ? $c['ns4'] : $ns['nameserver_4']; $client = $this->di['db']->getExistingModelById('Client', $model->client_id, 'Client not found'); $model->contact_first_name = $client->first_name; - $model->contact_last_name = $client->last_name; - $model->contact_email = $client->email; - $model->contact_company = $client->company; - $model->contact_address1 = $client->address_1; - $model->contact_address2 = $client->address_2; - $model->contact_country = $client->country; - $model->contact_city = $client->city; - $model->contact_state = $client->state; - $model->contact_postcode = $client->postcode; - $model->contact_phone_cc = $client->phone_cc; - $model->contact_phone = $client->phone; + $model->contact_last_name = $client->last_name; + $model->contact_email = $client->email; + $model->contact_company = $client->company; + $model->contact_address1 = $client->address_1; + $model->contact_address2 = $client->address_2; + $model->contact_country = $client->country; + $model->contact_city = $client->city; + $model->contact_state = $client->state; + $model->contact_postcode = $client->postcode; + $model->contact_phone_cc = $client->phone_cc; + $model->contact_phone = $client->phone; $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); @@ -212,31 +211,30 @@ class Service implements \Box\InjectionAwareInterface } /** - * Register or transfer domain on activation + * Register or transfer domain on activation. * - * @param \Model_ClientOrder $order * @return \Model_ServiceDomain */ public function action_activate(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); - $model = $orderService->getOrderService($order); + $model = $orderService->getOrderService($order); if (!$model instanceof \Model_ServiceDomain) { throw new \Box_Exception('Could not activate order. Service was not created'); } - //@adapterAction - list($domain, $adapter) = $this->_getD($model); - if ($model->action == 'register') { + // @adapterAction + [$domain, $adapter] = $this->_getD($model); + if ('register' == $model->action) { $adapter->registerDomain($domain); } - if ($model->action == 'transfer') { + if ('transfer' == $model->action) { $adapter->transferDomain($domain); } - //reset action - $model->action = NULL; + // reset action + $model->action = null; $this->di['db']->store($model); try { @@ -249,18 +247,17 @@ class Service implements \Box\InjectionAwareInterface } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_renew(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); - $model = $orderService->getOrderService($order); + $model = $orderService->getOrderService($order); if (!$model instanceof \RedBeanPHP\SimpleModel) { - throw new \Box_Exception('Order :id has no active service', array(':id' => $order->id)); + throw new \Box_Exception('Order :id has no active service', [':id' => $order->id]); } - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); $adapter->renewDomain($domain); $this->syncWhois($model, $order); @@ -269,10 +266,9 @@ class Service implements \Box\InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_suspend(\Model_ClientOrder $order) { @@ -280,10 +276,9 @@ class Service implements \Box\InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_unsuspend(\Model_ClientOrder $order) { @@ -291,26 +286,24 @@ class Service implements \Box\InjectionAwareInterface } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_cancel(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); - $model = $orderService->getOrderService($order); + $model = $orderService->getOrderService($order); if (!$model instanceof \RedBeanPHP\SimpleModel) { - throw new \Box_Exception('Order :id has no active service', array(':id' => $order->id)); + throw new \Box_Exception('Order :id has no active service', [':id' => $order->id]); } - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); $adapter->deleteDomain($domain); return true; } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_uncancel(\Model_ClientOrder $order) { @@ -320,17 +313,16 @@ class Service implements \Box\InjectionAwareInterface } /** - * @param \Model_ClientOrder $order * @return void */ public function action_delete(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); - $service = $orderService->getOrderService($order); + $service = $orderService->getOrderService($order); if ($service instanceof \Model_ServiceDomain) { - //cancel if not canceled - if ($order->status != \Model_ClientOrder::STATUS_CANCELED) { + // cancel if not canceled + if (\Model_ClientOrder::STATUS_CANCELED != $order->status) { $this->action_cancel($order); } $this->di['db']->trash($service); @@ -339,8 +331,8 @@ class Service implements \Box\InjectionAwareInterface protected function syncWhois(\Model_ServiceDomain $model, \Model_ClientOrder $order) { - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); // update whois $whois = $adapter->getDomainDetails($domain); @@ -350,26 +342,26 @@ class Service implements \Box\InjectionAwareInterface $model->locked = $locked; } - //sync whois + // sync whois $contact = $whois->getContactRegistrar(); $model->contact_first_name = $contact->getFirstName(); - $model->contact_last_name = $contact->getLastName(); - $model->contact_email = $contact->getEmail(); - $model->contact_company = $contact->getCompany(); - $model->contact_address1 = $contact->getAddress1(); - $model->contact_address2 = $contact->getAddress2(); - $model->contact_country = $contact->getCountry(); - $model->contact_city = $contact->getCity(); - $model->contact_state = $contact->getState(); - $model->contact_postcode = $contact->getZip(); - $model->contact_phone_cc = $contact->getTelCc(); - $model->contact_phone = $contact->getTel(); + $model->contact_last_name = $contact->getLastName(); + $model->contact_email = $contact->getEmail(); + $model->contact_company = $contact->getCompany(); + $model->contact_address1 = $contact->getAddress1(); + $model->contact_address2 = $contact->getAddress2(); + $model->contact_country = $contact->getCountry(); + $model->contact_city = $contact->getCity(); + $model->contact_state = $contact->getState(); + $model->contact_postcode = $contact->getZip(); + $model->contact_phone_cc = $contact->getTelCc(); + $model->contact_phone = $contact->getTel(); - $model->details = serialize($whois); - $model->expires_at = date('Y-m-d H:i:s', $whois->getExpirationTime()); + $model->details = serialize($whois); + $model->expires_at = date('Y-m-d H:i:s', $whois->getExpirationTime()); $model->registered_at = date('Y-m-d H:i:s', $whois->getRegistrationTime()); - $model->updated_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); } @@ -385,21 +377,21 @@ class Service implements \Box\InjectionAwareInterface $ns1 = $data['ns1']; $ns2 = $data['ns2']; - $ns3 = isset($data['ns3']) ? $data['ns3'] : NULL; - $ns4 = isset($data['ns4']) ? $data['ns4'] : NULL; + $ns3 = $data['ns3'] ?? null; + $ns4 = $data['ns4'] ?? null; - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); $domain->setNs1($ns1); $domain->setNs2($ns2); $domain->setNs3($ns3); $domain->setNs4($ns4); $adapter->modifyNs($domain); - $model->ns1 = $ns1; - $model->ns2 = $ns2; - $model->ns3 = $ns3; - $model->ns4 = $ns4; + $model->ns1 = $ns1; + $model->ns2 = $ns2; + $model->ns3 = $ns3; + $model->ns4 = $ns4; $model->updated_at = date('Y-m-d H:i:s'); $id = $this->di['db']->store($model); @@ -411,44 +403,44 @@ class Service implements \Box\InjectionAwareInterface public function updateContacts(\Model_ServiceDomain $model, $data) { - $required = array( + $required = [ 'contact' => 'Required field contact is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $contact = $data['contact']; - - $required = array( + + $required = [ 'first_name' => 'Required field first_name is missing', - 'last_name' => 'Required field last_name is missing', - 'email' => 'Required field email is missing', - 'company' => 'Required field company is missing', - 'address1' => 'Required field address1 is missing', - 'address2' => 'Required field address2 is missing', - 'country' => 'Required field country is missing', - 'city' => 'Required field city is missing', - 'state' => 'Required field state is missing', - 'postcode' => 'Required field postcode is missing', - 'phone_cc' => 'Required field phone_cc is missing', - 'phone' => 'Required field phone is missing', - ); + 'last_name' => 'Required field last_name is missing', + 'email' => 'Required field email is missing', + 'company' => 'Required field company is missing', + 'address1' => 'Required field address1 is missing', + 'address2' => 'Required field address2 is missing', + 'country' => 'Required field country is missing', + 'city' => 'Required field city is missing', + 'state' => 'Required field state is missing', + 'postcode' => 'Required field postcode is missing', + 'phone_cc' => 'Required field phone_cc is missing', + 'phone' => 'Required field phone is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $contact); $model->contact_first_name = $contact['first_name']; - $model->contact_last_name = $contact['last_name']; - $model->contact_email = $contact['email']; - $model->contact_company = $contact['company']; - $model->contact_address1 = $contact['address1']; - $model->contact_address2 = $contact['address2']; - $model->contact_country = $contact['country']; - $model->contact_city = $contact['city']; - $model->contact_state = $contact['state']; - $model->contact_postcode = $contact['postcode']; - $model->contact_phone_cc = $contact['phone_cc']; - $model->contact_phone = $contact['phone']; + $model->contact_last_name = $contact['last_name']; + $model->contact_email = $contact['email']; + $model->contact_company = $contact['company']; + $model->contact_address1 = $contact['address1']; + $model->contact_address2 = $contact['address2']; + $model->contact_country = $contact['country']; + $model->contact_city = $contact['city']; + $model->contact_state = $contact['state']; + $model->contact_postcode = $contact['postcode']; + $model->contact_phone_cc = $contact['phone_cc']; + $model->contact_phone = $contact['phone']; - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); $adapter->modifyContact($domain); $model->updated_at = date('Y-m-d H:i:s'); @@ -462,8 +454,8 @@ class Service implements \Box\InjectionAwareInterface public function getTransferCode(\Model_ServiceDomain $model) { - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); $epp = $adapter->getEpp($domain); return $epp; @@ -471,66 +463,66 @@ class Service implements \Box\InjectionAwareInterface public function lock(\Model_ServiceDomain $model) { - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); $epp = $adapter->lock($domain); - $model->locked = true; + $model->locked = true; $model->updated_at = date('Y-m-d H:i:s'); $id = $this->di['db']->store($model); $this->di['logger']->info('Locking domain #%s', $id); - return TRUE; + return true; } public function unlock(\Model_ServiceDomain $model) { - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); $epp = $adapter->unlock($domain); - $model->locked = false; + $model->locked = false; $model->updated_at = date('Y-m-d H:i:s'); $id = $this->di['db']->store($model); $this->di['logger']->info('Unlocking domain #%s', $id); - return TRUE; + return true; } public function enablePrivacyProtection(\Model_ServiceDomain $model) { - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); $adapter->enablePrivacyProtection($domain); - $model->privacy = TRUE; + $model->privacy = true; $model->updated_at = date('Y-m-d H:i:s'); $id = $this->di['db']->store($model); $this->di['logger']->info('Enabled privacy protection of #%s domain', $id); - return TRUE; + return true; } public function disablePrivacyProtection(\Model_ServiceDomain $model) { - //@adapterAction - list($domain, $adapter) = $this->_getD($model); + // @adapterAction + [$domain, $adapter] = $this->_getD($model); $adapter->disablePrivacyProtection($domain); - $model->privacy = FALSE; + $model->privacy = false; $model->updated_at = date('Y-m-d H:i:s'); $id = $this->di['db']->store($model); $this->di['logger']->info('Disabled privacy protection of #%s domain', $id); - return TRUE; + return true; } public function canBeTransfered(\Model_Tld $model, $sld) @@ -543,13 +535,13 @@ class Service implements \Box\InjectionAwareInterface throw new \Box_Exception('Domain can not be transferred', null, 403); } - //@adapterAction + // @adapterAction $domain = new \Registrar_Domain(); $domain->setTld($model->tld); $domain->setSld($sld); $tldRegistrar = $this->di['db']->load('TldRegistrar', $model->tld_registrar_id); - $adapter = $this->registrarGetRegistrarAdapter($tldRegistrar); + $adapter = $this->registrarGetRegistrarAdapter($tldRegistrar); return $adapter->isDomainCanBeTransfered($domain); } @@ -563,64 +555,64 @@ class Service implements \Box\InjectionAwareInterface $validator = $this->di['validator']; if (!$validator->isSldValid($sld)) { $safe_dom = htmlspecialchars($sld, ENT_QUOTES | ENT_HTML5, 'UTF-8'); - throw new \Box_Exception('Domain name :domain is not valid', array(':domain' => $safe_dom)); + throw new \Box_Exception('Domain name :domain is not valid', [':domain' => $safe_dom]); } if (!$model->allow_register) { throw new \Box_Exception('Domain can not be registered', null, 403); } - //@adapterAction + // @adapterAction $domain = new \Registrar_Domain(); $domain->setTld($model->tld); $domain->setSld($sld); $tldRegistrar = $this->di['db']->load('TldRegistrar', $model->tld_registrar_id); - $adapter = $this->registrarGetRegistrarAdapter($tldRegistrar); + $adapter = $this->registrarGetRegistrarAdapter($tldRegistrar); return $adapter->isDomainAvailable($domain); } public function syncExpirationDate($model) { - //@todo + // @todo } public function toApiArray(\Model_ServiceDomain $model, $deep = false, $identity = null) { - $data = array( - 'domain' => $model->sld . $model->tld, - 'sld' => $model->sld, - 'tld' => $model->tld, - 'ns1' => $model->ns1, - 'ns2' => $model->ns2, - 'ns3' => $model->ns3, - 'ns4' => $model->ns4, - 'period' => $model->period, - 'privacy' => $model->privacy, - 'locked' => $model->locked, + $data = [ + 'domain' => $model->sld.$model->tld, + 'sld' => $model->sld, + 'tld' => $model->tld, + 'ns1' => $model->ns1, + 'ns2' => $model->ns2, + 'ns3' => $model->ns3, + 'ns4' => $model->ns4, + 'period' => $model->period, + 'privacy' => $model->privacy, + 'locked' => $model->locked, 'registered_at' => $model->registered_at, - 'expires_at' => $model->expires_at, - 'contact' => array( + 'expires_at' => $model->expires_at, + 'contact' => [ 'first_name' => $model->contact_first_name, - 'last_name' => $model->contact_last_name, - 'email' => $model->contact_email, - 'company' => $model->contact_company, - 'address1' => $model->contact_address1, - 'address2' => $model->contact_address2, - 'country' => $model->contact_country, - 'city' => $model->contact_city, - 'state' => $model->contact_state, - 'postcode' => $model->contact_postcode, - 'phone_cc' => $model->contact_phone_cc, - 'phone' => $model->contact_phone, - ), - ); + 'last_name' => $model->contact_last_name, + 'email' => $model->contact_email, + 'company' => $model->contact_company, + 'address1' => $model->contact_address1, + 'address2' => $model->contact_address2, + 'country' => $model->contact_country, + 'city' => $model->contact_city, + 'state' => $model->contact_state, + 'postcode' => $model->contact_postcode, + 'phone_cc' => $model->contact_phone_cc, + 'phone' => $model->contact_phone, + ], + ]; if ($identity instanceof \Model_Admin) { $data['transfer_code'] = $model->transfer_code; - $tldRegistrar = $this->di['db']->load('TldRegistrar', $model->tld_registrar_id); + $tldRegistrar = $this->di['db']->load('TldRegistrar', $model->tld_registrar_id); $data['registrar'] = $tldRegistrar->name; } @@ -631,28 +623,28 @@ class Service implements \Box\InjectionAwareInterface { $action = $data['action']; - if ($action == 'owndomain') { + if ('owndomain' == $action) { $sld = $data['owndomain_sld']; $tld = $data['owndomain_tld']; } - if ($action == 'transfer') { + if ('transfer' == $action) { $sld = $data['transfer_sld']; $tld = $data['transfer_tld']; } - if ($action == 'register') { + if ('register' == $action) { $sld = $data['register_sld']; $tld = $data['register_tld']; } - return array($sld, $tld); + return [$sld, $tld]; } protected function _getD(\Model_ServiceDomain $model) { $orderService = $this->di['mod_service']('order'); - $order = $orderService->getServiceOrder($model); + $order = $orderService->getServiceOrder($model); $tldRegistrar = $this->di['db']->load('TldRegistrar', $model->tld_registrar_id); @@ -670,22 +662,22 @@ class Service implements \Box\InjectionAwareInterface $d->setNs3($model->ns3); $d->setNs4($model->ns4); - //merge info with current profile + // merge info with current profile $client = $this->di['db']->load('Client', $model->client_id); - $email = empty($model->contact_email) ? $client->email : $model->contact_email; + $email = empty($model->contact_email) ? $client->email : $model->contact_email; $first_name = empty($model->contact_first_name) ? $client->first_name : $model->contact_first_name; - $last_name = empty($model->contact_last_name) ? $client->last_name : $model->contact_last_name; - $city = empty($model->contact_city) ? $client->city : $model->contact_city; - $zip = empty($model->contact_postcode) ? $client->postcode : $model->contact_postcode; - $country = empty($model->contact_country) ? $client->country : $model->contact_country; - $state = empty($model->contact_state) ? $client->state : $model->contact_state; - $phone = empty($model->contact_phone) ? $client->phone : $model->contact_phone; - $phone_cc = empty($model->contact_phone_cc) ? $client->phone_cc : $model->contact_phone_cc; - $company = empty($model->contact_company) ? $client->company : $model->contact_company; - $address1 = empty($model->contact_address1) ? $client->address_1 : $model->contact_address1; - $address2 = empty($model->contact_address2) ? $client->address_2 : $model->contact_address2; - $birthday = !empty($client->birthday) ? $client->birthday: ''; + $last_name = empty($model->contact_last_name) ? $client->last_name : $model->contact_last_name; + $city = empty($model->contact_city) ? $client->city : $model->contact_city; + $zip = empty($model->contact_postcode) ? $client->postcode : $model->contact_postcode; + $country = empty($model->contact_country) ? $client->country : $model->contact_country; + $state = empty($model->contact_state) ? $client->state : $model->contact_state; + $phone = empty($model->contact_phone) ? $client->phone : $model->contact_phone; + $phone_cc = empty($model->contact_phone_cc) ? $client->phone_cc : $model->contact_phone_cc; + $company = empty($model->contact_company) ? $client->company : $model->contact_company; + $address1 = empty($model->contact_address1) ? $client->address_1 : $model->contact_address1; + $address2 = empty($model->contact_address2) ? $client->address_2 : $model->contact_address2; + $birthday = !empty($client->birthday) ? $client->birthday : ''; $company_number = !empty($client->company_number) ? $client->company_number : ''; $contact = new \Registrar_Domain_Contact(); @@ -723,7 +715,7 @@ class Service implements \Box\InjectionAwareInterface $d->setExpirationTime(strtotime($model->expires_at)); } - return array($d, $adapter); + return [$d, $adapter]; } public static function onBeforeAdminCronRun(\Box_Event $event) @@ -741,10 +733,9 @@ class Service implements \Box\InjectionAwareInterface public function batchSyncExpirationDates() { - $key = 'servicedomain_last_sync'; - $ss = $this->di['mod_service']('system'); + $ss = $this->di['mod_service']('system'); $last_time = $ss->getParamValue($key); if ($last_time && (time() - strtotime($last_time)) < 86400 * 30) { return false; @@ -768,18 +759,18 @@ class Service implements \Box\InjectionAwareInterface public function tldCreate($data) { - $model = $this->di['db']->dispense('Tld'); - $model->tld = $data['tld']; - $model->tld_registrar_id = $data['tld_registrar_id']; + $model = $this->di['db']->dispense('Tld'); + $model->tld = $data['tld']; + $model->tld_registrar_id = $data['tld_registrar_id']; $model->price_registration = $data['price_registration']; - $model->price_renew = $data['price_renew']; - $model->price_transfer = $data['price_transfer']; - $model->min_years = isset($data['min_years']) ? (int)$data['min_years'] : 1; - $model->allow_register = isset($data['allow_register']) ? (bool)$data['allow_register'] : true; - $model->allow_transfer = isset($data['allow_transfer']) ? (bool)$data['allow_transfer'] : true; - $model->active = isset($data['active']) ? (bool)$data['active'] : false; - $model->updated_at = date('Y-m-d H:i:s'); - $model->created_at = date('Y-m-d H:i:s'); + $model->price_renew = $data['price_renew']; + $model->price_transfer = $data['price_transfer']; + $model->min_years = isset($data['min_years']) ? (int) $data['min_years'] : 1; + $model->allow_register = isset($data['allow_register']) ? (bool) $data['allow_register'] : true; + $model->allow_transfer = isset($data['allow_transfer']) ? (bool) $data['allow_transfer'] : true; + $model->active = isset($data['active']) ? (bool) $data['active'] : false; + $model->updated_at = date('Y-m-d H:i:s'); + $model->created_at = date('Y-m-d H:i:s'); $id = $this->di['db']->store($model); @@ -809,34 +800,34 @@ class Service implements \Box\InjectionAwareInterface public function tldGetSearchQuery($data) { - $query = "SELECT * FROM tld"; + $query = 'SELECT * FROM tld'; - $hide_inactive = isset($data['hide_inactive']) ? (bool)$data['hide_inactive'] : FALSE; - $allow_register = $this->di['array_get']($data, 'allow_register', NULL); - $allow_transfer = $this->di['array_get']($data, 'allow_transfer', NULL); + $hide_inactive = isset($data['hide_inactive']) ? (bool) $data['hide_inactive'] : false; + $allow_register = $this->di['array_get']($data, 'allow_register', null); + $allow_transfer = $this->di['array_get']($data, 'allow_transfer', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; if ($hide_inactive) { - $where[] = "active = 1"; + $where[] = 'active = 1'; } - if (NULL !== $allow_register) { - $where[] = "allow_register = 1"; + if (null !== $allow_register) { + $where[] = 'allow_register = 1'; } - if (NULL !== $allow_transfer) { - $where[] = "allow_transfer = 1"; + if (null !== $allow_transfer) { + $where[] = 'allow_transfer = 1'; } if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); + $query = $query.' WHERE '.implode(' AND ', $where); } - $query = $query . " ORDER BY id ASC"; + $query = $query.' ORDER BY id ASC'; - return array($query, $bindings); + return [$query, $bindings]; } public function tldFindAllActive() @@ -846,19 +837,19 @@ class Service implements \Box\InjectionAwareInterface public function tldFindOneActiveById($id) { - return $this->di['db']->findOne('Tld', 'id = :id AND active = 1 ORDER by id ASC', array(':id' => $id));; + return $this->di['db']->findOne('Tld', 'id = :id AND active = 1 ORDER by id ASC', [':id' => $id]); } public function tldGetPairs() { - return $this->di['db']->getAssoc("SELECT id, tld from tld WHERE active = 1 ORDER by id ASC"); + return $this->di['db']->getAssoc('SELECT id, tld from tld WHERE active = 1 ORDER by id ASC'); } public function tldAlreadyRegistered($tld) { - $tld = $this->di['db']->findOne('Tld', 'tld = :tld ORDER by id ASC', array(':tld' => $tld)); + $tld = $this->di['db']->findOne('Tld', 'tld = :tld ORDER by id ASC', [':tld' => $tld]); - return ($tld instanceof \Model_Tld); + return $tld instanceof \Model_Tld; } public function tldRm(\Model_Tld $model) @@ -874,20 +865,20 @@ class Service implements \Box\InjectionAwareInterface { $tldRegistrar = $this->di['db']->load('TldRegistrar', $model->tld_registrar_id); - return array( - 'tld' => $model->tld, + return [ + 'tld' => $model->tld, 'price_registration' => $model->price_registration, - 'price_renew' => $model->price_renew, - 'price_transfer' => $model->price_transfer, - 'active' => $model->active, - 'allow_register' => $model->allow_register, - 'allow_transfer' => $model->allow_transfer, - 'min_years' => $model->min_years, - 'registrar' => array( - 'id' => $model->tld_registrar_id, + 'price_renew' => $model->price_renew, + 'price_transfer' => $model->price_transfer, + 'active' => $model->active, + 'allow_register' => $model->allow_register, + 'allow_transfer' => $model->allow_transfer, + 'min_years' => $model->min_years, + 'registrar' => [ + 'id' => $model->tld_registrar_id, 'title' => $tldRegistrar->name, - ) - ); + ], + ]; } /** @@ -895,15 +886,15 @@ class Service implements \Box\InjectionAwareInterface */ public function tldFindOneByTld($tld) { - return $this->di['db']->findOne('Tld', 'tld = :tld ORDER by id ASC', array(':tld' => $tld)); + return $this->di['db']->findOne('Tld', 'tld = :tld ORDER by id ASC', [':tld' => $tld]); } public function registrarGetSearchQuery($data) { - $query = "SELECT * FROM tld_registrar ORDER BY name ASC"; - $bindings = array(); + $query = 'SELECT * FROM tld_registrar ORDER BY name ASC'; + $bindings = []; - return array($query, $bindings); + return [$query, $bindings]; } public function registrarGetAvailable() @@ -912,8 +903,8 @@ class Service implements \Box\InjectionAwareInterface $exists = $this->di['db']->getAssoc($query); - $pattern = BB_PATH_LIBRARY . '/Registrar/Adapter/*.php'; - $adapters = array(); + $pattern = BB_PATH_LIBRARY.'/Registrar/Adapter/*.php'; + $adapters = []; foreach (glob($pattern) as $path) { $adapter = pathinfo($path, PATHINFO_FILENAME); if (!array_key_exists($adapter, $exists)) { @@ -926,7 +917,7 @@ class Service implements \Box\InjectionAwareInterface public function registrarGetPairs() { - $query = "SELECT tr.id, tr.name FROM tld_registrar tr ORDER BY tr.id DESC"; + $query = 'SELECT tr.id, tr.name FROM tld_registrar tr ORDER BY tr.id DESC'; return $this->di['db']->getAssoc($query); } @@ -945,33 +936,32 @@ class Service implements \Box\InjectionAwareInterface { $class = $this->registrarGetRegistrarAdapterClassName($model); - return call_user_func(array($class, 'getConfig')); + return call_user_func([$class, 'getConfig']); } private function registrarGetRegistrarAdapterClassName(\Model_TldRegistrar $model) { - if (!file_exists(BB_PATH_LIBRARY . '/Registrar/Adapter/' . $model->registrar . '.php')) { - throw new \Box_Exception("Domain registrar :adapter was not found", array(':adapter' => $model->registrar)); + if (!file_exists(BB_PATH_LIBRARY.'/Registrar/Adapter/'.$model->registrar.'.php')) { + throw new \Box_Exception('Domain registrar :adapter was not found', [':adapter' => $model->registrar]); } $class = sprintf('Registrar_Adapter_%s', $model->registrar); if (!class_exists($class)) { - throw new \Box_Exception("Registrar :adapter was not found", array(':adapter' => $class)); + throw new \Box_Exception('Registrar :adapter was not found', [':adapter' => $class]); } return $class; } - public function registrarGetRegistrarAdapter(\Model_TldRegistrar $r) { - $config = $this->registrarGetConfiguration($r); - $class = $this->registrarGetRegistrarAdapterClassName($r); + $config = $this->registrarGetConfiguration($r); + $class = $this->registrarGetRegistrarAdapterClassName($r); $registrar = new $class($config); if (!$registrar instanceof \Registrar_AdapterAbstract) { - throw new \Box_Exception('Registrar adapter :adapter should extend Registrar_AdapterAbstract', array(':adapter' => $class)); + throw new \Box_Exception('Registrar adapter :adapter should extend Registrar_AdapterAbstract', [':adapter' => $class]); } - + $registrar->setLog($this->di['logger']); if (isset($r->test_mode) && $r->test_mode) { @@ -984,7 +974,7 @@ class Service implements \Box\InjectionAwareInterface public function registrarCreate($code) { $model = $this->di['db']->dispense('TldRegistrar'); - $model->name = $code; + $model->name = $code; $model->registrar = $code; $model->test_mode = 0; @@ -998,7 +988,7 @@ class Service implements \Box\InjectionAwareInterface public function registrarCopy(\Model_TldRegistrar $model) { $new = $this->di['db']->dispense('TldRegistrar'); - $new->name = $model->name . " (Copy)"; + $new->name = $model->name.' (Copy)'; $new->registrar = $model->registrar; $new->test_mode = $model->test_mode; @@ -1026,7 +1016,7 @@ class Service implements \Box\InjectionAwareInterface public function registrarRm(\Model_TldRegistrar $model) { - $domains = $this->di['db']->find('ServiceDomain', 'tld_registrar_id = :registrar_id', array(':registrar_id' => $model->id)); + $domains = $this->di['db']->find('ServiceDomain', 'tld_registrar_id = :registrar_id', [':registrar_id' => $model->id]); if (count($domains) > 0) { throw new \Box_Exception('Can not remove registrar which has domains'); } @@ -1044,14 +1034,14 @@ class Service implements \Box\InjectionAwareInterface { $c = $this->registrarGetRegistrarAdapterConfig($model); - return array( - 'id' => $model->id, - 'title' => $model->name, - 'label' => $c['label'], - 'config' => $this->registrarGetConfiguration($model), - 'form' => $c['form'], + return [ + 'id' => $model->id, + 'title' => $model->name, + 'label' => $c['label'], + 'config' => $this->registrarGetConfiguration($model), + 'form' => $c['form'], 'test_mode' => $model->test_mode, - ); + ]; } public function updateDomain(\Model_ServiceDomain $s, $data) @@ -1061,14 +1051,13 @@ class Service implements \Box\InjectionAwareInterface $s->ns3 = $this->di['array_get']($data, 'ns3', $s->ns3); $s->ns4 = $this->di['array_get']($data, 'ns4', $s->ns4); - $s->period = (int)$this->di['array_get']($data, 'period', $s->period); - $s->privacy = (bool)$this->di['array_get']($data, 'privacy', $s->privacy); - $s->locked = (bool)$this->di['array_get']($data, 'locked', $s->locked); + $s->period = (int) $this->di['array_get']($data, 'period', $s->period); + $s->privacy = (bool) $this->di['array_get']($data, 'privacy', $s->privacy); + $s->locked = (bool) $this->di['array_get']($data, 'locked', $s->locked); - - $s->period = (int)$this->di['array_get']($data, 'period', $s->period); - $s->privacy = (bool)$this->di['array_get']($data, 'privacy', $s->privacy); - $s->locked = (bool)$this->di['array_get']($data, 'locked', $s->locked); + $s->period = (int) $this->di['array_get']($data, 'period', $s->period); + $s->privacy = (bool) $this->di['array_get']($data, 'privacy', $s->privacy); + $s->locked = (bool) $this->di['array_get']($data, 'locked', $s->locked); $s->transfer_code = $this->di['array_get']($data, 'transfer_code', $s->transfer_code); $s->updated_at = date('Y-m-d H:i:s'); @@ -1078,6 +1067,4 @@ class Service implements \Box\InjectionAwareInterface return true; } - - -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicedomain/ServiceTld.php b/src/bb-modules/Servicedomain/ServiceTld.php index 48e9f7da9..472af0f0f 100644 --- a/src/bb-modules/Servicedomain/ServiceTld.php +++ b/src/bb-modules/Servicedomain/ServiceTld.php @@ -1,6 +1,6 @@ di['db']->findOne('Tld', 'tld = ?', array($tld)); + return $this->di['db']->findOne('Tld', 'tld = ?', [$tld]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicedownloadable/Api/Admin.php b/src/bb-modules/Servicedownloadable/Api/Admin.php index dd5db9cd6..feda3d935 100644 --- a/src/bb-modules/Servicedownloadable/Api/Admin.php +++ b/src/bb-modules/Servicedownloadable/Api/Admin.php @@ -1,6 +1,6 @@ field content * * @return bool */ public function upload($data) { - $required = array( + $required = [ 'id' => 'Product ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Product', $data['id'], 'Product not found'); - if(!isset($_FILES['file_data'])) { + if (!isset($_FILES['file_data'])) { throw new \Box_Exception('File was not uploaded'); } $service = $this->getService(); + return $service->uploadProductFile($model); } @@ -49,27 +51,28 @@ class Admin extends \Api_Abstract * Uses $_FILES array so make sure your form is * enctype="multipart/form-data" * - * @param int $order_id - order id + * @param int $order_id - order id * @param file $file_data - field content * * @return bool */ public function update($data) { - $required = array( + $required = [ 'order_id' => 'Order ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $order = $this->di['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found'); $orderService = $this->di['mod_service']('order'); $serviceDownloadable = $orderService->getOrderService($order); - if(!$serviceDownloadable instanceof \Model_ServiceDownloadable) { + if (!$serviceDownloadable instanceof \Model_ServiceDownloadable) { throw new \Box_Exception('Order is not activated'); } $service = $this->getService(); + return $service->updateProductFile($serviceDownloadable, $order); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicedownloadable/Api/Client.php b/src/bb-modules/Servicedownloadable/Api/Client.php index efcc5c78c..6756c8b0e 100644 --- a/src/bb-modules/Servicedownloadable/Api/Client.php +++ b/src/bb-modules/Servicedownloadable/Api/Client.php @@ -1,6 +1,6 @@ getIdentity(); - $order = $this->di['db']->findOne('ClientOrder', 'id = :id AND client_id = :client_id', array(':id' => $data['order_id'], ':client_id' => $identity->id)); - if(!$order instanceof \Model_ClientOrder ) { + $order = $this->di['db']->findOne('ClientOrder', 'id = :id AND client_id = :client_id', [':id' => $data['order_id'], ':client_id' => $identity->id]); + if (!$order instanceof \Model_ClientOrder) { throw new \Box_Exception('Order not found'); } $orderService = $this->di['mod_service']('order'); $s = $orderService->getOrderService($order); - if(!$s instanceof \Model_ServiceDownloadable) { + if (!$s instanceof \Model_ServiceDownloadable) { throw new \Box_Exception('Order is not activated'); } $service = $this->getService(); + return (bool) $service->sendFile($s); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicedownloadable/Controller/Client.php b/src/bb-modules/Servicedownloadable/Controller/Client.php index 5b8c73c13..b269a8f0d 100644 --- a/src/bb-modules/Servicedownloadable/Controller/Client.php +++ b/src/bb-modules/Servicedownloadable/Controller/Client.php @@ -1,6 +1,6 @@ get('/servicedownloadable/get-file/:id', 'get_download', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/servicedownloadable/get-file/:id', 'get_download', ['id' => '[0-9]+'], get_class($this)); } public function get_download(\Box_App $app, $id) { $api = $this->di['api_client']; - $data = array( - 'order_id' => $id, - ); + $data = [ + 'order_id' => $id, + ]; $api->servicedownloadable_send_file($data); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicedownloadable/Service.php b/src/bb-modules/Servicedownloadable/Service.php index acab17c31..515fdb91e 100644 --- a/src/bb-modules/Servicedownloadable/Service.php +++ b/src/bb-modules/Servicedownloadable/Service.php @@ -1,6 +1,6 @@ config, 1); - $required = array( + $required = [ 'filename' => 'Product is not configured completely.', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $c); $data['filename'] = $c['filename']; + return array_merge($c, $data); } - + public function validateOrderData(array &$data) { - $required = array( + $required = [ 'filename' => 'Filename is missing in product config', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); } /** - * @param \Model_ClientOrder $order * @return \Model_ServiceDownloadable */ public function action_create(\Model_ClientOrder $order) { $c = json_decode($order->config, 1); - if (!is_array($c)){ + if (!is_array($c)) { throw new \Box_Exception(sprintf('Order #%s config is missing', $order->id)); } $this->validateOrderData($c); @@ -85,10 +86,9 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_renew(\Model_ClientOrder $order) { @@ -96,10 +96,9 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_suspend(\Model_ClientOrder $order) { @@ -107,10 +106,9 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_unsuspend(\Model_ClientOrder $order) { @@ -118,10 +116,9 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_cancel(\Model_ClientOrder $order) { @@ -129,10 +126,9 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_uncancel(\Model_ClientOrder $order) { @@ -140,23 +136,22 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order + * * @return void */ public function action_delete(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); $service = $orderService->getOrderService($order); - if($service instanceof \Model_ServiceDownloadable) { + if ($service instanceof \Model_ServiceDownloadable) { $this->di['db']->trash($service); } } public function hitDownload(\Model_ServiceDownloadable $model) { - $model->downloads += 1; + ++$model->downloads; $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); } @@ -164,22 +159,22 @@ class Service implements InjectionAwareInterface public function toApiArray(\Model_ServiceDownloadable $model, $deep = false, $identity = null) { $productService = $this->di['mod_service']('product'); - $result = array( - 'path' => $productService->getSavePath($model->filename), - 'filename' => $model->filename, - ); - - if($identity instanceof \Model_Admin) { + $result = [ + 'path' => $productService->getSavePath($model->filename), + 'filename' => $model->filename, + ]; + + if ($identity instanceof \Model_Admin) { $result['downloads'] = $model->downloads; } - + return $result; } public function uploadProductFile(\Model_Product $productModel) { $request = $this->di['request']; - if ($request->hasFiles() == 0) { + if (0 == $request->hasFiles()) { throw new \Box_Exception('Error uploading file'); } $files = $request->getUploadedFiles(); @@ -198,19 +193,19 @@ class Service implements InjectionAwareInterface $this->di['db']->store($productModel); $this->di['logger']->info('Uploaded new file for product %s', $productModel->id); + return true; } /** - * @param \Model_ServiceDownloadable $serviceDownloadable - * @param \Model_ClientOrder $order * @return bool + * * @throws \Box_Exception */ public function updateProductFile(\Model_ServiceDownloadable $serviceDownloadable, \Model_ClientOrder $order) { $request = $this->di['request']; - if ($request->hasFiles() == 0) { + if (0 == $request->hasFiles()) { throw new \Box_Exception('Error uploading file'); } $productService = $this->di['mod_service']('product'); @@ -224,6 +219,7 @@ class Service implements InjectionAwareInterface $this->di['db']->store($serviceDownloadable); $this->di['logger']->info('Uploaded new file for order %s', $order->id); + return true; } @@ -249,17 +245,18 @@ class Service implements InjectionAwareInterface } } - public function sendDownload($filename, $path) { - if(APPLICATION_ENV == 'testing') { - return ; + public function sendDownload($filename, $path) + { + if (APPLICATION_ENV == 'testing') { + return; } - header("Content-Type: application/force-download"); - header("Content-Type: application/octet-stream"); - header("Content-Type: application/download"); - header("Content-Description: File Transfer"); - header("Content-Disposition: attachment; filename=$filename".";"); - header("Content-Transfer-Encoding: binary"); + header('Content-Type: application/force-download'); + header('Content-Type: application/octet-stream'); + header('Content-Type: application/download'); + header('Content-Description: File Transfer'); + header("Content-Disposition: attachment; filename=$filename".';'); + header('Content-Transfer-Encoding: binary'); readfile($path); flush(); } @@ -269,13 +266,14 @@ class Service implements InjectionAwareInterface $info = $this->toApiArray($serviceDownloadable); $filename = $info['filename']; $path = $info['path']; - if(!$this->di['tools']->fileExists($path)) { + if (!$this->di['tools']->fileExists($path)) { throw new \Box_Exception('File can not be downloaded at the moment. Please contact support', null, 404); } $this->hitDownload($serviceDownloadable); $this->sendDownload($filename, $path); $this->di['logger']->info('Downloaded service %s file', $serviceDownloadable->id); + return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicehosting/Api/Admin.php b/src/bb-modules/Servicehosting/Api/Admin.php index be1e225d0..3144bedc3 100644 --- a/src/bb-modules/Servicehosting/Api/Admin.php +++ b/src/bb-modules/Servicehosting/Api/Admin.php @@ -1,6 +1,6 @@ _getService($data); + [$order, $s] = $this->_getService($data); $plan = $this->di['db']->getExistingModelById('ServiceHostingHp', $data['plan_id'], 'Hosting plan not found'); - + $service = $this->getService(); + return (bool) $service->changeAccountPlan($order, $s, $plan); } - + /** - * Change hosting account username - * - * @param int $order_id - Hosting account order id + * Change hosting account username. + * + * @param int $order_id - Hosting account order id * @param string $username - New username - * - * @return boolean + * + * @return bool */ public function change_username($data) { - list($order, $s) = $this->_getService($data); + [$order, $s] = $this->_getService($data); $service = $this->getService(); + return (bool) $service->changeAccountUsername($order, $s, $data); } - + /** - * Change hosting account ip - * - * @param int $order_id - Hosting account order id + * Change hosting account ip. + * + * @param int $order_id - Hosting account order id * @param string $username - New username - * - * @return boolean + * + * @return bool */ public function change_ip($data) { - list($order, $s) = $this->_getService($data); + [$order, $s] = $this->_getService($data); $service = $this->getService(); + return (bool) $service->changeAccountIp($order, $s, $data); } - + /** - * Change hosting account domain - * - * @param int $order_id - Hosting account order id - * @param string $tld - Top level domain value, ie: .com - * @param string $sld - Second level domain value, ie: domainname - * - * @return boolean + * Change hosting account domain. + * + * @param int $order_id - Hosting account order id + * @param string $tld - Top level domain value, ie: .com + * @param string $sld - Second level domain value, ie: domainname + * + * @return bool */ public function change_domain($data) { - list($order, $s) = $this->_getService($data); + [$order, $s] = $this->_getService($data); $service = $this->getService(); + return (bool) $service->changeAccountDomain($order, $s, $data); } - + /** * Change hosting account password. - * - * @param int $order_id - Hosting account order id - * @param string $password - New account password + * + * @param int $order_id - Hosting account order id + * @param string $password - New account password * @param string $password_confirm - Must be same value as password field - * - * @return boolean + * + * @return bool */ public function change_password($data) { - list($order, $s) = $this->_getService($data); + [$order, $s] = $this->_getService($data); $service = $this->getService(); + return (bool) $service->changeAccountPassword($order, $s, $data); } - + /** * Synchronize account with server values. - * + * * @param int $order_id - Hosting account order id - * - * @return boolean + * + * @return bool */ public function sync($data) { - list($order, $s) = $this->_getService($data); + [$order, $s] = $this->_getService($data); $service = $this->getService(); + return (bool) $service->sync($order, $s); } - + /** * Update account information on BoxBilling database. * This does not send actions to real account on hosting server. - * + * * @param int $order_id - Hosting account order id - * + * * @optional string $username - Hosting account username * @optional string $ip - Hosting account ip - * - * @return boolean + * + * @return bool */ public function update($data) { - list(, $s) = $this->_getService($data); + [, $s] = $this->_getService($data); $service = $this->getService(); + return (bool) $service->update($s, $data); } /** - * Get list of available server managers on system - * - * @return array + * Get list of available server managers on system. + * + * @return array */ public function manager_get_pairs($data) { @@ -142,8 +150,8 @@ class Admin extends \Api_Abstract } /** - * Get list of available hosting servers on system - * + * Get list of available hosting servers on system. + * * @return array */ public function server_get_pairs($data) @@ -152,19 +160,19 @@ class Admin extends \Api_Abstract } /** - * Get paginated list of servers - * + * Get paginated list of servers. + * * @return array */ public function server_get_list($data) { $servers = $this->di['db']->find('ServiceHostingServer', 'ORDER BY id ASC'); - $serversArr = array(); + $serversArr = []; foreach ($servers as $server) { $serversArr[] = $this->getService()->toHostingServerApiArray($server, false, $this->getIdentity()); } - list($sql, $params) = $this->getService()->getServersSearchQuery($data); + [$sql, $params] = $this->getService()->getServersSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $result = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); @@ -174,12 +182,12 @@ class Admin extends \Api_Abstract } /** - * Create new hosting server - * - * @param string $name - server name - * @param string $ip - server ip + * Create new hosting server. + * + * @param string $name - server name + * @param string $ip - server ip * @param string $manager - server manager code - * + * * @optional string $hostname - server hostname * @optional string $ns1 - default nameserver 1 * @optional string $ns2 - default nameserver 2 @@ -187,70 +195,77 @@ class Admin extends \Api_Abstract * @optional string $ns4 - default nameserver 4 * @optional string $username - server API login username * @optional string $password - server API login password - * @optional string $accesshash - server API login access hash + * @optional string $accesshash - server API login access hash * @optional string $port - server API port * @optional bool $secure - flag to define whether to use secure connection (https) to server or not (http) * @optional bool $active - flag to enable/disable server - * - * @return int - server id - * @throws \Box_Exception + * + * @return int - server id + * + * @throws \Box_Exception */ public function server_create($data) { - $required = array( - 'name' => 'Server name is missing', - 'ip' => 'Server IP is missing', + $required = [ + 'name' => 'Server name is missing', + 'ip' => 'Server IP is missing', 'manager' => 'Server manager is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); + return (int) $service->createServer($data['name'], $data['ip'], $data['manager'], $data); } /** - * Get server details - * + * Get server details. + * * @param int $id - server id + * * @return array - * - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function server_get($data) { - $required = array( - 'id' => 'Server id is missing', - ); + $required = [ + 'id' => 'Server id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found'); $service = $this->getService(); + return $service->toHostingServerApiArray($model, true, $this->getIdentity()); } /** - * Delete server - * + * Delete server. + * * @param int $id - server id - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function server_delete($data) { - $required = array( - 'id' => 'Server id is missing', - ); + $required = [ + 'id' => 'Server id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found'); + return (bool) $this->getService()->deleteServer($model); } /** - * Update server configuration - * + * Update server configuration. + * * @param int $id - server id - * + * * @optional string $hostname - server hostname * @optional string $ns1 - default nameserver 1 * @optional string $ns2 - default nameserver 2 @@ -258,39 +273,42 @@ class Admin extends \Api_Abstract * @optional string $ns4 - default nameserver 4 * @optional string $username - server API login username * @optional string $password - server API login password - * @optional string $accesshash - server API login access hash + * @optional string $accesshash - server API login access hash * @optional string $port - server API port * @optional bool $secure - flag to define whether to use secure connection (https) to server or not (http) * @optional bool $active - flag to enable/disable server - * - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function server_update($data) { - $required = array( - 'id' => 'Server id is missing', - ); + $required = [ + 'id' => 'Server id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found'); $service = $this->getService(); + return (bool) $service->updateServer($model, $data); } /** - * Test connection to server - * + * Test connection to server. + * * @param int $id - server id - * + * * @return bool - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function server_test_connection($data) { - $required = array( - 'id' => 'Server id is missing', - ); + $required = [ + 'id' => 'Server id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ServiceHostingServer', $data['id'], 'Server not found'); @@ -299,8 +317,8 @@ class Admin extends \Api_Abstract } /** - * Get hoting plan pairs - * + * Get hoting plan pairs. + * * @return array */ public function hp_get_pairs($data) @@ -309,17 +327,17 @@ class Admin extends \Api_Abstract } /** - * Get hostin plans paginated list - * + * Get hostin plans paginated list. + * * @return array */ public function hp_get_list($data) { - list ($sql, $params) = $this->getService()->getHpSearchQuery($data); + [$sql, $params] = $this->getService()->getHpSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $model = $this->di['db']->getExistingModelById('ServiceHostingHp', $item['id'], 'Post not found'); + $model = $this->di['db']->getExistingModelById('ServiceHostingHp', $item['id'], 'Post not found'); $pager['list'][$key] = $this->getService()->toHostingHpApiArray($model, false, $this->getIdentity()); } @@ -327,18 +345,19 @@ class Admin extends \Api_Abstract } /** - * Delete hosting plan - * + * Delete hosting plan. + * * @param int $id - hosting plan id - * - * @return boolean - * @throws \Box_Exception + * + * @return bool + * + * @throws \Box_Exception */ public function hp_delete($data) { - $required = array( - 'id' => 'Hosting plan ID is missing', - ); + $required = [ + 'id' => 'Hosting plan ID is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ServiceHostingHp', $data['id'], 'Hosting plan not found'); @@ -347,18 +366,19 @@ class Admin extends \Api_Abstract } /** - * Get hosting plan details - * + * Get hosting plan details. + * * @param int $id - hosting plan id - * + * * @return array - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function hp_get($data) { - $required = array( - 'id' => 'Hosting plan ID is missing', - ); + $required = [ + 'id' => 'Hosting plan ID is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ServiceHostingHp', $data['id'], 'Hosting plan not found'); @@ -367,60 +387,65 @@ class Admin extends \Api_Abstract } /** - * Update hosting plan details - * + * Update hosting plan details. + * * @param int $id - hosting plan id - * + * * @optional string $name - hosting plan name. Used as identifier on server - * + * * @return bool - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function hp_update($data) { - $required = array( - 'id' => 'Hosting plan ID is missing', - ); + $required = [ + 'id' => 'Hosting plan ID is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ServiceHostingHp', $data['id'], 'Hosting plan not found'); $service = $this->getService(); + return (bool) $service->updateHp($model, $data); } /** - * Update hosting plan details - * + * Update hosting plan details. + * * @param string $name - hosting plan name. Used as identifier on server - * + * * @return int - new hosting plan id - * @throws \Box_Exception + * + * @throws \Box_Exception */ public function hp_create($data) { - $required = array( - 'name' => 'Hosting plan name is missing', - ); + $required = [ + 'name' => 'Hosting plan name is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); + return (int) $service->createHp($data['name'], $data); } public function _getService($data) { - $required = array( - 'order_id' => 'Order ID name is missing', - ); + $required = [ + 'order_id' => 'Order ID name is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $order = $this->di['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found'); $orderSerivce = $this->di['mod_service']('order'); $s = $orderSerivce->getOrderService($order); - if(!$s instanceof \Model_ServiceHosting) { + if (!$s instanceof \Model_ServiceHosting) { throw new \Box_Exception('Order is not activated'); } - return array($order, $s); + + return [$order, $s]; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicehosting/Api/Client.php b/src/bb-modules/Servicehosting/Api/Client.php index 8371a6b27..f5b0a3bc6 100644 --- a/src/bb-modules/Servicehosting/Api/Client.php +++ b/src/bb-modules/Servicehosting/Api/Client.php @@ -1,6 +1,6 @@ _getService($data); + [$order, $s] = $this->_getService($data); + return $this->getService()->changeAccountUsername($order, $s, $data); } /** - * Change hosting account domain - * - * @param int $order_id - Hosting account order id - * @param string $password - New second level domain name, ie: mydomain + * Change hosting account domain. + * + * @param int $order_id - Hosting account order id + * @param string $password - New second level domain name, ie: mydomain * @param string $password_confirm - New top level domain, ie: .com - * - * @return boolean + * + * @return bool */ public function change_domain($data) { - list($order, $s) = $this->_getService($data); + [$order, $s] = $this->_getService($data); + return $this->getService()->changeAccountDomain($order, $s, $data); } /** - * Change hosting account password - * - * @param int $order_id - Hosting account order id - * @param string $password - New account password - * @param string $password_confirm - Repeat new password - * - * @return boolean + * Change hosting account password. + * + * @param int $order_id - Hosting account order id + * @param string $password - New account password + * @param string $password_confirm - Repeat new password + * + * @return bool */ public function change_password($data) { - list($order, $s) = $this->_getService($data); + [$order, $s] = $this->_getService($data); + return $this->getService()->changeAccountPassword($order, $s, $data); } /** - * Get hosting plans pairs. Usually for select box + * Get hosting plans pairs. Usually for select box. + * * @return array */ public function hp_get_pairs($data) @@ -71,21 +76,21 @@ class Client extends \Api_Abstract public function _getService($data) { - if(!isset($data['order_id'])) { + if (!isset($data['order_id'])) { throw new \Box_Exception('Order id is required'); } $identity = $this->getIdentity(); - $order = $this->di['db']->findOne('ClientOrder', 'id = ? and client_id = ?', array($data['order_id'], $identity->id)); - if(!$order instanceof \Model_ClientOrder ) { + $order = $this->di['db']->findOne('ClientOrder', 'id = ? and client_id = ?', [$data['order_id'], $identity->id]); + if (!$order instanceof \Model_ClientOrder) { throw new \Box_Exception('Order not found'); } $orderSerivce = $this->di['mod_service']('order'); $s = $orderSerivce->getOrderService($order); - if(!$s instanceof \Model_ServiceHosting) { + if (!$s instanceof \Model_ServiceHosting) { throw new \Box_Exception('Order is not activated'); } - return array($order, $s); + return [$order, $s]; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicehosting/Api/Guest.php b/src/bb-modules/Servicehosting/Api/Guest.php index 012083622..c83d2eab8 100644 --- a/src/bb-modules/Servicehosting/Api/Guest.php +++ b/src/bb-modules/Servicehosting/Api/Guest.php @@ -1,6 +1,6 @@ 'Product id is missing', - ); + $required = [ + 'product_id' => 'Product id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $product_id = $this->di['array_get']($data, 'product_id', 0); $product = $this->di['db']->getExistingModelById('Product', $product_id, 'Product was not found'); - if ($product->type !== \Model_Product::HOSTING){ + if (\Model_Product::HOSTING !== $product->type) { throw new \Box_Exception('Product type is invalid'); } return $this->getService()->getFreeTlds($product); - } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicehosting/Controller/Admin.php b/src/bb-modules/Servicehosting/Controller/Admin.php index 3e2f98dd5..8314168a8 100644 --- a/src/bb-modules/Servicehosting/Controller/Admin.php +++ b/src/bb-modules/Servicehosting/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'system', - 'index' => 140, + return [ + 'subpages' => [ + [ + 'location' => 'system', + 'index' => 140, 'label' => 'Hosting plans and servers', - 'uri' => $this->di['url']->adminLink('servicehosting'), + 'uri' => $this->di['url']->adminLink('servicehosting'), 'class' => '', - ), - ), - ); + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/servicehosting', 'get_index', null, get_class($this)); - $app->get('/servicehosting/plan/:id', 'get_plan', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/servicehosting/server/:id', 'get_server', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/servicehosting', 'get_index', null, get_class($this)); + $app->get('/servicehosting/plan/:id', 'get_plan', ['id' => '[0-9]+'], get_class($this)); + $app->get('/servicehosting/server/:id', 'get_server', ['id' => '[0-9]+'], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_servicehosting_index'); } public function get_plan(\Box_App $app, $id) { $api = $this->di['api_admin']; - $hp = $api->servicehosting_hp_get(array('id'=>$id)); - return $app->render('mod_servicehosting_hp', array('hp'=>$hp)); + $hp = $api->servicehosting_hp_get(['id' => $id]); + + return $app->render('mod_servicehosting_hp', ['hp' => $hp]); } public function get_server(\Box_App $app, $id) { $api = $this->di['api_admin']; - $server = $api->servicehosting_server_get(array('id'=>$id)); - return $app->render('mod_servicehosting_server', array('server'=>$server)); + $server = $api->servicehosting_server_get(['id' => $id]); + + return $app->render('mod_servicehosting_server', ['server' => $server]); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicehosting/Service.php b/src/bb-modules/Servicehosting/Service.php index bd96c488a..73b7d653d 100644 --- a/src/bb-modules/Servicehosting/Service.php +++ b/src/bb-modules/Servicehosting/Service.php @@ -1,6 +1,6 @@ _getDomainTuple($data); - return __(':hosting for :domain', array(':hosting'=>$product->title, ':domain'=>$sld.$tld)); - } catch(\Exception $e) { + [$sld, $tld] = $this->_getDomainTuple($data); + + return __(':hosting for :domain', [':hosting' => $product->title, ':domain' => $sld.$tld]); + } catch (\Exception $e) { // should never occur, but in case error_log($e->getMessage()); } @@ -50,24 +53,23 @@ class Service implements InjectionAwareInterface public function validateOrderData(array &$data) { - if(!isset($data['server_id'])) { + if (!isset($data['server_id'])) { throw new \Box_Exception('Hosting product is not configured completely. Configure server for hosting product.', null, 701); } - if(!isset($data['hosting_plan_id'])) { + if (!isset($data['hosting_plan_id'])) { throw new \Box_Exception('Hosting product is not configured completely. Configure hosting plan for hosting product.', null, 702); } - if(!isset($data['sld']) || empty($data['sld'])) { + if (!isset($data['sld']) || empty($data['sld'])) { throw new \Box_Exception('Domain name is not valid.', null, 703); } - if(!isset($data['tld']) || empty($data['tld'])) { + if (!isset($data['tld']) || empty($data['tld'])) { throw new \Box_Exception('Domain extension is not valid.', null, 704); } } /** - * * @todo - * @param \Model_ClientOrder $order + * * @return void */ public function action_create(\Model_ClientOrder $order) @@ -99,17 +101,17 @@ class Service implements InjectionAwareInterface { $orderService = $this->di['mod_service']('order'); $model = $orderService->getOrderService($order); - if(!$model instanceof \RedBean_SimpleModel) { - throw new \Box_Exception('Order :id has no active service', array(':id'=>$order->id)); + if (!$model instanceof \RedBean_SimpleModel) { + throw new \Box_Exception('Order :id has no active service', [':id' => $order->id]); } $pass = $this->di['tools']->generatePassword(10, 4); $c = $orderService->getConfig($order); - if(isset($c['password']) && !empty($c['password'])) { + if (isset($c['password']) && !empty($c['password'])) { $pass = $c['password']; } - if(isset($c['username']) && !empty($c['username'])) { + if (isset($c['username']) && !empty($c['username'])) { $username = $c['username']; } else { $username = $this->_generateUsername($model->sld.$model->tld); @@ -119,120 +121,119 @@ class Service implements InjectionAwareInterface $model->pass = $pass; $this->di['db']->store($model); - if(!isset($c['import']) || !$c['import']) { - list($adapter, $account) = $this->_getAM($model); + if (!isset($c['import']) || !$c['import']) { + [$adapter, $account] = $this->_getAM($model); $adapter->createAccount($account); } - return array( - 'username' => $username, - 'password' => $pass, - ); + return [ + 'username' => $username, + 'password' => $pass, + ]; } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_renew(\Model_ClientOrder $order) { // move expiration period to future $orderService = $this->di['mod_service']('order'); $model = $orderService->getOrderService($order); - if(!$model instanceof \RedBean_SimpleModel) { - throw new \Box_Exception('Order :id has no active service', array(':id'=>$order->id)); + if (!$model instanceof \RedBean_SimpleModel) { + throw new \Box_Exception('Order :id has no active service', [':id' => $order->id]); } - //@todo ? + // @todo ? $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return true; } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_suspend(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); $model = $orderService->getOrderService($order); - if(!$model instanceof \RedBean_SimpleModel) { - throw new \Box_Exception('Order :id has no active service', array(':id'=>$order->id)); + if (!$model instanceof \RedBean_SimpleModel) { + throw new \Box_Exception('Order :id has no active service', [':id' => $order->id]); } - list($adapter, $account) = $this->_getAM($model); + [$adapter, $account] = $this->_getAM($model); $adapter->suspendAccount($account); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return true; } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_unsuspend(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); $model = $orderService->getOrderService($order); - if(!$model instanceof \RedBean_SimpleModel) { - throw new \Box_Exception('Order :id has no active service', array(':id'=>$order->id)); + if (!$model instanceof \RedBean_SimpleModel) { + throw new \Box_Exception('Order :id has no active service', [':id' => $order->id]); } - list($adapter, $account) = $this->_getAM($model); + [$adapter, $account] = $this->_getAM($model); $adapter->unsuspendAccount($account); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return true; } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_cancel(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); $model = $orderService->getOrderService($order); - if(!$model instanceof \RedBean_SimpleModel) { - throw new \Box_Exception('Order :id has no active service', array(':id'=>$order->id)); + if (!$model instanceof \RedBean_SimpleModel) { + throw new \Box_Exception('Order :id has no active service', [':id' => $order->id]); } - list($adapter, $account) = $this->_getAM($model); + [$adapter, $account] = $this->_getAM($model); $adapter->cancelAccount($account); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return true; } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_uncancel(\Model_ClientOrder $order) { $this->action_create($order); $orderService = $this->di['mod_service']('order'); $model = $orderService->getOrderService($order); - list($adapter, $account) = $this->_getAM($model); + [$adapter, $account] = $this->_getAM($model); $adapter->createAccount($account); + return true; } /** - * @param \Model_ClientOrder $order * @return void */ public function action_delete(\Model_ClientOrder $order) { $orderService = $this->di['mod_service']('order'); $service = $orderService->getOrderService($order); - if($service instanceof \Model_ServiceHosting) { - //cancel if not canceled - if($order->status != \Model_ClientOrder::STATUS_CANCELED) { + if ($service instanceof \Model_ServiceHosting) { + // cancel if not canceled + if (\Model_ClientOrder::STATUS_CANCELED != $order->status) { $this->action_cancel($order); } $this->di['db']->trash($service); @@ -242,28 +243,29 @@ class Service implements InjectionAwareInterface public function changeAccountPlan(\Model_ClientOrder $order, \Model_ServiceHosting $model, \Model_ServiceHostingHp $hp) { $model->service_hosting_hp_id = $hp->id; - if($this->_performOnService($order)){ + if ($this->_performOnService($order)) { $package = $this->getServerPackage($hp); - list($adapter, $account) = $this->_getAM($model); + [$adapter, $account] = $this->_getAM($model); $adapter->changeAccountPackage($account, $package); } $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Changed hosting plan of account #%s', $model->id); - return TRUE; + + return true; } public function changeAccountUsername(\Model_ClientOrder $order, \Model_ServiceHosting $model, $data) { - if(!isset($data['username']) || empty($data['username'])) { + if (!isset($data['username']) || empty($data['username'])) { throw new \Box_Exception('Account username is missing or is not valid'); } $u = strtolower($data['username']); - if($this->_performOnService($order)){ - list($adapter, $account) = $this->_getAM($model); + if ($this->_performOnService($order)) { + [$adapter, $account] = $this->_getAM($model); $adapter->changeAccountUsername($account, $u); } @@ -272,19 +274,20 @@ class Service implements InjectionAwareInterface $this->di['db']->store($model); $this->di['logger']->info('Changed hosting account %s username', $model->id); - return TRUE; + + return true; } public function changeAccountIp(\Model_ClientOrder $order, \Model_ServiceHosting $model, $data) { - if(!isset($data['ip']) || empty($data['ip'])) { + if (!isset($data['ip']) || empty($data['ip'])) { throw new \Box_Exception('Account ip is missing or is not valid'); } $ip = $data['ip']; - if($this->_performOnService($order)){ - list($adapter, $account) = $this->_getAM($model); + if ($this->_performOnService($order)) { + [$adapter, $account] = $this->_getAM($model); $adapter->changeAccountIp($account, $ip); } @@ -292,12 +295,13 @@ class Service implements InjectionAwareInterface $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Changed hosting account %s ip', $model->id); - return TRUE; + + return true; } public function changeAccountDomain(\Model_ClientOrder $order, \Model_ServiceHosting $model, $data) { - if(!isset($data['tld']) || empty($data['tld']) || + if (!isset($data['tld']) || empty($data['tld']) || !isset($data['sld']) || empty($data['sld'])) { throw new \Box_Exception('Domain sld or tld is missing'); } @@ -305,8 +309,8 @@ class Service implements InjectionAwareInterface $sld = $data['sld']; $tld = $data['tld']; - if($this->_performOnService($order)){ - list($adapter, $account) = $this->_getAM($model); + if ($this->_performOnService($order)) { + [$adapter, $account] = $this->_getAM($model); $adapter->changeAccountDomain($account, $sld.$tld); } @@ -315,20 +319,21 @@ class Service implements InjectionAwareInterface $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Changed hosting account %s domain', $model->id); - return TRUE; + + return true; } public function changeAccountPassword(\Model_ClientOrder $order, \Model_ServiceHosting $model, $data) { - if(!isset($data['password']) || !isset($data['password_confirm']) + if (!isset($data['password']) || !isset($data['password_confirm']) || $data['password'] != $data['password_confirm']) { throw new \Box_Exception('Account password is missing or is not valid'); } $p = $data['password']; - if($this->_performOnService($order)){ - list($adapter, $account) = $this->_getAM($model); + if ($this->_performOnService($order)) { + [$adapter, $account] = $this->_getAM($model); $adapter->changeAccountPassword($account, $p); } @@ -336,65 +341,68 @@ class Service implements InjectionAwareInterface $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Changed hosting account %s password', $model->id); - return TRUE; + + return true; } public function sync(\Model_ClientOrder $order, \Model_ServiceHosting $model) { - list($adapter, $account) = $this->_getAM($model); + [$adapter, $account] = $this->_getAM($model); $updated = $adapter->synchronizeAccount($account); - if($account->getUsername() != $updated->getUsername()) { + if ($account->getUsername() != $updated->getUsername()) { $model->username = $updated->getUsername(); } - if($account->getIp() != $updated->getIp()) { + if ($account->getIp() != $updated->getIp()) { $model->ip = $updated->getIp(); } $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Synchronizing hosting account %s with server', $model->id); - return TRUE; + + return true; } private function _getDomainOrderId(\Model_ServiceHosting $model) { $orderService = $this->di['mod_service']('order'); $o = $orderService->getServiceOrder($model); - if($o instanceof \Model_ClientOrder ) { + if ($o instanceof \Model_ClientOrder) { $c = $orderService->getConfig($o); - if(isset($c['domain']) && isset($c['domain']['action'])) { + if (isset($c['domain']) && isset($c['domain']['action'])) { $action = $c['domain']['action']; - if($action == 'register' || $action == 'transfer') { - return $orderService->getRelatedOrderIdByType($o, 'domain'); + if ('register' == $action || 'transfer' == $action) { + return $orderService->getRelatedOrderIdByType($o, 'domain'); } } } - return NULL; + + return null; } private function _performOnService(\Model_ClientOrder $order) { - return ($order->status != \Model_ClientOrder::STATUS_FAILED_SETUP); + return \Model_ClientOrder::STATUS_FAILED_SETUP != $order->status; } /** - * Generate username by domain - * + * Generate username by domain. */ private function _generateUsername($domain_name) { - $username = preg_replace('/[^A-Za-z0-9]/', '', $domain_name); - $username = substr($username,0,7); - $randnum = rand(0, 9); - $username = $username . $randnum; + $username = preg_replace('/[^A-Za-z0-9]/', '', $domain_name); + $username = substr($username, 0, 7); + $randnum = rand(0, 9); + $username = $username.$randnum; + return $username; } public function _getAM(\Model_ServiceHosting $model, \Model_ServiceHostingHp $hp = null) { - if(null === $hp) { + if (null === $hp) { $hp = $this->di['db']->getExistingModelById('ServiceHostingHp', $model->service_hosting_hp_id, 'Hosting plan not found'); } @@ -403,7 +411,6 @@ class Service implements InjectionAwareInterface $hp_config = $hp->config; - $client = $this->di['server_client']; $client ->setEmail($c->email) @@ -424,7 +431,7 @@ class Service implements InjectionAwareInterface ->setPackage($p) ->setUsername($model->username) ->setReseller($model->reseller) - ->setDomain($model->sld . $model->tld) + ->setDomain($model->sld.$model->tld) ->setPassword($model->pass) ->setNs1($server->ns1) ->setNs2($server->ns2) @@ -434,12 +441,13 @@ class Service implements InjectionAwareInterface $orderService = $this->di['mod_service']('order'); $order = $orderService->getServiceOrder($model); - if($order instanceof \Model_ClientOrder ) { + if ($order instanceof \Model_ClientOrder) { $adapter = $this->getServerManagerWithLog($server, $order); } else { $adapter = $this->getServerManager($server); } - return array($adapter, $a); + + return [$adapter, $a]; } public function toApiArray(\Model_ServiceHosting $model, $deep = false, $identity = null) @@ -449,35 +457,35 @@ class Service implements InjectionAwareInterface $server = $this->toHostingServerApiArray($serviceHostingServerModel, $deep, $identity); $hp = $this->toHostingHpApiArray($serviceHostingHpModel, $deep, $identity); - return array( - 'ip' => $model->ip, - 'sld' => $model->sld, - 'tld' => $model->tld, - 'domain' => $model->sld.$model->tld, - 'username' => $model->username, - 'reseller' => $model->reseller, - 'server' => $server, - 'hosting_plan' => $hp, - 'domain_order_id' => $this->_getDomainOrderId($model), - ); + return [ + 'ip' => $model->ip, + 'sld' => $model->sld, + 'tld' => $model->tld, + 'domain' => $model->sld.$model->tld, + 'username' => $model->username, + 'reseller' => $model->reseller, + 'server' => $server, + 'hosting_plan' => $hp, + 'domain_order_id' => $this->_getDomainOrderId($model), + ]; } public function toHostingServerApiArray(\Model_ServiceHostingServer $model, $deep = false, $identity = null) { - list($cpanel_url, $whm_url) = $this->getMangerUrls($model); - $result = array( - 'name' => $model->name, - 'hostname' => $model->hostname, - 'ip' => $model->ip, - 'ns1' => $model->ns1, - 'ns2' => $model->ns2, - 'ns3' => $model->ns3, - 'ns4' => $model->ns4, - 'cpanel_url' => $cpanel_url, - 'reseller_cpanel_url' => $whm_url, - ); + [$cpanel_url, $whm_url] = $this->getMangerUrls($model); + $result = [ + 'name' => $model->name, + 'hostname' => $model->hostname, + 'ip' => $model->ip, + 'ns1' => $model->ns1, + 'ns2' => $model->ns2, + 'ns3' => $model->ns3, + 'ns4' => $model->ns4, + 'cpanel_url' => $cpanel_url, + 'reseller_cpanel_url' => $whm_url, + ]; - if($identity instanceof \Model_Admin) { + if ($identity instanceof \Model_Admin) { $result['id'] = $model->id; $result['active'] = $model->active; $result['secure'] = $model->secure; @@ -498,55 +506,53 @@ class Service implements InjectionAwareInterface private function _getDomainTuple($data) { - $required = array( + $required = [ 'domain' => 'Hosting product must have domain configuration', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $required = array( + $required = [ 'action' => 'Domain action is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data['domain']); - if($data['domain']['action'] == 'owndomain') { + if ('owndomain' == $data['domain']['action']) { $sld = $data['domain']['owndomain_sld']; $tld = $data['domain']['owndomain_tld']; } - if($data['domain']['action'] == 'register') { - - $required = array( + if ('register' == $data['domain']['action']) { + $required = [ 'register_sld' => 'Hosting product must have defined register_sld parameter', 'register_tld' => 'Hosting product must have defined register_tld parameter', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data['domain']); $sld = $data['domain']['register_sld']; $tld = $data['domain']['register_tld']; } - if($data['domain']['action'] == 'transfer') { - - $required = array( + if ('transfer' == $data['domain']['action']) { + $required = [ 'transfer_sld' => 'Hosting product must have defined transfer_sld parameter', 'transfer_tld' => 'Hosting product must have defined transfer_tld parameter', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data['domain']); $sld = $data['domain']['transfer_sld']; $tld = $data['domain']['transfer_tld']; } - return array($sld, $tld); + return [$sld, $tld]; } public function update(\Model_ServiceHosting $model, array $data) { - if(isset($data['username']) && !empty($data['username'])) { + if (isset($data['username']) && !empty($data['username'])) { $model->username = $data['username']; } - if(isset($data['ip']) && !empty($data['ip'])) { + if (isset($data['ip']) && !empty($data['ip'])) { $model->ip = $data['ip']; } @@ -554,47 +560,49 @@ class Service implements InjectionAwareInterface $this->di['db']->store($model); $this->di['logger']->info('Updated hosting account %s without sending actions to server', $model->id); + return true; } - public function getServerManagers() { - $d = array(); - foreach($this->_getServerManagers() as $p) { + $d = []; + foreach ($this->_getServerManagers() as $p) { $d[$p] = $this->getServerManagerConfig($p); } + return $d; } private function _getServerManagers() { - $dir = BB_PATH_LIBRARY . '/Server/Manager'; - $files = array(); + $dir = BB_PATH_LIBRARY.'/Server/Manager'; + $files = []; $directory = opendir($dir); - while($item = readdir($directory)){ - if(($item != ".") && ($item != "..") && ($item != ".svn") ){ + while ($item = readdir($directory)) { + if (('.' != $item) && ('..' != $item) && ('.svn' != $item)) { $files[] = pathinfo($item, PATHINFO_FILENAME); } } sort($files); + return $files; } public function getServerManagerConfig($manager) { - $filename = BB_PATH_LIBRARY . '/Server/Manager/'.$manager.'.php'; - if(!file_exists($filename)) { - return array(); + $filename = BB_PATH_LIBRARY.'/Server/Manager/'.$manager.'.php'; + if (!file_exists($filename)) { + return []; } $classname = 'Server_Manager_'.$manager; $method = 'getForm'; - if(!is_callable($classname.'::'.$method)) { - return array(); + if (!is_callable($classname.'::'.$method)) { + return []; } - return call_user_func(array($classname, $method)); + return call_user_func([$classname, $method]); } public function getServerPairs() @@ -604,10 +612,11 @@ class Service implements InjectionAwareInterface ORDER BY id ASC'; $rows = $this->di['db']->getAll($sql); - $result = array(); + $result = []; foreach ($rows as $record) { - $result[ $record['id'] ] = $record['name']; + $result[$record['id']] = $record['name']; } + return $result; } @@ -616,7 +625,8 @@ class Service implements InjectionAwareInterface $sql = 'SELECT * FROM service_hosting_server order by id ASC'; - return array($sql, array()); + + return [$sql, []]; } public function createServer($name, $ip, $manager, $data) @@ -625,10 +635,10 @@ class Service implements InjectionAwareInterface $model->name = $name; $model->ip = $ip; - $model->hostname = $this->di['array_get']($data, 'hostname'); + $model->hostname = $this->di['array_get']($data, 'hostname'); $model->assigned_ips = $this->di['array_get']($data, 'assigned_ips'); - $model->active = $this->di['array_get']($data, 'active', 1); - $model->status_url = $this->di['array_get']($data, 'status_url'); + $model->active = $this->di['array_get']($data, 'active', 1); + $model->status_url = $this->di['array_get']($data, 'status_url'); $model->max_accounts = $this->di['array_get']($data, 'max_accounts'); $model->ns1 = $this->di['array_get']($data, 'ns1'); @@ -636,16 +646,16 @@ class Service implements InjectionAwareInterface $model->ns3 = $this->di['array_get']($data, 'ns3'); $model->ns4 = $this->di['array_get']($data, 'ns4'); - $model->manager = $manager; - $model->username = $this->di['array_get']($data, 'username'); - $model->password = $this->di['array_get']($data, 'password'); + $model->manager = $manager; + $model->username = $this->di['array_get']($data, 'username'); + $model->password = $this->di['array_get']($data, 'password'); $model->accesshash = $this->di['array_get']($data, 'accesshash'); - $model->port = $this->di['array_get']($data, 'port'); - $model->secure = $this->di['array_get']($data, 'secure', 0); + $model->port = $this->di['array_get']($data, 'port'); + $model->secure = $this->di['array_get']($data, 'secure', 0); $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); - $newId = $this->di['db']->store($model); + $newId = $this->di['db']->store($model); $this->di['logger']->info('Added new hosting server %s', $newId); @@ -657,52 +667,54 @@ class Service implements InjectionAwareInterface $id = $model->id; $this->di['db']->trash($model); $this->di['logger']->info('Deleted hosting server %s', $id); + return true; } public function updateServer(\Model_ServiceHostingServer $model, array $data) { - $model->name = $this->di['array_get']($data, 'name', $model->name); - $model->ip = $this->di['array_get']($data, 'ip', $model->ip); + $model->name = $this->di['array_get']($data, 'name', $model->name); + $model->ip = $this->di['array_get']($data, 'ip', $model->ip); $model->hostname = $this->di['array_get']($data, 'hostname', $model->hostname); $assigned_ips = $this->di['array_get']($data, 'assigned_ips', ''); if (!empty($assigned_ips)) { - $array = explode(PHP_EOL, $data['assigned_ips']); - $array = array_map('trim', $array); - $array = array_diff($array, array('')); + $array = explode(PHP_EOL, $data['assigned_ips']); + $array = array_map('trim', $array); + $array = array_diff($array, ['']); $model->assigned_ips = json_encode($array); } - $model->active = $this->di['array_get']($data, 'active', $model->active); - $model->status_url = $this->di['array_get']($data, 'status_url', $model->status_url); + $model->active = $this->di['array_get']($data, 'active', $model->active); + $model->status_url = $this->di['array_get']($data, 'status_url', $model->status_url); $model->max_accounts = $this->di['array_get']($data, 'max_accounts', $model->max_accounts); - $model->ns1 = $this->di['array_get']($data, 'ns1', $model->ns1); - $model->ns2 = $this->di['array_get']($data, 'ns2', $model->ns2); - $model->ns3 = $this->di['array_get']($data, 'ns3', $model->ns3); - $model->ns4 = $this->di['array_get']($data, 'ns4', $model->ns4); - $model->manager = $this->di['array_get']($data, 'manager', $model->manager); - $model->accesshash = $this->di['array_get']($data, 'accesshash', $model->accesshash); - $model->port = $this->di['array_get']($data, 'port', $model->port); - $model->secure = $this->di['array_get']($data, 'secure', $model->secure); - $model->username = $this->di['array_get']($data, 'username', $model->username); - $model->password = $this->di['array_get']($data, 'password', $model->password); - $model->accesshash = $this->di['array_get']($data, 'accesshash', $model->accesshash); + $model->ns1 = $this->di['array_get']($data, 'ns1', $model->ns1); + $model->ns2 = $this->di['array_get']($data, 'ns2', $model->ns2); + $model->ns3 = $this->di['array_get']($data, 'ns3', $model->ns3); + $model->ns4 = $this->di['array_get']($data, 'ns4', $model->ns4); + $model->manager = $this->di['array_get']($data, 'manager', $model->manager); + $model->accesshash = $this->di['array_get']($data, 'accesshash', $model->accesshash); + $model->port = $this->di['array_get']($data, 'port', $model->port); + $model->secure = $this->di['array_get']($data, 'secure', $model->secure); + $model->username = $this->di['array_get']($data, 'username', $model->username); + $model->password = $this->di['array_get']($data, 'password', $model->password); + $model->accesshash = $this->di['array_get']($data, 'accesshash', $model->accesshash); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Update hosting server %s', $model->id); + return true; } public function getServerManager(\Model_ServiceHostingServer $model) { - if(empty($model->manager)) { + if (empty($model->manager)) { throw new \Box_Exception('Invalid server manager. Server was not configured properly.', null, 654); } - $config = array(); + $config = []; $config['ip'] = $model->ip; $config['host'] = $model->hostname; $config['port'] = $model->port; @@ -713,8 +725,8 @@ class Service implements InjectionAwareInterface $manager = $this->di['server_manager']($model->manager, $config); - if(!$manager instanceof \Server_Manager) { - throw new \Box_Exception('Server manager :adapter is not valid', array(':adapter'=>$model->manager)); + if (!$manager instanceof \Server_Manager) { + throw new \Box_Exception('Server manager :adapter is not valid', [':adapter' => $model->manager]); } return $manager; @@ -723,19 +735,20 @@ class Service implements InjectionAwareInterface public function testConnection(\Model_ServiceHostingServer $model) { $m = $this->getServerManager($model); + return $m->testConnection(); } - public function getHpPairs() { $sql = 'SELECT id, name FROM service_hosting_hp'; $rows = $this->di['db']->getAll($sql); - $result = array(); + $result = []; foreach ($rows as $record) { - $result[ $record['id'] ] = $record['name']; + $result[$record['id']] = $record['name']; } + return $result; } @@ -744,76 +757,78 @@ class Service implements InjectionAwareInterface $sql = 'SELECT * FROM service_hosting_hp ORDER BY id asc'; - return array($sql, array()); + + return [$sql, []]; } public function deleteHp(\Model_ServiceHostingHp $model) { $id = $model->id; - $serviceHosting = $this->di['db']->findOne('ServiceHosting', 'service_hosting_hp_id = ?', array($model->id)); - if($serviceHosting) { + $serviceHosting = $this->di['db']->findOne('ServiceHosting', 'service_hosting_hp_id = ?', [$model->id]); + if ($serviceHosting) { throw new \Box_Exception('Can not remove hosting plan which has active accounts'); } $this->di['db']->trash($model); $this->di['logger']->info('Deleted hosting plan %s', $id); + return true; } public function toHostingHpApiArray(\Model_ServiceHostingHp $model, $deep = false, $identity = null) { - $result = array( - 'id' => $model->id, + $result = [ + 'id' => $model->id, - 'name' => $model->name, - 'bandwidth' => $model->bandwidth, - 'quota' => $model->quota, + 'name' => $model->name, + 'bandwidth' => $model->bandwidth, + 'quota' => $model->quota, - 'max_ftp' => $model->max_ftp, - 'max_sql' => $model->max_sql, - 'max_pop' => $model->max_pop, - 'max_sub' => $model->max_sub, - 'max_park' => $model->max_park, - 'max_addon' => $model->max_addon, - 'config' => json_decode($model->config, 1), + 'max_ftp' => $model->max_ftp, + 'max_sql' => $model->max_sql, + 'max_pop' => $model->max_pop, + 'max_sub' => $model->max_sub, + 'max_park' => $model->max_park, + 'max_addon' => $model->max_addon, + 'config' => json_decode($model->config, 1), + + 'created_at' => $model->created_at, + 'updated_at' => $model->updated_at, + ]; - 'created_at' => $model->created_at, - 'updated_at' => $model->updated_at, - ); return $result; } public function updateHp(\Model_ServiceHostingHp $model, array $data) { - $model->name = $this->di['array_get']($data, 'name', $model->name); + $model->name = $this->di['array_get']($data, 'name', $model->name); $model->bandwidth = $this->di['array_get']($data, 'bandwidth', $model->bandwidth); - $model->quota = $this->di['array_get']($data, 'quota', $model->quota); + $model->quota = $this->di['array_get']($data, 'quota', $model->quota); $model->max_addon = $this->di['array_get']($data, 'max_addon', $model->max_addon); - $model->max_ftp = $this->di['array_get']($data, 'max_ftp', $model->max_ftp); - $model->max_sql = $this->di['array_get']($data, 'max_sql', $model->max_sql); - $model->max_pop = $this->di['array_get']($data, 'max_pop', $model->max_pop); - $model->max_sub = $this->di['array_get']($data, 'max_sub', $model->max_sub); - $model->max_park = $this->di['array_get']($data, 'max_park', $model->max_park); - + $model->max_ftp = $this->di['array_get']($data, 'max_ftp', $model->max_ftp); + $model->max_sql = $this->di['array_get']($data, 'max_sql', $model->max_sql); + $model->max_pop = $this->di['array_get']($data, 'max_pop', $model->max_pop); + $model->max_sub = $this->di['array_get']($data, 'max_sub', $model->max_sub); + $model->max_park = $this->di['array_get']($data, 'max_park', $model->max_park); /* add new config value to hosting plan */ $config = json_decode($model->config, 1); $inConfig = $this->di['array_get']($data, 'config'); - if(is_array($inConfig)) { - foreach($inConfig as $key=>$val) { - if(isset($config[$key])) { + if (is_array($inConfig)) { + foreach ($inConfig as $key => $val) { + if (isset($config[$key])) { $config[$key] = $val; } - if(isset($config[$key]) && empty ($val)) { - unset ($config[$key]); + if (isset($config[$key]) && empty($val)) { + unset($config[$key]); } } } $newConfigName = $this->di['array_get']($data, 'new_config_name'); $newConfigValue = $this->di['array_get']($data, 'new_config_value'); - if(!empty($newConfigName) && !empty($newConfigValue)) { + if (!empty($newConfigName) && !empty($newConfigValue)) { $config[$newConfigName] = $newConfigValue; } @@ -822,6 +837,7 @@ class Service implements InjectionAwareInterface $this->di['db']->store($model); $this->di['logger']->info('Updated hosting plan %s', $model->id); + return true; } @@ -831,28 +847,29 @@ class Service implements InjectionAwareInterface $model->name = $name; $model->bandwidth = $this->di['array_get']($data, 'bandwidth', 1024 * 1024); - $model->quota = $this->di['array_get']($data, 'quota', 1024 * 1024); + $model->quota = $this->di['array_get']($data, 'quota', 1024 * 1024); $model->max_addon = $this->di['array_get']($data, 'max_addon', 1); - $model->max_park = $this->di['array_get']($data, 'max_park', 1); - $model->max_sub = $this->di['array_get']($data, 'max_sub', 1); - $model->max_pop = $this->di['array_get']($data, 'max_pop', 1); - $model->max_sql = $this->di['array_get']($data, 'max_sql', 1); - $model->max_ftp = $this->di['array_get']($data, 'max_ftp', 1); + $model->max_park = $this->di['array_get']($data, 'max_park', 1); + $model->max_sub = $this->di['array_get']($data, 'max_sub', 1); + $model->max_pop = $this->di['array_get']($data, 'max_pop', 1); + $model->max_sql = $this->di['array_get']($data, 'max_sql', 1); + $model->max_ftp = $this->di['array_get']($data, 'max_ftp', 1); $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); $newId = $this->di['db']->store($model); $this->di['logger']->info('Added new hosting plan %s', $newId); + return $newId; } public function getServerPackage(\Model_ServiceHostingHp $model) { $config = json_decode($model->config, 1); - if (!is_array($config)){ - $config = array(); + if (!is_array($config)) { + $config = []; } $p = $this->di['server_package']; @@ -878,6 +895,7 @@ class Service implements InjectionAwareInterface $order_service = $this->di['mod_service']('order'); $log = $order_service->getLogger($order); $manager->setLog($log); + return $manager; } @@ -885,19 +903,22 @@ class Service implements InjectionAwareInterface { try { $m = $this->getServerManager($model); - return array($m->getLoginUrl(), $m->getResellerLoginUrl()); - } catch(\Exception $e) { - error_log('Error while retrieving cPanel url: '. $e->getMessage()); + + return [$m->getLoginUrl(), $m->getResellerLoginUrl()]; + } catch (\Exception $e) { + error_log('Error while retrieving cPanel url: '.$e->getMessage()); } - return array(false, false); + + return [false, false]; } public function prependOrderConfig(\Model_Product $product, array $data) { - list($sld, $tld) = $this->_getDomainTuple($data); + [$sld, $tld] = $this->_getDomainTuple($data); $data['sld'] = $sld; $data['tld'] = $tld; $c = $this->di['tools']->decodeJ($product->config); + return array_merge($c, $data); } @@ -912,47 +933,48 @@ class Service implements InjectionAwareInterface $drepo = $this->di['mod_service']('servicedomain'); $drepo->validateOrderData($dc); - if($action == 'owndomain') { + if ('owndomain' == $action) { return false; } - if(isset($c['free_domain']) && $c['free_domain']) { + if (isset($c['free_domain']) && $c['free_domain']) { $dc['free_domain'] = true; } - if(isset($c['free_transfer']) && $c['free_transfer']) { + if (isset($c['free_transfer']) && $c['free_transfer']) { $dc['free_transfer'] = true; } $table = $this->di['mod_service']('product'); $d = $table->getMainDomainProduct(); - if(!$d instanceof \Model_Product) { + if (!$d instanceof \Model_Product) { throw new \Box_Exception('Could not find main domain product'); } - return array('product'=>$d, 'config'=> $dc); + + return ['product' => $d, 'config' => $dc]; } /** - * @param \Model_Product $product * @return array */ public function getFreeTlds(\Model_Product $product) { $config = $this->di['tools']->decodeJ($product->config); - $freeTlds = $this->di['array_get']($config, 'free_tlds', array()); - $result = array(); - foreach ($freeTlds as $tld){ - $result[] = array('tld' => $tld); + $freeTlds = $this->di['array_get']($config, 'free_tlds', []); + $result = []; + foreach ($freeTlds as $tld) { + $result[] = ['tld' => $tld]; } - if (empty ($result)) { + if (empty($result)) { $query = 'active = 1 and allow_register = 1'; - $tlds = $this->di['db']->find('Tld', $query, array()); + $tlds = $this->di['db']->find('Tld', $query, []); $serviceDomainService = $this->di['mod_service']('Servicedomain'); foreach ($tlds as $model) { $result[] = $serviceDomainService->tldToApiArray($model); } } + return $result; } } diff --git a/src/bb-modules/Servicelicense/Api/Admin.php b/src/bb-modules/Servicelicense/Api/Admin.php index ef256c6d8..5f96a5757 100644 --- a/src/bb-modules/Servicelicense/Api/Admin.php +++ b/src/bb-modules/Servicelicense/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getLicensePlugins(); - $result = array(); - foreach($plugins as $plugin) { + $result = []; + foreach ($plugins as $plugin) { $filename = $plugin['filename']; $result[$filename] = $filename; } + return $result; } /** * Update license parameters. Set which validation rules must be applied - * for license - * + * for license. + * * @param int $order_id - License irder id - * + * * @optional string $plugin - New license plugin name * @optional bool $validate_ip - True to validate IP; False - to allow all IPs for this license * @optional bool $validate_host - True to validate hostname; False - to allow all hostnames for this license * @optional bool $validate_path - True to validate install paths; False - to allow all paths for this license * @optional bool $validate_version - True to validate version; False - to allow all versions for this license - * @optional array $ips - List of allowed IPs for this license - * @optional array $hosts - List of allowed hosts for this license - * @optional array $paths - List of allowed paths for this license - * @optional array $versions - List of allowed versions for this license - * - * @return boolean + * @optional array $ips - List of allowed IPs for this license + * @optional array $hosts - List of allowed hosts for this license + * @optional array $paths - List of allowed paths for this license + * @optional array $versions - List of allowed versions for this license + * + * @return bool */ public function update($data) { $s = $this->_getService($data); - - return $this->getService()->update($s, $data); + + return $this->getService()->update($s, $data); } - + /** * Reset license validation rules. - * + * * @param int $order_id - License service order id - * @return boolean + * + * @return bool */ public function reset($data) { $s = $this->_getService($data); + return $this->getService()->reset($s); } /** - * @param array $data * @return \Model_ServiceLicense + * * @throws \Box_Exception */ public function _getService(array $data) { - $required = array('order_id' => 'Order id is required'); + $required = ['order_id' => 'Order id is required']; $this->di['validator']->checkRequiredParamsForArray($required, $data); $order = $this->di['db']->getExistingModelById('clientOrder', $data['order_id'], 'Order not found'); $orderService = $this->di['mod_service']('order'); $s = $orderService->getOrderService($order); - if(!$s instanceof \Model_ServiceLicense) { + if (!$s instanceof \Model_ServiceLicense) { throw new \Box_Exception('Order is not activated'); } + return $s; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicelicense/Api/Client.php b/src/bb-modules/Servicelicense/Api/Client.php index a45d8d349..6ff09ae89 100644 --- a/src/bb-modules/Servicelicense/Api/Client.php +++ b/src/bb-modules/Servicelicense/Api/Client.php @@ -1,6 +1,6 @@ _getService($data); + return $this->getService()->reset($s); } public function _getService(array $data) { - $required = array('order_id' => 'Order id is required'); + $required = ['order_id' => 'Order id is required']; $this->di['validator']->checkRequiredParamsForArray($required, $data); $client = $this->getIdentity(); - $bindings = array( - ':id' => $data['order_id'], - ':client_id' => $client->id - ); + $bindings = [ + ':id' => $data['order_id'], + ':client_id' => $client->id, + ]; $order = $this->di['db']->findOne('ClientOrder', 'id = :id AND client_id = :client_id', $bindings); @@ -48,10 +51,10 @@ class Client extends \Api_Abstract $orderService = $this->di['mod_service']('order'); $s = $orderService->getOrderService($order); - if(!$s instanceof \Model_ServiceLicense) { + if (!$s instanceof \Model_ServiceLicense) { throw new \Box_Exception('Order is not activated'); } - + return $s; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicelicense/Api/Guest.php b/src/bb-modules/Servicelicense/Api/Guest.php index 8a3c9e53d..1bb7e8a42 100644 --- a/src/bb-modules/Servicelicense/Api/Guest.php +++ b/src/bb-modules/Servicelicense/Api/Guest.php @@ -1,6 +1,6 @@ getService()->checkLicenseDetails($data); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicelicense/Plugin/Simple.php b/src/bb-modules/Servicelicense/Plugin/Simple.php index 8654558d3..b33eb18a0 100644 --- a/src/bb-modules/Servicelicense/Plugin/Simple.php +++ b/src/bb-modules/Servicelicense/Plugin/Simple.php @@ -1,6 +1,6 @@ di['db']->load('Client', $order->client_id); + // $client = $this->di['db']->load('Client', $order->client_id); - $length = isset($config['length']) ? $config['length'] : 25; - $prefix = isset($config['prefix']) ? $config['prefix'] : NULL; + $length = $config['length'] ?? 25; + $prefix = $config['prefix'] ?? null; $character_array = array_merge(range('A', 'Z'), range(1, 9)); $size = count($character_array) - 1; $string = ''; - for($i = 1; $i < $length; $i++) { - $string .= ($i % 5 == 0) ? '-' : $character_array[rand(0, $size)]; + for ($i = 1; $i < $length; ++$i) { + $string .= (0 == $i % 5) ? '-' : $character_array[rand(0, $size)]; } - return $prefix . $string; + + return $prefix.$string; } /** * This method is optional. * Aditional validation rules can be applied to license validation logic. - * Method is called after "expiration, ip, version, path, hostname validations are passed" + * Method is called after "expiration, ip, version, path, hostname validations are passed". * * Should throw "LogicException" if validation fails * * @param Model_ServiceLicense $service - * @param array $data + * @param array $data + * * @return array - list of params to be attached to response message + * * @throws LogicException */ /* diff --git a/src/bb-modules/Servicelicense/Server.php b/src/bb-modules/Servicelicense/Server.php index 4e668ceb0..ee5120747 100644 --- a/src/bb-modules/Servicelicense/Server.php +++ b/src/bb-modules/Servicelicense/Server.php @@ -1,6 +1,6 @@ NULL, - 'created_at' => NULL, - 'expires_at' => NULL, - 'valid' => FALSE, - ); + private $_result = [ + 'licensed_to' => null, + 'created_at' => null, + 'expires_at' => null, + 'valid' => false, + ]; protected $di; @@ -42,7 +42,9 @@ class Server implements \Box\InjectionAwareInterface /** * @deprecated + * * @param type $data + * * @return type */ public function handle_deprecated($data) @@ -50,13 +52,13 @@ class Server implements \Box\InjectionAwareInterface try { $this->process($data); } catch (\LogicException $e) { - $this->_log->info($e->getMessage() . ' ' . $e->getCode()); - $this->_result['error'] = $e->getMessage(); + $this->_log->info($e->getMessage().' '.$e->getCode()); + $this->_result['error'] = $e->getMessage(); $this->_result['error_code'] = $e->getCode(); } catch (\Exception $e) { error_log($e); - $this->_log->info($e->getMessage() . ' ' . $e->getCode()); - $this->_result['error'] = 'Licensing server is temporary unavailable'; + $this->_log->info($e->getMessage().' '.$e->getCode()); + $this->_result['error'] = 'Licensing server is temporary unavailable'; $this->_result['error_code'] = $e->getCode(); } @@ -78,10 +80,10 @@ class Server implements \Box\InjectionAwareInterface private function getIp($checkProxy = true) { $ip = null; - if ($checkProxy && $this->getServer('HTTP_CLIENT_IP') != null) { + if ($checkProxy && null != $this->getServer('HTTP_CLIENT_IP')) { $ip = $this->getServer('HTTP_CLIENT_IP'); } else { - if ($checkProxy && $this->getServer('HTTP_X_FORWARDED_FOR') != null) { + if ($checkProxy && null != $this->getServer('HTTP_X_FORWARDED_FOR')) { $ip = $this->getServer('HTTP_X_FORWARDED_FOR'); } else { $ip = $this->getServer('REMOTE_ADDR'); @@ -89,7 +91,7 @@ class Server implements \Box\InjectionAwareInterface } $ips_arr = explode(',', $ip); - $ip = trim($ips_arr[0]); + $ip = trim($ips_arr[0]); return $ip; } @@ -97,10 +99,10 @@ class Server implements \Box\InjectionAwareInterface public function process($data) { if (!is_array($data)) { - $data = (json_decode($data, true)) ? json_decode($data, true) : array(); + $data = (json_decode($data, true)) ? json_decode($data, true) : []; } - if (empty ($data)) { + if (empty($data)) { throw new \LogicException('Invalid request. Parameters missing?', 1000); } @@ -109,7 +111,7 @@ class Server implements \Box\InjectionAwareInterface } $service = $this->di['mod_service']('servicelicense'); - $model = $this->di['db']->findOne('ServiceLicense', 'license_key = :license_key', array(':license_key' => $data['license'])); + $model = $this->di['db']->findOne('ServiceLicense', 'license_key = :license_key', [':license_key' => $data['license']]); if (!$model instanceof \Model_ServiceLicense) { throw new \LogicException('Your license key is not valid.', 1005); @@ -130,10 +132,10 @@ class Server implements \Box\InjectionAwareInterface throw new \LogicException('Path key is not present in call', 1004); } - $ip = $this->getIp(); - $host = $data['host']; + $ip = $this->getIp(); + $host = $data['host']; $version = $data['version']; - $path = $data['path']; + $path = $data['path']; if (!$service->isLicenseActive($model)) { throw new \LogicException('License is not active', 1006); @@ -156,9 +158,9 @@ class Server implements \Box\InjectionAwareInterface } $this->_result['licensed_to'] = $service->getOwnerName($model); - $this->_result['created_at'] = $model->created_at; - $this->_result['expires_at'] = $service->getExpirationDate($model); - $this->_result['valid'] = TRUE; + $this->_result['created_at'] = $model->created_at; + $this->_result['expires_at'] = $service->getExpirationDate($model); + $this->_result['valid'] = true; $array = $service->getAdditionalParams($model, $data); if (!empty($array)) { @@ -169,4 +171,4 @@ class Server implements \Box\InjectionAwareInterface return $this->_result; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicelicense/Service.php b/src/bb-modules/Servicelicense/Service.php index be9f93674..c37e998c7 100644 --- a/src/bb-modules/Servicelicense/Service.php +++ b/src/bb-modules/Servicelicense/Service.php @@ -1,6 +1,6 @@ config, 1); - if(!is_array($c)) { - return array(); + if (!is_array($c)) { + return []; } + return array_merge($c, $data); } /** - * Method is called before adding product to cart - * @param array $data - * @return boolean + * Method is called before adding product to cart. + * + * @return bool */ public function validateOrderData(array &$data) { @@ -67,22 +68,22 @@ class Service implements InjectionAwareInterface public function getLicensePlugins() { $dir = dirname(__FILE__).'/Plugin/'; - $files = array(); + $files = []; $directory = opendir($dir); - while($item = readdir($directory)){ + while ($item = readdir($directory)) { // We filter the elements that we don't want to appear ".", ".." and ".svn" - if(($item != ".") && ($item != "..") && ($item != ".svn") ){ - $info = pathinfo($item); - $info['path'] = $dir.$item; - $files[] = $info; - } + if (('.' != $item) && ('..' != $item) && ('.svn' != $item)) { + $info = pathinfo($item); + $info['path'] = $dir.$item; + $files[] = $info; + } } closedir($directory); + return $files; } /** - * @param \Model_ClientOrder $order * @return \Model_ServiceLicense */ public function action_create(\Model_ClientOrder $order) @@ -98,12 +99,12 @@ class Service implements InjectionAwareInterface $model->validate_path = (bool) $this->di['array_get']($c, 'validate_path', false); $model->validate_version = (bool) $this->di['array_get']($c, 'validate_version', false); $model->plugin = $this->di['array_get']($c, 'plugin', 'Simple'); - - $model->ips = NULL; - $model->versions = NULL; - $model->hosts = NULL; - $model->paths = NULL; - + + $model->ips = null; + $model->versions = null; + $model->hosts = null; + $model->paths = null; + $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); @@ -112,8 +113,7 @@ class Service implements InjectionAwareInterface } /** - * @param \Model_ClientOrder $order - * @return boolean + * @return bool */ public function action_activate(\Model_ClientOrder $order) { @@ -121,21 +121,21 @@ class Service implements InjectionAwareInterface $c = $orderService->getConfig($order); $iterations = $this->di['array_get']($c, 'iterations', 10); $model = $orderService->getOrderService($order); - if(!$model instanceof \Model_ServiceLicense) { + if (!$model instanceof \Model_ServiceLicense) { throw new \Box_Exception('Could not activate order. Service was not created'); } $plugin = $this->_getPlugin($model); - - if(!is_object($plugin)) { - throw new \Box_Exception('License plugin :plugin was not found', array(':plugin'=>$model->plugin)); + + if (!is_object($plugin)) { + throw new \Box_Exception('License plugin :plugin was not found', [':plugin' => $model->plugin]); } - if(!method_exists($plugin, 'generate')) { + if (!method_exists($plugin, 'generate')) { throw new \Box_Exception('License plugin do not have generate method'); } - if(method_exists($plugin, 'setDi')) { + if (method_exists($plugin, 'setDi')) { $plugin->setDi($this->di); } @@ -145,19 +145,19 @@ class Service implements InjectionAwareInterface if ($i++ >= $iterations) { throw new \Box_Exception('Maximum number of iterations reached while generating license key'); } - } while (null !== $this->di['db']->findOne('ServiceLicense', 'license_key = :license_key', array(':license_key' => $licenseKey))); + } while (null !== $this->di['db']->findOne('ServiceLicense', 'license_key = :license_key', [':license_key' => $licenseKey])); $model->license_key = $licenseKey; $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); + return true; } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_renew(\Model_ClientOrder $order) { @@ -165,10 +165,9 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_suspend(\Model_ClientOrder $order) { @@ -176,10 +175,9 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_unsuspend(\Model_ClientOrder $order) { @@ -187,10 +185,9 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_cancel(\Model_ClientOrder $order) { @@ -198,10 +195,9 @@ class Service implements InjectionAwareInterface } /** - * * @todo - * @param \Model_ClientOrder $order - * @return boolean + * + * @return bool */ public function action_uncancel(\Model_ClientOrder $order) { @@ -209,44 +205,44 @@ class Service implements InjectionAwareInterface } /** - * @param \Model_ClientOrder $order * @return void */ public function action_delete(\Model_ClientOrder $order) { $prderService = $this->di['mod_service']('order'); $service = $prderService->getOrderService($order); - if($service instanceof \Model_ServiceLicense) { + if ($service instanceof \Model_ServiceLicense) { $this->di['db']->trash($service); } } public function reset(\Model_ServiceLicense $model) { - $data = array( - 'id'=>$model->id, - 'ips'=>$model->ips, - 'hosts'=>$model->hosts, - 'paths'=>$model->paths, - 'versions'=>$model->versions, - 'client_id'=>$model->client_id - ); - $this->di['events_manager']->fire(array('event'=>'onBeforeServicelicenseReset', 'params'=>$data)); + $data = [ + 'id' => $model->id, + 'ips' => $model->ips, + 'hosts' => $model->hosts, + 'paths' => $model->paths, + 'versions' => $model->versions, + 'client_id' => $model->client_id, + ]; + $this->di['events_manager']->fire(['event' => 'onBeforeServicelicenseReset', 'params' => $data]); - $model->ips = json_encode(array()); - $model->hosts = json_encode(array()); - $model->paths = json_encode(array()); - $model->versions = json_encode(array()); + $model->ips = json_encode([]); + $model->hosts = json_encode([]); + $model->paths = json_encode([]); + $model->versions = json_encode([]); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Reset license %s information', $model->id); - $data = array( - 'id'=>$model->id, - 'client_id'=>$model->client_id, - 'updated_at'=>$model->updated_at - ); - $this->di['events_manager']->fire(array('event'=>'onAfterServicelicenseReset', 'params'=>$data)); + $data = [ + 'id' => $model->id, + 'client_id' => $model->client_id, + 'updated_at' => $model->updated_at, + ]; + $this->di['events_manager']->fire(['event' => 'onAfterServicelicenseReset', 'params' => $data]); + return true; } @@ -254,25 +250,27 @@ class Service implements InjectionAwareInterface { $prderService = $this->di['mod_service']('order'); $o = $prderService->getServiceOrder($model); - if($o instanceof \Model_ClientOrder) { - return ($o->status == \Model_ClientOrder::STATUS_ACTIVE); + if ($o instanceof \Model_ClientOrder) { + return \Model_ClientOrder::STATUS_ACTIVE == $o->status; } - return FALSE; + + return false; } public function isValidIp(\Model_ServiceLicense $model, $value) { $defined = $model->getAllowedIps(); - if(empty($defined)) { + if (empty($defined)) { $this->_addValue($model, 'ips', $value); - return TRUE; + + return true; } - if(!$model->validate_ip) { + if (!$model->validate_ip) { $this->_addValue($model, 'ips', $value); - return TRUE; - } + return true; + } return in_array($value, $defined); } @@ -280,14 +278,16 @@ class Service implements InjectionAwareInterface public function isValidVersion(\Model_ServiceLicense $model, $value) { $defined = $model->getAllowedVersions(); - if(empty($defined)) { + if (empty($defined)) { $this->_addValue($model, 'versions', $value); - return TRUE; + + return true; } - if(!$model->validate_version) { + if (!$model->validate_version) { $this->_addValue($model, 'versions', $value); - return TRUE; + + return true; } return in_array($value, $defined); @@ -296,14 +296,16 @@ class Service implements InjectionAwareInterface public function isValidPath(\Model_ServiceLicense $model, $value) { $defined = $model->getAllowedPaths(); - if(empty($defined)) { + if (empty($defined)) { $this->_addValue($model, 'paths', $value); - return TRUE; + + return true; } - if(!$model->validate_path) { + if (!$model->validate_path) { $this->_addValue($model, 'paths', $value); - return TRUE; + + return true; } return in_array($value, $defined); @@ -312,34 +314,38 @@ class Service implements InjectionAwareInterface public function isValidHost(\Model_ServiceLicense $model, $value) { $defined = $model->getAllowedHosts(); - if(empty($defined)) { + if (empty($defined)) { $this->_addValue($model, 'hosts', $value); - return TRUE; + + return true; } - if(!$model->validate_host) { + if (!$model->validate_host) { $this->_addValue($model, 'hosts', $value); - return TRUE; + + return true; } return in_array($value, $defined); } - public function getAdditionalParams(\Model_ServiceLicense $model, $data = array()) + public function getAdditionalParams(\Model_ServiceLicense $model, $data = []) { $plugin = $this->_getPlugin($model); - if(is_object($plugin) && method_exists($plugin, 'validate')) { + if (is_object($plugin) && method_exists($plugin, 'validate')) { $res = $plugin->validate($model, $data); - if(is_array($res)) { + if (is_array($res)) { return $res; } } - return array(); + + return []; } public function getOwnerName(\Model_ServiceLicense $model) { $client = $this->di['db']->load('Client', $model->client_id); + return $client->getFullName(); } @@ -347,29 +353,31 @@ class Service implements InjectionAwareInterface { $prderService = $this->di['mod_service']('order'); $o = $prderService->getServiceOrder($model); - if($o instanceof \Model_ClientOrder) { + if ($o instanceof \Model_ClientOrder) { return $o->expires_at; } + return date('Y-m-d H:i:s'); } public function toApiArray(\Model_ServiceLicense $model, $deep = false, $identity = null) { - $result = array( - 'license_key' => $model->license_key, - 'validate_ip' => (bool)$model->validate_ip, - 'validate_host' => (bool)$model->validate_host, - 'validate_version' => (bool)$model->validate_version, - 'validate_path' => (bool)$model->validate_path, - 'ips' => $model->getAllowedIps(), - 'hosts' => $model->getAllowedHosts(), - 'paths' => $model->getAllowedPaths(), - 'versions' => $model->getAllowedVersions(), - 'pinged_at' => $model->pinged_at, - ); - if($identity instanceof \Model_Admin) { + $result = [ + 'license_key' => $model->license_key, + 'validate_ip' => (bool) $model->validate_ip, + 'validate_host' => (bool) $model->validate_host, + 'validate_version' => (bool) $model->validate_version, + 'validate_path' => (bool) $model->validate_path, + 'ips' => $model->getAllowedIps(), + 'hosts' => $model->getAllowedHosts(), + 'paths' => $model->getAllowedPaths(), + 'versions' => $model->getAllowedVersions(), + 'pinged_at' => $model->pinged_at, + ]; + if ($identity instanceof \Model_Admin) { $result['plugin'] = $model->plugin; } + return $result; } @@ -378,7 +386,7 @@ class Service implements InjectionAwareInterface */ private function _addValue(\Model_ServiceLicense $model, $key, $value) { - $m = "getAllowed".ucfirst($key); + $m = 'getAllowed'.ucfirst($key); $allowed = $model->{$m}(); $allowed[] = $value; @@ -386,37 +394,39 @@ class Service implements InjectionAwareInterface $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); } - + private function _getPlugin(\Model_ServiceLicense $model) { $plugins = $this->getLicensePlugins(); - foreach($plugins as $plugin) { - if($model->plugin == $plugin['filename']) { + foreach ($plugins as $plugin) { + if ($model->plugin == $plugin['filename']) { require_once $plugin['path']; $class_name = 'Box\\Mod\\Servicelicense\\Plugin\\'.$model->plugin; + return new $class_name(); } } error_log(sprintf('License #%s plugin %s is not valid', $model->id, $model->plugin)); + return null; } public function update(\Model_ServiceLicense $s, array $data) { - $s->plugin = $this->di['array_get']($data, 'plugin', $s->plugin); - $s->validate_ip = (bool)$this->di['array_get']($data, 'validate_ip', $s->validate_ip); - $s->validate_host = (bool)$this->di['array_get']($data, 'validate_host', $s->validate_host); - $s->validate_path = (bool)$this->di['array_get']($data, 'validate_path', $s->validate_path); - $s->validate_version = (bool)$this->di['array_get']($data, 'validate_version', $s->validate_version); - if(isset($data['license_key']) && !empty($data['license_key'])) { + $s->plugin = $this->di['array_get']($data, 'plugin', $s->plugin); + $s->validate_ip = (bool) $this->di['array_get']($data, 'validate_ip', $s->validate_ip); + $s->validate_host = (bool) $this->di['array_get']($data, 'validate_host', $s->validate_host); + $s->validate_path = (bool) $this->di['array_get']($data, 'validate_path', $s->validate_path); + $s->validate_version = (bool) $this->di['array_get']($data, 'validate_version', $s->validate_version); + if (isset($data['license_key']) && !empty($data['license_key'])) { $s->license_key = $data['license_key']; } - foreach (array('ips', 'hosts', 'paths', 'versions') as $key) { - if(isset($data[$key])) { + foreach (['ips', 'hosts', 'paths', 'versions'] as $key) { + if (isset($data[$key])) { $array = explode(PHP_EOL, $data[$key]); $array = array_map('trim', $array); - $array = array_diff($array, array('')); + $array = array_diff($array, ['']); $s->{$key} = json_encode($array); } } @@ -428,28 +438,30 @@ class Service implements InjectionAwareInterface } /** - * @param array $data * @return array */ public function checkLicenseDetails(array $data) { $log = $this->di['logger']; $log->addWriter(new \Box_LogStream(BB_PATH_LOG.'/license.log')); - if($this->di['config']['debug']) $log ->debug(print_r($data, 1)); + if ($this->di['config']['debug']) { + $log->debug(print_r($data, 1)); + } /** * Return error code in result field if related to license error - * If error comes from BoxBilling core use $result['error'] field + * If error comes from BoxBilling core use $result['error'] field. + * * @since v2.7.1 */ - if(isset($data['format']) && $data['format'] == 2) { + if (isset($data['format']) && 2 == $data['format']) { $server = $this->di['license_server']; try { $result = $server->process($data); $result['error'] = null; $result['error_code'] = null; - } catch(\LogicException $e) { + } catch (\LogicException $e) { $result['licensed_to'] = null; $result['created_at'] = null; $result['expires_at'] = null; @@ -462,24 +474,26 @@ class Service implements InjectionAwareInterface } /** - * Old style api format return + * Old style api format return. + * * @deprecated */ - if(isset($data['legacy']) && $data['legacy']) { + if (isset($data['legacy']) && $data['legacy']) { $server = $this->di['license_server']; $array = $server->handle_deprecated($data); - if(APPLICATION_ENV == 'testing') { + if (APPLICATION_ENV == 'testing') { return $array; } header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json; charset=utf-8'); - print json_encode($array); + echo json_encode($array); exit(); } $server = $this->di['license_server']; + return $server->process($data); } } diff --git a/src/bb-modules/Servicemembership/Service.php b/src/bb-modules/Servicemembership/Service.php index c654397ba..6585ec7cd 100644 --- a/src/bb-modules/Servicemembership/Service.php +++ b/src/bb-modules/Servicemembership/Service.php @@ -1,6 +1,6 @@ di['mod_service']('order'); $service = $orderService->getOrderService($order); - if($service instanceof \Model_ServiceMembership) { + if ($service instanceof \Model_ServiceMembership) { $this->di['db']->trash($service); } } @@ -134,7 +126,7 @@ class Service implements \Box\InjectionAwareInterface public function toApiArray(\Model_ServiceMembership $model, $deep = false, $identity = null) { $result = $this->di['db']->toArray($model); + return $result; } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicesolusvm/Api/Admin.php b/src/bb-modules/Servicesolusvm/Api/Admin.php index d0b128f9a..619b51dee 100644 --- a/src/bb-modules/Servicesolusvm/Api/Admin.php +++ b/src/bb-modules/Servicesolusvm/Api/Admin.php @@ -1,6 +1,6 @@ di['db']->findOne('client_order', "id=:id AND service_type = 'solusvm' - ", - array(':id'=>$data['order_id'])); - - if(!$order) { + ", + [':id' => $data['order_id']]); + + if (!$order) { throw new \Box_Exception('Solusvm order not found'); } - + $s = $this->di['db']->findOne('service_solusvm', 'id=:id', - array(':id'=>$order->service_id)); - if(!$s) { + [':id' => $order->service_id]); + if (!$s) { throw new \Box_Exception('Order is not activated'); } - return array($order, $s); + + return [$order, $s]; } - + /** - * Update master server configuration + * Update master server configuration. + * * @param int $cluster_id - cluster ID + * * @return bool */ public function cluster_config_update($data) @@ -52,34 +55,41 @@ class Admin extends \Api_Abstract $cluster_id = (int) $this->di['array_get']($data, 'cluster_id', 1); $this->getService()->updateMasterConfig($cluster_id, $data); $this->di['logger']->info('Updated SolusVM API configuration'); + return true; } /** - * Return master server configuration + * Return master server configuration. + * * @param int $cluster_id - id of master server default = 1 + * * @return array */ public function cluster_config($data) { $cluster_id = (int) $this->di['array_get']($data, 'cluster_id', 1); + return $this->getService()->getMasterConfig($cluster_id); } - + /** - * Return virtualization types solusvm supports - * @return array + * Return virtualization types solusvm supports. + * + * @return array */ public function get_virtualization_types($data) { return $this->getService()->getVirtualizationTypes($data); } - + /** - * Return nodes available on solusvm master server - * @param string $by - list nodes by id or by name, default - name + * Return nodes available on solusvm master server. + * + * @param string $by - list nodes by id or by name, default - name * @param string $type - virtualization type - * @return array + * + * @return array */ public function get_nodes($data) { @@ -88,16 +98,21 @@ class Admin extends \Api_Abstract $type = $this->di['array_get']($data, 'type', 'openvz'); $nodes = $this->getService()->getNodes($type, $by); } catch (\Exception $exc) { - $nodes = array(); - if(BB_DEBUG) error_log($exc); + $nodes = []; + if (BB_DEBUG) { + error_log($exc); + } } + return $nodes; } - + /** - * Return plans available on solusvm master server + * Return plans available on solusvm master server. + * * @param string $type - virtualization type - * @return array + * + * @return array */ public function get_plans($data) { @@ -105,16 +120,21 @@ class Admin extends \Api_Abstract $type = $this->di['array_get']($data, 'type', 'openvz'); $plans = $this->getService()->getPlans($type); } catch (\Exception $exc) { - $plans = array(); - if(BB_DEBUG) error_log($exc); + $plans = []; + if (BB_DEBUG) { + error_log($exc); + } } + return $plans; } - + /** - * Return templates available on solusvm master server + * Return templates available on solusvm master server. + * * @param string $type - virtualization type - * @return array + * + * @return array */ public function get_templates($data) { @@ -122,252 +142,307 @@ class Admin extends \Api_Abstract $type = $this->di['array_get']($data, 'type', 'openvz'); $templates = $this->getService()->getTemplates($type); } catch (\Exception $exc) { - $templates = array(); - if(BB_DEBUG) error_log($exc); + $templates = []; + if (BB_DEBUG) { + error_log($exc); + } } + return $templates; } - + /** - * Reboot VPS + * Reboot VPS. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function reboot($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->reboot($order, $vps, $data); $this->di['logger']->info('Rebooted VPS. Order ID #%s', $order->id); - return true; - } - - /** - * Boot VPS - * @param int $order_id - order id - * @return bool - */ - public function boot($data) - { - list($order, $vps) = $this->_getService($data); - $this->getService()->boot($order, $vps, $data); - $this->di['logger']->info('Booted VPS. Order ID #%s', $order->id); - return true; - } - - /** - * Shutdown VPS - * @param int $order_id - order id - * @return bool - */ - public function shutdown($data) - { - list($order, $vps) = $this->_getService($data); - $this->getService()->shutdown($order, $vps, $data); - $this->di['logger']->info('Shut down VPS. Order ID #%s', $order->id); + return true; } /** - * Get status VPS + * Boot VPS. + * * @param int $order_id - order id + * + * @return bool + */ + public function boot($data) + { + [$order, $vps] = $this->_getService($data); + $this->getService()->boot($order, $vps, $data); + $this->di['logger']->info('Booted VPS. Order ID #%s', $order->id); + + return true; + } + + /** + * Shutdown VPS. + * + * @param int $order_id - order id + * + * @return bool + */ + public function shutdown($data) + { + [$order, $vps] = $this->_getService($data); + $this->getService()->shutdown($order, $vps, $data); + $this->di['logger']->info('Shut down VPS. Order ID #%s', $order->id); + + return true; + } + + /** + * Get status VPS. + * + * @param int $order_id - order id + * * @return disabled|online|offline */ public function status($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); + return $this->getService()->status($order, $vps, $data); } /** - * Retrieve more information about vps from sulusvm server + * Retrieve more information about vps from sulusvm server. + * * @param int $order_id - order id + * * @return array */ public function info($data) { - list(, $vps) = $this->_getService($data); + [, $vps] = $this->_getService($data); try { $result = $this->getService()->info($vps->vserverid); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc); - $result = array(); + $result = []; } + return $result; } - + /** - * Change root password for VPS - * @param int $order_id - order id + * Change root password for VPS. + * + * @param int $order_id - order id * @param string $password - new password - * @return bool + * + * @return bool */ public function set_root_password($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->set_root_password($order, $vps, $data); $this->di['logger']->info('Changed VPS root password. Order ID #%s', $order->id); + return true; } - + /** - * Change VPS plan - * @param int $order_id - order id - * @param string $plan - new plan name - * @return bool + * Change VPS plan. + * + * @param int $order_id - order id + * @param string $plan - new plan name + * + * @return bool */ public function set_plan($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->set_plan($order, $vps, $data); $this->di['logger']->info('Changed VPS plan. Order ID #%s', $order->id); + return true; } - + /** - * Change VPS hostname - * @param int $order_id - order id + * Change VPS hostname. + * + * @param int $order_id - order id * @param string $hostname - new hostname for vps - * @return bool + * + * @return bool */ public function set_hostname($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->set_hostname($order, $vps, $data); $this->di['logger']->info('Changed VPS hostname. Order ID #%s', $order->id); + return true; } - + /** - * Rebuild vps operating system with new template - * @param int $order_id - order id + * Rebuild vps operating system with new template. + * + * @param int $order_id - order id * @param string $template - new template - * @return bool + * + * @return bool */ public function rebuild($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->rebuild($order, $vps, $data); $this->di['logger']->info('Changed VPS template. Order ID #%s', $order->id); + return true; } - + /** - * Assign new IP from the pool + * Assign new IP from the pool. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function addip($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->addip($order, $vps, $data); $this->di['logger']->info('Added IP for VPS. Order ID #%s', $order->id); + return true; } - + /** - * Disable network + * Disable network. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function network_disable($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->network_disable($order, $vps, $data); $this->di['logger']->info('Disabled VPS network. Order ID #%s', $order->id); + return true; } - + /** - * Enable network + * Enable network. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function network_enable($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->network_enable($order, $vps, $data); $this->di['logger']->info('Enabled VPS network. Order ID #%s', $order->id); + return true; } - + /** - * Disable tun + * Disable tun. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function tun_disable($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->tun_disable($order, $vps, $data); $this->di['logger']->info('Disabled VPS TUN. Order ID #%s', $order->id); + return true; } - + /** - * Enable tun + * Enable tun. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function tun_enable($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->tun_enable($order, $vps, $data); $this->di['logger']->info('Enabled VPS TUN. Order ID #%s', $order->id); + return true; } - + /** - * Disable PAE + * Disable PAE. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function pae_enable($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->pae_enable($order, $vps, $data); $this->di['logger']->info('Enabled VPS PAE. Order ID #%s', $order->id); + return true; } - + /** - * Enable PAE + * Enable PAE. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function pae_disable($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->pae_disable($order, $vps, $data); $this->di['logger']->info('Disabled VPS PAE. Order ID #%s', $order->id); + return true; } - + /** - * List clients on SolusVM server + * List clients on SolusVM server. + * * @param bool $skip - skip imported clients, default - false + * * @return array */ public function client_list($data) { $skip = (bool) $this->di['array_get']($data, 'skip', false); $clients = $this->getService()->client_list(); - - if($skip) { - //skip imported clients - foreach($clients as $key=>$client) { - if($this->di['db']->findOne('client', 'aid = :aid', array('aid'=>$client['id']))) { + + if ($skip) { + // skip imported clients + foreach ($clients as $key => $client) { + if ($this->di['db']->findOne('client', 'aid = :aid', ['aid' => $client['id']])) { unset($clients[$key]); } } } - + return $clients; } - + /** - * List virtual server on SolusVM server + * List virtual server on SolusVM server. + * * @param bool $node_id - node id to list virtul servers - * @param bool $skip - skip imported servers, default - false + * @param bool $skip - skip imported servers, default - false + * * @return array */ public function node_virtualservers($data) @@ -375,21 +450,22 @@ class Admin extends \Api_Abstract $skip = (bool) $this->di['array_get']($data, 'skip', false); $node_id = $this->di['array_get']($data, 'node_id', 1); $servers = $this->getService()->node_virtualservers($node_id); - - if($skip) { - //skip imported servers - foreach($servers as $key=>$s) { - if($this->di['db']->findOne('service_solusvm', 'vserverid = :vserverid', array('vserverid'=>$s['vserverid']))) { + + if ($skip) { + // skip imported servers + foreach ($servers as $key => $s) { + if ($this->di['db']->findOne('service_solusvm', 'vserverid = :vserverid', ['vserverid' => $s['vserverid']])) { unset($servers[$key]); } } } - + return $servers; } - + /** - * Import selected servers to BoxBilling + * Import selected servers to BoxBilling. + * * @return string - log information regarding import process */ public function import_servers($data) @@ -397,66 +473,66 @@ class Admin extends \Api_Abstract $nodeid = $this->di['array_get']($data, 'node_id', null); $period = $this->di['array_get']($data, 'period', null); $product_id = $this->di['array_get']($data, 'product_id', null); - $selected = $this->di['array_get']($data, 'servers', array()); - if(empty($nodeid)) { + $selected = $this->di['array_get']($data, 'servers', []); + if (empty($nodeid)) { throw new \Box_Exception('Node is not selected for import.', null, 235); } - - if(empty($selected)) { + + if (empty($selected)) { throw new \Box_Exception('No servers selected for import.', null, 234); } - if(empty($product_id)) { + if (empty($product_id)) { throw new \Box_Exception('Select product for orders.'); } $product = $this->di['db']->load('product', $product_id); $pconfig = json_decode($product->config, 1); - $required = array( - 'node' => 'Product is not configured completely. Please provide solusvm node in product configuration page', - 'plan' => 'Product is not configured completely. Please provide solusvm plan in product configuration page', - ); + $required = [ + 'node' => 'Product is not configured completely. Please provide solusvm node in product configuration page', + 'plan' => 'Product is not configured completely. Please provide solusvm plan in product configuration page', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $log = ''; $servers = $this->node_virtualservers($data); foreach ($servers as $server) { - if(!in_array($server['vserverid'], $selected)) { + if (!in_array($server['vserverid'], $selected)) { continue; } - + try { - $ss = $this->di['db']->findOne('service_solusvm', 'vserverid = :vserverid', array('vserverid'=>$server['vserverid'])); - if($ss) { + $ss = $this->di['db']->findOne('service_solusvm', 'vserverid = :vserverid', ['vserverid' => $server['vserverid']]); + if ($ss) { throw new \Exception(sprintf('Server is already imported')); } - - $client = $this->di['db']->findOne('client', 'aid = :aid', array('aid'=>$server['clientid'])); - if(!$client) { + + $client = $this->di['db']->findOne('client', 'aid = :aid', ['aid' => $server['clientid']]); + if (!$client) { throw new \Exception(sprintf('Client with alternative id %s was not found', $server['clientid'])); } - - list($username, ) = $this->getService()->getSolusUserPassword($client); - - $odata = array( - 'client_id' => $client->id, - 'product_id' => $product_id, - 'period' => $period, - 'activate' => false, - 'invoice_option'=> 'no-invoice', - 'config'=> array( - 'hostname' => $server['hostname'], - 'template' => $server['template'], - ), - ); + + [$username] = $this->getService()->getSolusUserPassword($client); + + $odata = [ + 'client_id' => $client->id, + 'product_id' => $product_id, + 'period' => $period, + 'activate' => false, + 'invoice_option' => 'no-invoice', + 'config' => [ + 'hostname' => $server['hostname'], + 'template' => $server['template'], + ], + ]; $id = $this->di['api_admin']->order_create($odata); - + // create service $model = $this->di['db']->dispense('service_solusvm'); - $model->cluster_id = 1; //for future if ever BoxBilling supports multiple master servers - $model->client_id = $client->id; - $model->hostname = $server['hostname']; - $model->template = $server['template']; + $model->cluster_id = 1; // for future if ever BoxBilling supports multiple master servers + $model->client_id = $client->id; + $model->hostname = $server['hostname']; + $model->template = $server['template']; $model->vserverid = $server['vserverid']; $model->virtid = $server['ctid-xid']; $model->nodeid = $nodeid; @@ -469,78 +545,82 @@ class Admin extends \Api_Abstract $model->consoleuser = null; $model->consolepassword = null; $model->mainipaddress = $server['ipaddress']; - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); - - //activate order + + // activate order $o = $this->di['db']->load('client_order', $id); $o->service_id = $model->id; $o->status = 'active'; - $this->di['db']->store($o); - - $log .= sprintf('Created order #%s for server #%s', $id, $server['vserverid']) . PHP_EOL; - } catch(\Exception $e) { + $this->di['db']->store($o); + + $log .= sprintf('Created order #%s for server #%s', $id, $server['vserverid']).PHP_EOL; + } catch (\Exception $e) { $log .= sprintf('Order for server #%s was not imported due to error "%s"', $server['vserverid'], $e->getMessage()).PHP_EOL; } - } - + $this->di['logger']->info('Imported VPS from SolusVM to BoxBilling'); + return $log; } - + /** - * Import selected clients to BoxBilling + * Import selected clients to BoxBilling. + * * @return string - log information regarding import process */ public function import_clients($data) { - $selected = $this->di['array_get']($data, 'clients', array()); - if(empty($selected)) { + $selected = $this->di['array_get']($data, 'clients', []); + if (empty($selected)) { throw new \Box_Exception('No clients selected for import.', null, 233); } - + $clients = $this->client_list($data); - if(empty($clients)) { + if (empty($clients)) { throw new \Box_Exception('No clients found on SolusVM server.'); } - + $log = ''; - foreach($clients as $client) { - if(!in_array($client['id'], $selected)) { + foreach ($clients as $client) { + if (!in_array($client['id'], $selected)) { continue; } $password = substr(md5(random_bytes(13)), 0, 8); - $cdata = array( - 'aid' => $client['id'], - 'email' => $client['email'], - 'company' => $client['company'], - 'first_name' => $client['firstname'], - 'last_name' => $client['lastname'], - 'password' => $password, - 'notes' => 'Imported from SolusVM server', - 'created_at' => date('Y-m-d H:i:s', strtotime($client['created'])), - ); + $cdata = [ + 'aid' => $client['id'], + 'email' => $client['email'], + 'company' => $client['company'], + 'first_name' => $client['firstname'], + 'last_name' => $client['lastname'], + 'password' => $password, + 'notes' => 'Imported from SolusVM server', + 'created_at' => date('Y-m-d H:i:s', strtotime($client['created'])), + ]; try { $id = $this->di['api_admin']->client_create($cdata); $c = $this->di['db']->load('client', $id); $this->getService()->setSolusUserPassword($c, $client['username'], $password); - $log .= sprintf('Imported client #%s', $client['id']) . PHP_EOL; - } catch(\Exception $e) { + $log .= sprintf('Imported client #%s', $client['id']).PHP_EOL; + } catch (\Exception $e) { $log .= sprintf('Client #%s was not imported due to error "%s"', $client['id'], $e->getMessage()).PHP_EOL; } } - + $this->di['logger']->info('Imported clients from SolusVM to BoxBilling'); + return $log; } - + /** - * Test connection to master server + * Test connection to master server. + * * @param int $order_id - order id * @optional string $return - if value = bool - does not return error but returns bool value - * @return bool + * + * @return bool */ public function test_connection($data) { @@ -550,35 +630,38 @@ class Admin extends \Api_Abstract $this->getService()->testConnection($data); $can_connect = true; } catch (\Exception $exc) { - if($return != 'bool') { + if ('bool' != $return) { throw $exc; } } + return $can_connect; } - + /** * Update existing order service * This method used to change clients data if order setup fails * or you have changed data on solusVM server and you need to sync with - * BoxBilling database - * @return boolean + * BoxBilling database. + * + * @return bool */ public function update($data) { - list(, $vps) = $this->_getService($data); + [, $vps] = $this->_getService($data); - $vps->plan = $this->di['array_get']($data, 'plan', $vps->plan); - $vps->template = $this->di['array_get']($data, 'template', $vps->template); - $vps->hostname = $this->di['array_get']($data, 'hostname', $vps->hostname); - $vps->mainipaddress = $this->di['array_get']($data, 'mainipaddress', $vps->mainipaddress); - $vps->custommemory = $this->di['array_get']($data, 'custommemory', $vps->custommemory); + $vps->plan = $this->di['array_get']($data, 'plan', $vps->plan); + $vps->template = $this->di['array_get']($data, 'template', $vps->template); + $vps->hostname = $this->di['array_get']($data, 'hostname', $vps->hostname); + $vps->mainipaddress = $this->di['array_get']($data, 'mainipaddress', $vps->mainipaddress); + $vps->custommemory = $this->di['array_get']($data, 'custommemory', $vps->custommemory); $vps->customdiskspace = $this->di['array_get']($data, 'customdiskspace', $vps->customdiskspace); $vps->custombandwidth = $this->di['array_get']($data, 'custombandwidth', $vps->custombandwidth); - $vps->customcpu = $this->di['array_get']($data, 'customcpu', $vps->customcpu); + $vps->customcpu = $this->di['array_get']($data, 'customcpu', $vps->customcpu); $this->di['db']->store($vps); - + $this->di['logger']->info('Updated VPS service %s details', $vps->id); + return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicesolusvm/Api/Client.php b/src/bb-modules/Servicesolusvm/Api/Client.php index e79b7eada..a0d0ac987 100644 --- a/src/bb-modules/Servicesolusvm/Api/Client.php +++ b/src/bb-modules/Servicesolusvm/Api/Client.php @@ -1,6 +1,6 @@ di['db']->findOne('client_order', "id=:id AND client_id = :cid AND service_type = 'solusvm' - ", - array(':id'=>$data['order_id'], ':cid'=>$this->getIdentity()->id)); - - if(!$order) { + ", + [':id' => $data['order_id'], ':cid' => $this->getIdentity()->id]); + + if (!$order) { throw new \Box_Exception('Solusvm order not found'); } - + $s = $this->di['db']->findOne('service_solusvm', 'id=:id AND client_id = :cid', - array(':id'=>$order->service_id, ':cid'=>$this->getIdentity()->id)); - if(!$s) { + [':id' => $order->service_id, ':cid' => $this->getIdentity()->id]); + if (!$s) { throw new \Box_Exception('Order is not activated'); } - return array($order, $s); + + return [$order, $s]; } - + /** - * Reboot VPS + * Reboot VPS. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function reboot($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->reboot($order, $vps, $data); $this->di['logger']->info('Rebooted VPS. Order ID #%s', $order->id); + return true; } /** - * Boot VPS + * Boot VPS. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function boot($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->boot($order, $vps, $data); $this->di['logger']->info('Booted VPS. Order ID #%s', $order->id); + return true; } /** - * Shutdown VPS + * Shutdown VPS. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function shutdown($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->shutdown($order, $vps, $data); $this->di['logger']->info('Shut down VPS. Order ID #%s', $order->id); + return true; } /** - * Get status VPS + * Get status VPS. + * * @param int $order_id - order id + * * @return online|offline */ public function status($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); + return $this->getService()->status($order, $vps, $data); } /** - * Retrieve more information about vps from sulusvm server + * Retrieve more information about vps from sulusvm server. + * * @param int $order_id - order id + * * @return array */ public function info($data) { - list(, $vps) = $this->_getService($data); + [, $vps] = $this->_getService($data); try { $result = $this->getService()->info($vps->vserverid); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc); - $result = array(); + $result = []; } + return $result; } - + /** - * Change root password for VPS - * @param int $order_id - order id + * Change root password for VPS. + * + * @param int $order_id - order id * @param string $password - new password - * @return bool + * + * @return bool */ public function set_root_password($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->set_root_password($order, $vps, $data); $this->di['logger']->info('Changed VPS root password. Order ID #%s', $order->id); + return true; } /** - * Change hostname for VPS + * Change hostname for VPS. + * * @param int $order_id - order id - * @return bool + * + * @return bool */ public function set_hostname($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->set_hostname($order, $vps, $data); $this->di['logger']->info('Changed VPS hostname. Order ID #%s', $order->id); + return true; } /** - * Change client area password for solusvm user - * @param int $order_id - order id + * Change client area password for solusvm user. + * + * @param int $order_id - order id * @param string $password - new password - * @return bool + * + * @return bool */ public function change_password($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->client_change_password($order, $vps, $data); $this->di['logger']->info('Changed SolusVM client area password. Order ID #%s', $order->id); + return true; } /** - * Rebuild vps operating system with new template - * @param int $order_id - order id + * Rebuild vps operating system with new template. + * + * @param int $order_id - order id * @param string $template - template idetification - * @return bool + * + * @return bool */ public function rebuild($data) { - list($order, $vps) = $this->_getService($data); + [$order, $vps] = $this->_getService($data); $this->getService()->rebuild($order, $vps, $data); $this->di['logger']->info('Changed VPS template. Order ID #%s', $order->id); + return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicesolusvm/Api/Guest.php b/src/bb-modules/Servicesolusvm/Api/Guest.php index 62945c81b..2e9b18497 100644 --- a/src/bb-modules/Servicesolusvm/Api/Guest.php +++ b/src/bb-modules/Servicesolusvm/Api/Guest.php @@ -1,6 +1,6 @@ di['array_get']($data, 'type', 'openvz'); $templates = $this->getService()->getTemplates($type); } catch (\Exception $exc) { - $templates = array(); - if(BB_DEBUG) error_log($exc); + $templates = []; + if (BB_DEBUG) { + error_log($exc); + } } - + return $templates; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicesolusvm/Controller/Admin.php b/src/bb-modules/Servicesolusvm/Controller/Admin.php index 5ebd20974..0c1db8f5b 100644 --- a/src/bb-modules/Servicesolusvm/Controller/Admin.php +++ b/src/bb-modules/Servicesolusvm/Controller/Admin.php @@ -1,6 +1,6 @@ get('/servicesolusvm', 'get_index', array(), get_class($this)); - $app->get('/servicesolusvm/import/clients', 'get_import_clients', array(), get_class($this)); - $app->get('/servicesolusvm/import/servers', 'get_import_servers', array(), get_class($this)); + $app->get('/servicesolusvm', 'get_index', [], get_class($this)); + $app->get('/servicesolusvm/import/clients', 'get_import_clients', [], get_class($this)); + $app->get('/servicesolusvm/import/servers', 'get_import_servers', [], get_class($this)); } - + public function get_index(\Box_App $app) { $this->di['is_admin_logged']; @@ -48,12 +48,14 @@ class Admin implements \Box\InjectionAwareInterface public function get_import_clients(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_servicesolusvm_import_clients'); } public function get_import_servers(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_servicesolusvm_import_servers'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Servicesolusvm/Service.php b/src/bb-modules/Servicesolusvm/Service.php index 4336e57c7..75faca17b 100644 --- a/src/bb-modules/Servicesolusvm/Service.php +++ b/src/bb-modules/Servicesolusvm/Service.php @@ -1,6 +1,6 @@ di['db']->exec($sql); } public function uninstall() { - $this->di['db']->exec("DROP TABLE IF EXISTS `service_solusvm`"); + $this->di['db']->exec('DROP TABLE IF EXISTS `service_solusvm`'); } public function getCartProductTitle($product, array $data) { return __('Virtual private server :title', - array( - ':title' => $product->title, + [ + ':title' => $product->title, ':template' => $data['template'], - ':hostname' => $data['hostname'])); + ':hostname' => $data['hostname'], ]); } public function validateOrderData(array $data) @@ -89,7 +89,7 @@ class Service implements InjectionAwareInterface $ValidHostnameRegex = "/^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$/"; if (!preg_match($ValidHostnameRegex, $data['hostname'])) { - throw new \Box_Exception('Hostname :hostname is not valid.', array(':hostname' => $data['hostname']), 7102); + throw new \Box_Exception('Hostname :hostname is not valid.', [':hostname' => $data['hostname']], 7102); } if (!isset($data['template']) || empty($data['template'])) { @@ -128,27 +128,27 @@ class Service implements InjectionAwareInterface AND meta_key = 'config' "; - $c = array( - 'id' => $data['id'], - 'key' => $data['key'], + $c = [ + 'id' => $data['id'], + 'key' => $data['key'], 'ipaddress' => $data['ipaddress'], - 'secure' => $data['secure'], - 'port' => $data['port'], - 'usertype' => 'admin', - ); - $params = array( - 'config' => json_encode($c), + 'secure' => $data['secure'], + 'port' => $data['port'], + 'usertype' => 'admin', + ]; + $params = [ + 'config' => json_encode($c), 'cluster_id' => $cluster_id, - ); + ]; $this->di['db']->exec($sql, $params); } /** - * @param integer $cluster_id + * @param int $cluster_id */ public function getMasterConfig($cluster_id) { - $sql = " + $sql = " SELECT meta_value FROM extension_meta WHERE extension = 'mod_servicesolusvm' @@ -156,14 +156,14 @@ class Service implements InjectionAwareInterface AND rel_id = :cluster_id AND meta_key = 'config' "; - $config = $this->di['db']->getCell($sql, array('cluster_id' => $cluster_id)); + $config = $this->di['db']->getCell($sql, ['cluster_id' => $cluster_id]); if (!$config) { - $config = array(); - $meta = $this->di['db']->dispense('extension_meta'); - $meta->extension = 'mod_servicesolusvm'; - $meta->rel_type = 'cluster'; - $meta->rel_id = $cluster_id; - $meta->meta_key = 'config'; + $config = []; + $meta = $this->di['db']->dispense('extension_meta'); + $meta->extension = 'mod_servicesolusvm'; + $meta->rel_type = 'cluster'; + $meta->rel_id = $cluster_id; + $meta->meta_key = 'config'; $meta->meta_value = json_encode($config); $meta->created_at = date('Y-m-d H:i:s'); $meta->updated_at = date('Y-m-d H:i:s'); @@ -183,19 +183,19 @@ class Service implements InjectionAwareInterface public function setSolusUserPassword($client, $username, $password) { - $meta = $this->di['db']->dispense('extension_meta'); - $meta->extension = 'mod_servicesolusvm'; - $meta->client_id = $client->id; - $meta->meta_key = 'solusvm_username'; + $meta = $this->di['db']->dispense('extension_meta'); + $meta->extension = 'mod_servicesolusvm'; + $meta->client_id = $client->id; + $meta->meta_key = 'solusvm_username'; $meta->meta_value = $username; $meta->created_at = date('Y-m-d H:i:s'); $meta->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($meta); - $meta = $this->di['db']->dispense('extension_meta'); - $meta->extension = 'mod_servicesolusvm'; - $meta->client_id = $client->id; - $meta->meta_key = 'solusvm_password'; + $meta = $this->di['db']->dispense('extension_meta'); + $meta->extension = 'mod_servicesolusvm'; + $meta->client_id = $client->id; + $meta->meta_key = 'solusvm_password'; $meta->meta_value = $password; $meta->created_at = date('Y-m-d H:i:s'); $meta->updated_at = date('Y-m-d H:i:s'); @@ -204,15 +204,15 @@ class Service implements InjectionAwareInterface public function getSolusUserPassword($client) { - $sql = " + $sql = " SELECT meta_value FROM extension_meta WHERE client_id = :cid AND extension = 'mod_servicesolusvm' AND meta_key = :key "; - $username = $this->di['db']->getCell($sql, array('cid' => $client->id, 'key' => 'solusvm_username')); - $password = $this->di['db']->getCell($sql, array('cid' => $client->id, 'key' => 'solusvm_password')); + $username = $this->di['db']->getCell($sql, ['cid' => $client->id, 'key' => 'solusvm_username']); + $password = $this->di['db']->getCell($sql, ['cid' => $client->id, 'key' => 'solusvm_password']); if (!$username) { $username = $client->email; @@ -220,21 +220,22 @@ class Service implements InjectionAwareInterface $this->setSolusUserPassword($client, $username, $password); } - return array($username, $password); + return [$username, $password]; } /** * @param $order + * * @return void */ public function create($order) { $c = json_decode($order->config, 1); $this->validateOrderData($c); - $model = $this->di['db']->dispense('service_solusvm'); - $model->client_id = $order->client_id; - $model->hostname = strtolower($c['hostname']); - $model->template = $c['template']; + $model = $this->di['db']->dispense('service_solusvm'); + $model->client_id = $order->client_id; + $model->hostname = strtolower($c['hostname']); + $model->template = $c['template']; $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); @@ -244,6 +245,7 @@ class Service implements InjectionAwareInterface /** * @param $order + * * @return void */ public function activate($order, $model) @@ -252,7 +254,7 @@ class Service implements InjectionAwareInterface throw new \Box_Exception('Could not activate order. Service was not created', null, 7456); } - $client = $this->di['db']->load('client', $order->client_id); + $client = $this->di['db']->load('client', $order->client_id); $product = $this->di['db']->load('product', $order->product_id); if (!$product) { throw new \Box_Exception('Could not activate order because ordered product does not exists', null, 7457); @@ -260,7 +262,7 @@ class Service implements InjectionAwareInterface $pconfig = json_decode($product->config, 1); - list($username, $password) = $this->getSolusUserPassword($client); + [$username, $password] = $this->getSolusUserPassword($client); try { $this->_getApi()->client_checkexists($username); @@ -269,78 +271,79 @@ class Service implements InjectionAwareInterface } if (!isset($pconfig['node'])) { - throw new \Box_Exception('Could not activate order. Product :id configuration is missing node parameter', array(':id' => $product->id), 7458); + throw new \Box_Exception('Could not activate order. Product :id configuration is missing node parameter', [':id' => $product->id], 7458); } if (!isset($pconfig['plan'])) { - throw new \Box_Exception('Could not activate order. Product :id configuration is missing plan parameter', array(':id' => $product->id), 7459); + throw new \Box_Exception('Could not activate order. Product :id configuration is missing plan parameter', [':id' => $product->id], 7459); } if (!isset($pconfig['vtype'])) { - throw new \Box_Exception('Could not activate order. Product :id configuration is missing virtualization type parameter', array(':id' => $product->id), 7460); + throw new \Box_Exception('Could not activate order. Product :id configuration is missing virtualization type parameter', [':id' => $product->id], 7460); } if (!isset($pconfig['ips'])) { - throw new \Box_Exception('Could not activate order. Product :id configuration is missing ips amount parameter', array(':id' => $product->id), 7461); + throw new \Box_Exception('Could not activate order. Product :id configuration is missing ips amount parameter', [':id' => $product->id], 7461); } - $type = $pconfig['vtype']; - $node = $pconfig['node']; + $type = $pconfig['vtype']; + $node = $pconfig['node']; $nodegroup = $this->di['array_get']($pconfig, 'nodegroup', null); $template = $model->template; $hostname = $model->hostname; - $plan = $pconfig['plan']; - $ips = $pconfig['ips']; + $plan = $pconfig['plan']; + $ips = $pconfig['ips']; - $hvmt = $this->di['array_get']($pconfig, 'hvmt', null); - $custommemory = $this->di['array_get']($pconfig, 'custommemory', null); + $hvmt = $this->di['array_get']($pconfig, 'hvmt', null); + $custommemory = $this->di['array_get']($pconfig, 'custommemory', null); $customdiskspace = $this->di['array_get']($pconfig, 'customdiskspace', null); $custombandwidth = $this->di['array_get']($pconfig, 'custombandwidth', null); - $customcpu = $this->di['array_get']($pconfig, 'customcpu', null); - $customextraip = $this->di['array_get']($pconfig, 'customextraip', null); - $issuelicense = $this->di['array_get']($pconfig, 'issuelicense', null); + $customcpu = $this->di['array_get']($pconfig, 'customcpu', null); + $customextraip = $this->di['array_get']($pconfig, 'customextraip', null); + $issuelicense = $this->di['array_get']($pconfig, 'issuelicense', null); $result = $this->_getApi()->vserver_create($type, $node, $nodegroup, $hostname, $password, $username, $plan, $template, $ips, $hvmt, $custommemory, $customdiskspace, $custombandwidth, $customcpu, $customextraip, $issuelicense); - $model->cluster_id = 1; //for future if ever BoxBilling supports multiple master servers - $model->vserverid = $result['vserverid']; - $model->virtid = $result['virtid']; - $model->nodeid = $result['nodeid']; - $model->type = $type; - $model->plan = $plan; - $model->node = $node; - $model->nodegroup = $nodegroup; - $model->hostname = $result['hostname']; - $model->rootpassword = ''; //$result['rootpassword']; - $model->username = $username; - $model->ips = $ips; - $model->hvmt = $hvmt; - $model->consoleuser = $result['consoleuser']; - $model->consolepassword = ''; //$result['consolepassword']; - $model->custommemory = $custommemory; + $model->cluster_id = 1; // for future if ever BoxBilling supports multiple master servers + $model->vserverid = $result['vserverid']; + $model->virtid = $result['virtid']; + $model->nodeid = $result['nodeid']; + $model->type = $type; + $model->plan = $plan; + $model->node = $node; + $model->nodegroup = $nodegroup; + $model->hostname = $result['hostname']; + $model->rootpassword = ''; // $result['rootpassword']; + $model->username = $username; + $model->ips = $ips; + $model->hvmt = $hvmt; + $model->consoleuser = $result['consoleuser']; + $model->consolepassword = ''; // $result['consolepassword']; + $model->custommemory = $custommemory; $model->customdiskspace = $customdiskspace; $model->custombandwidth = $custombandwidth; - $model->customcpu = $customcpu; - $model->customextraip = $customextraip; - $model->issuelicense = $issuelicense; - $model->mainipaddress = $result['mainipaddress']; - $model->extraipaddress = $this->di['array_get']($result, 'extraipaddress', null); - $model->updated_at = date('Y-m-d H:i:s'); + $model->customcpu = $customcpu; + $model->customextraip = $customextraip; + $model->issuelicense = $issuelicense; + $model->mainipaddress = $result['mainipaddress']; + $model->extraipaddress = $this->di['array_get']($result, 'extraipaddress', null); + $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); - //pass params to event hook - return array( - 'rootpassword' => $result['rootpassword'], + // pass params to event hook + return [ + 'rootpassword' => $result['rootpassword'], 'consolepassword' => $result['consolepassword'], - ); + ]; } /** - * Suspend VPS + * Suspend VPS. * * @param $order - * @return boolean + * + * @return bool */ public function suspend($order, $model) { @@ -353,7 +356,8 @@ class Service implements InjectionAwareInterface /** * @param $order - * @return boolean + * + * @return bool */ public function unsuspend($order, $model) { @@ -366,7 +370,8 @@ class Service implements InjectionAwareInterface /** * @param $order - * @return boolean + * + * @return bool */ public function cancel($order, $model) { @@ -374,9 +379,9 @@ class Service implements InjectionAwareInterface } /** - * * @param $order - * @return boolean + * + * @return bool */ public function uncancel($order, $model) { @@ -385,7 +390,8 @@ class Service implements InjectionAwareInterface /** * @param $order - * @return boolean + * + * @return bool */ public function delete($order, $model) { @@ -432,7 +438,7 @@ class Service implements InjectionAwareInterface return $result; } - public function set_root_password($order, $model, $params = array()) + public function set_root_password($order, $model, $params = []) { if (!isset($params['password']) || strlen($params['password']) < 4) { throw new \Box_Exception('Root password must be longer than 4 symbols', null, 8789); @@ -440,13 +446,13 @@ class Service implements InjectionAwareInterface $pass = $params['password']; $this->_getApi()->vserver_rootpassword($model->vserverid, $pass); - $model->rootpassword = ''; //$pass; + $model->rootpassword = ''; // $pass; $this->di['db']->store($model); return true; } - public function set_plan($order, $model, $params = array()) + public function set_plan($order, $model, $params = []) { if (!isset($params['plan']) || empty($params['plan'])) { throw new \Box_Exception('Plan name must not be empty', null, 8790); @@ -458,7 +464,7 @@ class Service implements InjectionAwareInterface return true; } - public function set_hostname($order, $model, $params = array()) + public function set_hostname($order, $model, $params = []) { if (!isset($params['hostname']) || empty($params['hostname'])) { throw new \Box_Exception('Hostname must not be empty', null, 8791); @@ -470,7 +476,7 @@ class Service implements InjectionAwareInterface return true; } - public function rebuild($order, $model, $params = array()) + public function rebuild($order, $model, $params = []) { if (!isset($params['template']) || empty($params['template'])) { throw new \Box_Exception('Template must not be empty', null, 8792); @@ -482,39 +488,39 @@ class Service implements InjectionAwareInterface return true; } - public function addip($order, $model, $params = array()) + public function addip($order, $model, $params = []) { $this->_getApi()->vserver_addip($model->vserverid); return true; } - public function network_disable($order, $model, $params = array()) + public function network_disable($order, $model, $params = []) { return $this->_getApi()->vserver_network_disable($model->vserverid); } - public function network_enable($order, $model, $params = array()) + public function network_enable($order, $model, $params = []) { return $this->_getApi()->vserver_network_enable($model->vserverid); } - public function tun_disable($order, $model, $params = array()) + public function tun_disable($order, $model, $params = []) { return $this->_getApi()->vserver_tun_disable($model->vserverid); } - public function tun_enable($order, $model, $params = array()) + public function tun_enable($order, $model, $params = []) { return $this->_getApi()->vserver_tun_enable($model->vserverid); } - public function pae_disable($order, $model, $params = array()) + public function pae_disable($order, $model, $params = []) { return $this->_getApi()->vserver_pae($model->vserverid, 'off'); } - public function pae_enable($order, $model, $params = array()) + public function pae_enable($order, $model, $params = []) { return $this->_getApi()->vserver_pae($model->vserverid, 'on'); } @@ -529,7 +535,7 @@ class Service implements InjectionAwareInterface return $this->_getApi()->node_virtualservers($nodeid); } - public function client_change_password($order, $model, $params = array()) + public function client_change_password($order, $model, $params = []) { if (!isset($params['password']) || strlen($params['password']) < 4) { throw new \Box_Exception('Password must be longer than 4 symbols', null, 8790); @@ -543,31 +549,31 @@ class Service implements InjectionAwareInterface AND extension = 'mod_servicesolusvm' AND meta_key = :key "; - $this->di['db']->exec($sql, array('cid' => $model->client_id, 'key' => 'solusvm_password', 'pass' => $params['password'])); + $this->di['db']->exec($sql, ['cid' => $model->client_id, 'key' => 'solusvm_password', 'pass' => $params['password']]); return true; } public function getVirtualizationTypes($data) { - return array( - "openvz" => 'OpenVz', - "xen" => 'Xen', - "xen hvm" => 'Xen HVM', - "kvm" => 'KVM', - ); + return [ + 'openvz' => 'OpenVz', + 'xen' => 'Xen', + 'xen hvm' => 'Xen HVM', + 'kvm' => 'KVM', + ]; } public function getNodes($type, $by) { - if ($by == 'id') { + if ('id' == $by) { $result = $this->_getApi()->node_idlist($type); } else { $result = $this->_getApi()->listnodes($type); } $list = explode(',', $result['nodes']); - $res = array(); + $res = []; foreach ($list as $p) { $res[$p] = $p; } @@ -579,14 +585,14 @@ class Service implements InjectionAwareInterface { $templates = $this->_getApi()->listtemplates($type); $list = explode(',', $templates['templates']); - if($type == 'kvm' && isset($templates['templateskvm'])) { + if ('kvm' == $type && isset($templates['templateskvm'])) { $list = explode(',', $templates['templateskvm']); } - if($type == 'xen hvm' && isset($templates['templateshvm'])) { + if ('xen hvm' == $type && isset($templates['templateshvm'])) { $list = explode(',', $templates['templateshvm']); } - $res = array(); + $res = []; foreach ($list as $p) { $res[$p] = $p; } @@ -597,8 +603,8 @@ class Service implements InjectionAwareInterface public function getPlans($type = 'openvz') { $plans = $this->_getApi()->listplans($type); - $list = explode(',', $plans['plans']); - $res = array(); + $list = explode(',', $plans['plans']); + $res = []; foreach ($list as $p) { $res[$p] = $p; } @@ -626,45 +632,44 @@ class Service implements InjectionAwareInterface { $c = $this->getMasterConfig(1); if ($c['secure']) { - if ($c["port"]) { - $cport = $c["port"]; + if ($c['port']) { + $cport = $c['port']; } else { - $cport = "5656"; + $cport = '5656'; } - $url = "https://" . $c['ipaddress'] . ":" . $cport; + $url = 'https://'.$c['ipaddress'].':'.$cport; } else { - if ($c["port"]) { - $cport = $c["port"]; + if ($c['port']) { + $cport = $c['port']; } else { - $cport = "5353"; + $cport = '5353'; } - $url = "http://" . $c['ipaddress'] . ":" . $cport; + $url = 'http://'.$c['ipaddress'].':'.$cport; } $client = $this->di['db']->load('client', $model->client_id); - list($username, $password) = $this->getSolusUserPassword($client); + [$username, $password] = $this->getSolusUserPassword($client); - return array( - 'id' => $model->id, - 'vserverid' => $model->vserverid, - 'virtid' => $model->virtid, - 'hostname' => $model->hostname, - 'plan' => $model->plan, - 'template' => $model->template, - 'mainipaddress' => $model->mainipaddress, - 'rootpassword' => $model->rootpassword, - 'consoleuser' => $model->consoleuser, + return [ + 'id' => $model->id, + 'vserverid' => $model->vserverid, + 'virtid' => $model->virtid, + 'hostname' => $model->hostname, + 'plan' => $model->plan, + 'template' => $model->template, + 'mainipaddress' => $model->mainipaddress, + 'rootpassword' => $model->rootpassword, + 'consoleuser' => $model->consoleuser, 'consolepassword' => $model->consolepassword, - 'custommemory' => $model->custommemory, + 'custommemory' => $model->custommemory, 'customdiskspace' => $model->customdiskspace, 'custombandwidth' => $model->custombandwidth, - 'customcpu' => $model->customcpu, + 'customcpu' => $model->customcpu, - 'master_url' => $url, - 'username' => $username, - 'password' => $password, - ); + 'master_url' => $url, + 'username' => $username, + 'password' => $password, + ]; } } - diff --git a/src/bb-modules/Servicesolusvm/SolusVM.php b/src/bb-modules/Servicesolusvm/SolusVM.php index 8f4444fe5..a7730fe59 100644 --- a/src/bb-modules/Servicesolusvm/SolusVM.php +++ b/src/bb-modules/Servicesolusvm/SolusVM.php @@ -2,13 +2,13 @@ namespace Box\Mod\Servicesolusvm; -class SolusVM implements \Box\InjectionAwareInterface{ - +class SolusVM implements \Box\InjectionAwareInterface +{ protected $api_host = null; // SolusVM Controlpanel URL protected $api_ID = ''; // API ID protected $api_key = ''; // API KEY - protected $_parameters = array(); + protected $_parameters = []; /** * @var \Box_Di @@ -31,9 +31,9 @@ class SolusVM implements \Box\InjectionAwareInterface{ return $this->di; } - /** - * SolusVM Controlpanel URL + * SolusVM Controlpanel URL. + * * @return string */ public function getApiHost() @@ -83,13 +83,14 @@ class SolusVM implements \Box\InjectionAwareInterface{ public function buildUrl(array $config) { - return $config['protocol'] ."://". $config['ipaddress'] . ":" . $config['port'] . "/api/" . $config['usertype'] . "/command.php"; + return $config['protocol'].'://'.$config['ipaddress'].':'.$config['port'].'/api/'.$config['usertype'].'/command.php'; } public function getSecureUrl(array $config) { $config['port'] = $this->di['array_get']($config, 'port', 5656); $config['protocol'] = 'https'; + return $this->buildUrl($config); } @@ -97,21 +98,22 @@ class SolusVM implements \Box\InjectionAwareInterface{ { $config['port'] = $this->di['array_get']($config, 'port', 5353); $config['protocol'] = 'http'; + return $this->buildUrl($config); } public function setConfig(array $c) { - $required = array( - 'id' => 'API ID is missing', - 'key' => 'API key is missing', + $required = [ + 'id' => 'API ID is missing', + 'key' => 'API key is missing', 'ipaddress' => 'API ip address is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $c); $c['usertype'] = $this->di['array_get']($c, 'usertype', 'admin'); - $c['secure'] = $this->di['array_get']($c, 'secure', false); - $c['port'] = $this->di['array_get']($c, 'port', null); + $c['secure'] = $this->di['array_get']($c, 'secure', false); + $c['port'] = $this->di['array_get']($c, 'port', null); $url = $this->getUrl($c); @@ -127,12 +129,12 @@ class SolusVM implements \Box\InjectionAwareInterface{ /** * @param string $action */ - private function callAPI($action, $raw_response = false){ - + private function callAPI($action, $raw_response = false) + { $postfields = array_merge( - array('id' => $this->api_ID), - array('key' => $this->api_key), - array('action'=>$action), + ['id' => $this->api_ID], + ['key' => $this->api_key], + ['action' => $action], $this->_parameters); $ch = curl_init(); @@ -142,35 +144,35 @@ class SolusVM implements \Box\InjectionAwareInterface{ curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:")); + curl_setopt($ch, CURLOPT_HTTPHEADER, ['Expect:']); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $return = curl_exec($ch); $curl_error = curl_error($ch); - if($curl_error) { + if ($curl_error) { throw new \Exception($curl_error, 8755); } curl_close($ch); - if(empty($return)){ + if (empty($return)) { throw new \Exception('Empty response from SolusVM server.', 8766); } - //used by client-list action - if($raw_response) { + // used by client-list action + if ($raw_response) { return $return; } - $result = $match = array(); + $result = $match = []; preg_match_all('/<(.*?)>([^<]+)<\/\\1>/i', $return, $match); foreach ($match[1] as $x => $y) { $result[$y] = $match[2][$x]; } - if($result['status'] != "success" && isset($result['statusmsg'])){ + if ('success' != $result['status'] && isset($result['statusmsg'])) { throw new \Exception($result['statusmsg'], 8777); } @@ -217,9 +219,9 @@ class SolusVM implements \Box\InjectionAwareInterface{ Failure Returns ....... : error error message */ - public function vserver_create($type, $node, $nodegroup, $hostname, $password, $username, $plan, $template, $ips, $hvmt = '', $custommemory = '', $customdiskspace = '', $custombandwidth = '', $customcpu = '', $customextraip = '', $issuelicense = ''){ - - $this->_parameters = array( + public function vserver_create($type, $node, $nodegroup, $hostname, $password, $username, $plan, $template, $ips, $hvmt = '', $custommemory = '', $customdiskspace = '', $custombandwidth = '', $customcpu = '', $customextraip = '', $issuelicense = '') + { + $this->_parameters = [ 'type' => $type, 'node' => $node, 'nodegroup' => $nodegroup, @@ -235,68 +237,65 @@ class SolusVM implements \Box\InjectionAwareInterface{ 'custombandwidth' => $custombandwidth, 'customcpu' => $customcpu, 'customextraip' => $customextraip, - 'issuelicense' => $issuelicense - ); - return $this->callAPI("vserver-create"); + 'issuelicense' => $issuelicense, + ]; + + return $this->callAPI('vserver-create'); } - public function vserver_checkexists($vserverid){ + public function vserver_checkexists($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; - $this->_parameters = array( - 'vserverid' => $vserverid - ); - - return $this->callAPI("vserver-checkexists"); + return $this->callAPI('vserver-checkexists'); } - public function client_checkexists($username){ - - $this->_parameters = array( - 'username' => $username - ); - - return $this->callAPI("client-checkexists"); + public function client_checkexists($username) + { + $this->_parameters = [ + 'username' => $username, + ]; + return $this->callAPI('client-checkexists'); } - public function client_delete($username){ - - $this->_parameters = array( - 'username' => $username - ); - - return $this->callAPI("client-delete"); + public function client_delete($username) + { + $this->_parameters = [ + 'username' => $username, + ]; + return $this->callAPI('client-delete'); } - public function vserver_status($vserverid){ - - $this->_parameters = array( - 'vserverid' => $vserverid - ); - - return $this->callAPI("vserver-status"); + public function vserver_status($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + return $this->callAPI('vserver-status'); } - public function client_create($username, $password, $email, $firstname, $lastname, $company = ''){ - - $this->_parameters = array( + public function client_create($username, $password, $email, $firstname, $lastname, $company = '') + { + $this->_parameters = [ 'username' => $username, 'password' => $password, 'email' => $email, 'firstname' => $firstname, 'lastname' => $lastname, - 'company' => $company - ); - - return $this->callAPI("client-create"); + 'company' => $company, + ]; + return $this->callAPI('client-create'); } - public function reseller_create($username, $password, $email, $firstname, $lastname, $company = '', $usernameprefix = '', $maxvps = '', $maxusers = '', $maxmem = '', $maxburst = '', $maxdisk = '', $maxbw = '', $maxipv4 = '', $maxipv6 = '', $nodegroup = '', $mediagroups = '', $openvz = '', $xenpv = '', $xenhvm = '', $kvm = ''){ - - $this->_parameters = array( + public function reseller_create($username, $password, $email, $firstname, $lastname, $company = '', $usernameprefix = '', $maxvps = '', $maxusers = '', $maxmem = '', $maxburst = '', $maxdisk = '', $maxbw = '', $maxipv4 = '', $maxipv6 = '', $nodegroup = '', $mediagroups = '', $openvz = '', $xenpv = '', $xenhvm = '', $kvm = '') + { + $this->_parameters = [ 'username' => $username, 'password' => $password, 'email' => $email, @@ -317,16 +316,15 @@ class SolusVM implements \Box\InjectionAwareInterface{ 'openvz' => $openvz, 'xenpv' => $xenpv, 'xenhvm' => $xenhvm, - 'kvm' => $kvm - ); - - return $this->callAPI("reseller-create"); + 'kvm' => $kvm, + ]; + return $this->callAPI('reseller-create'); } - public function reseller_modifyresources($username, $maxvps = '', $maxusers = '', $maxmem = '', $maxburst = '', $maxdisk = '', $maxbw = '', $maxipv4 = '', $maxipv6 = '', $nodegroup = '', $mediagroups = '', $openvz = '', $xenpv = '', $xenhvm = '', $kvm = ''){ - - $this->_parameters = array( + public function reseller_modifyresources($username, $maxvps = '', $maxusers = '', $maxmem = '', $maxburst = '', $maxdisk = '', $maxbw = '', $maxipv4 = '', $maxipv6 = '', $nodegroup = '', $mediagroups = '', $openvz = '', $xenpv = '', $xenhvm = '', $kvm = '') + { + $this->_parameters = [ 'username' => $username, 'maxvps' => $maxvps, 'maxusers' => $maxusers, @@ -341,333 +339,394 @@ class SolusVM implements \Box\InjectionAwareInterface{ 'openvz' => $openvz, 'xenpv' => $xenpv, 'xenhvm' => $xenhvm, - 'kvm' => $kvm - ); - - return $this->callAPI("reseller-modifyresources"); + 'kvm' => $kvm, + ]; + return $this->callAPI('reseller-modifyresources'); } - public function reseller_info($username){ - - $this->_parameters = array( - 'username' => $username - ); - - return $this->callAPI("reseller-info-delete"); - - } - - public function reseller_list(){ - return $this->callAPI("reseller-list"); - } - - public function reseller_delete($username){ - - $this->_parameters = array( - 'username' => $username - ); - - return $this->callAPI("reseller-delete"); - - } - - public function client_updatepassword($username, $password){ - $this->_parameters = array( + public function reseller_info($username) + { + $this->_parameters = [ 'username' => $username, - 'password' => $password - ); - return $this->callAPI("client-updatepassword"); + ]; + + return $this->callAPI('reseller-info-delete'); } - public function vserver_addip($vserverid){ - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-addip"); + public function reseller_list() + { + return $this->callAPI('reseller-list'); } - public function vserver_changeowner($vserverid, $clientid){ - $this->_parameters = array( + public function reseller_delete($username) + { + $this->_parameters = [ + 'username' => $username, + ]; + + return $this->callAPI('reseller-delete'); + } + + public function client_updatepassword($username, $password) + { + $this->_parameters = [ + 'username' => $username, + 'password' => $password, + ]; + + return $this->callAPI('client-updatepassword'); + } + + public function vserver_addip($vserverid) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'clientid' => $clientid - ); - return $this->callAPI("vserver-changeowner"); + ]; + + return $this->callAPI('vserver-addip'); } - public function vserver_reboot($vserverid){ - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-reboot"); - } - - public function vserver_shutdown($vserverid){ - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-shutdown"); - } - - public function vserver_boot($vserverid){ - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-boot"); - } - - public function vserver_suspend($vserverid){ - - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-suspend"); - } - - public function vserver_unsuspend($vserverid){ - - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-unsuspend"); - } - - public function vserver_tun_enable($vserverid){ - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-tun-enable"); - } - - public function vserver_network_enable($vserverid){ - - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-network-enable"); - } - - public function vserver_network_disable($vserverid){ - - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-network-disable"); - } - - public function vserver_consolepass($vserverid, $consolepassword){ - $this->_parameters = array( + public function vserver_changeowner($vserverid, $clientid) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'consolepassword' => $consolepassword - ); - return $this->callAPI("vserver-consolepass"); + 'clientid' => $clientid, + ]; + + return $this->callAPI('vserver-changeowner'); } - public function vserver_vncpass($vserverid, $vncpassword){ - - $this->_parameters = array( + public function vserver_reboot($vserverid) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'vncpassword' => $vncpassword - ); - return $this->callAPI("vserver-vncpass"); + ]; + + return $this->callAPI('vserver-reboot'); } - public function vserver_vnc($vserverid){ - - $this->_parameters = array( - 'vserverid' => $vserverid - ); - - return $this->callAPI("vserver-vnc"); - - } - - public function vserver_console($vserverid){ - - $this->_parameters = array( - 'vserverid' => $vserverid - ); - - return $this->callAPI("vserver-console"); - - } - - public function vserver_tun_disable($vserverid){ - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-tun-disable"); - } - - public function vserver_mountiso($vserverid, $iso){ - $this->_parameters = array( + public function vserver_shutdown($vserverid) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'iso' => $iso - ); - return $this->callAPI("vserver-mountiso"); + ]; + + return $this->callAPI('vserver-shutdown'); } - public function vserver_unmountiso($vserverid){ - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-unmountiso"); + public function vserver_boot($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-boot'); + } + + public function vserver_suspend($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-suspend'); + } + + public function vserver_unsuspend($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-unsuspend'); + } + + public function vserver_tun_enable($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-tun-enable'); + } + + public function vserver_network_enable($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-network-enable'); + } + + public function vserver_network_disable($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-network-disable'); + } + + public function vserver_consolepass($vserverid, $consolepassword) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + 'consolepassword' => $consolepassword, + ]; + + return $this->callAPI('vserver-consolepass'); + } + + public function vserver_vncpass($vserverid, $vncpassword) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + 'vncpassword' => $vncpassword, + ]; + + return $this->callAPI('vserver-vncpass'); + } + + public function vserver_vnc($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-vnc'); + } + + public function vserver_console($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-console'); + } + + public function vserver_tun_disable($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-tun-disable'); + } + + public function vserver_mountiso($vserverid, $iso) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + 'iso' => $iso, + ]; + + return $this->callAPI('vserver-mountiso'); + } + + public function vserver_unmountiso($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-unmountiso'); } /** * @param string $pae */ - public function vserver_pae($vserverid, $pae){ - $this->_parameters = array( + public function vserver_pae($vserverid, $pae) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'pae' => $pae - ); - return $this->callAPI("vserver-pae"); + 'pae' => $pae, + ]; + + return $this->callAPI('vserver-pae'); } - public function vserver_bootorder($vserverid, $bootorder){ - $this->_parameters = array( + public function vserver_bootorder($vserverid, $bootorder) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'bootorder' => $bootorder - ); - return $this->callAPI("vserver-bootorder"); + 'bootorder' => $bootorder, + ]; + + return $this->callAPI('vserver-bootorder'); } - public function vserver_terminate($vserverid, $deleteclient = false){ - $this->_parameters = array( + public function vserver_terminate($vserverid, $deleteclient = false) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'deleteclient' => $deleteclient - ); - return $this->callAPI("vserver-terminate"); + 'deleteclient' => $deleteclient, + ]; + + return $this->callAPI('vserver-terminate'); } - public function vserver_rebuild($vserverid, $template){ - $this->_parameters = array( + public function vserver_rebuild($vserverid, $template) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'template' => $template - ); - return $this->callAPI("vserver-rebuild"); + 'template' => $template, + ]; + + return $this->callAPI('vserver-rebuild'); } - public function vserver_change($vserverid, $plan){ - $this->_parameters = array( + public function vserver_change($vserverid, $plan) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'plan' => $plan - ); - return $this->callAPI("vserver-change"); + 'plan' => $plan, + ]; + + return $this->callAPI('vserver-change'); } - public function vserver_rootpassword($vserverid, $rootpassword){ - $this->_parameters = array( + public function vserver_rootpassword($vserverid, $rootpassword) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'rootpassword' => $rootpassword - ); - return $this->callAPI("vserver-rootpassword"); + 'rootpassword' => $rootpassword, + ]; + + return $this->callAPI('vserver-rootpassword'); } - public function vserver_hostname($vserverid, $hostname){ - $this->_parameters = array( + public function vserver_hostname($vserverid, $hostname) + { + $this->_parameters = [ 'vserverid' => $vserverid, - 'hostname' => $hostname - ); - return $this->callAPI("vserver-hostname"); + 'hostname' => $hostname, + ]; + + return $this->callAPI('vserver-hostname'); } - public function listnodes($type){ - $this->_parameters = array( - 'type' => $type - ); - return $this->callAPI("listnodes"); + public function listnodes($type) + { + $this->_parameters = [ + 'type' => $type, + ]; + + return $this->callAPI('listnodes'); } - public function node_idlist($type){ - $this->_parameters = array( - 'type' => $type - ); - return $this->callAPI("node-idlist"); + public function node_idlist($type) + { + $this->_parameters = [ + 'type' => $type, + ]; + + return $this->callAPI('node-idlist'); } - public function listnodegroups(){ - return $this->callAPI("listnodegroups"); + public function listnodegroups() + { + return $this->callAPI('listnodegroups'); } - public function client_list(){ - $xml = $this->callAPI("client-list", true); - $a = json_decode(json_encode((array) simplexml_load_string($xml)),1); + public function client_list() + { + $xml = $this->callAPI('client-list', true); + $a = json_decode(json_encode((array) simplexml_load_string($xml)), 1); + return $a['client']; } /** * @param string $type */ - public function listplans($type){ - $this->_parameters = array( - 'type' => $type - ); - return $this->callAPI("listplans"); + public function listplans($type) + { + $this->_parameters = [ + 'type' => $type, + ]; + + return $this->callAPI('listplans'); } - public function listtemplates($type){ - $this->_parameters = array( - 'type' => $type - ); - return $this->callAPI("listtemplates"); + public function listtemplates($type) + { + $this->_parameters = [ + 'type' => $type, + ]; + + return $this->callAPI('listtemplates'); } - public function listiso($type){ - $this->_parameters = array( - 'type' => $type - ); - return $this->callAPI("listiso"); + public function listiso($type) + { + $this->_parameters = [ + 'type' => $type, + ]; + + return $this->callAPI('listiso'); } - public function node_iplist($nodeid){ - $this->_parameters = array( - 'nodeid' => $nodeid - ); - return $this->callAPI("node-iplist"); + public function node_iplist($nodeid) + { + $this->_parameters = [ + 'nodeid' => $nodeid, + ]; + + return $this->callAPI('node-iplist'); } - public function node_virtualservers($nodeid){ - $this->_parameters = array( - 'nodeid' => $nodeid - ); - $xml = $this->callAPI("node-virtualservers", true); - $a = json_decode(json_encode((array) simplexml_load_string($xml)),1); + public function node_virtualservers($nodeid) + { + $this->_parameters = [ + 'nodeid' => $nodeid, + ]; + $xml = $this->callAPI('node-virtualservers', true); + $a = json_decode(json_encode((array) simplexml_load_string($xml)), 1); - //one server - if(isset($a['virtualserver']['vserverid'])) { - return array($a['virtualserver']); + // one server + if (isset($a['virtualserver']['vserverid'])) { + return [$a['virtualserver']]; } else { return $a['virtualserver']; } } - public function vserver_info($vserverid){ - $this->_parameters = array( - 'vserver-info' => $vserverid - ); - return $this->callAPI("vserver-info"); + public function vserver_info($vserverid) + { + $this->_parameters = [ + 'vserver-info' => $vserverid, + ]; + + return $this->callAPI('vserver-info'); } - public function vserver_infoall($vserverid){ - $this->_parameters = array( - 'vserverid' => $vserverid - ); - return $this->callAPI("vserver-infoall"); + public function vserver_infoall($vserverid) + { + $this->_parameters = [ + 'vserverid' => $vserverid, + ]; + + return $this->callAPI('vserver-infoall'); } - public function node_xenresources($nodeid){ - $this->_parameters = array( - 'nodeid' => $nodeid - ); - return $this->callAPI("node-xenresources"); + public function node_xenresources($nodeid) + { + $this->_parameters = [ + 'nodeid' => $nodeid, + ]; + + return $this->callAPI('node-xenresources'); } - public function node_statistics($nodeid){ - $this->_parameters = array( - 'nodeid' => $nodeid - ); - return $this->callAPI("node-statistics"); + public function node_statistics($nodeid) + { + $this->_parameters = [ + 'nodeid' => $nodeid, + ]; + + return $this->callAPI('node-statistics'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Spamchecker/Api/Guest.php b/src/bb-modules/Spamchecker/Api/Guest.php index 04a186184..19b17a56f 100644 --- a/src/bb-modules/Spamchecker/Api/Guest.php +++ b/src/bb-modules/Spamchecker/Api/Guest.php @@ -1,6 +1,6 @@ di['mod_config']('Spamchecker'); - $result = array( - 'publickey' => $this->di['array_get']($config, 'captcha_recaptcha_publickey', null), - 'enabled' => $this->di['array_get']($config, 'captcha_enabled', false), - 'version' => $this->di['array_get']($config, 'captcha_version', null), - ); + $result = [ + 'publickey' => $this->di['array_get']($config, 'captcha_recaptcha_publickey', null), + 'enabled' => $this->di['array_get']($config, 'captcha_enabled', false), + 'version' => $this->di['array_get']($config, 'captcha_version', null), + ]; + return $result; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Spamchecker/Service.php b/src/bb-modules/Spamchecker/Service.php index 9f34b4303..64f6d57ea 100644 --- a/src/bb-modules/Spamchecker/Service.php +++ b/src/bb-modules/Spamchecker/Service.php @@ -1,6 +1,6 @@ getDi(); $params = $event->getParameters(); $client = $di['db']->load('Client', $params['client_id']); - $comment = array( - 'comment_type' => 'comment', - 'comment_author' => $client->first_name . ' ' . $client->last_name, - 'comment_author_email' => $client->email, - 'comment_content' => $params['message'], - ); + $comment = [ + 'comment_type' => 'comment', + 'comment_author' => $client->first_name.' '.$client->last_name, + 'comment_author_email' => $client->email, + 'comment_content' => $params['message'], + ]; $spamCheckerService = $di['mod_service']('Spamchecker'); $spamCheckerService->isCommentSpam($event, $comment); @@ -61,14 +60,14 @@ class Service implements InjectionAwareInterface $spamCheckerService = $di['mod_service']('Spamchecker'); $spamCheckerService->forumSpamChecker($event); } - + public static function onBeforeClientRepliedInForum(\Box_Event $event) { $di = $event->getDi(); $spamCheckerService = $di['mod_service']('Spamchecker'); $spamCheckerService->forumSpamChecker($event); } - + public static function onBeforeClientSignUp(\Box_Event $event) { $di = $event->getDi(); @@ -92,11 +91,11 @@ class Service implements InjectionAwareInterface { $di = $event->getDi(); $config = $di['mod_config']('Spamchecker'); - if(isset($config['block_ips']) && $config['block_ips'] && isset($config['blocked_ips'])) { + if (isset($config['block_ips']) && $config['block_ips'] && isset($config['blocked_ips'])) { $blocked_ips = explode(PHP_EOL, $config['blocked_ips']); $blocked_ips = array_map('trim', $blocked_ips); - if(in_array($di['request']->getClientAddress(), $blocked_ips)) { - throw new \Box_Exception('Your IP addresss (:ip) is blocked. Please contact our support to lift your block.', array(':ip'=>$di['request']->getClientAddress()), 403); + if (in_array($di['request']->getClientAddress(), $blocked_ips)) { + throw new \Box_Exception('Your IP addresss (:ip) is blocked. Please contact our support to lift your block.', [':ip' => $di['request']->getClientAddress()], 403); } } } @@ -108,25 +107,26 @@ class Service implements InjectionAwareInterface { $di = $event->getDi(); $config = $di['mod_config']('Spamchecker'); - if(!isset($config['akismet_enabled']) || !$config['akismet_enabled']) { + if (!isset($config['akismet_enabled']) || !$config['akismet_enabled']) { return false; } - - require_once BB_PATH_MODS . '/Spamchecker/akismet.curl.class.php'; - + + require_once BB_PATH_MODS.'/Spamchecker/akismet.curl.class.php'; + $akismet = new \akismet($config['akismet_api_key'], $di['config']['url']); - if(!$akismet->valid_key()) { + if (!$akismet->valid_key()) { $extensionService = $di['mod_service']('Extension'); - if($extensionService->isExtensionActive('mod', 'notification')) { + if ($extensionService->isExtensionActive('mod', 'notification')) { $notificationService = $di['mod_service']('Notification'); $notificationService->create('Akismet Key is not valid!'); } else { error_log('Akismet Key is not valid!'); } + return false; } - if($akismet->is_spam($comment)) { + if ($akismet->is_spam($comment)) { throw new \Box_Exception('Akismet detected this message is spam'); } } @@ -134,37 +134,36 @@ class Service implements InjectionAwareInterface public function isSpam(\Box_Event $event) { $di = $event->getDi(); - $params = $event->getParameters(); - $data = array( - 'ip' => $this->di['array_get']($params, 'ip', NULL), - 'email' => $this->di['array_get']($params, 'email', NULL), - 'recaptcha_challenge_field' => $this->di['array_get']($params, 'recaptcha_challenge_field', NULL), - 'recaptcha_response_field' => $this->di['array_get']($params, 'recaptcha_response_field', NULL), - ); + $params = $event->getParameters(); + $data = [ + 'ip' => $this->di['array_get']($params, 'ip', null), + 'email' => $this->di['array_get']($params, 'email', null), + 'recaptcha_challenge_field' => $this->di['array_get']($params, 'recaptcha_challenge_field', null), + 'recaptcha_response_field' => $this->di['array_get']($params, 'recaptcha_response_field', null), + ]; $config = $di['mod_config']('Spamchecker'); if (isset($config['captcha_enabled']) && $config['captcha_enabled']) { - if (isset($config['captcha_version']) && $config['captcha_version'] == 2) { - - if (!isset($config['captcha_recaptcha_privatekey']) || $config['captcha_recaptcha_privatekey'] == '') { + if (isset($config['captcha_version']) && 2 == $config['captcha_version']) { + if (!isset($config['captcha_recaptcha_privatekey']) || '' == $config['captcha_recaptcha_privatekey']) { throw new \Box_Exception("To use reCAPTCHA you must get an API key from here"); } - if (!isset($params['g-recaptcha-response']) || $params['g-recaptcha-response'] == '') { - throw new \Box_Exception("You have to complete the CAPTCHA to continue"); + if (!isset($params['g-recaptcha-response']) || '' == $params['g-recaptcha-response']) { + throw new \Box_Exception('You have to complete the CAPTCHA to continue'); } - $postData = array( - 'secret' => $config['captcha_recaptcha_privatekey'], + $postData = [ + 'secret' => $config['captcha_recaptcha_privatekey'], 'response' => $params['g-recaptcha-response'], - 'remoteip' => $di['request']->getClientAddress() - ); - - $options = [ - 'form_params' => $postData + 'remoteip' => $di['request']->getClientAddress(), ]; - $response = $di['guzzle_client']->request('POST', 'https://google.com/recaptcha/api/siteverify', $options); + + $options = [ + 'form_params' => $postData, + ]; + $response = $di['guzzle_client']->request('POST', 'https://google.com/recaptcha/api/siteverify', $options); $body = $response->getBody()->getContents(); $content = json_decode($body, true); @@ -175,21 +174,20 @@ class Service implements InjectionAwareInterface throw new \Box_Exception('reCAPTCHA verification failed.'); } } - - if(isset($config['sfs']) && $config['sfs']) { + + if (isset($config['sfs']) && $config['sfs']) { $spamCheckerService = $di['mod_service']('Spamchecker'); $spamCheckerService->isInStopForumSpamDatabase($data); } } - + /** - * Pass params: + * Pass params:. * * ip * email * username * - * @param array $data * @return bool */ public function isInStopForumSpamDatabase(array $data) @@ -199,17 +197,17 @@ class Service implements InjectionAwareInterface $file_contents = $this->di['tools']->file_get_contents($url); $json = json_decode($file_contents); - if(!is_object($json) || isset($json->success) && !$json->success) { + if (!is_object($json) || isset($json->success) && !$json->success) { return false; } - if(isset($json->username->appears) && $json->username->appears) { + if (isset($json->username->appears) && $json->username->appears) { throw new \Box_Exception('Your username is blacklisted in the Stop Forum Spam database'); } - if(isset($json->email->appears) && $json->email->appears) { + if (isset($json->email->appears) && $json->email->appears) { throw new \Box_Exception('Your e-mail is blacklisted in the Stop Forum Spam database'); } - if(isset($json->ip->appears) && $json->ip->appears) { + if (isset($json->ip->appears) && $json->ip->appears) { throw new \Box_Exception('Your IP address is blacklisted in the Stop Forum Spam database'); } diff --git a/src/bb-modules/Spamchecker/akismet.curl.class.php b/src/bb-modules/Spamchecker/akismet.curl.class.php index aa729d2e2..262d2edbd 100755 --- a/src/bb-modules/Spamchecker/akismet.curl.class.php +++ b/src/bb-modules/Spamchecker/akismet.curl.class.php @@ -1,13 +1,13 @@ 'This is a test comment', * 'permalink' => 'http://yoursite.com/post.php?id=9999', * ); - * + * * $akismet = new akismet('akismet_api_key'); - * + * * //If there was no problem connecting to Akismet. * if(!$akismet->error) { - * + * * //Check to see if the key is valid * if($akismet->valid_key()) { * print 'Akismet Key is valid!'; * } - * + * * if($akismet->is_spam($bad_comment)) { * print 'Comment Spam!'; * } else { @@ -42,9 +42,8 @@ * } * ?> * - * - * @package akismet.curl.class.php * @version 1.0.0 <4/18/2008> + * * @author David Pennington <@codexplorer.com> * @copyright Copyright (c) 2008 CodeXplorer * @license http://www.gnu.org/licenses/gpl-3.0.html (GPL v3) @@ -52,283 +51,263 @@ ********************************** 80 Columns ********************************* */ - - - - // Used by the Akismet class to communicate with the Akismet service -class akismet { - +class akismet +{ private $api_version = '1.1'; private $connection_handle; - private $urls = array(); + private $urls = []; public $api_key; public $site_url; public $error = null; - - + /** - * Class Constructor function + * Class Constructor function. * - * @access Private - * @param String $api_key The Akismet API Key from wordpress.com - * @param String $site_url The (optional) site URL of this site - * @return void - */ - function __construct($api_key=null, $site_url=null) { - - //Set the key to use - if($api_key) { + * @param string $api_key The Akismet API Key from wordpress.com + * @param string $site_url The (optional) site URL of this site + * + * @return void + */ + public function __construct($api_key = null, $site_url = null) + { + // Set the key to use + if ($api_key) { $this->api_key = $api_key; } else { $this->error = true; throw new Exception(__('Akismet API Key not set.')); } - - //If no site URL was given - if(!$site_url) { - //Set it to the current site - $this->site_url = 'http://'. $_SERVER['SERVER_NAME']; + + // If no site URL was given + if (!$site_url) { + // Set it to the current site + $this->site_url = 'http://'.$_SERVER['SERVER_NAME']; } else { - //Set the site url + // Set the site url $this->site_url = $site_url; } - - //Set the REST API URL's that we will use - $this->urls = array( - 'verify' => 'rest.akismet.com/'. $this->api_version - . '/verify-key', - 'check_spam' => $this->api_key. '.rest.akismet.com/' - . $this->api_version. '/comment-check', - 'submit_spam' => $this->api_key. '.rest.akismet.com/' - . $this->api_version. '/submit-spam', - 'submit_ham' => $this->api_key. '.rest.akismet.com/' - . $this->api_version. '/submit-ham' - ); - - //Now connect + + // Set the REST API URL's that we will use + $this->urls = [ + 'verify' => 'rest.akismet.com/'.$this->api_version + .'/verify-key', + 'check_spam' => $this->api_key.'.rest.akismet.com/' + .$this->api_version.'/comment-check', + 'submit_spam' => $this->api_key.'.rest.akismet.com/' + .$this->api_version.'/submit-spam', + 'submit_ham' => $this->api_key.'.rest.akismet.com/' + .$this->api_version.'/submit-ham', + ]; + + // Now connect $this->connect(); - } - - + /** - * Initializes a new cURL session/handle + * Initializes a new cURL session/handle. * - * @access Public - * @return boolean - */ - public function connect() { - - //If there is no connection - if(!is_resource($this->connection_handle)) { - //Try to create one - if(!$this->connection_handle = curl_init()) { + * @return bool + */ + public function connect() + { + // If there is no connection + if (!is_resource($this->connection_handle)) { + // Try to create one + if (!$this->connection_handle = curl_init()) { $this->error = true; throw new Exception(__('Could not start new CURL instance')); } } - - //Include header in result? (no) + + // Include header in result? (no) curl_setopt($this->connection_handle, CURLOPT_HEADER, 0); - //Do a regular HTTP POST? (yes) + // Do a regular HTTP POST? (yes) curl_setopt($this->connection_handle, CURLOPT_POST, 1); - //The maximum number of seconds to allow cURL to execute - curl_setopt($this->connection_handle, CURLOPT_TIMEOUT, 6); - //Return the transfer as a string - instead of printing it + // The maximum number of seconds to allow cURL to execute + curl_setopt($this->connection_handle, CURLOPT_TIMEOUT, 6); + // Return the transfer as a string - instead of printing it curl_setopt($this->connection_handle, CURLOPT_RETURNTRANSFER, 1); - //The "User-Agent" header to be used in a HTTP request - curl_setopt($this->connection_handle, CURLOPT_USERAGENT, - "CodeXplorer/1.0.0 | Askimet/1.0.0"); - //Don't use a cached version of the url + // The "User-Agent" header to be used in a HTTP request + curl_setopt($this->connection_handle, CURLOPT_USERAGENT, + 'CodeXplorer/1.0.0 | Askimet/1.0.0'); + // Don't use a cached version of the url curl_setopt($this->connection_handle, CURLOPT_FRESH_CONNECT, 1); - + return true; - } - - + /** - * Close the current cURL session/handle + * Close the current cURL session/handle. * - * @access Public - * @return boolean - */ - public function close() { - - //If there is no connection - if(is_resource($this->connection_handle)) { - //Try to close it - if(!curl_close($this->connection_handle)) { + * @return bool + */ + public function close() + { + // If there is no connection + if (is_resource($this->connection_handle)) { + // Try to close it + if (!curl_close($this->connection_handle)) { $this->error = true; throw new Exception(__('Could not close the CURL instance')); } } + return true; - } - - + /** - * Send a request through the current cURL session + * Send a request through the current cURL session. * - * @access Private - * @param String $request The data to be $_POST'ed - * @param String $url The URL to send it too - * @return boolean|string - */ - private function send_data($request=null, $url=null) { - - //Set the url to send data too + * @param string $request The data to be $_POST'ed + * @param string $url The URL to send it too + * + * @return bool|string + */ + private function send_data($request = null, $url = null) + { + // Set the url to send data too curl_setopt($this->connection_handle, CURLOPT_URL, $url); - //The data to post in the HTTP operation + // The data to post in the HTTP operation curl_setopt($this->connection_handle, CURLOPT_POSTFIELDS, $request); - - //Send Data and grab the result - if(!$response = curl_exec($this->connection_handle)) { + + // Send Data and grab the result + if (!$response = curl_exec($this->connection_handle)) { $this->error = true; throw new Exception(__('Could not send cURL request')); } - + return $response; } - - + /** - * Check if Akismet API key is valid + * Check if Akismet API key is valid. * - * @access Public - * @return boolean - */ - public function valid_key() { + * @return bool + */ + public function valid_key() + { $string = $this->create_query_string( - array('key' => $this->api_key, 'blog' => $this->site_url) + ['key' => $this->api_key, 'blog' => $this->site_url] ); - return ($this->send_data($string, $this->urls['verify']) == 'valid'); + + return 'valid' == $this->send_data($string, $this->urls['verify']); } - - + /** - * Format the comment array in accordance to the Akismet API + * Format the comment array in accordance to the Akismet API. * - * @access Public - * @param Array $comment An array containing comment information - * @return void - */ - public function is_spam($comment) { - //Add this site_url + * @param array $comment An array containing comment information + * + * @return void + */ + public function is_spam($comment) + { + // Add this site_url $comment['blog'] = $this->site_url; - - //Convert array to string + + // Convert array to string $comment = $this->create_query_string($comment); - //Add $_SERVER data to string + // Add $_SERVER data to string $comment .= $this->create_server_string(); - - //Send the request to Akismet! + + // Send the request to Akismet! $response = $this->send_data($comment, $this->urls['check_spam']); - return ($response == 'true'); - + + return 'true' == $response; } - - + /** * Submit a comment that Akismet missed as SPAM! * - * @access Public - * @param Array $comment Comment information - * @param Array $server_data Optional extra $_SERVER data - * @return void - */ - public function submit_spam($comment, $server_data=null) { - - //Add this site_url + * @param array $comment Comment information + * @param array $server_data Optional extra $_SERVER data + * + * @return void + */ + public function submit_spam($comment, $server_data = null) + { + // Add this site_url $comment['blog'] = $this->site_url; - - //Convert array to string + + // Convert array to string $comment = $this->create_query_string($comment); - - //Optionally add stored $_SERVER data about the spam - if($server_data) { - //Add stored $_SERVER data to the string. - //Note: do NOT use current user's data as it might be an admin! + + // Optionally add stored $_SERVER data about the spam + if ($server_data) { + // Add stored $_SERVER data to the string. + // Note: do NOT use current user's data as it might be an admin! $comment .= $this->create_query_string($server_data); } - - //Send the request to Akismet! + + // Send the request to Akismet! $this->send_data($comment, $this->urls['submit_spam']); - } - - + /** * Let Akismet know that the comment was valid and NOT spam. * - * @access Public - * @param Array $comment Comment information - * @param Array $server_data Optional extra $_SERVER data - * @return void - */ - public function submit_ham($comment, $server_data=null) { - - //Add this site_url + * @param array $comment Comment information + * @param array $server_data Optional extra $_SERVER data + * + * @return void + */ + public function submit_ham($comment, $server_data = null) + { + // Add this site_url $comment['blog'] = $this->site_url; - - //Convert array to string + + // Convert array to string $comment = $this->create_query_string($comment); - - //Optionally add stored $_SERVER data about the spam - if($server_data) { - //Add stored $_SERVER data to the string. - //Note: do NOT use current user's data as it might be an admin! + + // Optionally add stored $_SERVER data about the spam + if ($server_data) { + // Add stored $_SERVER data to the string. + // Note: do NOT use current user's data as it might be an admin! $comment .= $this->create_query_string($server_data); } - - //Send the request to Akismet! + + // Send the request to Akismet! $this->send_data($comment, $this->urls['submit_ham']); - } - - + /** - * Build a query string containing the items in the given array + * Build a query string containing the items in the given array. * - * @access Public - * @return String + * @return string */ - public function create_query_string($array=null) { + public function create_query_string($array = null) + { $query_string = null; - if(is_array($array)) { - foreach($array as $key => $value) { - $query_string .= $key. '='. urlencode($value). '&'; + if (is_array($array)) { + foreach ($array as $key => $value) { + $query_string .= $key.'='.urlencode($value).'&'; } } + return $query_string; } - - + /** * Build a query string containing $_SERVER info to help Akismet fight spam! * - * @access Private - * @return String + * @return string */ - private function create_server_string() { - - $array = array( + private function create_server_string() + { + $array = [ 'SERVER_PROTOCOL' => $_SERVER['SERVER_PROTOCOL'], 'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'], - 'QUERY_STRING' => $_SERVER['QUERY_STRING'], - 'HTTP_REFERER' => $_SERVER['HTTP_REFERER'], - 'REMOTE_PORT' => $_SERVER['REMOTE_PORT'], + 'QUERY_STRING' => $_SERVER['QUERY_STRING'], + 'HTTP_REFERER' => $_SERVER['HTTP_REFERER'], + 'REMOTE_PORT' => $_SERVER['REMOTE_PORT'], 'HTTP_ACCEPT' => $_SERVER['HTTP_ACCEPT'], - 'user_agent' => $_SERVER['HTTP_USER_AGENT'], - 'referrer' => $_SERVER['HTTP_REFERER'], - 'user_ip' => ($_SERVER['REMOTE_ADDR'] != getenv('SERVER_ADDR')) ? + 'user_agent' => $_SERVER['HTTP_USER_AGENT'], + 'referrer' => $_SERVER['HTTP_REFERER'], + 'user_ip' => ($_SERVER['REMOTE_ADDR'] != getenv('SERVER_ADDR')) ? $_SERVER['REMOTE_ADDR'] : getenv('HTTP_X_FORWARDED_FOR'), - 'blog' => $this->site_url); - + 'blog' => $this->site_url, ]; + return $this->create_query_string($array); } - } - diff --git a/src/bb-modules/Staff/Api/Admin.php b/src/bb-modules/Staff/Api/Admin.php index e787c29c1..a22a24801 100644 --- a/src/bb-modules/Staff/Api/Admin.php +++ b/src/bb-modules/Staff/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getSearchQuery($data); + [$sql, $params] = $this->getService()->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); - foreach($pager['list'] as $key => $item){ + foreach ($pager['list'] as $key => $item) { $staff = $this->di['db']->getExistingModelById('Admin', $item['id'], 'Admin is not found'); $pager['list'][$key] = $this->getService()->toModel_AdminApiiArray($staff); } return $pager; - } - + /** - * Get staff member by id - * + * Get staff member by id. + * * @param int $id - staff member ID + * * @return array - * @throws Exception + * + * @throws Exception */ public function get($data) { - $required = array( + $required = [ 'id' => 'ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found'); + return $this->getService()->toModel_AdminApiiArray($model); } - + /** - * Update staff member - * + * Update staff member. + * * @param int $id - staff member ID - * + * * @optional string $email - new email * @optional string $name - new name * @optional string $status - new status * @optional string $signature - new signature - * @optional int $admin_group_id - new group id - * - * @return boolean - * @throws Exception + * @optional int $admin_group_id - new group id + * + * @return bool + * + * @throws Exception */ public function update($data) { - $required = array( + $required = [ 'id' => 'ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found'); @@ -81,128 +86,133 @@ class Admin extends \Api_Abstract } /** - * Completely delete staff member. Removes all related acitivity from logs - * + * Completely delete staff member. Removes all related acitivity from logs. + * * @param int $id - staff member ID - * @return boolean - * @throws Exception + * + * @return bool + * + * @throws Exception */ public function delete($data) { - $required = array( + $required = [ 'id' => 'ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found'); - + return $this->getService()->delete($model); } /** - * Change staff member password - * - * @param int $id - staff member ID - * @param string $password - new staff member password - * @param string $password_confirm - repeat new staff member password - * @return boolean - * @throws Exception + * Change staff member password. + * + * @param int $id - staff member ID + * @param string $password - new staff member password + * @param string $password_confirm - repeat new staff member password + * + * @return bool + * + * @throws Exception */ public function change_password($data) { - $required = array( + $required = [ 'id' => 'ID is missing', 'password' => 'Password required', 'password_confirm' => 'Password confirmation required', - ); + ]; $validator = $this->di['validator']; $validator->checkRequiredParamsForArray($required, $data); - - if($data['password'] != $data['password_confirm']) { + + if ($data['password'] != $data['password_confirm']) { throw new \Box_Exception('Passwords do not match'); } - $validator->isPasswordStrong($data['password']); $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found'); + return $this->getService()->changePassword($model, $data['password']); } - + /** - * Create new staff member - * - * @param string $email - email of new staff member - * @param string $password - password of new staff member - * @param string $name - name of new staff member + * Create new staff member. + * + * @param string $email - email of new staff member + * @param string $password - password of new staff member + * @param string $name - name of new staff member * @param string $admin_group_id - admin group id of new staff member - * + * * @optional string $signature - signature of new staff member - * + * * @return int - ID of newly created staff member - * @throws Exception + * + * @throws Exception */ public function create($data) { - $required = array( + $required = [ 'email' => 'Email param is missing', 'password' => 'Password param is missing', 'name' => 'Name param is missing', 'admin_group_id' => 'Group id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - return $this->getService()->create($data); } /** - * Return staff member permissions - * + * Return staff member permissions. + * * @param int $id - staff member id - * + * * @return array */ public function permissions_get($data) { - $required = array( + $required = [ 'id' => 'ID is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found'); - + return $this->getService()->getPermissions($model->id); } - + /** - * Update staff member permissions - * - * @param int $id - staff member id + * Update staff member permissions. + * + * @param int $id - staff member id * @param array $permissions - staff member permissions - * + * * @return bool */ public function permissions_update($data) { - $required = array( + $required = [ 'id' => 'ID is missing', 'permissions' => 'Permissions parameter missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('Admin', $data['id'], 'Staff member not found'); $this->getService()->setPermissions($model->id, $data['permissions']); - + $this->di['logger']->info('Changed staff member %s permisions', $model->id); + return true; } /** - * Return pairs of staff member groups - * - * @return type + * Return pairs of staff member groups. + * + * @return type */ public function group_get_pairs($data) { @@ -210,16 +220,17 @@ class Admin extends \Api_Abstract } /** - * Return paginate list of staff members groups - * @return array + * Return paginate list of staff members groups. + * + * @return array */ public function group_get_list($data) { - list($sql, $params) = $this->getService()->getAdminGroupSearchQuery($data); + [$sql, $params] = $this->getService()->getAdminGroupSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { - $model = $this->di['db']->getExistingModelById('AdminGroup', $item['id'], 'Post not found'); + $model = $this->di['db']->getExistingModelById('AdminGroup', $item['id'], 'Post not found'); $pager['list'][$key] = $this->getService()->toAdminGroupApiArray($model, false, $this->getIdentity()); } @@ -227,35 +238,38 @@ class Admin extends \Api_Abstract } /** - * Create new staff members group - * + * Create new staff members group. + * * @param string $name - name of staff members group - * + * * @return int - new staff group ID - * @throws Exception + * + * @throws Exception */ public function group_create($data) { - $required = array( + $required = [ 'name' => 'Staff group is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); + return $this->getService()->createGroup($data['name']); } /** - * Return staff group details - * + * Return staff group details. + * * @param int $id - group id + * * @return array - group details - * @throws Exception + * + * @throws Exception */ public function group_get($data) { - - $required = array( + $required = [ 'id' => 'Group id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('AdminGroup', $data['id'], 'Group not found'); @@ -264,38 +278,42 @@ class Admin extends \Api_Abstract } /** - * Remove staff group - * + * Remove staff group. + * * @param int $id - group id - * @return boolean - * @throws Exception + * + * @return bool + * + * @throws Exception */ public function group_delete($data) { - $required = array( + $required = [ 'id' => 'Group id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('AdminGroup', $data['id'], 'Group not found'); + return $this->getService()->deleteGroup($model); } /** - * Update staff group - * + * Update staff group. + * * @param int $id - group id - * + * * @optional int $name - new group name - * - * @return boolean - * @throws Exception + * + * @return bool + * + * @throws Exception */ public function group_update($data) { - $required = array( + $required = [ 'id' => 'Group id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('AdminGroup', $data['id'], 'Group not found'); @@ -304,13 +322,13 @@ class Admin extends \Api_Abstract } /** - * Get paginated list of staff logins history - * + * Get paginated list of staff logins history. + * * @return array */ public function login_history_get_list($data) { - list($sql, $params) = $this->getService()->getActivityAdminHistorySearchQuery($data); + [$sql, $params] = $this->getService()->getActivityAdminHistorySearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page); foreach ($pager['list'] as $key => $item) { @@ -324,52 +342,58 @@ class Admin extends \Api_Abstract } /** - * Get details of login history event - * + * Get details of login history event. + * * @param int $id - event id + * * @return array - * @throws ErrorException + * + * @throws ErrorException */ public function login_history_get($data) { - $required = array( + $required = [ 'id' => 'Id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ActivityAdminHistory', $data['id'], 'Event not found'); - + return $this->getService()->toActivityAdminHistoryApiArray($model); } - + /** - * Delete login history event - * + * Delete login history event. + * * @param int $id - event id - * @return boolean - * @throws ErrorException + * + * @return bool + * + * @throws ErrorException */ public function login_history_delete($data) { - $required = array( + $required = [ 'id' => 'Id not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('ActivityAdminHistory', $data['id'], 'Event not found'); return $this->getService()->deleteLoginHistory($model); } - + /** - * Returns currently loggen in staff member information + * Returns currently loggen in staff member information. * * @return array + * * @deprecated moved to profile module * @codeCoverageIgnore + * * @example * * Array - * ( + * ( * [id] => 1 * [role] => staff * [admin_group_id] => 1 @@ -381,8 +405,8 @@ class Admin extends \Api_Abstract * [api_token] => 29baba87f1c120f1b7fc6b0139167003 * [created_at] => 1310024416 * [updated_at] => 1310024416 - * ) - * + * ) + * */ public function profile_get() { @@ -390,29 +414,35 @@ class Admin extends \Api_Abstract } /** - * Clear session data and logout from system + * Clear session data and logout from system. + * * @deprecated moved to profile module * @codeCoverageIgnore - * @return boolean + * + * @return bool */ public function profile_logout() { - if($_COOKIE) { // testing env fix - $this->di['cookie']->set('BOXADMR', "", time() - 3600, '/'); + if ($_COOKIE) { // testing env fix + $this->di['cookie']->set('BOXADMR', '', time() - 3600, '/'); } $this->di['session']->delete('admin'); $this->di['logger']->info('Logged out'); + return true; } /** - * Update currently logged in staff member details - * + * Update currently logged in staff member details. + * * @optional string $email - new email * @optional string $name - new name * @optional string $signature - new signature + * * @deprecated moved to profile module - * @return boolean + * + * @return bool + * * @throws Exception * @codeCoverageIgnore */ @@ -420,8 +450,8 @@ class Admin extends \Api_Abstract { $event_params = $data; $event_params['id'] = $this->getIdentity()->id; - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminStaffProfileUpdate', 'params'=>$event_params)); - + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffProfileUpdate', 'params' => $event_params]); + $admin = $this->getIdentity(); $admin->email = $this->di['array_get']($data, 'email', $admin->email); @@ -430,82 +460,90 @@ class Admin extends \Api_Abstract $admin->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($admin); - $event_params = array(); + $event_params = []; $event_params['id'] = $this->getIdentity()->id; - $this->di['events_manager']->fire(array('event'=>'onAfterAdminStaffProfileUpdate', 'params'=>$event_params)); - + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffProfileUpdate', 'params' => $event_params]); + $this->di['logger']->info('Updated profile'); + return true; } /** - * Generates new API token for currently logged in staff member + * Generates new API token for currently logged in staff member. + * * @deprecated moved to profile module - * @return boolean - * @codeCoverageIgnore + * + * @return bool + * @codeCoverageIgnore */ public function profile_generate_api_key($data) { $admin = $this->getIdentity(); - - $event_params = array(); + + $event_params = []; $event_params['id'] = $this->getIdentity()->id; - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminStaffApiKeyChange', 'params'=>$event_params)); - + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffApiKeyChange', 'params' => $event_params]); + $admin->api_token = $this->di['tools']->generatePassword(32); $admin->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($admin); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminStaffApiKeyChange', 'params'=>$event_params)); - + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffApiKeyChange', 'params' => $event_params]); + $this->di['logger']->info('Generated new API key'); + return true; } /** - * Change password for currently logged in staff member - * - * @param string $password - new password + * Change password for currently logged in staff member. + * + * @param string $password - new password * @param string $password_confirm - repeat new password - * @return boolean + * + * @return bool + * * @deprecated moved to profile module + * * @throws Exception - * @codeCoverageIgnore + * @codeCoverageIgnore */ public function profile_change_password($data) { - $required = array( - 'password' => 'Password required', + $required = [ + 'password' => 'Password required', 'password_confirm' => 'Password confirmation required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - if($data['password'] != $data['password_confirm']) { + if ($data['password'] != $data['password_confirm']) { throw new \Box_Exception('Passwords do not match'); } $this->di['validator']->isPasswordStrong($data['password']); - + $event_params = $data; $event_params['id'] = $this->getIdentity()->id; - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminStaffProfilePasswordChange', 'params'=>$event_params)); - + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffProfilePasswordChange', 'params' => $event_params]); + $admin = $this->getIdentity(); $admin->pass = $data['password']; $admin->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($admin); - $event_params = array(); + $event_params = []; $event_params['id'] = $this->getIdentity()->id; - $this->di['events_manager']->fire(array('event'=>'onAfterAdminStaffProfilePasswordChange', 'params'=>$event_params)); - + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffProfilePasswordChange', 'params' => $event_params]); + $this->di['logger']->info('Changed profile password'); + return true; } /** - * Deletes admin login logs with given IDs + * Deletes admin login logs with given IDs. * * @param array $ids - IDs for deletion * @@ -513,15 +551,15 @@ class Admin extends \Api_Abstract */ public function batch_delete_logs($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->login_history_delete(array('id' => $id)); + $this->login_history_delete(['id' => $id]); } return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Staff/Api/Guest.php b/src/bb-modules/Staff/Api/Guest.php index bf569ff06..ad6d0428e 100644 --- a/src/bb-modules/Staff/Api/Guest.php +++ b/src/bb-modules/Staff/Api/Guest.php @@ -1,6 +1,6 @@ di['db']->findOne('Admin', '1=1')) == 0); - if(!$allow) { + $allow = (0 == count($this->di['db']->findOne('Admin', '1=1'))); + if (!$allow) { throw new \Box_Exception('Administrator account already exists', null, 55); } - $required = array( + $required = [ 'email' => 'Administrator email is missing.', 'password' => 'Administrator password is missing.', - ); - $validator = $this->di['validator']; + ]; + $validator = $this->di['validator']; $validator->checkRequiredParamsForArray($required, $data); $validator->isEmailValid($data['email']); $validator->isPasswordStrong($data['password']); $result = $this->getService()->createAdmin($data); - if ($result){ + if ($result) { $this->login($data); } + return true; } - + /** * Login to admin area and save information to session. - * - * @param string $email - admin email - * @param string $password - admin password - * + * + * @param string $email - admin email + * @param string $password - admin password + * * @optional string $remember - pass value "1" to create remember me cookie + * * @return array - * @throws Exception + * + * @throws Exception */ public function login($data) { - $required = array( + $required = [ 'email' => 'Email required', 'password' => 'Password required', - ); - $validator = $this->di['validator']; + ]; + $validator = $this->di['validator']; $validator->checkRequiredParamsForArray($required, $data); $config = $this->getMod()->getConfig(); - //check ip - if(isset($config['allowed_ips']) && isset($config['check_ip']) && $config['check_ip']) { + // check ip + if (isset($config['allowed_ips']) && isset($config['check_ip']) && $config['check_ip']) { $allowed_ips = explode(PHP_EOL, $config['allowed_ips']); - if(!empty($allowed_ips)) { + if (!empty($allowed_ips)) { $allowed_ips = array_map('trim', $allowed_ips); - if(!in_array($this->getIp(), $allowed_ips)) { - throw new \Box_Exception('You are not allowed to login to admin area from :ip address', array(':ip'=>$this->getIp()), 403); + if (!in_array($this->getIp(), $allowed_ips)) { + throw new \Box_Exception('You are not allowed to login to admin area from :ip address', [':ip' => $this->getIp()], 403); } } } return $this->getService()->login($data['email'], $data['password'], $this->getIp()); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Staff/Controller/Admin.php b/src/bb-modules/Staff/Controller/Admin.php index 4e7b3b81c..bf28e7d66 100644 --- a/src/bb-modules/Staff/Controller/Admin.php +++ b/src/bb-modules/Staff/Controller/Admin.php @@ -1,6 +1,6 @@ array( - array( - 'location' => 'activity', - 'index' => 400, + return [ + 'subpages' => [ + [ + 'location' => 'activity', + 'index' => 400, 'label' => 'Staff logins history', - 'uri' => $this->di['url']->adminLink('staff/logins'), + 'uri' => $this->di['url']->adminLink('staff/logins'), 'class' => '', - ), - ), - ); + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/staff/login', 'get_login', array(), get_class($this)); - $app->get('/staff/manage/:id', 'get_manage', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/staff/group/:id', 'get_group', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/staff/profile', 'get_profile', array(), get_class($this)); - $app->get('/staff/logins', 'get_history', array(), get_class($this)); + $app->get('/staff/login', 'get_login', [], get_class($this)); + $app->get('/staff/manage/:id', 'get_manage', ['id' => '[0-9]+'], get_class($this)); + $app->get('/staff/group/:id', 'get_group', ['id' => '[0-9]+'], get_class($this)); + $app->get('/staff/profile', 'get_profile', [], get_class($this)); + $app->get('/staff/logins', 'get_history', [], get_class($this)); } - + public function get_login(\Box_App $app) { // check if at least one admin exists. // if not show admin create form $service = $this->di['mod_service']('staff'); $count = $service->getAdminsCount(); - $create = ($count == 0); - return $app->render('mod_staff_login', array('create_admin'=>$create)); + $create = (0 == $count); + + return $app->render('mod_staff_login', ['create_admin' => $create]); } - + public function get_profile(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_staff_profile'); } public function get_manage(\Box_App $app, $id) { $api = $this->di['api_admin']; - $staff = $api->staff_get(array('id'=>$id)); + $staff = $api->staff_get(['id' => $id]); - $extensionService = $this->di['mod_service']("Extension"); + $extensionService = $this->di['mod_service']('Extension'); $mods = $extensionService->getCoreAndActiveModules(); - return $app->render('mod_staff_manage', array('staff'=>$staff, 'mods'=>$mods)); + + return $app->render('mod_staff_manage', ['staff' => $staff, 'mods' => $mods]); } public function get_group(\Box_App $app, $id) { $api = $this->di['api_admin']; - $group = $api->staff_group_get(array('id'=>$id)); + $group = $api->staff_group_get(['id' => $id]); - $extensionService = $this->di['mod_service']("Extension"); + $extensionService = $this->di['mod_service']('Extension'); $mods = $extensionService->getCoreAndActiveModules(); - return $app->render('mod_staff_group', array('group'=>$group, 'mods'=>$mods)); + + return $app->render('mod_staff_group', ['group' => $group, 'mods' => $mods]); } + public function get_history(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_staff_login_history'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Staff/Service.php b/src/bb-modules/Staff/Service.php index c3e4fe283..f8d4000cc 100644 --- a/src/bb-modules/Staff/Service.php +++ b/src/bb-modules/Staff/Service.php @@ -1,6 +1,6 @@ di['events_manager']->fire(array('event'=>'onBeforeAdminLogin', 'params'=>$event_params)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminLogin', 'params' => $event_params]); $model = $this->authorizeAdmin($email, $password); - if(!$model instanceof \Model_Admin ) { - $this->di['events_manager']->fire(array('event'=>'onEventAdminLoginFailed', 'params'=>$event_params)); + if (!$model instanceof \Model_Admin) { + $this->di['events_manager']->fire(['event' => 'onEventAdminLoginFailed', 'params' => $event_params]); throw new \Box_Exception('Check your login details', null, 403); } - $this->di['events_manager']->fire(array('event'=>'onAfterAdminLogin', 'params'=>array('id'=>$model->id, 'ip'=>$ip))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminLogin', 'params' => ['id' => $model->id, 'ip' => $ip]]); - $result = array( - 'id' => $model->id, - 'email' => $model->email, - 'name' => $model->name, - 'role' => $model->role, - ); + $result = [ + 'id' => $model->id, + 'email' => $model->email, + 'name' => $model->name, + 'role' => $model->role, + ]; $this->di['session']->set('admin', $result); @@ -67,64 +67,64 @@ class Service implements InjectionAwareInterface public function getAdminsCount() { - $sql = "SELECT COUNT(*) FROM admin WHERE 1"; + $sql = 'SELECT COUNT(*) FROM admin WHERE 1'; + return $this->di['db']->getCell($sql); } public function setPermissions($member_id, $array) { - $sql="UPDATE admin SET permissions = :p WHERE id = :id"; + $sql = 'UPDATE admin SET permissions = :p WHERE id = :id'; $pdo = $this->di['pdo']; $stmt = $pdo->prepare($sql); $stmt->bindValue('p', json_encode($array)); $stmt->bindValue('id', $member_id); $stmt->execute(); + return true; } - + public function getPermissions($member_id) { - $sql="SELECT permissions FROM admin WHERE id = :id"; + $sql = 'SELECT permissions FROM admin WHERE id = :id'; $pdo = $this->di['pdo']; $stmt = $pdo->prepare($sql); - $stmt->execute(array('id'=>$member_id)); + $stmt->execute(['id' => $member_id]); $json = $stmt->fetchColumn(); $permissions = json_decode($json, 1); - if(!$permissions) { - return array(); + if (!$permissions) { + return []; } + return $permissions; } - + public function hasPermission($member, $mod, $method = null) { - if($member->role == \Model_Admin::ROLE_CRON || $member->role == \Model_Admin::ROLE_ADMIN) { + if (\Model_Admin::ROLE_CRON == $member->role || \Model_Admin::ROLE_ADMIN == $member->role) { return true; } - + $permissions = null; - if(is_null($permissions)) { + if (is_null($permissions)) { $permissions = $this->getPermissions($member->id); } - - if(empty($permissions)) { + + if (empty($permissions)) { return false; } - - if(!array_key_exists($mod, $permissions)) { + + if (!array_key_exists($mod, $permissions)) { return false; } - - if(!is_null($method) && is_array($permissions[$mod]) && !in_array($method, $permissions[$mod])) { + + if (!is_null($method) && is_array($permissions[$mod]) && !in_array($method, $permissions[$mod])) { return false; } - + return true; } - /** - * @param \Box_Event $event - */ public static function onAfterClientOrderCreate(\Box_Event $event) { $di = $event->getDi(); @@ -135,25 +135,22 @@ class Service implements InjectionAwareInterface $orderTicketService = $di['mod_service']('order'); $order = $orderTicketService->toApiArray($orderModel, true); - $email = array(); - $email['to_staff'] = true; - $email['code'] = 'mod_staff_client_order'; - $email['order'] = $order; + $email = []; + $email['to_staff'] = true; + $email['code'] = 'mod_staff_client_order'; + $email['order'] = $order; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } - /** - * @param \Box_Event $event - */ public static function onAfterClientOpenTicket(\Box_Event $event) { $di = $event->getDi(); $params = $event->getParameters(); - + try { $supportTicketService = $di['mod_service']('support'); $ticketModel = $supportTicketService->getTicketById($params['id']); @@ -162,20 +159,21 @@ class Service implements InjectionAwareInterface $helpdeskModel = $di['db']->load('SupportHelpdesk', $ticketModel->support_helpdesk_id); $emailService = $di['mod_service']('email'); if (!empty($helpdeskModel->email)) { - $email = array(); - $email['to'] = $helpdeskModel->email; - $email['code'] = 'mod_support_helpdesk_ticket_open'; + $email = []; + $email['to'] = $helpdeskModel->email; + $email['code'] = 'mod_support_helpdesk_ticket_open'; $email['ticket'] = $ticket; $emailService->sendTemplate($email); + return true; } - $email = array(); - $email['to_staff'] = true; - $email['code'] = 'mod_staff_ticket_open'; - $email['ticket'] = $ticket; + $email = []; + $email['to_staff'] = true; + $email['code'] = 'mod_staff_ticket_open'; + $email['ticket'] = $ticket; $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } @@ -184,20 +182,20 @@ class Service implements InjectionAwareInterface { $params = $event->getParameters(); $di = $event->getDi(); - + try { $supportTicketService = $di['mod_service']('support'); $ticketModel = $supportTicketService->getTicketById($params['id']); $ticket = $supportTicketService->toApiArray($ticketModel, true); - $email = array(); - $email['to_staff'] = true; - $email['code'] = 'mod_staff_ticket_reply'; - $email['ticket'] = $ticket; + $email = []; + $email['to_staff'] = true; + $email['code'] = 'mod_staff_ticket_reply'; + $email['ticket'] = $ticket; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } @@ -206,39 +204,39 @@ class Service implements InjectionAwareInterface { $params = $event->getParameters(); $di = $event->getDi(); - + try { $supportTicketService = $di['mod_service']('support'); $ticketModel = $supportTicketService->getTicketById($params['id']); $ticket = $supportTicketService->toApiArray($ticketModel, true); - $email = array(); - $email['to_staff'] = true; - $email['code'] = 'mod_staff_ticket_close'; - $email['ticket'] = $ticket; + $email = []; + $email['to_staff'] = true; + $email['code'] = 'mod_staff_ticket_close'; + $email['ticket'] = $ticket; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } - + public static function onAfterGuestPublicTicketOpen(\Box_Event $event) { $params = $event->getParameters(); $di = $event->getDi(); - + try { $supportTicketService = $di['mod_service']('support'); $ticketModel = $supportTicketService->getPublicTicketById($params['id']); $ticket = $supportTicketService->publicToApiArray($ticketModel, true); - $email = array(); - $email['to_staff'] = true; - $email['code'] = 'mod_staff_pticket_open'; - $email['ticket'] = $ticket; + $email = []; + $email['to_staff'] = true; + $email['code'] = 'mod_staff_pticket_open'; + $email['ticket'] = $ticket; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } @@ -247,17 +245,17 @@ class Service implements InjectionAwareInterface { $params = $event->getParameters(); $di = $event->getDi(); - + try { $clientService = $di['mod_service']('client'); - $email = array(); - $email['to_staff'] = true; - $email['code'] = 'mod_staff_client_signup'; - $email['c'] = $clientService ->get(array('id' => $params['id'])); + $email = []; + $email['to_staff'] = true; + $email['code'] = 'mod_staff_client_signup'; + $email['c'] = $clientService->get(['id' => $params['id']]); $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } @@ -268,99 +266,98 @@ class Service implements InjectionAwareInterface { $params = $event->getParameters(); $di = $event->getDi(); - + try { $supportTicketService = $di['mod_service']('support'); $ticketModel = $supportTicketService->getPublicTicketById($params['id']); $ticket = $supportTicketService->publicToApiArray($ticketModel, true); - $email = array(); - $email['to_staff'] = true; - $email['code'] = 'mod_staff_pticket_reply'; - $email['ticket'] = $ticket; + $email = []; + $email['to_staff'] = true; + $email['code'] = 'mod_staff_pticket_reply'; + $email['ticket'] = $ticket; $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } - /** - * @param \Box_Event $event - */ + public static function onAfterGuestPublicTicketClose(\Box_Event $event) { $params = $event->getParameters(); $di = $event->getDi(); - + try { $supportService = $di['mod_service']('Support'); $publicTicket = $di['db']->load('SupportPTicket', $params['id']); $ticket = $supportService->publicToApiArray($publicTicket); - $email = array(); - $email['to_staff'] = true; - $email['code'] = 'mod_staff_pticket_close'; - $email['ticket'] = $ticket; + $email = []; + $email['to_staff'] = true; + $email['code'] = 'mod_staff_pticket_close'; + $email['ticket'] = $ticket; $emailService = $di['mod_service']('Email'); $emailService->sendTemplate($email); - } catch(\Exception $exc) { + } catch (\Exception $exc) { error_log($exc->getMessage()); } } - public function getList($data){ + public function getList($data) + { $data['no_cron'] = true; - list ($query, $params) = $this->getSearchQuery($data); + [$query, $params] = $this->getSearchQuery($data); $di = $this->getDi(); $pager = $di['pager']; $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + return $pager->getSimpleResultSet($query, $params, $per_page); } public function getSearchQuery($data) { - $query = "SELECT * FROM admin"; + $query = 'SELECT * FROM admin'; - $search = $this->di['array_get']($data, 'search', NULL); - $status = $this->di['array_get']($data, 'status', NULL); + $search = $this->di['array_get']($data, 'search', null); + $status = $this->di['array_get']($data, 'status', null); $no_cron = (bool) $this->di['array_get']($data, 'no_cron', false); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; - if($search) { + if ($search) { $search = "%$search%"; - $where[] = "(name LIKE :name OR email LIKE :email )"; + $where[] = '(name LIKE :name OR email LIKE :email )'; $bindings[':name'] = $search; $bindings[':email'] = $search; } - if($status) { - $where[] = "status = :status"; + if ($status) { + $where[] = 'status = :status'; $bindings[':status'] = $status; } - if($no_cron) { - $where[] = "role != :role"; - $bindings[':role'] = \Model_Admin::ROLE_CRON; + if ($no_cron) { + $where[] = 'role != :role'; + $bindings[':role'] = \Model_Admin::ROLE_CRON; } if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); + $query = $query.' WHERE '.implode(' AND ', $where); } - $query .= " ORDER BY `admin_group_id` ASC, id ASC"; + $query .= ' ORDER BY `admin_group_id` ASC, id ASC'; - return array($query, $bindings); + return [$query, $bindings]; } - /** * @return \Model_Admin */ public function getCronAdmin() { - $cron = $this->di['db']->findOne('Admin', 'role = :role', array(':role'=>\Model_Admin::ROLE_CRON)); - if($cron instanceof \Model_Admin) { + $cron = $this->di['db']->findOne('Admin', 'role = :role', [':role' => \Model_Admin::ROLE_CRON]); + if ($cron instanceof \Model_Admin) { return $cron; } @@ -368,43 +365,44 @@ class Service implements InjectionAwareInterface $cron->role = \Model_Admin::ROLE_CRON; $cron->admin_group_id = 1; $cron->email = $this->di['tools']->generatePassword().'@'.$this->di['tools']->generatePassword().'.com'; - $cron->pass = $this->di['password']->hashIt(uniqid() . microtime()); - $cron->name = "System Cron Job"; - $cron->signature = ""; + $cron->pass = $this->di['password']->hashIt(uniqid().microtime()); + $cron->name = 'System Cron Job'; + $cron->signature = ''; $cron->protected = 1; $cron->status = 'active'; $cron->created_at = date('Y-m-d H:i:s'); $cron->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($cron); + return $cron; } public function toModel_AdminApiiArray(\Model_Admin $model, $deep = false) { - $data = array( - 'id' => $model->id, - 'role' => $model->role, - 'admin_group_id' => $model->admin_group_id, - 'email' => $model->email, - 'name' => $model->name, - 'status' => $model->status, - 'signature' => $model->signature, - 'created_at' => $model->created_at, - 'updated_at' => $model->updated_at, - ); + $data = [ + 'id' => $model->id, + 'role' => $model->role, + 'admin_group_id' => $model->admin_group_id, + 'email' => $model->email, + 'name' => $model->name, + 'status' => $model->status, + 'signature' => $model->signature, + 'created_at' => $model->created_at, + 'updated_at' => $model->updated_at, + ]; $data['protected'] = $model->protected; $adminGroupModel = $this->di['db']->load('AdminGroup', $model->admin_group_id); - $data['group']['id'] = $adminGroupModel->id; - $data['group']['name'] = $adminGroupModel->name; + $data['group']['id'] = $adminGroupModel->id; + $data['group']['name'] = $adminGroupModel->name; return $data; } public function update(\Model_Admin $model, $data) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminStaffUpdate', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffUpdate', 'params' => ['id' => $model->id]]); $model->email = $this->di['array_get']($data, 'email', $model->email); $model->admin_group_id = $this->di['array_get']($data, 'admin_group_id', $model->admin_group_id); @@ -414,39 +412,42 @@ class Service implements InjectionAwareInterface $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminStaffUpdate', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffUpdate', 'params' => ['id' => $model->id]]); $this->di['logger']->info('Updated staff member %s details', $model->id); + return true; } public function delete(\Model_Admin $model) { - if($model->protected) { + if ($model->protected) { throw new \Box_Exception('This administrator account is protected and can not be removed'); } - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminStaffDelete', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffDelete', 'params' => ['id' => $model->id]]); $id = $model->id; $this->di['db']->trash($model); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminStaffDelete', 'params'=>array('id'=>$id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffDelete', 'params' => ['id' => $id]]); $this->di['logger']->info('Deleted staff member %s', $id); + return true; } public function changePassword(\Model_Admin $model, $password) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminStaffPasswordChange', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffPasswordChange', 'params' => ['id' => $model->id]]); $model->pass = $this->di['password']->hashIt($password); $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); - $this->di['events_manager']->fire(array('event'=>'onAfterAdminStaffPasswordChange', 'params'=>array('id'=>$model->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffPasswordChange', 'params' => ['id' => $model->id]]); $this->di['logger']->info('Changed staff member %s password', $model->id); + return true; } @@ -455,32 +456,32 @@ class Service implements InjectionAwareInterface $systemService = $this->di['mod_service']('system'); $systemService->checkLimits('Model_Admin', 3); - $signature = $this->di['array_get']($data, 'signature', NULL); + $signature = $this->di['array_get']($data, 'signature', null); - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminStaffCreate', 'params'=>$data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminStaffCreate', 'params' => $data]); $model = $this->di['db']->dispense('Admin'); - $model->role = \Model_Admin::ROLE_STAFF; - $model->admin_group_id = $data['admin_group_id']; - $model->email = $data['email']; - $model->pass = $this->di['password']->hashIt($data['password']); - $model->name = $data['name']; - $model->status = $model->getStatus($data['status']); - $model->signature = $signature; - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); + $model->role = \Model_Admin::ROLE_STAFF; + $model->admin_group_id = $data['admin_group_id']; + $model->email = $data['email']; + $model->pass = $this->di['password']->hashIt($data['password']); + $model->name = $data['name']; + $model->status = $model->getStatus($data['status']); + $model->signature = $signature; + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); try { $newId = $this->di['db']->store($model); - } catch(\RedBeanPHP\RedException $e) { - throw new \Box_Exception('Staff member with email :email is already registered', array(':email'=>$data['email']), 788954); + } catch (\RedBeanPHP\RedException $e) { + throw new \Box_Exception('Staff member with email :email is already registered', [':email' => $data['email']], 788954); } - $this->di['events_manager']->fire(array('event'=>'onAfterAdminStaffCreate', 'params'=>array('id'=>$newId))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminStaffCreate', 'params' => ['id' => $newId]]); $this->di['logger']->info('Created new staff member %s', $newId); - return (int)$newId; + return (int) $newId; } public function createAdmin(array $data) @@ -502,6 +503,7 @@ class Service implements InjectionAwareInterface $this->_sendMail($admin, $data['password']); $data['remember'] = true; + return $newId; } @@ -510,10 +512,10 @@ class Service implements InjectionAwareInterface $sql = 'SELECT id, name FROM admin_group'; $rows = $this->di['db']->getAll($sql); - $result = array(); + $result = []; - foreach($rows as $row){ - $result[ $row['id'] ] = $row['name']; + foreach ($rows as $row) { + $result[$row['id']] = $row['name']; } return $result; @@ -524,13 +526,14 @@ class Service implements InjectionAwareInterface $sql = 'SELECT * FROM admin_group order by id asc'; - return array($sql, array()); + + return [$sql, []]; } public function createGroup($name) { $systemService = $this->di['mod_service']('system'); - $systemService ->checkLimits('Model_AdminGroup', 2); + $systemService->checkLimits('Model_AdminGroup', 2); $model = $this->di['db']->dispense('AdminGroup'); $model->name = $name; @@ -540,50 +543,53 @@ class Service implements InjectionAwareInterface $groupId = $this->di['db']->store($model); $this->di['logger']->info('Created new staff group %s', $groupId); - return (int) $groupId; + return (int) $groupId; } public function toAdminGroupApiArray(\Model_AdminGroup $model, $deep = false, $identity = null) { - $data = array(); + $data = []; $data['id'] = $model->id; $data['name'] = $model->name; $data['created_at'] = $model->created_at; $data['updated_at'] = $model->updated_at; + return $data; } public function deleteGroup(\Model_AdminGroup $model) { $id = $model->id; - if($model->id == 1) { + if (1 == $model->id) { throw new \Box_Exception('Administrators group can not be removed'); } $sql = 'SELECT count(1) FROM admin WHERE admin_group_id = :id'; - $staffMembersInGroup = $this->di['db']->getCell($sql, array('id' => $model->id)); - if($staffMembersInGroup > 0) { + $staffMembersInGroup = $this->di['db']->getCell($sql, ['id' => $model->id]); + if ($staffMembersInGroup > 0) { throw new \Box_Exception('Can not remove group which has staff members'); } $this->di['db']->trash($model); $this->di['logger']->info('Deleted staff group %s', $id); + return true; } public function updateGroup(\Model_AdminGroup $model, $data) { - if (isset($data['name'])){ + if (isset($data['name'])) { $model->name = $data['name']; } $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Updated staff group %s', $model->id); + return true; } @@ -594,43 +600,43 @@ class Service implements InjectionAwareInterface LEFT JOIN admin as a on m.admin_id = a.id '; - $search = $this->di['array_get']($data, 'search', NULL); - $admin_id = $this->di['array_get']($data, 'admin_id', NULL); + $search = $this->di['array_get']($data, 'search', null); + $admin_id = $this->di['array_get']($data, 'admin_id', null); - $where = array(); - $params = array(); - if($search) { + $where = []; + $params = []; + if ($search) { $where[] = ' a.name LIKE :name OR a.id LIKE :id OR a.email LIKE :email '; - $params['name'] = "%$search%"; - $params['id'] = "%$search%"; - $params['email'] = "%$search%"; + $params['name'] = "%$search%"; + $params['id'] = "%$search%"; + $params['email'] = "%$search%"; } - if($admin_id) { + if ($admin_id) { $where[] = 'm.admin_id = :admin_id'; $params['admin_id'] = $admin_id; } - if (!empty($where)){ + if (!empty($where)) { $sql .= ' WHERE '.implode(' AND ', $where); } $sql .= ' ORDER BY m.id DESC'; - return array($sql, $params); + return [$sql, $params]; } public function toActivityAdminHistoryApiArray(\Model_ActivityAdminHistory $model, $deep = false) { - $result = array( - 'id' => $model->id, - 'ip' => $model->ip, + $result = [ + 'id' => $model->id, + 'ip' => $model->ip, 'created_at' => $model->created_at, - ); + ]; if ($model->admin_id) { $adminModel = $this->di['db']->load('Admin', $model->admin_id); if ($adminModel instanceof \Model_Admin && $adminModel->id) { - $result['staff']['id'] = $adminModel->id; - $result['staff']['name'] = $adminModel->name; + $result['staff']['id'] = $adminModel->id; + $result['staff']['name'] = $adminModel->name; $result['staff']['email'] = $adminModel->email; } } @@ -641,6 +647,7 @@ class Service implements InjectionAwareInterface public function deleteLoginHistory(\Model_ActivityAdminHistory $model) { $this->di['db']->trash($model); + return true; } @@ -653,18 +660,18 @@ class Service implements InjectionAwareInterface $admin_url = $this->di['url']->adminLink('/'); $content = "Hi $admin_name, ".PHP_EOL; - $content .= "You have successfully setup BoxBilling at ".BB_URL.PHP_EOL; - $content .= "Access client area at: ".$client_url.PHP_EOL; - $content .= "Access admin area at: ".$admin_url." with login details:".PHP_EOL; - $content .= "Email: ".$admin_email.PHP_EOL; - $content .= "Password: ".$admin_pass.PHP_EOL.PHP_EOL; + $content .= 'You have successfully setup BoxBilling at '.BB_URL.PHP_EOL; + $content .= 'Access client area at: '.$client_url.PHP_EOL; + $content .= 'Access admin area at: '.$admin_url.' with login details:'.PHP_EOL; + $content .= 'Email: '.$admin_email.PHP_EOL; + $content .= 'Password: '.$admin_pass.PHP_EOL.PHP_EOL; - $content .= "Read BoxBilling documentation to get started http://docs.boxbilling.org/".PHP_EOL; - $content .= "Thank You for using BoxBilling.".PHP_EOL; + $content .= 'Read BoxBilling documentation to get started http://docs.boxbilling.org/'.PHP_EOL; + $content .= 'Thank You for using BoxBilling.'.PHP_EOL; $subject = sprintf('BoxBilling is ready at "%s"', BB_URL); - $systemService = $this->di['mod_service']('system'); + $systemService = $this->di['mod_service']('system'); $from = $systemService->getParamValue('company_email'); $emailService = $this->di['mod_service']('Email'); $emailService->sendMail($admin_email, $from, $subject, $content); @@ -672,12 +679,11 @@ class Service implements InjectionAwareInterface public function authorizeAdmin($email, $plainTextPassword) { - $model = $this->di['db']->findOne('Admin', 'email = ? AND status = ?', array($email, \Model_Admin::STATUS_ACTIVE)); - if ($model == null){ + $model = $this->di['db']->findOne('Admin', 'email = ? AND status = ?', [$email, \Model_Admin::STATUS_ACTIVE]); + if (null == $model) { return null; } return $this->di['auth']->authorizeUser($model, $plainTextPassword); } - } diff --git a/src/bb-modules/Stats/Api/Admin.php b/src/bb-modules/Stats/Api/Admin.php index ebfee3648..4d34cc0d2 100644 --- a/src/bb-modules/Stats/Api/Admin.php +++ b/src/bb-modules/Stats/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getOrdersStatuses($data); } - + /** - * Get active orders stats grouped by products + * Get active orders stats grouped by products. * * @return array */ public function get_product_summary($data) { - return $this->getService()->getProductSummary($data); + return $this->getService()->getProductSummary($data); } - + /** - * Get product sales + * Get product sales. * * @return array */ public function get_product_sales($data) { - return $this->getService()->getProductSales($data); + return $this->getService()->getProductSales($data); } /** - * Get income and refunds statistics + * Get income and refunds statistics. * * @return array */ @@ -87,7 +89,7 @@ class Admin extends \Api_Abstract */ public function get_refunds($data) { - return $this->getService()->getRefunds($data); + return $this->getService()->getRefunds($data); } /** @@ -101,11 +103,11 @@ class Admin extends \Api_Abstract */ public function get_income($data) { - return $this->getService()->getIncome($data); + return $this->getService()->getIncome($data); } /** - * Return statistics for orders + * Return statistics for orders. * * @optional string $date_from - day since income are counted * @optional string $date_to - day until income are counted @@ -130,20 +132,20 @@ class Admin extends \Api_Abstract { return $this->getService()->getTableStats('client', $data); } - + /** - * Get number of clients in country - * + * Get number of clients in country. + * * @return array */ public function client_countries($data) { return $this->getService()->getClientCountries($data); } - + /** - * Get number of sales by country - * + * Get number of sales by country. + * * @return array */ public function sales_countries($data) @@ -178,4 +180,4 @@ class Admin extends \Api_Abstract { return $this->getService()->getTableStats('support_ticket', $data); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Stats/Service.php b/src/bb-modules/Stats/Service.php index c75676b84..727963297 100644 --- a/src/bb-modules/Stats/Service.php +++ b/src/bb-modules/Stats/Service.php @@ -1,6 +1,6 @@ di['pdo']; - $total_query = "SELECT COUNT(1) FROM :table"; + $total_query = 'SELECT COUNT(1) FROM :table'; $yeste_query = "SELECT COUNT(1) FROM :table WHERE DATE_FORMAT(`created_at`, '%Y-%m-%d') = DATE_SUB(CURDATE(), INTERVAL 1 DAY)"; $today_query = "SELECT COUNT(1) FROM :table WHERE DATE_FORMAT(`created_at`, '%Y-%m-%d') = CURDATE()"; $month_query = "SELECT COUNT(1) FROM :table WHERE DATE_FORMAT(`created_at`, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')"; @@ -139,7 +139,7 @@ class Service implements InjectionAwareInterface public function getSummaryIncome() { - $stats = array(); + $stats = []; $pdo = $this->di['pdo']; @@ -177,6 +177,7 @@ class Service implements InjectionAwareInterface $orderService = $this->di['mod_service']('order'); $c = $orderService->counter(); unset($c['total']); + return $c; } @@ -189,29 +190,30 @@ class Service implements InjectionAwareInterface GROUP BY o.product_id ORDER BY orders DESC "; + return $this->di['db']->getAll($query); } public function getProductSales($data) { - list($time_from, $time_to) = $this->_getDateInterval($data); + [$time_from, $time_to] = $this->_getDateInterval($data); $pdo = $this->di['pdo']; - $query = "SELECT title, COUNT(product_id) as sales + $query = 'SELECT title, COUNT(product_id) as sales FROM `client_order` WHERE status = :status AND `created_at` BETWEEN :date_from AND :date_to GROUP BY product_id - "; + '; $stmt = $pdo->prepare($query); $stmt->execute( - array( - 'status' => 'active', + [ + 'status' => 'active', 'date_from' => date('Y-m-d', $time_from), - 'date_to' => date('Y-m-d', $time_to), - ) + 'date_to' => date('Y-m-d', $time_to), + ] ); return $stmt->fetchAll(\PDO::FETCH_KEY_PAIR); @@ -221,19 +223,20 @@ class Service implements InjectionAwareInterface { $pdo = $this->di['pdo']; - $query = "SELECT COALESCE(SUM(base_refund), 0) AS `refund`, COALESCE(SUM(base_income), 0) AS `income` + $query = 'SELECT COALESCE(SUM(base_refund), 0) AS `refund`, COALESCE(SUM(base_income), 0) AS `income` FROM `invoice` WHERE approved = 1 AND (status = :status1 OR status = :status2) - "; + '; $stmt = $pdo->prepare($query); - $stmt->execute(array( - 'status1' => \Model_Invoice::STATUS_PAID, - 'status2' => \Model_Invoice::STATUS_REFUNDED, - )); + $stmt->execute([ + 'status1' => \Model_Invoice::STATUS_PAID, + 'status2' => \Model_Invoice::STATUS_REFUNDED, + ]); $results = $stmt->fetchAll(\PDO::FETCH_ASSOC); + return $results[0]; } @@ -242,11 +245,11 @@ class Service implements InjectionAwareInterface $time_from = strtotime('-1 month'); $time_to = strtotime('+1 day'); - if(isset($data['date_from']) && !empty($data['date_from'])) { + if (isset($data['date_from']) && !empty($data['date_from'])) { $time_from = strtotime($data['date_from']); } - if(isset($data['date_to']) && !empty($data['date_to'])) { + if (isset($data['date_to']) && !empty($data['date_to'])) { $time_to = strtotime($data['date_to']); } @@ -261,14 +264,15 @@ class Service implements InjectionAwareInterface $stmt = $pdo->prepare($query); $stmt->execute( - array( - 'status' => \Model_Invoice::STATUS_REFUNDED, + [ + 'status' => \Model_Invoice::STATUS_REFUNDED, 'date_from' => date('Y-m-d', $time_from), - 'date_to' => date('Y-m-d', $time_to), - ) + 'date_to' => date('Y-m-d', $time_to), + ] ); $results = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR); + return $this->_genFlotArray($results, $time_from, $time_to); } @@ -277,11 +281,11 @@ class Service implements InjectionAwareInterface $time_from = strtotime('-1 month'); $time_to = strtotime('+1 day'); - if(isset($data['date_from']) && !empty($data['date_from'])) { + if (isset($data['date_from']) && !empty($data['date_from'])) { $time_from = strtotime($data['date_from']); } - if(isset($data['date_to']) && !empty($data['date_to'])) { + if (isset($data['date_to']) && !empty($data['date_to'])) { $time_to = strtotime($data['date_to']); } @@ -296,21 +300,22 @@ class Service implements InjectionAwareInterface $stmt = $pdo->prepare($query); $stmt->execute( - array( - 'status' => \Model_Invoice::STATUS_PAID, + [ + 'status' => \Model_Invoice::STATUS_PAID, 'date_from' => date('Y-m-d', $time_from), - 'date_to' => date('Y-m-d', $time_to), - ) + 'date_to' => date('Y-m-d', $time_to), + ] ); $results = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR); + return $this->_genFlotArray($results, $time_from, $time_to); } public function getClientCountries($data) { $limit = (int) $this->di['array_get']($data, 'limit', 10); - $q=" + $q = " SELECT country, COUNT(id) as clients FROM `client` GROUP BY `country` @@ -320,13 +325,14 @@ class Service implements InjectionAwareInterface $pdo = $this->di['pdo']; $stmt = $pdo->prepare($q); $stmt->execute(); + return $stmt->fetchAll(\PDO::FETCH_KEY_PAIR); } public function getSalesByCountry($data) { $limit = (int) $this->di['array_get']($data, 'limit', 10); - $q=" + $q = " SELECT buyer_country, COUNT(id) as sales FROM `invoice` WHERE status = 'paid' @@ -337,6 +343,7 @@ class Service implements InjectionAwareInterface $pdo = $this->di['pdo']; $stmt = $pdo->prepare($q); $stmt->execute(); + return $stmt->fetchAll(\PDO::FETCH_KEY_PAIR); } @@ -345,27 +352,27 @@ class Service implements InjectionAwareInterface $time_from = strtotime('-1 month'); $time_to = strtotime('+1 day'); - if(isset($data['date_from']) && !empty($data['date_from'])) { + if (isset($data['date_from']) && !empty($data['date_from'])) { $time_from = strtotime($data['date_from']); } - if(isset($data['date_to']) && !empty($data['date_to'])) { + if (isset($data['date_to']) && !empty($data['date_to'])) { $time_to = strtotime($data['date_to']); } - return array($time_from, $time_to); + return [$time_from, $time_to]; } - public function getTableStats($table, $data = array()) + public function getTableStats($table, $data = []) { $time_from = strtotime('-1 month'); $time_to = strtotime('+1 day'); - if(isset($data['date_from']) && !empty($data['date_from'])) { + if (isset($data['date_from']) && !empty($data['date_from'])) { $time_from = strtotime($data['date_from']); } - if(isset($data['date_to']) && !empty($data['date_to'])) { + if (isset($data['date_to']) && !empty($data['date_to'])) { $time_to = strtotime($data['date_to']); } @@ -378,32 +385,33 @@ class Service implements InjectionAwareInterface $stmt = $pdo->prepare($query); $stmt->execute( - array( + [ 'date_from' => date('Y-m-d', $time_from), - 'date_to' => date('Y-m-d', $time_to), - ) + 'date_to' => date('Y-m-d', $time_to), + ] ); $results = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR); + return $this->_genFlotArray($results, $time_from, $time_to); } /** - * @param integer $time_from - * @param integer $time_to + * @param int $time_from + * @param int $time_to */ private function _genFlotArray($results, $time_from, $time_to) { - $data = array(); + $data = []; // Loop between timestamps, 1 day at a time do { - $time_from = strtotime('+1 day',$time_from); + $time_from = strtotime('+1 day', $time_from); $dom = date('Y-m-d', $time_from); $c = $this->di['array_get']($results, $dom, 0); - $data[] = array($time_from * 1000, (int)$c); + $data[] = [$time_from * 1000, (int) $c]; } while ($time_to > $time_from); array_pop($data); + return $data; } } - \ No newline at end of file diff --git a/src/bb-modules/Support/Api/Admin.php b/src/bb-modules/Support/Api/Admin.php index d8d10517f..95efb40a2 100644 --- a/src/bb-modules/Support/Api/Admin.php +++ b/src/bb-modules/Support/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getSearchQuery($data); + [$sql, $bindings] = $this->getService()->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - $pager = $this->di['pager']->getAdvancedResultSet($sql, $bindings, $per_page); - foreach($pager['list'] as $key => $ticketArr){ + $pager = $this->di['pager']->getAdvancedResultSet($sql, $bindings, $per_page); + foreach ($pager['list'] as $key => $ticketArr) { $ticket = $this->di['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found'); $pager['list'][$key] = $this->getService()->toApiArray($ticket, true, $this->getIdentity()); } @@ -39,7 +41,7 @@ class Admin extends \Api_Abstract } /** - * Return ticket full details + * Return ticket full details. * * @param int $id - ticket id * @@ -47,9 +49,9 @@ class Admin extends \Api_Abstract */ public function ticket_get($data) { - $required = array( - 'id' => 'Ticket id is missing' - ); + $required = [ + 'id' => 'Ticket id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found'); @@ -58,7 +60,7 @@ class Admin extends \Api_Abstract } /** - * Update ticket details + * Update ticket details. * * @param int $id - ticket id * @@ -71,9 +73,9 @@ class Admin extends \Api_Abstract */ public function ticket_update($data) { - $required = array( - 'id' => 'Ticket id is missing' - ); + $required = [ + 'id' => 'Ticket id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found'); @@ -82,19 +84,19 @@ class Admin extends \Api_Abstract } /** - * Update ticket message + * Update ticket message. * - * @param int $id - ticket id + * @param int $id - ticket id * @param string $content - new message content * * @return bool */ public function ticket_message_update($data) { - $required = array( - 'id' => 'Ticket message id is missing', - 'content' => 'Ticket message content is missing' - ); + $required = [ + 'id' => 'Ticket message id is missing', + 'content' => 'Ticket message content is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportTicketMessage', $data['id'], 'Ticket message not found'); @@ -111,9 +113,9 @@ class Admin extends \Api_Abstract */ public function ticket_delete($data) { - $required = array( + $required = [ 'id' => 'Ticket id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found'); @@ -122,19 +124,19 @@ class Admin extends \Api_Abstract } /** - * Add new conversation message to to ticket + * Add new conversation message to to ticket. * - * @param int $id - ticket id + * @param int $id - ticket id * @param string $content - ticket message content * * @return int - ticket message id */ public function ticket_reply($data) { - $required = array( - 'id' => 'Ticket id is missing', - 'content' => 'Ticket message content is missing' - ); + $required = [ + 'id' => 'Ticket id is missing', + 'content' => 'Ticket message content is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $data['content'] = preg_replace('/javascript:\/\/|\%0(d|a)/i', '', $data['content']); @@ -145,22 +147,22 @@ class Admin extends \Api_Abstract } /** - * Close ticket + * Close ticket. * * @param int $id - ticket id * - * @return boolean + * @return bool */ public function ticket_close($data) { - $required = array( + $required = [ 'id' => 'Ticket id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $ticket = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found'); - if ($ticket->status == \Model_SupportTicket::CLOSED) { + if (\Model_SupportTicket::CLOSED == $ticket->status) { return true; } @@ -171,10 +173,10 @@ class Admin extends \Api_Abstract * Method to create open new ticket. Tickets can have tasks assigned to them * via optional parameters. * - * @param int $client_id - ticket client id - * @param string $content - ticket message content - * @param string $subject - ticket subject - * @param int $support_helpdesk_id - Ticket helpdesk id. + * @param int $client_id - ticket client id + * @param string $content - ticket message content + * @param string $subject - ticket subject + * @param int $support_helpdesk_id - Ticket helpdesk id * * @optional string $status - Ticket status. Default - on hold * @@ -182,30 +184,29 @@ class Admin extends \Api_Abstract */ public function ticket_create($data) { - $required = array( - 'client_id' => 'Client id is missing', - 'content' => 'Ticket content required', - 'subject' => 'Ticket subject required', - 'support_helpdesk_id' => 'Ticket support_helpdesk_id is required' - ); + $required = [ + 'client_id' => 'Client id is missing', + 'content' => 'Ticket content required', + 'subject' => 'Ticket subject required', + 'support_helpdesk_id' => 'Ticket support_helpdesk_id is required', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $data['content'] = preg_replace('/javascript:\/\/|\%0(d|a)/i', '', $data['content']); - $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found'); + $client = $this->di['db']->getExistingModelById('Client', $data['client_id'], 'Client not found'); $helpdesk = $this->di['db']->getExistingModelById('SupportHelpdesk', $data['support_helpdesk_id'], 'Helpdesk invalid'); return $this->getService()->ticketCreateForAdmin($client, $helpdesk, $data, $this->getIdentity()); - } /** * Action to close all tickets which have not received any replies for a - * time defined in helpdesk + * time defined in helpdesk. * * Run by cron job * - * @return boolean + * @return bool */ public function batch_ticket_auto_close($data) { @@ -213,7 +214,7 @@ class Admin extends \Api_Abstract $expiredArr = $this->getService()->getExpired(); foreach ($expiredArr as $ticketArr) { - $ticketModel = $this->di['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found'); + $ticketModel = $this->di['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found'); if (!$this->getService()->autoClose($ticketModel)) { $this->di['logger']->info('Ticket %s was not closed', $ticketModel->id); } @@ -224,11 +225,11 @@ class Admin extends \Api_Abstract /** * Action to close all inquiries which have not received any replies for a - * time defined in helpdesk + * time defined in helpdesk. * * Run by cron job * - * @return boolean + * @return bool */ public function batch_public_ticket_auto_close($data) { @@ -244,7 +245,8 @@ class Admin extends \Api_Abstract } /** - * Return tickets statuses with counter + * Return tickets statuses with counter. + * * @return */ public function ticket_get_statuses($data) @@ -257,59 +259,63 @@ class Admin extends \Api_Abstract } /** - * Get paginated list of inquiries + * Get paginated list of inquiries. * * @return array */ public function public_ticket_get_list($data) { - list($sql, $bindings) = $this->getService()->publicGetSearchQuery($data); + [$sql, $bindings] = $this->getService()->publicGetSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - $pager = $this->di['pager']->getAdvancedResultSet($sql, $bindings, $per_page); + $pager = $this->di['pager']->getAdvancedResultSet($sql, $bindings, $per_page); - foreach($pager['list'] as $key => $ticketArr){ + foreach ($pager['list'] as $key => $ticketArr) { $ticket = $this->di['db']->getExistingModelById('SupportPTicket', $ticketArr['id'], 'Ticket not found'); $pager['list'][$key] = $this->getService()->publicToApiArray($ticket); } + return $pager; } /** - * Create new inquiry. Send email + * Create new inquiry. Send email. * - * @param string $name - receivers name - * @param string $email - receivers email + * @param string $name - receivers name + * @param string $email - receivers email * @param string $subject - email subject * @param string $message - email message * * @return int - inquiry id + * * @throws \Box_Exception */ public function public_ticket_create($data) { - $required = array( - 'name' => 'Client name parameter is missing', - 'email' => 'Client email parameter is missing', + $required = [ + 'name' => 'Client name parameter is missing', + 'email' => 'Client email parameter is missing', 'subject' => 'Subject parameter is missing', - 'message' => 'Ticket message is missing' - ); + 'message' => 'Ticket message is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->publicTicketCreate($data, $this->getIdentity()); } /** - * Get inquiry details + * Get inquiry details. * * @param int $id - inquiry id + * * @return array + * * @throws \Box_Exception */ public function public_ticket_get($data) { - $required = array( + $required = [ 'id' => 'Ticket id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); @@ -318,17 +324,19 @@ class Admin extends \Api_Abstract } /** - * Delete inquiry + * Delete inquiry. * * @param int $id - inquiry id + * * @return bool + * * @throws \Box_Exception */ public function public_ticket_delete($data) { - $required = array( + $required = [ 'id' => 'Ticket id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); @@ -337,17 +345,19 @@ class Admin extends \Api_Abstract } /** - * Set iquery status to closed + * Set iquery status to closed. * * @param int $id - inquiry id + * * @return array + * * @throws \Box_Exception */ public function public_ticket_close($data) { - $required = array( + $required = [ 'id' => 'Ticket id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $ticket = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); @@ -356,7 +366,7 @@ class Admin extends \Api_Abstract } /** - * Update inquiry details + * Update inquiry details. * * @param int $id - inquiry id * @@ -364,13 +374,14 @@ class Admin extends \Api_Abstract * @optional string $status - status * * @return bool + * * @throws \Box_Exception */ public function public_ticket_update($data) { - $required = array( + $required = [ 'id' => 'Ticket id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); @@ -379,20 +390,21 @@ class Admin extends \Api_Abstract } /** - * Post new reply to inquiry + * Post new reply to inquiry. * - * @param int $id - inquiry id + * @param int $id - inquiry id * @param string $content - text message * * @return bool + * * @throws \Box_Exception */ public function public_ticket_reply($data) { - $required = array( - 'id' => 'Ticket id is missing', + $required = [ + 'id' => 'Ticket id is missing', 'content' => 'Ticket content required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $ticket = $this->di['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); @@ -401,7 +413,7 @@ class Admin extends \Api_Abstract } /** - * Return tickets statuses with counter + * Return tickets statuses with counter. */ public function public_ticket_get_statuses($data) { @@ -413,19 +425,20 @@ class Admin extends \Api_Abstract } /** - * Get helpdesk list + * Get helpdesk list. * * @return array */ public function helpdesk_get_list($data) { - list($sql, $bindings) = $this->getService()->helpdeskGetSearchQuery($data); + [$sql, $bindings] = $this->getService()->helpdeskGetSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); + return $this->di['pager']->getSimpleResultSet($sql, $bindings, $per_page); } /** - * Get pairs of helpdesks + * Get pairs of helpdesks. * * @return array */ @@ -435,17 +448,19 @@ class Admin extends \Api_Abstract } /** - * Get helpdesk details + * Get helpdesk details. * * @param int $id - helpdesk id + * * @return array + * * @throws \Box_Exception */ public function helpdesk_get($data) { - $required = array( + $required = [ 'id' => 'Help desk id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportHelpdesk', $data['id'], 'Help desk not found'); @@ -454,7 +469,7 @@ class Admin extends \Api_Abstract } /** - * Update helpdesk parameters + * Update helpdesk parameters. * * @param int $id - helpdesk id * @@ -464,14 +479,15 @@ class Admin extends \Api_Abstract * @optional int $close_after - time to wait for reply before auto closing ticket * @optional string $signature - helpdesk signature * - * @return boolean + * @return bool + * * @throws \Box_Exception */ public function helpdesk_update($data) { - $required = array( + $required = [ 'id' => 'Help desk id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportHelpdesk', $data['id'], 'Help desk not found'); @@ -480,7 +496,7 @@ class Admin extends \Api_Abstract } /** - * Create new helpdesk + * Create new helpdesk. * * @param string $name - new helpdesk title * @@ -490,31 +506,33 @@ class Admin extends \Api_Abstract * @optional string $signature - helpdesk signature * * @return int - id + * * @throws \Box_Exception */ public function helpdesk_create($data) { - $required = array( + $required = [ 'name' => 'Help desk title is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->helpdeskCreate($data); } /** - * Delete helpdesk + * Delete helpdesk. * * @param int $id - helpdesk id * - * @return boolean + * @return bool + * * @throws \Box_Exception */ public function helpdesk_delete($data) { - $required = array( + $required = [ 'id' => 'Help desk id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportHelpdesk', $data['id'], 'Help desk not found'); @@ -523,17 +541,17 @@ class Admin extends \Api_Abstract } /** - * Get list of canned responses + * Get list of canned responses. * * @return array */ public function canned_get_list($data) { - list($sql, $bindings) = $this->getService()->cannedGetSearchQuery($data); + [$sql, $bindings] = $this->getService()->cannedGetSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); $pager = $this->di['pager']->getSimpleResultSet($sql, $bindings, $per_page); - foreach($pager['list'] as $key => $item){ + foreach ($pager['list'] as $key => $item) { $staff = $this->di['db']->getExistingModelById('SupportPr', $item['id'], 'Canned response not found'); $pager['list'][$key] = $this->getService()->cannedToApiArray($staff); } @@ -542,34 +560,35 @@ class Admin extends \Api_Abstract } /** - * Get list of canned responses grouped by category + * Get list of canned responses grouped by category. * * @return array */ public function canned_pairs() { - $res = $this->di['db']->getAssoc('SELECT id, title FROM support_pr_category WHERE 1'); - $list = array(); + $res = $this->di['db']->getAssoc('SELECT id, title FROM support_pr_category WHERE 1'); + $list = []; foreach ($res as $id => $title) { - $list[$title] = $this->di['db']->getAssoc('SELECT id, title FROM support_pr WHERE support_pr_category_id = :id', array('id' => $id)); + $list[$title] = $this->di['db']->getAssoc('SELECT id, title FROM support_pr WHERE support_pr_category_id = :id', ['id' => $id]); } return $list; } /** - * Get canned response details + * Get canned response details. * * @param int $id - canned response id * * @return array + * * @throws \Box_Exception */ public function canned_get($data) { - $required = array( + $required = [ 'id' => 'Canned reply id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportPr', $data['id'], 'Canned reply not found'); @@ -578,18 +597,19 @@ class Admin extends \Api_Abstract } /** - * Delete canned response + * Delete canned response. * * @param id $id - canned response id * - * @return boolean + * @return bool + * * @throws \Box_Exception */ public function canned_delete($data) { - $required = array( + $required = [ 'id' => 'Canned reply id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportPr', $data['id'], 'Canned reply not found'); @@ -598,31 +618,32 @@ class Admin extends \Api_Abstract } /** - * Create new canned response + * Create new canned response. * - * @param string $title - canned response title - * @param int $category_id - canned response category id + * @param string $title - canned response title + * @param int $category_id - canned response category id * * @optional string $content - canned response content * * @return int + * * @throws \Box_Exception */ public function canned_create($data) { - $required = array( - 'title' => 'Canned reply title is missing', - 'category_id' => 'Canned reply category id is missing' - ); + $required = [ + 'title' => 'Canned reply title is missing', + 'category_id' => 'Canned reply category id is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - $content = $this->di['array_get']($data, 'content', NULL); + $content = $this->di['array_get']($data, 'content', null); return $this->getService()->cannedCreate($data['title'], $data['category_id'], $content); } /** - * Update canned response + * Update canned response. * * @param int $id - canned response id * @@ -631,13 +652,14 @@ class Admin extends \Api_Abstract * @optional string $content - canned response content * * @return bool + * * @throws \Box_Exception */ public function canned_update($data) { - $required = array( + $required = [ 'id' => 'Canned reply id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportPr', $data['id'], 'Canned reply not found'); @@ -646,7 +668,7 @@ class Admin extends \Api_Abstract } /** - * Get canned response pairs + * Get canned response pairs. * * @return array */ @@ -656,17 +678,19 @@ class Admin extends \Api_Abstract } /** - * Get canned response category + * Get canned response category. * * @param int $id - canned response category id + * * @return array + * * @throws \Box_Exception */ public function canned_category_get($data) { - $required = array( + $required = [ 'id' => 'Canned category id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportPrCategory', $data['id'], 'Canned category not found'); @@ -675,20 +699,21 @@ class Admin extends \Api_Abstract } /** - * Get canned response category + * Get canned response category. * * @param int $id - canned response category id * * @optional string $title - new category title * * @return bool + * * @throws \Box_Exception */ public function canned_category_update($data) { - $required = array( + $required = [ 'id' => 'Canned category id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportPrCategory', $data['id'], 'Canned category not found'); @@ -699,18 +724,19 @@ class Admin extends \Api_Abstract } /** - * Delete canned response category + * Delete canned response category. * * @param int $id - canned response category id * * @return bool + * * @throws \Box_Exception */ public function canned_category_delete($data) { - $required = array( + $required = [ 'id' => 'Canned category id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportPrCategory', $data['id'], 'Canned category not found'); @@ -719,38 +745,40 @@ class Admin extends \Api_Abstract } /** - * Create canned response category + * Create canned response category. * * @param string $title - canned response category title * * @return int - new category id + * * @throws \Box_Exception */ public function canned_category_create($data) { - $required = array( + $required = [ 'title' => 'Canned category title is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->cannedCategoryCreate($data['title']); } /** - * Add note to support ticket + * Add note to support ticket. * - * @param int $ticket_id - support ticket id to add note to - * @param string $note - note + * @param int $ticket_id - support ticket id to add note to + * @param string $note - note * * @return int - new note id + * * @throws \Box_Exception */ public function note_create($data) { - $required = array( + $required = [ 'ticket_id' => 'ticket_id is missing', - 'note' => 'Note is missing', - ); + 'note' => 'Note is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $ticket = $this->di['db']->getExistingModelById('SupportTicket', $data['ticket_id'], 'Ticket not found'); @@ -759,18 +787,19 @@ class Admin extends \Api_Abstract } /** - * Delete note from support ticket + * Delete note from support ticket. * * @param int $id - note id * * @return bool + * * @throws \Box_Exception */ public function note_delete($data) { - $required = array( + $required = [ 'id' => 'Note id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportTicketNote', $data['id'], 'Note not found'); @@ -779,28 +808,28 @@ class Admin extends \Api_Abstract } /** - * Set support ticket related task to completed + * Set support ticket related task to completed. * * @param int $id - support ticket id * - * @return boolean + * @return bool + * * @throws \Box_Exception */ public function task_complete($data) { - $required = array( + $required = [ 'id' => 'Ticket id is missing', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $model = $this->di['db']->getExistingModelById('SupportTicket', $data['id'], 'Ticket not found'); return $this->getService()->ticketTaskComplete($model); - } /** - * Deletes tickets with given IDs + * Deletes tickets with given IDs. * * @param array $ids - IDs for deletion * @@ -808,20 +837,20 @@ class Admin extends \Api_Abstract */ public function batch_delete($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->ticket_delete(array('id' => $id)); + $this->ticket_delete(['id' => $id]); } return true; } /** - * Deletes tickets with given IDs + * Deletes tickets with given IDs. * * @param array $ids - IDs for deletion * @@ -829,15 +858,15 @@ class Admin extends \Api_Abstract */ public function batch_delete_public($data) { - $required = array( + $required = [ 'ids' => 'IDs not passed', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); foreach ($data['ids'] as $id) { - $this->public_ticket_delete(array('id' => $id)); + $this->public_ticket_delete(['id' => $id]); } return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Support/Api/Client.php b/src/bb-modules/Support/Api/Client.php index ccee1310f..170637c75 100644 --- a/src/bb-modules/Support/Api/Client.php +++ b/src/bb-modules/Support/Api/Client.php @@ -1,6 +1,6 @@ getIdentity(); + $identity = $this->getIdentity(); $data['client_id'] = $identity->id; - list($sql, $bindings) = $this->getService()->getSearchQuery($data); + [$sql, $bindings] = $this->getService()->getSearchQuery($data); $per_page = $this->di['array_get']($data, 'per_page', $this->di['pager']->getPer_page()); - $pager = $this->di['pager']->getAdvancedResultSet($sql, $bindings, $per_page); - foreach($pager['list'] as $key => $ticketArr){ + $pager = $this->di['pager']->getAdvancedResultSet($sql, $bindings, $per_page); + foreach ($pager['list'] as $key => $ticketArr) { $ticket = $this->di['db']->getExistingModelById('SupportTicket', $ticketArr['id'], 'Ticket not found'); $pager['list'][$key] = $this->getService()->toApiArray($ticket, true, $this->getIdentity()); } @@ -42,7 +44,7 @@ class Client extends \Api_Abstract } /** - * Return ticket full details + * Return ticket full details. * * @param int $id - ticket id * @@ -50,9 +52,9 @@ class Client extends \Api_Abstract */ public function ticket_get($data) { - $required = array( + $required = [ 'id' => 'Ticket id required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $ticket = $this->getService()->findOneByClient($this->getIdentity(), $data['id']); @@ -74,9 +76,9 @@ class Client extends \Api_Abstract * Method to create open new ticket. Tickets can have tasks assigned to them * via optional parameters. * - * @param string $content - ticket message content - * @param string $subject - ticket subject - * @param string $support_helpdesk_id - Ticket helpdesk id. + * @param string $content - ticket message content + * @param string $subject - ticket subject + * @param string $support_helpdesk_id - Ticket helpdesk id * * @optional int $rel_type - Ticket relation type * @optional int $rel_id - Ticket relation id @@ -87,11 +89,11 @@ class Client extends \Api_Abstract */ public function ticket_create($data) { - $required = array( - 'content' => 'Ticket content required', - 'subject' => 'Ticket subject required', + $required = [ + 'content' => 'Ticket content required', + 'subject' => 'Ticket subject required', 'support_helpdesk_id' => 'Ticket support_helpdesk_id required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $data['content'] = preg_replace('/javascript:\/\/|\%0(d|a)/i', '', $data['content']); @@ -101,36 +103,35 @@ class Client extends \Api_Abstract $client = $this->getIdentity(); return $this->getService()->ticketCreateForClient($client, $helpdesk, $data); - } /** - * Add new conversation message to ticket. Ticket will be reopened if closed + * Add new conversation message to ticket. Ticket will be reopened if closed. * - * @param int $id - ticket id + * @param int $id - ticket id * @param string $content - ticket message * * @return bool */ public function ticket_reply($data) { - $required = array( - 'id' => 'Ticket ID required', + $required = [ + 'id' => 'Ticket ID required', 'content' => 'Ticket content required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $data['content'] = preg_replace('/javascript:\/\/|\%0(d|a)/i', '', $data['content']); $client = $this->getIdentity(); - $bindings = array( - ':id' => $data['id'], - ':client_id' => $client->id - ); + $bindings = [ + ':id' => $data['id'], + ':client_id' => $client->id, + ]; $ticket = $this->di['db']->findOne('SupportTicket', 'id = :id AND client_id = :client_id', $bindings); - if (!$ticket instanceof \Model_SupportTicket){ + if (!$ticket instanceof \Model_SupportTicket) { throw new \Box_Exception('Ticket not found'); } @@ -139,21 +140,22 @@ class Client extends \Api_Abstract } $result = $this->getService()->ticketReply($ticket, $client, $data['content']); + return ($result > 0) ? true : false; } /** - * Close ticket + * Close ticket. * * @param int $id - ticket id * - * @return boolean + * @return bool */ public function ticket_close($data) { - $required = array( + $required = [ 'id' => 'Ticket ID required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $client = $this->getIdentity(); diff --git a/src/bb-modules/Support/Api/Guest.php b/src/bb-modules/Support/Api/Guest.php index 1ec9d2c65..9c13e7d42 100644 --- a/src/bb-modules/Support/Api/Guest.php +++ b/src/bb-modules/Support/Api/Guest.php @@ -1,6 +1,6 @@ 'Please enter your name', - 'email' => 'Please enter your email', + $required = [ + 'name' => 'Please enter your name', + 'email' => 'Please enter your email', 'subject' => 'Please enter your subject', 'message' => 'Please enter your message', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); if (strlen($data['message']) < 4) { throw new \Box_Exception('Please enter your message'); } - + return $this->getService()->ticketCreateForGuest($data); } /** - * Get public ticket + * Get public ticket. * * @param string $hash - public ticket hash * @@ -52,9 +54,9 @@ class Guest extends \Api_Abstract */ public function ticket_get($data) { - $required = array( + $required = [ 'hash' => 'Public ticket hash required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $publicTicket = $this->getService()->publicFindOneByHash($data['hash']); @@ -63,7 +65,7 @@ class Guest extends \Api_Abstract } /** - * Close public ticket + * Close public ticket. * * @param string $hash - public ticket hash * @@ -71,9 +73,9 @@ class Guest extends \Api_Abstract */ public function ticket_close($data) { - $required = array( + $required = [ 'hash' => 'Public ticket hash required', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $publicTicket = $this->getService()->publicFindOneByHash($data['hash']); @@ -82,24 +84,23 @@ class Guest extends \Api_Abstract } /** - * Reply to public ticket + * Reply to public ticket. * - * @param string $hash - public ticket hash + * @param string $hash - public ticket hash * @param string $message - public ticket reply message * * @return string - ticket hash - * */ public function ticket_reply($data) { - $required = array( - 'hash' => 'Public ticket hash required', + $required = [ + 'hash' => 'Public ticket hash required', 'message' => 'Message is required and can not be blank', - ); + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $publicTicket = $this->getService()->publicFindOneByHash($data['hash']); return $this->getService()->publicTicketReplyForGuest($publicTicket, $data['message']); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Support/Controller/Admin.php b/src/bb-modules/Support/Controller/Admin.php index ba0d748e5..02e5b9399 100644 --- a/src/bb-modules/Support/Controller/Admin.php +++ b/src/bb-modules/Support/Controller/Admin.php @@ -1,6 +1,6 @@ array( - 'location' => 'support', - 'index' => 500, + return [ + 'group' => [ + 'location' => 'support', + 'index' => 500, 'label' => 'Support', 'class' => 'support', 'sprite_class' => 'dark-sprite-icon sprite-dialog', - ), - 'subpages' => array( - array( - 'location' => 'support', + ], + 'subpages' => [ + [ + 'location' => 'support', 'label' => 'Client tickets', - 'uri' => $this->di['url']->adminLink('support', array('status' => 'open')), - 'index' => 100, - 'class' => '', - ), - array( - 'location' => 'support', + 'uri' => $this->di['url']->adminLink('support', ['status' => 'open']), + 'index' => 100, + 'class' => '', + ], + [ + 'location' => 'support', 'label' => 'Advanced ticket search', - 'uri' => $this->di['url']->adminLink('support', array('show_filter' => 1)), - 'index' => 200, - 'class' => '', - ), - array( - 'location' => 'support', + 'uri' => $this->di['url']->adminLink('support', ['show_filter' => 1]), + 'index' => 200, + 'class' => '', + ], + [ + 'location' => 'support', 'label' => 'Public tickets', - 'uri' => $this->di['url']->adminLink('support/public-tickets', array('status' => 'open')), - 'index' => 300, - 'class' => '', - ), - array( - 'location' => 'support', + 'uri' => $this->di['url']->adminLink('support/public-tickets', ['status' => 'open']), + 'index' => 300, + 'class' => '', + ], + [ + 'location' => 'support', 'label' => 'Canned responses', 'uri' => $this->di['url']->adminLink('support/canned-responses'), - 'index' => 400, - 'class' => '', - ), - ), - ); + 'index' => 400, + 'class' => '', + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/support', 'get_index', array(), get_class($this)); - $app->get('/support/', 'get_index', array(), get_class($this)); - $app->get('/support/index', 'get_index', array(), get_class($this)); - $app->get('/support/ticket/:id','get_ticket', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/support/ticket/:id/message/:messageid','get_ticket', array('id'=>'[0-9]+', 'messageid' => '[0-9]+'), get_class($this)); - $app->get('/support/public-tickets', 'get_public_tickets', array(), get_class($this)); - $app->get('/support/public-ticket/:id', 'get_public_ticket', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/support/helpdesks', 'get_helpdesks', array(), get_class($this)); - $app->get('/support/helpdesk/:id', 'get_helpdesk', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/support/canned-responses', 'get_canned_list', array(), get_class($this)); - $app->get('/support/canned/:id', 'get_canned', array('id'=>'[0-9]+'), get_class($this)); - $app->get('/support/canned-category/:id', 'get_canned_cat', array('id'=>'[0-9]+'), get_class($this)); + $app->get('/support', 'get_index', [], get_class($this)); + $app->get('/support/', 'get_index', [], get_class($this)); + $app->get('/support/index', 'get_index', [], get_class($this)); + $app->get('/support/ticket/:id', 'get_ticket', ['id' => '[0-9]+'], get_class($this)); + $app->get('/support/ticket/:id/message/:messageid', 'get_ticket', ['id' => '[0-9]+', 'messageid' => '[0-9]+'], get_class($this)); + $app->get('/support/public-tickets', 'get_public_tickets', [], get_class($this)); + $app->get('/support/public-ticket/:id', 'get_public_ticket', ['id' => '[0-9]+'], get_class($this)); + $app->get('/support/helpdesks', 'get_helpdesks', [], get_class($this)); + $app->get('/support/helpdesk/:id', 'get_helpdesk', ['id' => '[0-9]+'], get_class($this)); + $app->get('/support/canned-responses', 'get_canned_list', [], get_class($this)); + $app->get('/support/canned/:id', 'get_canned', ['id' => '[0-9]+'], get_class($this)); + $app->get('/support/canned-category/:id', 'get_canned_cat', ['id' => '[0-9]+'], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_support_tickets'); } - + public function get_ticket(\Box_App $app, $id, $messageid = '') { $api = $this->di['api_admin']; - $ticket = $api->support_ticket_get(array('id'=>$id)); - + $ticket = $api->support_ticket_get(['id' => $id]); + $cdm = ''; $mod = $this->di['mod']('support'); $config = $mod->getConfig(); - + try { - if(isset($config['delay_enable']) && $config['delay_enable'] && isset($config['delay_hours']) && $config['delay_hours'] >= 0) { + if (isset($config['delay_enable']) && $config['delay_enable'] && isset($config['delay_hours']) && $config['delay_hours'] >= 0) { $last_message = end($ticket['messages']); reset($ticket); $hours_passed = (round((time() - strtotime($last_message['created_at'])) / 3600) > $config['delay_hours']); - if($hours_passed) { - $delay_canned = $api->support_canned_get(array('id'=>$config['delay_message_id'])); - $cdm = $delay_canned['content']; + if ($hours_passed) { + $delay_canned = $api->support_canned_get(['id' => $config['delay_message_id']]); + $cdm = $delay_canned['content']; } } } catch (\Exception $e) { error_log($e->getMessage()); } - - return $app->render('mod_support_ticket', array('ticket'=>$ticket, 'canned_delay_message'=>$cdm, 'request_message' => $messageid)); + + return $app->render('mod_support_ticket', ['ticket' => $ticket, 'canned_delay_message' => $cdm, 'request_message' => $messageid]); } - + public function get_public_tickets(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_support_public_tickets'); } - + public function get_public_ticket(\Box_App $app, $id) { $api = $this->di['api_admin']; - $ticket = $api->support_public_ticket_get(array('id'=>$id)); - return $app->render('mod_support_public_ticket', array('ticket'=>$ticket)); + $ticket = $api->support_public_ticket_get(['id' => $id]); + + return $app->render('mod_support_public_ticket', ['ticket' => $ticket]); } - + public function get_helpdesk(\Box_App $app, $id) { $api = $this->di['api_admin']; - $helpdesk = $api->support_helpdesk_get(array('id'=>$id)); - return $app->render('mod_support_helpdesk', array('helpdesk'=>$helpdesk)); + $helpdesk = $api->support_helpdesk_get(['id' => $id]); + + return $app->render('mod_support_helpdesk', ['helpdesk' => $helpdesk]); } - + public function get_helpdesks(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_support_helpdesks'); } - + public function get_canned_list(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_support_canned_responses'); } - + public function get_canned(\Box_App $app, $id) { $api = $this->di['api_admin']; - $c = $api->support_canned_get(array('id'=>$id)); - return $app->render('mod_support_canned_response', array('response'=>$c)); + $c = $api->support_canned_get(['id' => $id]); + + return $app->render('mod_support_canned_response', ['response' => $c]); } - + public function get_canned_cat(\Box_App $app, $id) { $api = $this->di['api_admin']; - $c = $api->support_canned_category_get(array('id'=>$id)); - return $app->render('mod_support_canned_category', array('category'=>$c)); + $c = $api->support_canned_category_get(['id' => $id]); + + return $app->render('mod_support_canned_category', ['category' => $c]); } - -} \ No newline at end of file +} diff --git a/src/bb-modules/Support/Controller/Client.php b/src/bb-modules/Support/Controller/Client.php index d35fb289c..680cdb8ac 100644 --- a/src/bb-modules/Support/Controller/Client.php +++ b/src/bb-modules/Support/Controller/Client.php @@ -1,6 +1,6 @@ get('/support', 'get_tickets', array(), get_class($this)); - $app->get('/support/ticket/:id', 'get_ticket', array(), get_class($this)); - $app->get('/support/contact-us', 'get_contact_us', array(), get_class($this)); - $app->get('/support/contact-us/conversation/:hash', 'get_contact_us_conversation', array('hash'=>'[a-z0-9]+'), get_class($this)); + $app->get('/support', 'get_tickets', [], get_class($this)); + $app->get('/support/ticket/:id', 'get_ticket', [], get_class($this)); + $app->get('/support/contact-us', 'get_contact_us', [], get_class($this)); + $app->get('/support/contact-us/conversation/:hash', 'get_contact_us_conversation', ['hash' => '[a-z0-9]+'], get_class($this)); } - + public function get_tickets(\Box_App $app) { $this->di['is_client_logged']; + return $app->render('mod_support_tickets'); } public function get_ticket(\Box_App $app, $id) { $api = $this->di['api_client']; - $ticket = $api->support_ticket_get(array('id'=>$id)); - return $app->render('mod_support_ticket', array('ticket'=>$ticket)); + $ticket = $api->support_ticket_get(['id' => $id]); + + return $app->render('mod_support_ticket', ['ticket' => $ticket]); } - + public function get_contact_us(\Box_App $app) { return $app->render('mod_support_contact_us'); @@ -62,11 +63,11 @@ class Client implements \Box\InjectionAwareInterface public function get_contact_us_conversation(\Box_App $app, $hash) { $api = $this->di['api_guest']; - $data = array( - 'hash' => $hash, - ); + $data = [ + 'hash' => $hash, + ]; $array = $api->support_ticket_get($data); - return $app->render('mod_support_contact_us_conversation', array('ticket'=>$array)); - } -} \ No newline at end of file + return $app->render('mod_support_contact_us_conversation', ['ticket' => $array]); + } +} diff --git a/src/bb-modules/Support/Service.php b/src/bb-modules/Support/Service.php index 8c548cbc3..331d4a8d3 100644 --- a/src/bb-modules/Support/Service.php +++ b/src/bb-modules/Support/Service.php @@ -1,6 +1,6 @@ getDi(); - $params = $event->getParameters(); + $params = $event->getParameters(); $supportService = $di['mod_service']('support'); $emailService = $di['mod_service']('email'); @@ -38,10 +38,10 @@ class Service implements \Box\InjectionAwareInterface $identity = $di['loggedin_client']; $ticketArr = $supportService->toApiArray($ticketObj, true, $identity); - $email = array(); + $email = []; $email['to_client'] = $ticketObj->client_id; - $email['code'] = 'mod_support_ticket_open'; - $email['ticket'] = $ticketArr; + $email['code'] = 'mod_support_ticket_open'; + $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { error_log($exc->getMessage()); @@ -53,18 +53,17 @@ class Service implements \Box\InjectionAwareInterface $di = $event->getDi(); $supportService = $di['mod_service']('support'); $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); - + $params = $event->getParameters(); try { $ticketObj = $supportService->getTicketById($params['id']); - $identity = $di['loggedin_admin']; + $identity = $di['loggedin_admin']; $ticketArr = $supportService->toApiArray($ticketObj, true, $identity); - $email = array(); + $email = []; $email['to_client'] = $ticketObj->client_id; - $email['code'] = 'mod_support_ticket_staff_open'; - $email['ticket'] = $ticketArr; + $email['code'] = 'mod_support_ticket_staff_open'; + $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { error_log($exc->getMessage()); @@ -76,17 +75,17 @@ class Service implements \Box\InjectionAwareInterface $di = $event->getDi(); $supportService = $di['mod_service']('support'); $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); + $params = $event->getParameters(); try { - $identity = $di['loggedin_admin']; + $identity = $di['loggedin_admin']; $ticketObj = $supportService->getTicketById($params['id']); $ticketArr = $supportService->toApiArray($ticketObj, true, $identity); - $email = array(); + $email = []; $email['to_client'] = $ticketObj->client_id; - $email['code'] = 'mod_support_ticket_staff_close'; - $email['ticket'] = $ticketArr; + $email['code'] = 'mod_support_ticket_staff_close'; + $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { error_log($exc->getMessage()); @@ -98,17 +97,17 @@ class Service implements \Box\InjectionAwareInterface $di = $event->getDi(); $supportService = $di['mod_service']('support'); $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); + $params = $event->getParameters(); try { $ticketObj = $supportService->getTicketById($params['id']); - $identity = $di['loggedin_admin']; + $identity = $di['loggedin_admin']; $ticketArr = $supportService->toApiArray($ticketObj, true, $identity); - $email = array(); + $email = []; $email['to_client'] = $ticketObj->client_id; - $email['code'] = 'mod_support_ticket_staff_reply'; - $email['ticket'] = $ticketArr; + $email['code'] = 'mod_support_ticket_staff_reply'; + $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { error_log($exc->getMessage()); @@ -120,17 +119,17 @@ class Service implements \Box\InjectionAwareInterface $di = $event->getDi(); $supportService = $di['mod_service']('support'); $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); + $params = $event->getParameters(); try { $ticketObj = $supportService->getPublicTicketById($params['id']); $ticketArr = $supportService->publicToApiArray($ticketObj, true); - $email = array(); - $email['to'] = $ticketArr['author_email']; + $email = []; + $email['to'] = $ticketArr['author_email']; $email['to_name'] = $ticketArr['author_name']; - $email['code'] = 'mod_support_pticket_open'; - $email['ticket'] = $ticketArr; + $email['code'] = 'mod_support_pticket_open'; + $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { error_log($exc->getMessage()); @@ -142,18 +141,18 @@ class Service implements \Box\InjectionAwareInterface $di = $event->getDi(); $supportService = $di['mod_service']('support'); $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); + $params = $event->getParameters(); try { $ticketObj = $supportService->getPublicTicketById($params['id']); - $identity = $di['loggedin_admin']; + $identity = $di['loggedin_admin']; $ticketArr = $supportService->publicToApiArray($ticketObj, true, $identity); - $email = array(); - $email['to'] = $ticketArr['author_email']; + $email = []; + $email['to'] = $ticketArr['author_email']; $email['to_name'] = $ticketArr['author_name']; - $email['code'] = 'mod_support_pticket_staff_open'; - $email['ticket'] = $ticketArr; + $email['code'] = 'mod_support_pticket_staff_open'; + $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { error_log($exc->getMessage()); @@ -165,18 +164,18 @@ class Service implements \Box\InjectionAwareInterface $di = $event->getDi(); $supportService = $di['mod_service']('support'); $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); + $params = $event->getParameters(); try { $ticketObj = $supportService->getPublicTicketById($params['id']); - $identity = $di['loggedin_admin']; + $identity = $di['loggedin_admin']; $ticketArr = $supportService->publicToApiArray($ticketObj, true, $identity); - $email = array(); - $email['to'] = $ticketArr['author_email']; + $email = []; + $email['to'] = $ticketArr['author_email']; $email['to_name'] = $ticketArr['author_name']; - $email['code'] = 'mod_support_pticket_staff_reply'; - $email['ticket'] = $ticketArr; + $email['code'] = 'mod_support_pticket_staff_reply'; + $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { error_log($exc->getMessage()); @@ -188,18 +187,18 @@ class Service implements \Box\InjectionAwareInterface $di = $event->getDi(); $supportService = $di['mod_service']('support'); $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); + $params = $event->getParameters(); try { $ticketObj = $supportService->getPublicTicketById($params['id']); - $identity = $di['loggedin_admin']; + $identity = $di['loggedin_admin']; $ticketArr = $supportService->publicToApiArray($ticketObj, true, $identity); - $email = array(); - $email['to'] = $ticketArr['author_email']; + $email = []; + $email['to'] = $ticketArr['author_email']; $email['to_name'] = $ticketArr['author_name']; - $email['code'] = 'mod_support_pticket_staff_close'; - $email['ticket'] = $ticketArr; + $email['code'] = 'mod_support_pticket_staff_close'; + $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { error_log($exc->getMessage()); @@ -213,35 +212,36 @@ class Service implements \Box\InjectionAwareInterface public function getPublicTicketById($id) { - return $this->di['db']->getExistingModelById('SupportPTicket', $id, 'Ticket not found');; + return $this->di['db']->getExistingModelById('SupportPTicket', $id, 'Ticket not found'); } /** - * Return array of ticket statuses + * Return array of ticket statuses. */ public function getStatuses() { - $data = array( + $data = [ \Model_SupportTicket::OPENED => 'Open', \Model_SupportTicket::ONHOLD => 'On hold', \Model_SupportTicket::CLOSED => 'Closed', - ); + ]; return $data; } /** - * Find ticket for client - * @param \Model_Client $c + * Find ticket for client. + * * @param int $id + * * @return \Model_SupportTicket */ public function findOneByClient(\Model_Client $c, $id) { - $bindings = array( - ':id' => $id, - ':client_id' => $c->id - ); + $bindings = [ + ':id' => $id, + ':client_id' => $c->id, + ]; $ticket = $this->di['db']->findOne('SupportTicket', 'id = :id AND client_id = :client_id', $bindings); @@ -254,126 +254,126 @@ class Service implements \Box\InjectionAwareInterface public function getSearchQuery($data) { - $query = "SELECT st.* + $query = 'SELECT st.* FROM support_ticket st JOIN support_ticket_message stm ON stm.support_ticket_id = st.id - LEFT JOIN client c ON st.client_id = c.id"; + LEFT JOIN client c ON st.client_id = c.id'; - $search = $this->di['array_get']($data, 'search', NULL); - $id = $this->di['array_get']($data, 'id', NULL); - $status = $this->di['array_get']($data, 'status', NULL); - $client = $this->di['array_get']($data, 'client', NULL); - $client_id = $this->di['array_get']($data, 'client_id', NULL); - $order_id = $this->di['array_get']($data, 'order_id', NULL); - $subject = $this->di['array_get']($data, 'subject', NULL); - $content = $this->di['array_get']($data, 'content', NULL); - $helpdesk = $this->di['array_get']($data, 'support_helpdesk_id', NULL); - $created_at = $this->di['array_get']($data, 'created_at', NULL); - $date_from = $this->di['array_get']($data, 'date_from', NULL); - $date_to = $this->di['array_get']($data, 'date_to', NULL); - $priority = $this->di['array_get']($data, 'priority', NULL); + $search = $this->di['array_get']($data, 'search', null); + $id = $this->di['array_get']($data, 'id', null); + $status = $this->di['array_get']($data, 'status', null); + $client = $this->di['array_get']($data, 'client', null); + $client_id = $this->di['array_get']($data, 'client_id', null); + $order_id = $this->di['array_get']($data, 'order_id', null); + $subject = $this->di['array_get']($data, 'subject', null); + $content = $this->di['array_get']($data, 'content', null); + $helpdesk = $this->di['array_get']($data, 'support_helpdesk_id', null); + $created_at = $this->di['array_get']($data, 'created_at', null); + $date_from = $this->di['array_get']($data, 'date_from', null); + $date_to = $this->di['array_get']($data, 'date_to', null); + $priority = $this->di['array_get']($data, 'priority', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; if ($id) { - $where[] = "st.id = :ticket_id"; + $where[] = 'st.id = :ticket_id'; $bindings[':ticket_id'] = $id; } if ($priority) { - $where[] = "st.priority = :priority"; + $where[] = 'st.priority = :priority'; $bindings[':priority'] = $priority; } if ($helpdesk) { - $where[] = "st.support_helpdesk_id = :support_helpdesk_id"; + $where[] = 'st.support_helpdesk_id = :support_helpdesk_id'; $bindings[':support_helpdesk_id'] = $helpdesk; } if ($client) { - $where[] = "c.first_name LIKE :first_name"; - $where[] = "c.last_name LIKE :last_name"; - $bindings[':first_name'] = "%" . $client . "%"; - $bindings[':last_name'] = "%" . $client . "%"; + $where[] = 'c.first_name LIKE :first_name'; + $where[] = 'c.last_name LIKE :last_name'; + $bindings[':first_name'] = '%'.$client.'%'; + $bindings[':last_name'] = '%'.$client.'%'; } if ($client_id) { - $where[] = "c.id = :client_id"; + $where[] = 'c.id = :client_id'; $bindings[':client_id'] = $client_id; } if ($content) { - $where[] = "stm.content LIKE :content"; - $bindings[':content'] = "%" . $content . "%"; + $where[] = 'stm.content LIKE :content'; + $bindings[':content'] = '%'.$content.'%'; } if ($subject) { - $where[] = "st.subject LIKE :subject"; - $bindings[':subject'] = "%" . $subject . "%"; + $where[] = 'st.subject LIKE :subject'; + $bindings[':subject'] = '%'.$subject.'%'; } if ($status) { - $where[] = "st.status = :status"; + $where[] = 'st.status = :status'; $bindings[':status'] = $status; } if ($order_id) { - $where[] = "st.rel_type = :rel_type AND st.rel_id = :rel_id"; + $where[] = 'st.rel_type = :rel_type AND st.rel_id = :rel_id'; $bindings[':rel_type'] = \Model_SupportTicket::REL_TYPE_ORDER; - $bindings[':rel_id'] = $order_id; + $bindings[':rel_id'] = $order_id; } if ($created_at) { - $where[] = "DATE_FORMAT(st.created_at, '%Y-%m-%d') = :created_at"; + $where[] = "DATE_FORMAT(st.created_at, '%Y-%m-%d') = :created_at"; $bindings[':created_at'] = date('Y-m-d', strtotime($created_at)); } if ($date_from) { - $where[] = "UNIX_TIMESTAMP(st.created_at) >= :date_from"; + $where[] = 'UNIX_TIMESTAMP(st.created_at) >= :date_from'; $bindings[':date_from'] = strtotime($date_from); } if ($date_to) { - $where[] = "UNIX_TIMESTAMP(st.created_at) <= :date_to"; + $where[] = 'UNIX_TIMESTAMP(st.created_at) <= :date_to'; $bindings[':date_to'] = strtotime($date_to); } - //smartSearch + // smartSearch if ($search) { if (is_numeric($search)) { - $where[] = "st.id = :ticket_id"; + $where[] = 'st.id = :ticket_id'; $bindings[':ticket_id'] = $search; } else { - $search = "%" . $search . "%"; - $where[] = "(stm.content LIKE :content OR st.subject LIKE :subject)"; + $search = '%'.$search.'%'; + $where[] = '(stm.content LIKE :content OR st.subject LIKE :subject)'; $bindings[':content'] = $search; $bindings[':subject'] = $search; } } if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); + $query = $query.' WHERE '.implode(' AND ', $where); } - $query .= " GROUP BY st.id ORDER BY st.priority ASC, st.id DESC"; + $query .= ' GROUP BY st.id ORDER BY st.priority ASC, st.id DESC'; - return array($query, $bindings); + return [$query, $bindings]; } public function counter() { - $query = "SELECT status, COUNT(id) as counter + $query = 'SELECT status, COUNT(id) as counter FROM support_ticket - GROUP BY status"; + GROUP BY status'; $data = $this->di['db']->getAssoc($query); - return array( - 'total' => array_sum($data), + return [ + 'total' => array_sum($data), \Model_SupportTicket::OPENED => $this->di['array_get']($data, \Model_SupportTicket::OPENED, 0), \Model_SupportTicket::CLOSED => $this->di['array_get']($data, \Model_SupportTicket::CLOSED, 0), \Model_SupportTicket::ONHOLD => $this->di['array_get']($data, \Model_SupportTicket::ONHOLD, 0), - ); + ]; } public function getLatest() @@ -383,16 +383,16 @@ class Service implements \Box\InjectionAwareInterface public function getExpired() { - $bindings = array( - ':status' => \Model_SupportTicket::ONHOLD - ); + $bindings = [ + ':status' => \Model_SupportTicket::ONHOLD, + ]; - $sql = "SELECT st.* + $sql = 'SELECT st.* FROM support_ticket as st LEFT JOIN support_helpdesk sh ON sh.id = st.support_helpdesk_id WHERE st.status = :status AND DATE_ADD(st.updated_at, INTERVAL sh.close_after HOUR) < NOW() - ORDER BY st.id ASC"; + ORDER BY st.id ASC'; return $this->di['db']->getAll($sql, $bindings); } @@ -402,7 +402,7 @@ class Service implements \Box\InjectionAwareInterface $query = "SELECT COUNT(m.id) as counter FROM support_ticket WHERE 'status' = :'status' GROUP BY 'status' LIMIT 1"; - return $this->di['db']->getCell($query, array(':status' => $status)); + return $this->di['db']->getCell($query, [':status' => $status]); } public function getActiveTicketsCountForOrder(\Model_ClientOrder $model) @@ -412,24 +412,24 @@ class Service implements \Box\InjectionAwareInterface AND rel_type = 'order' AND (status = :status1 OR status = :status2)"; - $bindings = array( + $bindings = [ ':order_id' => $model->id, - ':status1' => \Model_SupportTicket::OPENED, - ':status2' => \Model_SupportTicket::ONHOLD, - ); + ':status1' => \Model_SupportTicket::OPENED, + ':status2' => \Model_SupportTicket::ONHOLD, + ]; return $this->di['db']->getCell($query, $bindings); } public function checkIfTaskAlreadyExists(\Model_Client $client, $rel_id, $rel_type, $rel_task) { - $bindings = array( - ':client_id' => $client->id, - ':rel_id' => $rel_id, - ':rel_type' => $rel_type, - ':rel_task' => $rel_task, - ':rel_status' => \Model_SupportTicket::REL_STATUS_PENDING - ); + $bindings = [ + ':client_id' => $client->id, + ':rel_id' => $rel_id, + ':rel_type' => $rel_type, + ':rel_task' => $rel_task, + ':rel_status' => \Model_SupportTicket::REL_STATUS_PENDING, + ]; $ticket = $this->di['db']->findOne( 'SupportTicket', @@ -440,20 +440,20 @@ class Service implements \Box\InjectionAwareInterface AND rel_status = :rel_status', $bindings); - return ($ticket instanceof \Model_SupportTicket); + return $ticket instanceof \Model_SupportTicket; } public function closeTicket(\Model_SupportTicket $ticket, $identity) { - $ticket->status = \Model_SupportTicket::CLOSED; + $ticket->status = \Model_SupportTicket::CLOSED; $ticket->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($ticket); if ($identity instanceof \Model_Admin) { - $this->di['events_manager']->fire(array('event' => 'onAfterAdminCloseTicket', 'params' => array('id' => $ticket->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminCloseTicket', 'params' => ['id' => $ticket->id]]); } elseif ($identity instanceof \Model_Client) { - $this->di['events_manager']->fire(array('event' => 'onAfterClientCloseTicket', 'params' => array('id' => $ticket->id))); + $this->di['events_manager']->fire(['event' => 'onAfterClientCloseTicket', 'params' => ['id' => $ticket->id]]); } $this->di['logger']->info('Closed ticket "%s"', $ticket->id); @@ -463,45 +463,45 @@ class Service implements \Box\InjectionAwareInterface public function autoClose(\Model_SupportTicket $model) { - $model->status = \Model_SupportTicket::CLOSED; + $model->status = \Model_SupportTicket::CLOSED; $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Ticket %s was closed', $model->id); - return TRUE; + return true; } public function canBeReopened(\Model_SupportTicket $model) { - if ($model->status != \Model_SupportTicket::CLOSED) { + if (\Model_SupportTicket::CLOSED != $model->status) { return true; } $helpdesk = $this->di['db']->getExistingModelById('SupportHelpdesk', $model->support_helpdesk_id); - return (bool)$helpdesk->can_reopen; + return (bool) $helpdesk->can_reopen; } private function _getRelDetails(\Model_SupportTicket $model) { if (!$model->rel_type || !$model->rel_id) { - return array(); + return []; } - $result = array( - 'id' => $model->rel_id, - 'type' => $model->rel_type, - 'task' => $model->rel_task, + $result = [ + 'id' => $model->rel_id, + 'type' => $model->rel_type, + 'task' => $model->rel_task, 'new_value' => $model->rel_new_value, - 'status' => $model->rel_status, - ); + 'status' => $model->rel_status, + ]; $client = $this->di['db']->load('Client', $model->client_id); - if ($model->rel_type == \Model_SupportTicket::REL_TYPE_ORDER) { + if (\Model_SupportTicket::REL_TYPE_ORDER == $model->rel_type) { $orderService = $this->di['mod_service']('order'); - $o = $orderService->findForClientById($client, $model->rel_id); + $o = $orderService->findForClientById($client, $model->rel_id); if ($o instanceof \Model_ClientOrder) { $result['order'] = $orderService->toApiArray($o, false); } @@ -512,7 +512,7 @@ class Service implements \Box\InjectionAwareInterface public function rmByClient(\Model_Client $client) { - $clientTickets = $this->di['db']->find('SupportTicket', 'client_id = :client_id', array(':client_id' => $client->id)); + $clientTickets = $this->di['db']->find('SupportTicket', 'client_id = :client_id', [':client_id' => $client->id]); foreach ($clientTickets as $ticket) { $this->di['db']->trash($ticket); } @@ -520,12 +520,12 @@ class Service implements \Box\InjectionAwareInterface public function rm(\Model_SupportTicket $model) { - $supportTicketNotes = $this->di['db']->find('SupportTicketNote', 'support_ticket_id = :support_ticket_id', array(':support_ticket_id' => $model->id)); + $supportTicketNotes = $this->di['db']->find('SupportTicketNote', 'support_ticket_id = :support_ticket_id', [':support_ticket_id' => $model->id]); foreach ($supportTicketNotes as $note) { $this->di['db']->trash($note); } - $supportTicketMessages = $this->di['db']->find('SupportTicketMessage', 'support_ticket_id = :support_ticket_id', array(':support_ticket_id' => $model->id)); + $supportTicketMessages = $this->di['db']->find('SupportTicketMessage', 'support_ticket_id = :support_ticket_id', [':support_ticket_id' => $model->id]); foreach ($supportTicketMessages as $message) { $this->di['db']->trash($message); } @@ -541,14 +541,14 @@ class Service implements \Box\InjectionAwareInterface public function toApiArray(\Model_SupportTicket $model, $deep = true, $identity = null) { - $firstSupportTicketMessage = $this->di['db']->findOne('SupportTicketMessage', 'support_ticket_id = :support_ticket_id ORDER by id ASC LIMIT 1', array(':support_ticket_id' => $model->id)); - $supportHelpdesk = $this->di['db']->load('SupportHelpdesk', $model->support_helpdesk_id); + $firstSupportTicketMessage = $this->di['db']->findOne('SupportTicketMessage', 'support_ticket_id = :support_ticket_id ORDER by id ASC LIMIT 1', [':support_ticket_id' => $model->id]); + $supportHelpdesk = $this->di['db']->load('SupportHelpdesk', $model->support_helpdesk_id); - $data = $this->di['db']->toArray($model); - $data['replies'] = $this->messageGetRepliesCount($model); - $data['first'] = $this->messageToApiArray($firstSupportTicketMessage); + $data = $this->di['db']->toArray($model); + $data['replies'] = $this->messageGetRepliesCount($model); + $data['first'] = $this->messageToApiArray($firstSupportTicketMessage); $data['helpdesk'] = $this->helpdeskToApiArray($supportHelpdesk); - $data['client'] = $this->getClientApiArrayForTicket($model); + $data['client'] = $this->getClientApiArrayForTicket($model); if ($deep) { $messages = $this->messageGetTicketMessages($model); @@ -558,9 +558,9 @@ class Service implements \Box\InjectionAwareInterface } if ($identity instanceof \Model_Admin) { - $data['rel'] = $this->_getRelDetails($model); - $data['priority'] = $model->priority; - $supportTicketNotes = $this->di['db']->find('SupportTicketNote', 'support_ticket_id = :support_ticket_id', array(':support_ticket_id' => $model->id)); + $data['rel'] = $this->_getRelDetails($model); + $data['priority'] = $model->priority; + $supportTicketNotes = $this->di['db']->find('SupportTicketNote', 'support_ticket_id = :support_ticket_id', [':support_ticket_id' => $model->id]); foreach ($supportTicketNotes as $note) { $data['notes'][] = $this->noteToApiArray($note); @@ -579,9 +579,9 @@ class Service implements \Box\InjectionAwareInterface return $clientService->toApiArray($client); } else { - error_log('Missing client for ticket ' . $ticket->id); + error_log('Missing client for ticket '.$ticket->id); - return array(); + return []; } } @@ -589,10 +589,10 @@ class Service implements \Box\InjectionAwareInterface { $admin = $this->di['db']->load('Admin', $model->admin_id); - return array( - 'name' => $admin->getFullName(), + return [ + 'name' => $admin->getFullName(), 'email' => $admin->email, - ); + ]; } public function noteRm(\Model_SupportTicketNote $model) @@ -607,7 +607,7 @@ class Service implements \Box\InjectionAwareInterface public function noteToApiArray(\Model_SupportTicketNote $model, $deep = false, $identity = null) { - $data = $this->di['db']->toArray($model); + $data = $this->di['db']->toArray($model); $data['author'] = $this->noteGetAuthorDetails($model); return $data; @@ -615,44 +615,45 @@ class Service implements \Box\InjectionAwareInterface public function helpdeskGetSearchQuery($data) { - $query = "SELECT * FROM support_helpdesk"; + $query = 'SELECT * FROM support_helpdesk'; - $search = $this->di['array_get']($data, 'search', NULL); + $search = $this->di['array_get']($data, 'search', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; if ($search) { - $search = "%" . $search . "%"; - $where[] = "(name LIKE :name OR email LIKE :email OR signature LIKE :signature)"; - $bindings[':name'] = $search; - $bindings[':email'] = $search; + $search = '%'.$search.'%'; + $where[] = '(name LIKE :name OR email LIKE :email OR signature LIKE :signature)'; + $bindings[':name'] = $search; + $bindings[':email'] = $search; $bindings[':signature'] = $search; } if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); + $query = $query.' WHERE '.implode(' AND ', $where); } - $query .= " ORDER BY id DESC"; + $query .= ' ORDER BY id DESC'; - return array($query, $bindings); + return [$query, $bindings]; } public function helpdeskGetPairs() { - return $this->di['db']->getAssoc("SELECT id, name FROM support_helpdesk");; + return $this->di['db']->getAssoc('SELECT id, name FROM support_helpdesk'); } public function helpdeskRm(\Model_SupportHelpdesk $model) { $id = $model->id; - $tickets = $this->di['db']->find('SupportTicket', 'support_helpdesk_id = :support_helpdesk_id', array(':support_helpdesk_id' => $model->id)); + $tickets = $this->di['db']->find('SupportTicket', 'support_helpdesk_id = :support_helpdesk_id', [':support_helpdesk_id' => $model->id]); if (count($tickets) > 0) { throw new \Box_Exception('Can not remove helpdesk which has tickets'); } $this->di['db']->trash($model); $this->di['logger']->info('Deleted helpdesk #%s', $id); + return true; } @@ -663,19 +664,19 @@ class Service implements \Box\InjectionAwareInterface public function messageGetTicketMessages(\Model_SupportTicket $model) { - return $this->di['db']->find('supportTicketMessage', 'support_ticket_id = :support_ticket_id ORDER BY id ASC', array(':support_ticket_id' => $model->id)); + return $this->di['db']->find('supportTicketMessage', 'support_ticket_id = :support_ticket_id ORDER BY id ASC', [':support_ticket_id' => $model->id]); } public function messageGetRepliesCount(\Model_SupportTicket $model) { - $query = "SELECT COUNT(id) as counter + $query = 'SELECT COUNT(id) as counter FROM support_ticket_message WHERE support_ticket_id = :support_ticket_id - GROUP BY support_ticket_id"; + GROUP BY support_ticket_id'; - $bindings = array( - ':support_ticket_id' => $model->id - ); + $bindings = [ + ':support_ticket_id' => $model->id, + ]; return $this->di['db']->getCell($query, $bindings); } @@ -685,18 +686,18 @@ class Service implements \Box\InjectionAwareInterface if ($model->admin_id) { $author = $this->di['db']->load('Admin', $model->admin_id); } else { - $author = $this->di['db']->load('Client', $model->client_id);; + $author = $this->di['db']->load('Client', $model->client_id); } - return array( - 'name' => $author->getFullName(), + return [ + 'name' => $author->getFullName(), 'email' => $author->email, - ); + ]; } public function messageToApiArray(\Model_SupportTicketMessage $model) { - $data = $this->di['db']->toArray($model); + $data = $this->di['db']->toArray($model); $data['author'] = $this->messageGetAuthorDetails($model); return $data; @@ -719,7 +720,7 @@ class Service implements \Box\InjectionAwareInterface public function ticketMessageUpdate(\Model_SupportTicketMessage $model, $content) { - $model->content = $content; + $model->content = $content; $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); @@ -732,18 +733,18 @@ class Service implements \Box\InjectionAwareInterface */ public function ticketReply(\Model_SupportTicket $ticket, $identity, $content) { - $msg = $this->di['db']->dispense('SupportTicketMessage'); + $msg = $this->di['db']->dispense('SupportTicketMessage'); $msg->support_ticket_id = $ticket->id; if ($identity instanceof \Model_Admin) { $msg->admin_id = $identity->id; } elseif ($identity instanceof \Model_Client) { $msg->client_id = $identity->id; } - $msg->content = $content; - $msg->ip = $this->di['request']->getClientAddress(); + $msg->content = $content; + $msg->ip = $this->di['request']->getClientAddress(); $msg->created_at = date('Y-m-d H:i:s'); $msg->updated_at = date('Y-m-d H:i:s'); - $msgId = $this->di['db']->store($msg); + $msgId = $this->di['db']->store($msg); if ($identity instanceof \Model_Admin) { $ticket->status = \Model_SupportTicket::ONHOLD; @@ -755,9 +756,9 @@ class Service implements \Box\InjectionAwareInterface $this->di['db']->store($ticket); if ($identity instanceof \Model_Admin) { - $this->di['events_manager']->fire(array('event' => 'onAfterAdminReplyTicket', 'params' => array('id' => $ticket->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminReplyTicket', 'params' => ['id' => $ticket->id]]); } elseif ($identity instanceof \Model_Client) { - $this->di['events_manager']->fire(array('event' => 'onAfterClientReplyTicket', 'params' => array('id' => $ticket->id))); + $this->di['events_manager']->fire(['event' => 'onAfterClientReplyTicket', 'params' => ['id' => $ticket->id]]); } $this->di['logger']->info('Replied to ticket "%s"', $ticket->id); @@ -769,71 +770,70 @@ class Service implements \Box\InjectionAwareInterface { $status = $this->di['array_get']($data, 'status', \Model_SupportTicket::ONHOLD); - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminOpenTicket', 'params' => $data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminOpenTicket', 'params' => $data]); - $ticket = $this->di['db']->dispense('SupportTicket');; - $ticket->client_id = $client->id; - $ticket->status = $status; - $ticket->subject = $data['subject']; + $ticket = $this->di['db']->dispense('SupportTicket'); + $ticket->client_id = $client->id; + $ticket->status = $status; + $ticket->subject = $data['subject']; $ticket->support_helpdesk_id = $helpdesk->id; - $ticket->created_at = date('Y-m-d H:i:s'); - $ticket->updated_at = date('Y-m-d H:i:s'); - $ticketId = $this->di['db']->store($ticket); + $ticket->created_at = date('Y-m-d H:i:s'); + $ticket->updated_at = date('Y-m-d H:i:s'); + $ticketId = $this->di['db']->store($ticket); - $msg = $this->di['db']->dispense('SupportTicketMessage'); - $msg->admin_id = $identity->id; + $msg = $this->di['db']->dispense('SupportTicketMessage'); + $msg->admin_id = $identity->id; $msg->support_ticket_id = $ticketId; - $msg->content = $data['content']; - $msg->ip = $this->di['request']->getClientAddress(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); + $msg->content = $data['content']; + $msg->ip = $this->di['request']->getClientAddress(); + $msg->created_at = date('Y-m-d H:i:s'); + $msg->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($msg); - - $this->di['events_manager']->fire(array('event' => 'onAfterAdminOpenTicket', 'params' => array('id' => $ticketId))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminOpenTicket', 'params' => ['id' => $ticketId]]); $this->di['logger']->info('Admin opened new ticket "%s"', $ticketId); - return (int)$ticketId; + return (int) $ticketId; } public function ticketCreateForGuest($data) { $this->di['validator']->isEmailValid($data['email']); - $event_params = $data; + $event_params = $data; $event_params['ip'] = $this->di['request']->getClientAddress(); - $altered = $this->di['events_manager']->fire(array('event' => 'onBeforeGuestPublicTicketOpen', 'params' => $event_params)); + $altered = $this->di['events_manager']->fire(['event' => 'onBeforeGuestPublicTicketOpen', 'params' => $event_params]); $status = 'open'; $subject = $this->di['array_get']($data, 'subject'); $message = $this->di['array_get']($data, 'message'); - if (is_array($altered)){ - $status = $this->di['array_get']($altered, 'status'); + if (is_array($altered)) { + $status = $this->di['array_get']($altered, 'status'); $subject = $this->di['array_get']($altered, 'subject'); $message = $this->di['array_get']($altered, 'message'); } - $ticket = $this->di['db']->dispense('SupportPTicket'); - $ticket->hash = sha1(random_bytes(13)); - $ticket->author_name = $data['name']; + $ticket = $this->di['db']->dispense('SupportPTicket'); + $ticket->hash = sha1(random_bytes(13)); + $ticket->author_name = $data['name']; $ticket->author_email = $data['email']; - $ticket->subject = $subject; - $ticket->status = $status; - $ticket->created_at = date('Y-m-d H:i:s'); - $ticket->updated_at = date('Y-m-d H:i:s'); - $ticketId = $this->di['db']->store($ticket); + $ticket->subject = $subject; + $ticket->status = $status; + $ticket->created_at = date('Y-m-d H:i:s'); + $ticket->updated_at = date('Y-m-d H:i:s'); + $ticketId = $this->di['db']->store($ticket); - $msg = $this->di['db']->dispense('SupportPTicketMessage'); + $msg = $this->di['db']->dispense('SupportPTicketMessage'); $msg->support_p_ticket_id = $ticket->id; - $msg->content = $message; - $msg->ip = $this->di['request']->getClientAddress(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); + $msg->content = $message; + $msg->ip = $this->di['request']->getClientAddress(); + $msg->created_at = date('Y-m-d H:i:s'); + $msg->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($msg); - $this->di['events_manager']->fire(array('event' => 'onAfterGuestPublicTicketOpen', 'params' => array('id' => $ticketId))); + $this->di['events_manager']->fire(['event' => 'onAfterGuestPublicTicketOpen', 'params' => ['id' => $ticketId]]); $this->di['logger']->info('"%s" opened public ticket "%s"', $ticket->author_email, $ticketId); @@ -844,7 +844,7 @@ class Service implements \Box\InjectionAwareInterface { $hours = $config['wait_hours']; - $lastTicket = $this->di['db']->findOne('SupportTicket', 'client_id = :client_id ORDER BY created_at DESC', array(':client_id' => $client->id)); + $lastTicket = $this->di['db']->findOne('SupportTicket', 'client_id = :client_id ORDER BY created_at DESC', [':client_id' => $client->id]); if (!$lastTicket instanceof \Model_SupportTicket) { return true; } @@ -860,59 +860,57 @@ class Service implements \Box\InjectionAwareInterface public function ticketCreateForClient(\Model_Client $client, \Model_SupportHelpdesk $helpdesk, array $data) { - //@todo validate task params - $rel_id = $this->di['array_get']($data, 'rel_id', NULL); - $rel_type = $this->di['array_get']($data, 'rel_type', NULL); + // @todo validate task params + $rel_id = $this->di['array_get']($data, 'rel_id', null); + $rel_type = $this->di['array_get']($data, 'rel_type', null); - - if (!is_null($rel_id) && $rel_type == \Model_SupportTicket::REL_TYPE_ORDER) { + if (!is_null($rel_id) && \Model_SupportTicket::REL_TYPE_ORDER == $rel_type) { $orderService = $this->di['mod_service']('order'); - $o = $orderService->findForClientById($client, $rel_id); + $o = $orderService->findForClientById($client, $rel_id); if (!$o instanceof \Model_ClientOrder) { - throw new \Box_Exception('Order ID does not exist'); + throw new \Box_Exception('Order ID does not exist'); } } - $rel_task = $this->di['array_get']($data, 'rel_task', NULL); - $rel_new_value = $this->di['array_get']($data, 'rel_new_value', NULL); - $rel_status = isset($data['rel_task']) ? \Model_SupportTicket::REL_STATUS_PENDING : \Model_SupportTicket::REL_STATUS_COMPLETE; + $rel_task = $this->di['array_get']($data, 'rel_task', null); + $rel_new_value = $this->di['array_get']($data, 'rel_new_value', null); + $rel_status = isset($data['rel_task']) ? \Model_SupportTicket::REL_STATUS_PENDING : \Model_SupportTicket::REL_STATUS_COMPLETE; // check if support ticket with same uncompleted task already exists if ($rel_id && $rel_type && $rel_task && $this->checkIfTaskAlreadyExists($client, $rel_id, $rel_type, $rel_task)) { throw new \Box_Exception('We have already received this request.'); } - $mod = $this->di['mod']('support'); + $mod = $this->di['mod']('support'); $config = $mod->getConfig(); if (isset($config['wait_hours']) && is_numeric($config['wait_hours'])) { $this->canClientSubmitNewTicket($client, $config); } - $event_params = $data; + $event_params = $data; $event_params['client_id'] = $client->id; - $this->di['events_manager']->fire(array('event' => 'onBeforeClientOpenTicket', 'params' => $event_params)); + $this->di['events_manager']->fire(['event' => 'onBeforeClientOpenTicket', 'params' => $event_params]); - - $ticket = $this->di['db']->dispense('SupportTicket'); - $ticket->client_id = $client->id; - $ticket->subject = $data['subject']; + $ticket = $this->di['db']->dispense('SupportTicket'); + $ticket->client_id = $client->id; + $ticket->subject = $data['subject']; $ticket->support_helpdesk_id = $helpdesk->id; - $ticket->created_at = date('Y-m-d H:i:s'); - $ticket->updated_at = date('Y-m-d H:i:s'); + $ticket->created_at = date('Y-m-d H:i:s'); + $ticket->updated_at = date('Y-m-d H:i:s'); // related task with ticket - $ticket->rel_id = $rel_id; - $ticket->rel_type = $rel_type; - $ticket->rel_task = $rel_task; + $ticket->rel_id = $rel_id; + $ticket->rel_type = $rel_type; + $ticket->rel_task = $rel_task; $ticket->rel_new_value = $rel_new_value; - $ticket->rel_status = $rel_status; + $ticket->rel_status = $rel_status; $ticketId = $this->di['db']->store($ticket); $this->messageCreateForTicket($ticket, $client, $data['content']); - $this->di['events_manager']->fire(array('event' => 'onAfterClientOpenTicket', 'params' => array('id' => $ticket->id))); + $this->di['events_manager']->fire(['event' => 'onAfterClientOpenTicket', 'params' => ['id' => $ticket->id]]); if (isset($config['autorespond_enable']) && $config['autorespond_enable'] @@ -924,20 +922,19 @@ class Service implements \Box\InjectionAwareInterface $this->di['logger']->info('Submitted new ticket "%s"', $ticketId); - return (int)$ticketId; + return (int) $ticketId; } private function cannedReply(\Model_SupportTicket $ticket, $cannedId) { try { - $cannedObj = $this->di['db']->getExistingModelById('SupportPr', $cannedId, 'Canned reply not found'); - $canned = $this->cannedToApiArray($cannedObj); + $cannedObj = $this->di['db']->getExistingModelById('SupportPr', $cannedId, 'Canned reply not found'); + $canned = $this->cannedToApiArray($cannedObj); $staffService = $this->di['mod_service']('staff'); - $admin = $staffService->getCronAdmin(); + $admin = $staffService->getCronAdmin(); if (isset($canned['content']) && $admin instanceof \Model_Admin) { $this->ticketReply($ticket, $admin, $canned['content']); } - } catch (\Exception $e) { error_log($e->getMessage()); } @@ -948,7 +945,7 @@ class Service implements \Box\InjectionAwareInterface */ public function messageCreateForTicket(\Model_SupportTicket $ticket, $identity, $content) { - $msg = $this->di['db']->dispense('SupportTicketMessage'); + $msg = $this->di['db']->dispense('SupportTicketMessage'); $msg->support_ticket_id = $ticket->id; if ($identity instanceof \Model_Admin) { $msg->admin_id = $identity->id; @@ -957,8 +954,8 @@ class Service implements \Box\InjectionAwareInterface } else { throw new \Box_Exception('Identity is not valid'); } - $msg->content = $content; - $msg->ip = $this->di['request']->getClientAddress(); + $msg->content = $content; + $msg->ip = $this->di['request']->getClientAddress(); $msg->created_at = date('Y-m-d H:i:s'); $msg->updated_at = date('Y-m-d H:i:s'); @@ -967,20 +964,20 @@ class Service implements \Box\InjectionAwareInterface public function publicGetStatuses() { - $data = array( + $data = [ \Model_SupportPTicket::OPENED => 'Open', \Model_SupportPTicket::ONHOLD => 'On hold', \Model_SupportPTicket::CLOSED => 'Closed', - ); + ]; return $data; } public function publicFindOneByHash($hash) { - $bindings = array( - ':hash' => $hash - ); + $bindings = [ + ':hash' => $hash, + ]; $publicTicket = $this->di['db']->findOne('SupportPTicket', 'hash = :hash', $bindings); if (!$publicTicket instanceof \Model_SupportPTicket) { @@ -992,88 +989,88 @@ class Service implements \Box\InjectionAwareInterface public function publicGetSearchQuery($data) { - $query = "SELECT spt.* FROM support_p_ticket spt + $query = 'SELECT spt.* FROM support_p_ticket spt LEFT JOIN support_p_ticket_message sptm - ON spt.id = sptm.support_p_ticket_id"; + ON spt.id = sptm.support_p_ticket_id'; - $search = $this->di['array_get']($data, 'search', NULL); + $search = $this->di['array_get']($data, 'search', null); - $id = $this->di['array_get']($data, 'id', NULL); - $status = $this->di['array_get']($data, 'status', NULL); - $name = $this->di['array_get']($data, 'name', NULL); - $email = $this->di['array_get']($data, 'email', NULL); - $subject = $this->di['array_get']($data, 'subject', NULL); - $content = $this->di['array_get']($data, 'content', NULL); + $id = $this->di['array_get']($data, 'id', null); + $status = $this->di['array_get']($data, 'status', null); + $name = $this->di['array_get']($data, 'name', null); + $email = $this->di['array_get']($data, 'email', null); + $subject = $this->di['array_get']($data, 'subject', null); + $content = $this->di['array_get']($data, 'content', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; if ($id) { - $where[] = "spt.id = :p_ticket_id"; + $where[] = 'spt.id = :p_ticket_id'; $bindings[':p_ticket_id'] = $id; } if ($status) { - $where[] = "spt.status = :p_ticket_status"; + $where[] = 'spt.status = :p_ticket_status'; $bindings[':p_ticket_status'] = $status; } if ($email) { - $where[] = "spt.author_email = :p_ticket_author_email"; + $where[] = 'spt.author_email = :p_ticket_author_email'; $bindings[':p_ticket_author_email'] = $email; } if ($name) { - $where[] = "spt.author_name = :p_ticket_author_name"; + $where[] = 'spt.author_name = :p_ticket_author_name'; $bindings[':p_ticket_author_name'] = $name; } if ($content) { - $where[] = "spt.content LIKE :p_ticket_content"; + $where[] = 'spt.content LIKE :p_ticket_content'; $bindings[':p_ticket_content'] = "%$content%"; } if ($subject) { - $where[] = "spt.subject LIKE :p_ticket_subject"; + $where[] = 'spt.subject LIKE :p_ticket_subject'; $bindings[':p_ticket_subject'] = "%$subject%"; } - //smartSearch + // smartSearch if ($search) { if (is_numeric($search)) { - $where[] = "spt.id = :p_ticket_id"; + $where[] = 'spt.id = :p_ticket_id'; $bindings[':p_ticket_id'] = $search; } else { - $search = "%" . $search . "%"; - $where[] = "sptm.content LIKE :p_message_content OR spt.subject LIKE :p_ticket_subject"; + $search = '%'.$search.'%'; + $where[] = 'sptm.content LIKE :p_message_content OR spt.subject LIKE :p_ticket_subject'; $bindings[':p_message_content'] = $search; - $bindings[':p_ticket_subject'] = $search; + $bindings[':p_ticket_subject'] = $search; } } if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); + $query = $query.' WHERE '.implode(' AND ', $where); } - $query .= " GROUP BY spt.id, sptm.id ORDER BY spt.id DESC, sptm.id ASC"; + $query .= ' GROUP BY spt.id, sptm.id ORDER BY spt.id DESC, sptm.id ASC'; - return array($query, $bindings); + return [$query, $bindings]; } public function publicCounter() { - $query = "SELECT status, COUNT(id) as counter + $query = 'SELECT status, COUNT(id) as counter FROM support_p_ticket - GROUP BY status"; + GROUP BY status'; $data = $this->di['db']->getAssoc($query); - return array( - 'total' => array_sum($data), - \Model_SupportPTicket::OPENED => isset($data[\Model_SupportPTicket::OPENED]) ? $data[\Model_SupportPTicket::OPENED] : 0, - \Model_SupportPTicket::CLOSED => isset($data[\Model_SupportPTicket::CLOSED]) ? $data[\Model_SupportPTicket::CLOSED] : 0, - \Model_SupportPTicket::ONHOLD => isset($data[\Model_SupportPTicket::ONHOLD]) ? $data[\Model_SupportPTicket::ONHOLD] : 0, - ); + return [ + 'total' => array_sum($data), + \Model_SupportPTicket::OPENED => $data[\Model_SupportPTicket::OPENED] ?? 0, + \Model_SupportPTicket::CLOSED => $data[\Model_SupportPTicket::CLOSED] ?? 0, + \Model_SupportPTicket::ONHOLD => $data[\Model_SupportPTicket::ONHOLD] ?? 0, + ]; } public function publicGetLatest() @@ -1083,19 +1080,19 @@ class Service implements \Box\InjectionAwareInterface public function publicCountByStatus($status) { - $query = "SELECT COUNT(id) as counter + $query = 'SELECT COUNT(id) as counter FROM support_p_ticket WHERE status = :status - GROUP BY status"; + GROUP BY status'; - return $this->di['db']->getCell($query, array(':status' => $status)); + return $this->di['db']->getCell($query, [':status' => $status]); } public function publicGetExpired() { - $bindings = array( - ':status' => \Model_SupportPTicket::ONHOLD - ); + $bindings = [ + ':status' => \Model_SupportPTicket::ONHOLD, + ]; $publicTicket = $this->di['db']->find('SupportPTicket', 'status = :status AND DATE_ADD(updated_at, INTERVAL 48 HOUR) < NOW() ORDER BY id ASC', $bindings); @@ -1104,18 +1101,17 @@ class Service implements \Box\InjectionAwareInterface public function publicCloseTicket(\Model_SupportPTicket $model, $identity) { - $model->status = 'closed'; + $model->status = 'closed'; $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); if ($identity instanceof \Model_Admin) { - $this->di['events_manager']->fire(array('event' => 'onAfterAdminPublicTicketClose', 'params' => array('id' => $model->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminPublicTicketClose', 'params' => ['id' => $model->id]]); $this->di['logger']->info('Public Ticket %s was closed', $model->id); } elseif ($identity instanceof \Model_Guest) { - $this->di['events_manager']->fire(array('event' => 'onAfterGuestPublicTicketClose', 'params' => array('id' => $model->id))); + $this->di['events_manager']->fire(['event' => 'onAfterGuestPublicTicketClose', 'params' => ['id' => $model->id]]); $this->di['logger']->info('"%s" closed public ticket "%s"', $model->author_email, $model->id); - } return true; @@ -1123,22 +1119,22 @@ class Service implements \Box\InjectionAwareInterface public function publicAutoClose(\Model_SupportPTicket $model) { - $model->status = 'closed'; + $model->status = 'closed'; $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); $this->di['logger']->info('Public Ticket %s was closed', $model->id); - return TRUE; + return true; } public function publicRm(\Model_SupportPTicket $model) { - $id = $model->id; - $bindings = array( - ':support_p_ticket_id' => $model->id - ); + $id = $model->id; + $bindings = [ + ':support_p_ticket_id' => $model->id, + ]; $messages = $this->di['db']->find('SupportPTicketMessage', 'support_p_ticket_id = :support_p_ticket_id', $bindings); foreach ($messages as $message) { @@ -1154,9 +1150,9 @@ class Service implements \Box\InjectionAwareInterface public function publicToApiArray(\Model_SupportPTicket $model, $deep = true) { - $data = $this->di['db']->toArray($model); - $messages = array(); - $messagesArr = $this->di['db']->find('SupportPTicketMessage', 'support_p_ticket_id = :support_p_ticket_id ORDER BY id', array(':support_p_ticket_id' => $model->id)); + $data = $this->di['db']->toArray($model); + $messages = []; + $messagesArr = $this->di['db']->find('SupportPTicketMessage', 'support_p_ticket_id = :support_p_ticket_id ORDER BY id', [':support_p_ticket_id' => $model->id]); foreach ($messagesArr as $msg) { $messages[] = $this->publicMessageToApiArray($msg); } @@ -1165,7 +1161,7 @@ class Service implements \Box\InjectionAwareInterface if ($first instanceof \Model_SupportPTicketMessage) { $data['author'] = $this->publicMessageGetAuthorDetails($first); } else { - $data['author'] = array(); + $data['author'] = []; } $data['messages'] = $messages; @@ -1177,23 +1173,23 @@ class Service implements \Box\InjectionAwareInterface if ($model->admin_id) { $author = $this->di['db']->getExistingModelById('Admin', $model->admin_id); - return array( - 'name' => $author->getFullName(), + return [ + 'name' => $author->getFullName(), 'email' => $author->email, - ); + ]; } $ticket = $this->di['db']->getExistingModelById('SupportPTicket', $model->support_p_ticket_id); - return array( - 'name' => $ticket->author_name, + return [ + 'name' => $ticket->author_name, 'email' => $ticket->author_email, - ); + ]; } public function publicMessageToApiArray(\Model_SupportPTicketMessage $model, $deep = true) { - $data = $this->di['db']->toArray($model); + $data = $this->di['db']->toArray($model); $data['author'] = $this->publicMessageGetAuthorDetails($model); return $data; @@ -1203,28 +1199,28 @@ class Service implements \Box\InjectionAwareInterface { $this->di['validator']->isEmailValid($data['email']); - $this->di['events_manager']->fire(array('event' => 'onBeforeAdminPublicTicketOpen', 'params' => $data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminPublicTicketOpen', 'params' => $data]); - $ticket = $this->di['db']->dispense('SupportPTicket'); - $ticket->hash = sha1(random_bytes(13)); - $ticket->author_name = $data['name']; + $ticket = $this->di['db']->dispense('SupportPTicket'); + $ticket->hash = sha1(random_bytes(13)); + $ticket->author_name = $data['name']; $ticket->author_email = $data['email']; - $ticket->subject = $data['subject']; - $ticket->status = 'open'; - $ticket->created_at = date('Y-m-d H:i:s'); - $ticket->updated_at = date('Y-m-d H:i:s'); - $ticketId = $this->di['db']->store($ticket); + $ticket->subject = $data['subject']; + $ticket->status = 'open'; + $ticket->created_at = date('Y-m-d H:i:s'); + $ticket->updated_at = date('Y-m-d H:i:s'); + $ticketId = $this->di['db']->store($ticket); - $msg = $this->di['db']->dispense('SupportPTicketMessage'); + $msg = $this->di['db']->dispense('SupportPTicketMessage'); $msg->support_p_ticket_id = $ticketId; - $msg->admin_id = $identity->id; - $msg->content = $data['message']; - $msg->ip = $this->di['request']->getClientAddress(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); + $msg->admin_id = $identity->id; + $msg->content = $data['message']; + $msg->ip = $this->di['request']->getClientAddress(); + $msg->created_at = date('Y-m-d H:i:s'); + $msg->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($msg); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminPublicTicketOpen', 'params' => array('id' => $ticketId))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminPublicTicketOpen', 'params' => ['id' => $ticketId]]); $this->di['logger']->info('Opened public ticket for email "%s"', $ticket->author_email); @@ -1245,20 +1241,20 @@ class Service implements \Box\InjectionAwareInterface public function publicTicketReply(\Model_SupportPTicket $ticket, \Model_Admin $identity, $content) { - $msg = $this->di['db']->dispense('SupportPTicketMessage'); + $msg = $this->di['db']->dispense('SupportPTicketMessage'); $msg->support_p_ticket_id = $ticket->id; - $msg->admin_id = $identity->id; - $msg->content = $content; - $msg->ip = $this->di['request']->getClientAddress(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); - $messageId = $this->di['db']->store($msg); + $msg->admin_id = $identity->id; + $msg->content = $content; + $msg->ip = $this->di['request']->getClientAddress(); + $msg->created_at = date('Y-m-d H:i:s'); + $msg->updated_at = date('Y-m-d H:i:s'); + $messageId = $this->di['db']->store($msg); - $ticket->status = \Model_SupportPTicket::ONHOLD; + $ticket->status = \Model_SupportPTicket::ONHOLD; $ticket->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($ticket); - $this->di['events_manager']->fire(array('event' => 'onAfterAdminPublicTicketReply', 'params' => array('id' => $ticket->id))); + $this->di['events_manager']->fire(['event' => 'onAfterAdminPublicTicketReply', 'params' => ['id' => $ticket->id]]); $this->di['logger']->info('Replied to public ticket "%s"', $ticket->id); @@ -1267,19 +1263,19 @@ class Service implements \Box\InjectionAwareInterface public function publicTicketReplyForGuest(\Model_SupportPTicket $ticket, $message) { - $msg = $this->di['db']->dispense('SupportPTicketMessage'); + $msg = $this->di['db']->dispense('SupportPTicketMessage'); $msg->support_p_ticket_id = $ticket->id; - $msg->content = $message; - $msg->ip = $this->di['request']->getClientAddress(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); + $msg->content = $message; + $msg->ip = $this->di['request']->getClientAddress(); + $msg->created_at = date('Y-m-d H:i:s'); + $msg->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($msg); - $ticket->status = \Model_SupportPTicket::OPENED; + $ticket->status = \Model_SupportPTicket::OPENED; $ticket->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($ticket); - $this->di['events_manager']->fire(array('event' => 'onAfterGuestPublicTicketReply', 'params' => array('id' => $ticket->id))); + $this->di['events_manager']->fire(['event' => 'onAfterGuestPublicTicketReply', 'params' => ['id' => $ticket->id]]); $this->di['logger']->info('Client "%s" replied to public ticket "%s"', $ticket->author_email, $ticket->id); @@ -1294,7 +1290,7 @@ class Service implements \Box\InjectionAwareInterface $model->close_after = $this->di['array_get']($data, 'close_after', $model->close_after); $model->signature = $this->di['array_get']($data, 'signature', $model->signature); $model->updated_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $id = $this->di['db']->store($model); $this->di['logger']->info('Updated helpdesk #%s', $id); @@ -1303,15 +1299,15 @@ class Service implements \Box\InjectionAwareInterface public function helpdeskCreate($data) { - $model = $this->di['db']->dispense('SupportHelpdesk'); - $model->name = $data['name']; - $model->email = $this->di['array_get']($data, 'email', NULL); - $model->can_reopen = $this->di['array_get']($data, 'can_reopen', NULL); - $model->close_after = $this->di['array_get']($data, 'close_after', NULL); - $model->signature = $this->di['array_get']($data, 'signature', NULL); - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $model = $this->di['db']->dispense('SupportHelpdesk'); + $model->name = $data['name']; + $model->email = $this->di['array_get']($data, 'email', null); + $model->can_reopen = $this->di['array_get']($data, 'can_reopen', null); + $model->close_after = $this->di['array_get']($data, 'close_after', null); + $model->signature = $this->di['array_get']($data, 'signature', null); + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); + $id = $this->di['db']->store($model); $this->di['logger']->info('Created helpdesk #%s', $id); @@ -1320,39 +1316,39 @@ class Service implements \Box\InjectionAwareInterface public function cannedGetSearchQuery($data) { - $query = "SELECT sp.* FROM support_pr sp + $query = 'SELECT sp.* FROM support_pr sp LEFT JOIN support_pr_category spc - ON spc.id = sp.support_pr_category_id"; + ON spc.id = sp.support_pr_category_id'; - $search = $this->di['array_get']($data, 'search', NULL); + $search = $this->di['array_get']($data, 'search', null); - $where = array(); - $bindings = array(); + $where = []; + $bindings = []; if ($search) { - $search = "%" . $search . "%"; - $where[] = "title LIKE :title OR content LIKE :content"; - $bindings[':title'] = $search; + $search = '%'.$search.'%'; + $where[] = 'title LIKE :title OR content LIKE :content'; + $bindings[':title'] = $search; $bindings[':content'] = $search; } if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); + $query = $query.' WHERE '.implode(' AND ', $where); } - $query .= " ORDER BY sp.support_pr_category_id ASC"; + $query .= ' ORDER BY sp.support_pr_category_id ASC'; - return array($query, $bindings); + return [$query, $bindings]; } public function cannedGetGroupedPairs() { - $query = "SELECT sp.title as r_title, spc.title as c_title FROM support_pr sp + $query = 'SELECT sp.title as r_title, spc.title as c_title FROM support_pr sp LEFT JOIN support_pr_category spc - ON spc.id = sp.support_pr_category_id"; + ON spc.id = sp.support_pr_category_id'; $data = $this->di['db']->getAll($query); - $res = array(); + $res = []; foreach ($data as $r) { $res[$r['c_title']][$r['id']] = $r['r_title']; } @@ -1373,15 +1369,15 @@ class Service implements \Box\InjectionAwareInterface public function cannedToApiArray(\Model_SupportPr $model) { - $result = $this->di['db']->toArray($model); + $result = $this->di['db']->toArray($model); $category = $this->di['db']->load('SupportPrCategory', $model->support_pr_category_id); if ($category instanceof \Model_SupportPrCategory) { - $result['category'] = array( - 'id' => $category->id, + $result['category'] = [ + 'id' => $category->id, 'title' => $category->title, - ); + ]; } else { - $result['category'] = array(); + $result['category'] = []; } return $result; @@ -1389,7 +1385,7 @@ class Service implements \Box\InjectionAwareInterface public function cannedCategoryGetPairs() { - return $this->di['db']->getAssoc("SELECT id, title FROM support_pr_category"); + return $this->di['db']->getAssoc('SELECT id, title FROM support_pr_category'); } public function cannedCategoryRm(\Model_SupportPrCategory $model) @@ -1411,13 +1407,13 @@ class Service implements \Box\InjectionAwareInterface $systemService = $this->di['mod_service']('system'); $systemService->checkLimits('Model_SupportPr', 5); - $model = $this->di['db']->dispense('SupportPr'); + $model = $this->di['db']->dispense('SupportPr'); $model->support_pr_category_id = $categoryId; - $model->title = $title; - $model->content = $content; - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $model->title = $title; + $model->content = $content; + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); + $id = $this->di['db']->store($model); $this->di['logger']->info('Created new canned response #%s', $id); @@ -1439,11 +1435,11 @@ class Service implements \Box\InjectionAwareInterface public function cannedCategoryCreate($title) { - $model = $this->di['db']->dispense('SupportPrCategory'); - $model->title = $title; + $model = $this->di['db']->dispense('SupportPrCategory'); + $model->title = $title; $model->created_at = date('Y-m-d H:i:s'); $model->updated_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $id = $this->di['db']->store($model); $this->di['logger']->info('Created new canned response category #%s', $id); @@ -1452,9 +1448,9 @@ class Service implements \Box\InjectionAwareInterface public function cannedCategoryUpdate(\Model_SupportPrCategory $model, $title) { - $model->title = $title; + $model->title = $title; $model->updated_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $id = $this->di['db']->store($model); $this->di['logger']->info('Updated canned response category #%s', $id); @@ -1463,13 +1459,13 @@ class Service implements \Box\InjectionAwareInterface public function noteCreate(\Model_SupportTicket $ticket, \Model_Admin $identity, $note) { - $model = $this->di['db']->dispense('SupportTicketNote'); + $model = $this->di['db']->dispense('SupportTicketNote'); $model->support_ticket_id = $ticket->id; - $model->admin_id = $identity->id; - $model->note = $note; - $model->created_at = date('Y-m-d H:i:s'); - $model->updated_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $model->admin_id = $identity->id; + $model->note = $note; + $model->created_at = date('Y-m-d H:i:s'); + $model->updated_at = date('Y-m-d H:i:s'); + $id = $this->di['db']->store($model); $this->di['logger']->info('Added note to ticket #%s', $id); @@ -1480,11 +1476,10 @@ class Service implements \Box\InjectionAwareInterface { $model->rel_status = \Model_SupportTicket::REL_STATUS_COMPLETE; $model->updated_at = date('Y-m-d H:i:s'); - $id = $this->di['db']->store($model); + $id = $this->di['db']->store($model); $this->di['logger']->info('Marked ticket #%s task as complete', $id); return true; } - } diff --git a/src/bb-modules/System/Api/Admin.php b/src/bb-modules/System/Api/Admin.php index 4a631fc60..945b4ec17 100644 --- a/src/bb-modules/System/Api/Admin.php +++ b/src/bb-modules/System/Api/Admin.php @@ -1,6 +1,6 @@ 'Parameter key is missing', - ); + $required = [ + 'key' => 'Parameter key is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->getParamValue($data['key']); } /** - * Get all defined system params - * + * Get all defined system params. + * * @return array */ public function get_params($data) @@ -45,61 +48,64 @@ class Admin extends \Api_Abstract } /** - * Updated parameters array with new values. Creates new setting if it was + * Updated parameters array with new values. Creates new setting if it was * not defined earlier. You can create new parameters using this method. * This method accepts any number of parameters you pass. - * + * * @param string $key - name of the parameter to be changed/created - * + * * @return bool */ public function update_params($data) { return $this->getService()->updateParams($data); } - + /** * System messages about working environment. - * + * * @param string $type - messages type to be returned: info - * + * * @return array */ public function messages($data) { $type = $this->di['array_get']($data, 'type', 'info'); + return $this->getService()->getMessages($type); } - + /** - * Check if passed file name template exists for admin area - * + * Check if passed file name template exists for admin area. + * * @param string $file - template file name, example: mod_index_dashboard.phtml + * * @return bool */ public function template_exists($data) { - if(!isset($data['file'])) { + if (!isset($data['file'])) { return false; } - + return $this->getService()->templateExists($data['file'], $this->getIdentity()); } - + /** - * Parse string like BoxBilling template - * + * Parse string like BoxBilling template. + * * @param string $_tpl - Template text to be parsed - * + * * @optional bool $_try - if true, will not throw error if template is not valid, returns _tpl string * @optional int $_client_id - if passed client id, then client API will also be available - * + * * @return string */ public function string_render($data) { - if(!isset($data['_tpl'])) { + if (!isset($data['_tpl'])) { error_log('_tpl parameter not passed'); + return ''; } $tpl = $data['_tpl']; @@ -107,44 +113,48 @@ class Admin extends \Api_Abstract $vars = $data; unset($vars['_tpl'], $vars['_try']); + return $this->getService()->renderString($tpl, $try_render, $vars); } - + /** - * Returns system environment information. - * + * Returns system environment information. + * * @return array */ public function env($data) { $ip = $this->di['array_get']($data, 'ip', null); + return $this->getService()->getEnv($ip); } /** - * Method to check if staff member has permission to access module - * + * Method to check if staff member has permission to access module. + * * @param string $mod - module name - * + * * @optional string $f - module method name - * + * * @return bool + * * @throws \Box_Exception */ public function is_allowed($data) { - $required = array( - 'mod' => 'mod key is missing', - ); + $required = [ + 'mod' => 'mod key is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); - + $f = $this->di['array_get']($data, 'f', null); $service = $this->di['mod_service']('Staff'); + return $service->hasPermission($this->getIdentity(), $data['mod'], $f); } /** - * Clear system cache + * Clear system cache. * * @return bool */ @@ -152,4 +162,4 @@ class Admin extends \Api_Abstract { return $this->getService()->clearCache(); } -} \ No newline at end of file +} diff --git a/src/bb-modules/System/Api/Guest.php b/src/bb-modules/System/Api/Guest.php index 5a6067969..35e32f3e5 100644 --- a/src/bb-modules/System/Api/Guest.php +++ b/src/bb-modules/System/Api/Guest.php @@ -1,6 +1,6 @@ getService()->getVersion(); } - + /** - * Returns company information - * + * Returns company information. + * * @return array */ public function company() { return $this->getService()->getCompany(); } - + /** - * Returns world wide phone codes - * + * Returns world wide phone codes. + * * @optional $country - if passed country code the result will be phone code only - * + * * @return array */ public function phone_codes($data) { - return $this->getService()->getPhoneCodes($data); + return $this->getService()->getPhoneCodes($data); } - + /** - * Returns USA states list - * + * Returns USA states list. + * * @return array */ public function states() @@ -60,8 +61,8 @@ class Guest extends \Api_Abstract } /** - * Returns list of european union countries - * + * Returns list of european union countries. + * * @return array */ public function countries_eunion() @@ -70,60 +71,61 @@ class Guest extends \Api_Abstract } /** - * Returns list of world countries - * + * Returns list of world countries. + * * @return array */ public function countries() { - return $this->getService()->getCountries(); + return $this->getService()->getCountries(); } /** - * Returns system parameter by key - * + * Returns system parameter by key. + * * @param string $key - Parameter name - * + * * @return string */ public function param($data) { - $required = array( - 'key' => 'Parameter key is missing', - ); + $required = [ + 'key' => 'Parameter key is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->getPublicParamValue($data['key']); } /** - * Return list of available payment periods - * + * Return list of available payment periods. + * * @return array */ public function periods() { - return \Box_Period::getPredefined(); + return \Box_Period::getPredefined(); } /** - * Gets period title by identifier - * + * Gets period title by identifier. + * * @param string $code - Period code name, ie: 1M => Monthly - * - * @return string + * + * @return string */ public function period_title($data) { - $code = $this->di['array_get']($data, 'code', NULL); - if($code == NULL) { + $code = $this->di['array_get']($data, 'code', null); + if (null == $code) { return '-'; } + return $this->getService()->getPeriod($code); } /** - * Returns info for paginator according to list + * Returns info for paginator according to list. * * @return array */ @@ -135,48 +137,52 @@ class Guest extends \Api_Abstract $itemsCount = $data['total']; $p = new \Box_Paginator($itemsCount, $current_page, $limit, $midrange); + return $p->toArray(); } /** - * If called from template file this function returns current url + * If called from template file this function returns current url. + * * @return string */ public function current_url() { return $this->di['request']->getURI(); } - + /** - * Check if passed file name template exists for client area - * + * Check if passed file name template exists for client area. + * * @param string $file - template file name, example: mod_index_dashboard.phtml + * * @return bool */ public function template_exists($data) { - if(!isset($data['file'])) { + if (!isset($data['file'])) { return false; } return $this->getService()->templateExists($data['file']); } - + /** - * Get current client locale - * + * Get current client locale. + * * @return string */ public function locale() { $cookie = $this->di['cookie']; - $locale = $this->di['config']['locale'];; - if ($cookie->has('BBLANG')){ + $locale = $this->di['config']['locale']; + if ($cookie->has('BBLANG')) { $bblang = $cookie->get('BBLANG'); - if (!empty($bblang)){ + if (!empty($bblang)) { $locale = $bblang; } } + return $locale; } @@ -184,6 +190,7 @@ class Guest extends \Api_Abstract { $messages = $this->getService()->getPendingMessages(); $this->getService()->clearPendingMessages(); + return $messages; } -} \ No newline at end of file +} diff --git a/src/bb-modules/System/Controller/Admin.php b/src/bb-modules/System/Controller/Admin.php index 4bf3fe5ec..da40ac6fa 100644 --- a/src/bb-modules/System/Controller/Admin.php +++ b/src/bb-modules/System/Controller/Admin.php @@ -1,6 +1,6 @@ array( - 'index' => 600, - 'location' => 'system', - 'label' => 'Configuration', - 'class' => 'settings', + return [ + 'group' => [ + 'index' => 600, + 'location' => 'system', + 'label' => 'Configuration', + 'class' => 'settings', 'sprite_class' => 'dark-sprite-icon sprite-cog3', - ), - 'subpages'=> array( - array( - 'location' => 'system', + ], + 'subpages' => [ + [ + 'location' => 'system', 'label' => 'Settings', - 'index' => 100, + 'index' => 100, 'uri' => $this->di['url']->adminLink('system'), - 'class' => '', - ), - ), - ); + 'class' => '', + ], + ], + ]; } - + public function register(\Box_App &$app) { - $app->get('/system', 'get_index', array(), get_class($this)); - $app->get('/system/', 'get_index', array(), get_class($this)); - $app->get('/system/index', 'get_index', array(), get_class($this)); - $app->get('/system/activity', 'get_activity', array(), get_class($this)); + $app->get('/system', 'get_index', [], get_class($this)); + $app->get('/system/', 'get_index', [], get_class($this)); + $app->get('/system/index', 'get_index', [], get_class($this)); + $app->get('/system/activity', 'get_activity', [], get_class($this)); } public function get_index(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_system_index'); } - + public function get_activity(\Box_App $app) { $this->di['is_admin_logged']; + return $app->render('mod_system_activity'); } -} \ No newline at end of file +} diff --git a/src/bb-modules/System/Service.php b/src/bb-modules/System/Service.php index 3f156095c..8033e6a7c 100644 --- a/src/bb-modules/System/Service.php +++ b/src/bb-modules/System/Service.php @@ -1,6 +1,6 @@ di['pdo']; $stmt = $pdo->prepare($query); - $stmt->execute(array('param'=>$param)); + $stmt->execute(['param' => $param]); $results = $stmt->fetchColumn(); - if($results === false) { + if (false === $results) { return $default; } + return $results; } @@ -53,18 +53,18 @@ class Service { $pdo = $this->di['pdo']; - if($this->paramExists($param)) { - $query="UPDATE setting SET value = :value WHERE param = :param"; + if ($this->paramExists($param)) { + $query = 'UPDATE setting SET value = :value WHERE param = :param'; $stmt = $pdo->prepare($query); - $stmt->execute(array('param'=>$param, 'value'=>$value)); - } else if($createIfNotExists) { + $stmt->execute(['param' => $param, 'value' => $value]); + } elseif ($createIfNotExists) { try { - $query="INSERT INTO setting (param, value, created_at, updated_at) VALUES (:param, :value, :created_at, :updated_at)"; + $query = 'INSERT INTO setting (param, value, created_at, updated_at) VALUES (:param, :value, :created_at, :updated_at)'; $stmt = $pdo->prepare($query); - $stmt->execute(array('param'=>$param, 'value'=>$value, 'created_at'=>date('Y-m-d H:i:s'), 'updated_at'=>date('Y-m-d H:i:s'))); - } catch(\Exception $e) { - //ignore duplicate key error - if($e->getCode() != 23000) { + $stmt->execute(['param' => $param, 'value' => $value, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); + } catch (\Exception $e) { + // ignore duplicate key error + if (23000 != $e->getCode()) { throw $e; } } @@ -76,13 +76,14 @@ class Service public function paramExists($param) { $pdo = $this->di['pdo']; - $q = "SELECT id + $q = 'SELECT id FROM setting - WHERE param = :param"; + WHERE param = :param'; $stmt = $pdo->prepare($q); - $stmt->execute(array('param'=>$param)); + $stmt->execute(['param' => $param]); $results = $stmt->fetchColumn(); - return (bool)$results; + + return (bool) $results; } /** @@ -90,24 +91,25 @@ class Service */ private function _getMultipleParams($params) { - if (!is_array($params)){ - return array(); + if (!is_array($params)) { + return []; } $query = "SELECT param, value FROM setting WHERE param IN('".implode("', '", $params)."') "; $rows = $this->di['db']->getAll($query); - $result = array(); - foreach($rows as $row){ - $result[ $row['param'] ] = $row['value']; + $result = []; + foreach ($rows as $row) { + $result[$row['param']] = $row['value']; } + return $result; } public function getCompany() { - $c = array( + $c = [ 'company_name', 'company_email', 'company_tel', @@ -123,34 +125,35 @@ class Service 'company_privacy_policy', 'company_tos', 'company_vat_number', - ); + ]; $results = $this->_getMultipleParams($c); - return array( - 'www' => $this->di['config']['url'], - 'name' => $this->di['array_get']($results, 'company_name', NULL), - 'email' => $this->di['array_get']($results, 'company_email', NULL), - 'tel' => $this->di['array_get']($results, 'company_tel', NULL), - 'signature' => $this->di['array_get']($results, 'company_signature', NULL), - 'logo_url' => $this->di['array_get']($results, 'company_logo', NULL), - 'address_1' => $this->di['array_get']($results, 'company_address_1', NULL), - 'address_2' => $this->di['array_get']($results, 'company_address_2', NULL), - 'address_3' => $this->di['array_get']($results, 'company_address_3', NULL), - 'account_number' => $this->di['array_get']($results, 'company_account_number', NULL), - 'number' => $this->di['array_get']($results, 'company_number', NULL), - 'note' => $this->di['array_get']($results, 'company_note', NULL), - 'privacy_policy' => $this->di['array_get']($results, 'company_privacy_policy', NULL), - 'tos' => $this->di['array_get']($results, 'company_tos', NULL), - 'vat_number' => $this->di['array_get']($results, 'company_vat_number', NULL), - ); + + return [ + 'www' => $this->di['config']['url'], + 'name' => $this->di['array_get']($results, 'company_name', null), + 'email' => $this->di['array_get']($results, 'company_email', null), + 'tel' => $this->di['array_get']($results, 'company_tel', null), + 'signature' => $this->di['array_get']($results, 'company_signature', null), + 'logo_url' => $this->di['array_get']($results, 'company_logo', null), + 'address_1' => $this->di['array_get']($results, 'company_address_1', null), + 'address_2' => $this->di['array_get']($results, 'company_address_2', null), + 'address_3' => $this->di['array_get']($results, 'company_address_3', null), + 'account_number' => $this->di['array_get']($results, 'company_account_number', null), + 'number' => $this->di['array_get']($results, 'company_number', null), + 'note' => $this->di['array_get']($results, 'company_note', null), + 'privacy_policy' => $this->di['array_get']($results, 'company_privacy_policy', null), + 'tos' => $this->di['array_get']($results, 'company_tos', null), + 'vat_number' => $this->di['array_get']($results, 'company_vat_number', null), + ]; } public function getLanguages($deep = false) { $path = BB_PATH_LANGS; - $locales = array(); + $locales = []; if ($handle = opendir($path)) { while (false !== ($entry = readdir($handle))) { - if ($entry != ".svn" && $entry != "." && $entry != ".." && is_dir($path . DIRECTORY_SEPARATOR . $entry)) { + if ('.svn' != $entry && '.' != $entry && '..' != $entry && is_dir($path.DIRECTORY_SEPARATOR.$entry)) { $locales[] = $entry; } } @@ -161,86 +164,88 @@ class Service return $locales; } - $details = array(); + $details = []; foreach ($locales as $locale) { - $file = $path . '/' . $locale . '/LC_MESSAGES/messages.po'; + $file = $path.'/'.$locale.'/LC_MESSAGES/messages.po'; if (file_exists($file)) { $lNames = $this->getLocales(); if (isset($lNames[$locale]) && !empty($lNames[$locale])) { $title = $lNames[$locale]; - }else{ + } else { $title = null; } - $details[] = array( + $details[] = [ 'locale' => $locale, - 'title' => $title, - ); + 'title' => $title, + ]; } } return $details; } - + public function getParams($data) { - $query = "SELECT param, value - FROM setting"; + $query = 'SELECT param, value + FROM setting'; $rows = $this->di['db']->getAll($query); - $result = array(); - foreach($rows as $row){ - $result[ $row['param'] ] = $row['value']; + $result = []; + foreach ($rows as $row) { + $result[$row['param']] = $row['value']; } + return $result; } public function updateParams($data) { - $this->di['events_manager']->fire(array('event'=>'onBeforeAdminSettingsUpdate', 'params'=>$data)); + $this->di['events_manager']->fire(['event' => 'onBeforeAdminSettingsUpdate', 'params' => $data]); - foreach($data as $key=>$val) { + foreach ($data as $key => $val) { $this->setParamValue($key, $val, true); } - $this->di['events_manager']->fire(array('event'=>'onAfterAdminSettingsUpdate')); + $this->di['events_manager']->fire(['event' => 'onAfterAdminSettingsUpdate']); $this->di['logger']->info('Updated system general settings'); + return true; } public function getMessages($type) { - $msgs = array(); + $msgs = []; try { $updater = $this->di['updater']; - if($updater->getCanUpdate()) { + if ($updater->getCanUpdate()) { $version = $updater->getLatestVersion(); $msgs['info'][] = sprintf('BoxBilling %s is available for download.', $version); } - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e->getMessage()); } $last_exec = $this->getParamValue('last_cron_exec'); - if(!$last_exec) { + if (!$last_exec) { $msgs['info'][] = 'Cron was never executed. Make sure you have setup cron job.'; } $install = BB_PATH_ROOT.'/install'; - if($this->di['tools']->fileExists(BB_PATH_ROOT.'/install')) { + if ($this->di['tools']->fileExists(BB_PATH_ROOT.'/install')) { $msgs['info'][] = sprintf('Install module "%s" still exists. Please remove it for security reasons.', $install); } - if($this->getVersion() == "0.0.1") { + if ('0.0.1' == $this->getVersion()) { $msgs['info'][] = 'BoxBilling couldn\'t find valid version information. This is okay if you downloaded BoxBilling directly from the master branch, instead of a released version. But beware, the master branch may not be stable enough for production use.'; } - if(!extension_loaded('openssl')) { + if (!extension_loaded('openssl')) { $msgs['info'][] = sprintf('BoxBilling requires %s extension to be enabled on this server for security reasons.', 'php openssl'); } - return $this->di['array_get']($msgs, $type, array()); + return $this->di['array_get']($msgs, $type, []); } public function templateExists($file, $identity = null) @@ -253,7 +258,7 @@ class Service $themeService = $this->di['mod_service']('theme'); $theme = $themeService->getThemeConfig($client); foreach ($theme['paths'] as $path) { - if ($this->di['tools']->fileExists($path . DIRECTORY_SEPARATOR . $file)) { + if ($this->di['tools']->fileExists($path.DIRECTORY_SEPARATOR.$file)) { return true; } } @@ -264,46 +269,43 @@ class Service public function renderString($tpl, $try_render, $vars) { $twig = $this->di['twig']; - //add client api if _client_id is set - if(isset($vars['_client_id'])) { + // add client api if _client_id is set + if (isset($vars['_client_id'])) { $identity = $this->di['db']->load('Client', $vars['_client_id']); - if($identity instanceof \Model_Client) { - try{ + if ($identity instanceof \Model_Client) { + try { $twig->addGlobal('client', $this->di['api_client']); - } - catch (\Exception $e){ + } catch (\Exception $e) { error_log('api_client could not be added to template: '.$e->getMessage()); } } - } - else{ + } else { // attempt adding admin api to twig - try { - $twig->addGlobal('admin', $this->di['api_admin']); - } catch(\Exception $e) { - //skip if admin is not logged in - } + try { + $twig->addGlobal('admin', $this->di['api_admin']); + } catch (\Exception $e) { + // skip if admin is not logged in + } } try { $template = $twig->load($tpl); - $parsed = $template->render($vars); + $parsed = $template->render($vars); } catch (\Exception $e) { - //$twig->load throws error when $tpl is string + // $twig->load throws error when $tpl is string $parsed = $this->createTemplateFromString($tpl, $try_render, $vars); - } return $parsed; } - public function createTemplateFromString($tpl, $try_render, $vars){ - try{ - $twig = $this->di['twig']; - $template = $twig->createTemplate($tpl); - $parsed = $template->render($vars); - } - catch(\Exception $e){ + public function createTemplateFromString($tpl, $try_render, $vars) + { + try { + $twig = $this->di['twig']; + $template = $twig->createTemplate($tpl); + $parsed = $template->render($vars); + } catch (\Exception $e) { $parsed = $tpl; if (!$try_render) { throw $e; @@ -316,15 +318,16 @@ class Service public function clearCache() { $this->di['tools']->emptyFolder(BB_PATH_CACHE); + return true; } public function getEnv($ip) { - if(isset($ip)) { + if (isset($ip)) { try { return $this->di['tools']->get_url('https://api.ipify.org', 2); - } catch(\Exception $e) { + } catch (\Exception $e) { return ''; } } @@ -341,115 +344,117 @@ class Service $request = $this->di['request']; $pageURL = 'http'; $https = $request->getScheme(); - if (isset($https) && $https == "https") { - $pageURL .= "s"; + if (isset($https) && 'https' == $https) { + $pageURL .= 's'; } - $pageURL .= "://"; + $pageURL .= '://'; - $serverPort = $request->getServer("SERVER_PORT"); - if (isset($serverPort) && $serverPort != "80" && $serverPort != "443") { - $pageURL .= $request->getServer("SERVER_NAME").":".$request->getServer("SERVER_PORT"); + $serverPort = $request->getServer('SERVER_PORT'); + if (isset($serverPort) && '80' != $serverPort && '443' != $serverPort) { + $pageURL .= $request->getServer('SERVER_NAME').':'.$request->getServer('SERVER_PORT'); } else { - $pageURL .= $request->getServer("SERVER_NAME"); + $pageURL .= $request->getServer('SERVER_NAME'); } $this_page = $request->getURI(); - if (strpos($this_page, "?") !== false) { - $a = explode("?", $this_page); + if (false !== strpos($this_page, '?')) { + $a = explode('?', $this_page); $this_page = reset($a); } - return $pageURL . $this_page; + + return $pageURL.$this_page; } public function getPeriod($code) { $p = \Box_Period::getPredefined(); - if(isset($p[$code])) { + if (isset($p[$code])) { return $p[$code]; } $p = new \Box_Period($code); + return $p->getTitle(); } public function getPublicParamValue($param) { - $query = "SELECT value + $query = 'SELECT value FROM setting WHERE param = :param AND public = 1 - "; + '; $pdo = $this->di['pdo']; $stmt = $pdo->prepare($query); - $stmt->execute(array('param'=>$param)); + $stmt->execute(['param' => $param]); $results = $stmt->fetchColumn(); - if($results === false) { - throw new \Box_Exception('Parameter :param does not exist', array(':param'=>$param)); + if (false === $results) { + throw new \Box_Exception('Parameter :param does not exist', [':param' => $param]); } + return $results; } public function getLocales() { - return array - ( - 'aa' => 'Afar', - 'ab' => 'Abkhazian', - 'af' => 'Afrikaans', + return [ + 'aa' => 'Afar', + 'ab' => 'Abkhazian', + 'af' => 'Afrikaans', 'af_ZA' => 'Afrikaans (South Africa)', - 'am' => 'Amharic', + 'am' => 'Amharic', 'am_ET' => 'Amharic (Ethiopia)', - 'ar' => 'Arabic', + 'ar' => 'Arabic', 'ar_AA' => 'Arabic (Unitag)', 'ar_SA' => 'Arabic (Saudi Arabia)', - 'as' => 'Assamese', + 'as' => 'Assamese', 'as_IN' => 'Assamese (India)', - 'ay' => 'Aymara', - 'az' => 'Azerbaijani', + 'ay' => 'Aymara', + 'az' => 'Azerbaijani', 'az_AZ' => 'Azerbaijani (Azerbaijan)', - 'ba' => 'Bashkir', - 'be' => 'Belarusian', + 'ba' => 'Bashkir', + 'be' => 'Belarusian', 'be_BY' => 'Belarusian (Belarus)', - 'bg' => 'Bulgarian', + 'bg' => 'Bulgarian', 'bg_BG' => 'Bulgarian (Bulgaria)', - 'bh' => 'Bihari', - 'bi' => 'Bislama', - 'bn' => 'Bengali', + 'bh' => 'Bihari', + 'bi' => 'Bislama', + 'bn' => 'Bengali', 'bn_BD' => 'Bengali (Bangladesh)', 'bn_ID' => 'Bengali (India)', - 'bo' => 'Tibetan', + 'bo' => 'Tibetan', 'bo_CN' => 'Tibetan (China)', - 'br' => 'Breton', - 'bs' => 'Bosnian', + 'br' => 'Breton', + 'bs' => 'Bosnian', 'bs_BA' => 'Bosnian (Bosnia and Herzegovina)', - 'ca' => 'Catalan', + 'ca' => 'Catalan', 'ca_ES' => 'Catalan (Spain)', - 'co' => 'Corsican', - 'cr' => 'Cree', - 'cs' => 'Czech', + 'co' => 'Corsican', + 'cr' => 'Cree', + 'cs' => 'Czech', 'cs_CZ' => 'Czech (Czech Republic)', - 'cy' => 'Welsh', + 'cy' => 'Welsh', 'cy_GB' => 'Welsh (United Kingdom)', - 'da' => 'Danish', + 'da' => 'Danish', 'da_DK' => 'Danish (Denmark)', - 'de' => 'German', + 'de' => 'German', 'de_AT' => 'German (Austria)', 'de_CH' => 'German (Switzerland)', 'de_DE' => 'German (Germany)', - 'dz' => 'Dzongkha', + 'dz' => 'Dzongkha', 'dz_BT' => 'Dzongkha (Bhutan)', - 'el' => 'Greek', + 'el' => 'Greek', 'el_GR' => 'Greek (Greece)', - 'en' => 'English', + 'en' => 'English', 'en_AU' => 'English (Australia)', 'en_CA' => 'English (Canada)', 'en_GB' => 'English (United Kingdom)', 'en_IE' => 'English (Ireland)', 'en_US' => 'English (United States)', 'en_ZA' => 'English (South Africa)', - 'eo' => 'Esperanto', - 'es' => 'Spanish', + 'eo' => 'Esperanto', + 'es' => 'Spanish', 'es_AR' => 'Spanish (Argentina)', 'es_BO' => 'Spanish (Bolivia)', 'es_CL' => 'Spanish (Chile)', @@ -467,452 +472,452 @@ class Service 'es_SV' => 'Spanish (El Salvador)', 'es_UY' => 'Spanish (Uruguay)', 'es_VE' => 'Spanish (Venezuela)', - 'et' => 'Estonian', + 'et' => 'Estonian', 'et_EE' => 'Estonian (Estonia)', - 'eu' => 'Basque', + 'eu' => 'Basque', 'eu_ES' => 'Basque (Spain)', - 'fa' => 'Persian', + 'fa' => 'Persian', 'fa_IR' => 'Persian (Iran)', - 'fi' => 'Finnish', + 'fi' => 'Finnish', 'fi_FI' => 'Finnish (Finland)', - 'fj' => 'Fiji', - 'fo' => 'Faroese', + 'fj' => 'Fiji', + 'fo' => 'Faroese', 'fo_FO' => 'Faroese (Faroe Islands)', - 'fr' => 'French', + 'fr' => 'French', 'fr_CA' => 'French (Canada)', 'fr_CH' => 'French (Switzerland)', 'fr_FR' => 'French (France)', - 'fy' => 'Frisian', + 'fy' => 'Frisian', 'fy_NL' => 'Frisian (Netherlands)', - 'ga' => 'Irish', + 'ga' => 'Irish', 'ga_IE' => 'Irish (Ireland)', - 'gd' => 'Scots Gaelic', - 'gl' => 'Galician', + 'gd' => 'Scots Gaelic', + 'gl' => 'Galician', 'gl_ES' => 'Galician (Spain)', - 'gn' => 'Guarani', - 'gu' => 'Gujarati', + 'gn' => 'Guarani', + 'gu' => 'Gujarati', 'gu_IN' => 'Gujarati (India)', - 'ha' => 'Hausa', - 'he' => 'Hebrew', + 'ha' => 'Hausa', + 'he' => 'Hebrew', 'he_IL' => 'Hebrew (Israel)', - 'hi' => 'Hindi', + 'hi' => 'Hindi', 'hi_IN' => 'Hindi (India)', - 'hr' => 'Croatian', + 'hr' => 'Croatian', 'hr_HR' => 'Croatian (Croatia)', - 'hu' => 'Hungarian', + 'hu' => 'Hungarian', 'hu_HU' => 'Hungarian (Hungary)', - 'hy' => 'Armenian', + 'hy' => 'Armenian', 'hy_AM' => 'Armenian (Armenia)', - 'ia' => 'Interlingua', - 'id' => 'Indonesian', + 'ia' => 'Interlingua', + 'id' => 'Indonesian', 'id_ID' => 'Indonesian (Indonesia)', - 'ie' => 'Interlingue', - 'ik' => 'Inupiak', - 'is' => 'Icelandic', + 'ie' => 'Interlingue', + 'ik' => 'Inupiak', + 'is' => 'Icelandic', 'is_IS' => 'Icelandic (Iceland)', - 'it' => 'Italian', + 'it' => 'Italian', 'it_CH' => 'Italian (Switzerland)', 'it_IT' => 'Italian (Italy)', - 'iu' => 'Inuktitut (Eskimo)', - 'ja' => 'Japanese', + 'iu' => 'Inuktitut (Eskimo)', + 'ja' => 'Japanese', 'ja_JP' => 'Japanese (Japan)', - 'jv' => 'Javanese', - 'ka' => 'Georgian', + 'jv' => 'Javanese', + 'ka' => 'Georgian', 'ka_GE' => 'Georgian (Georgia)', - 'kk' => 'Kazakh', + 'kk' => 'Kazakh', 'kk_KZ' => 'Kazakh (Kazakhstan)', - 'kl' => 'Greenlandic', - 'km' => 'Cambodian', - 'kn' => 'Kannada', + 'kl' => 'Greenlandic', + 'km' => 'Cambodian', + 'kn' => 'Kannada', 'kn_IN' => 'Kannada (India)', - 'ko' => 'Korean', + 'ko' => 'Korean', 'ko_KR' => 'Korean (Korea)', - 'ks' => 'Kashmiri', + 'ks' => 'Kashmiri', 'ks_IN' => 'Kashmiri (India)', - 'ku' => 'Kurdish', + 'ku' => 'Kurdish', 'ku_IQ' => 'Kurdish (Iraq)', - 'ky' => 'Kirghiz', - 'la' => 'Latin', - 'ln' => 'Lingala', - 'lo' => 'Lao', + 'ky' => 'Kirghiz', + 'la' => 'Latin', + 'ln' => 'Lingala', + 'lo' => 'Lao', 'lo_LA' => 'Lao (Laos)', - 'lt' => 'Lithuanian', + 'lt' => 'Lithuanian', 'lt_LT' => 'Lithuanian (Lithuania)', - 'lv' => 'Latvian', + 'lv' => 'Latvian', 'lv_LV' => 'Latvian (Latvia)', - 'mg' => 'Malagasy', - 'mi' => 'Maori', - 'mk' => 'Macedonian', + 'mg' => 'Malagasy', + 'mi' => 'Maori', + 'mk' => 'Macedonian', 'mk_MK' => 'Macedonian (Macedonia)', - 'ml' => 'Malayalam', + 'ml' => 'Malayalam', 'ml_IN' => 'Malayalam (India)', - 'mn' => 'Mongolian', + 'mn' => 'Mongolian', 'mn_MN' => 'Mongolian (Mongolia)', - 'mo' => 'Moldavian', - 'mr' => 'Marathi', + 'mo' => 'Moldavian', + 'mr' => 'Marathi', 'mr_IN' => 'Marathi (India)', - 'ms' => 'Malay', + 'ms' => 'Malay', 'ms_MY' => 'Malay (Malaysia)', - 'mt' => 'Maltese', + 'mt' => 'Maltese', 'mt_MT' => 'Maltese (Malta)', - 'my' => 'Burmese', + 'my' => 'Burmese', 'my_MM' => 'Burmese (Myanmar)', - 'na' => 'Nauru', - 'ne' => 'Nepali', + 'na' => 'Nauru', + 'ne' => 'Nepali', 'ne_NP' => 'Nepali (Nepal)', - 'nl' => 'Dutch', + 'nl' => 'Dutch', 'nl_BE' => 'Dutch (Belgium)', 'nl_NL' => 'Dutch (Netherlands)', - 'no' => 'Norwegian', + 'no' => 'Norwegian', 'no_NO' => 'Norwegian (Norway)', - 'oc' => 'Occitan', - 'or' => 'Oriya', + 'oc' => 'Occitan', + 'or' => 'Oriya', 'or_IN' => 'Oriya (India)', - 'pa' => 'Punjabi', + 'pa' => 'Punjabi', 'pa_IN' => 'Punjabi (India)', - 'pl' => 'Polish', + 'pl' => 'Polish', 'pl_PL' => 'Polish (Poland)', - 'ps' => 'Pashto, Pushto', - 'pt' => 'Portuguese', + 'ps' => 'Pashto, Pushto', + 'pt' => 'Portuguese', 'pt_BR' => 'Portuguese (Brazil)', 'pt_PT' => 'Portuguese (Portugal)', - 'qu' => 'Quechua', - 'rm' => 'Romansh', - 'rn' => 'Kirundi', - 'ro' => 'Romanian', + 'qu' => 'Quechua', + 'rm' => 'Romansh', + 'rn' => 'Kirundi', + 'ro' => 'Romanian', 'ro_RO' => 'Romanian (Romania)', - 'ru' => 'Russian', + 'ru' => 'Russian', 'ru_RU' => 'Russian (Russia)', - 'rw' => 'Kinyarwanda', - 'sa' => 'Sanskrit', - 'sd' => 'Sindhi', - 'sg' => 'Sango', - 'sh' => 'Serbo-Croatian', - 'si' => 'Sinhala', + 'rw' => 'Kinyarwanda', + 'sa' => 'Sanskrit', + 'sd' => 'Sindhi', + 'sg' => 'Sango', + 'sh' => 'Serbo-Croatian', + 'si' => 'Sinhala', 'si_LK' => 'Sinhala (Sri Lanka)', - 'sk' => 'Slovak', + 'sk' => 'Slovak', 'sk_SK' => 'Slovak (Slovakia)', - 'sl' => 'Slovenian', + 'sl' => 'Slovenian', 'sl_SI' => 'Slovenian (Slovenia)', - 'sm' => 'Samoan', - 'sn' => 'Shona', - 'so' => 'Somali', - 'sq' => 'Albanian', + 'sm' => 'Samoan', + 'sn' => 'Shona', + 'so' => 'Somali', + 'sq' => 'Albanian', 'sq_AL' => 'Albanian (Albania)', - 'sr' => 'Serbian', + 'sr' => 'Serbian', 'sr_RS' => 'Serbian (Serbia)', - 'ss' => 'Siswati', - 'st' => 'Sotho', + 'ss' => 'Siswati', + 'st' => 'Sotho', 'st_ZA' => 'Sotho (South Africa)', - 'su' => 'Sudanese', - 'sv' => 'Swedish', + 'su' => 'Sudanese', + 'sv' => 'Swedish', 'sv_FI' => 'Swedish (Finland)', 'sv_SE' => 'Swedish (Sweden)', - 'sw' => 'Swahili', + 'sw' => 'Swahili', 'sw_KE' => 'Swahili (Kenya)', - 'ta' => 'Tamil', + 'ta' => 'Tamil', 'ta_IN' => 'Tamil (India)', 'ta_LK' => 'Tamil (Sri Lanka)', - 'te' => 'Telugu', + 'te' => 'Telugu', 'te_IN' => 'Telugu (India)', - 'tg' => 'Tajik', + 'tg' => 'Tajik', 'tg_TJ' => 'Tajik (Tajikistan)', - 'th' => 'Thai', + 'th' => 'Thai', 'th_TH' => 'Thai (Thailand)', - 'ti' => 'Tigrinya', - 'tk' => 'Turkmen', - 'tl' => 'Tagalog', + 'ti' => 'Tigrinya', + 'tk' => 'Turkmen', + 'tl' => 'Tagalog', 'tl_PH' => 'Tagalog (Philippines)', - 'tn' => 'Setswana', - 'to' => 'Tonga', - 'tr' => 'Turkish', + 'tn' => 'Setswana', + 'to' => 'Tonga', + 'tr' => 'Turkish', 'tr_TR' => 'Turkish (Turkey)', - 'ts' => 'Tsonga', - 'tt' => 'Tatar', - 'tw' => 'Twi', - 'ug' => 'Uigur', - 'uk' => 'Ukrainian', + 'ts' => 'Tsonga', + 'tt' => 'Tatar', + 'tw' => 'Twi', + 'ug' => 'Uigur', + 'uk' => 'Ukrainian', 'uk_UA' => 'Ukrainian (Ukraine)', - 'ur' => 'Urdu', + 'ur' => 'Urdu', 'ur_PK' => 'Urdu (Pakistan)', - 'uz' => 'Uzbek', - 'vi' => 'Vietnamese', + 'uz' => 'Uzbek', + 'vi' => 'Vietnamese', 'vi_VN' => 'Vietnamese (Vietnam)', - 'vo' => 'Volapuk', - 'wo' => 'Wolof', + 'vo' => 'Volapuk', + 'wo' => 'Wolof', 'wo_SN' => 'Wolof (Senegal)', - 'xh' => 'Xhosa', - 'yi' => 'Yiddish', - 'yo' => 'Yoruba', - 'za' => 'Zhuang', - 'zh' => 'Chinese', + 'xh' => 'Xhosa', + 'yi' => 'Yiddish', + 'yo' => 'Yoruba', + 'za' => 'Zhuang', + 'zh' => 'Chinese', 'zh_CN' => 'Chinese (China)', 'zh_HK' => 'Chinese (Hong Kong)', 'zh_TW' => 'Chinese (Taiwan)', - 'zu' => 'Zulu', - 'zu_ZA' => 'Zulu (South Africa)' - ); + 'zu' => 'Zulu', + 'zu_ZA' => 'Zulu (South Africa)', + ]; } public function getCountries() { - //default countries - $countries = array( - "AF" => "Afghanistan", - "AX" => "Aland Islands", - "AL" => "Albania", - "DZ" => "Algeria", - "AS" => "American Samoa", - "AD" => "Andorra", - "AO" => "Angola", - "AI" => "Anguilla", - "AQ" => "Antarctica", - "AG" => "Antigua and Barbuda", - "AR" => "Argentina", - "AM" => "Armenia", - "AW" => "Aruba", - "AU" => "Australia", - "AT" => "Austria", - "AZ" => "Azerbaijan", - "BS" => "Bahamas", - "BH" => "Bahrain", - "BD" => "Bangladesh", - "BB" => "Barbados", - "BY" => "Belarus", - "BE" => "Belgium", - "BZ" => "Belize", - "BJ" => "Benin", - "BM" => "Bermuda", - "BT" => "Bhutan", - "BO" => "Bolivia", - "BQ" => "Bonaire, Sint Eustatius and Saba", - "BA" => "Bosnia and Herzegovina", - "BW" => "Botswana", - "BR" => "Brazil", - "IO" => "British Indian Ocean Territory", - "VG" => "British Virgin Islands", - "BN" => "Brunei", - "BG" => "Bulgaria", - "BF" => "Burkina Faso", - "BI" => "Burundi", - "CV" => "Cabo Verde", - "KH" => "Cambodia", - "CM" => "Cameroon", - "CA" => "Canada", - "KY" => "Cayman Islands", - "CF" => "Central African Republic", - "TD" => "Chad", - "CL" => "Chile", - "CN" => "China", - "CX" => "Christmas Island", - "CC" => "Cocos (Keeling) Islands", - "CO" => "Colombia", - "KM" => "Comoros", - "CD" => "Congo (Democratic Republic of the)", - "CG" => "Congo (Republic of the)", - "CK" => "Cook Islands", - "CR" => "Costa Rica", - "CI" => "Cote D'Ivoire", - "HR" => "Croatia", - "CU" => "Cuba", - "CW" => "Curacao", - "CY" => "Cyprus", - "CZ" => "Czechia", - "DK" => "Denmark", - "DJ" => "Djibouti", - "DM" => "Dominica", - "DO" => "Dominican Republic", - "EC" => "Ecuador", - "EG" => "Egypt", - "SV" => "El Salvador", - "GQ" => "Equatorial Guinea", - "ER" => "Eritrea", - "EE" => "Estonia", - "SZ" => "Eswatini", - "ET" => "Ethiopia", - "FK" => "Falkland Islands (Islas Malvinas)", - "FO" => "Faroe Islands", - "FJ" => "Fiji", - "FI" => "Finland", - "FR" => "France", - "GF" => "French Guiana", - "PF" => "French Polynesia", - "TF" => "French Southern Territories", - "GA" => "Gabon", - "GM" => "Gambia", - "GE" => "Georgia", - "DE" => "Germany", - "GH" => "Ghana", - "GI" => "Gibraltar", - "GR" => "Greece", - "GL" => "Greenland", - "GD" => "Grenada", - "GP" => "Guadeloupe", - "GU" => "Guam", - "GT" => "Guatemala", - "GG" => "Guernsey", - "GN" => "Guinea", - "GW" => "Guinea-Bissau", - "GY" => "Guyana", - "HT" => "Haiti", - "HN" => "Honduras", - "HK" => "Hong Kong", - "HU" => "Hungary", - "IS" => "Iceland", - "IN" => "India", - "ID" => "Indonesia", - "IR" => "Iran", - "IQ" => "Iraq", - "IE" => "Ireland", - "IM" => "Isle of Man", - "IL" => "Israel", - "IT" => "Italy", - "JM" => "Jamaica", - "JP" => "Japan", - "JE" => "Jersey", - "JO" => "Jordan", - "KZ" => "Kazakhstan", - "KE" => "Kenya", - "KI" => "Kiribati", - "KW" => "Kuwait", - "KG" => "Kyrgyzstan", - "LA" => "Laos", - "LV" => "Latvia", - "LB" => "Lebanon", - "LS" => "Lesotho", - "LR" => "Liberia", - "LY" => "Libya", - "LI" => "Liechtenstein", - "LT" => "Lithuania", - "LU" => "Luxembourg", - "MO" => "Macau", - "MG" => "Madagascar", - "MW" => "Malawi", - "MY" => "Malaysia", - "MV" => "Maldives", - "ML" => "Mali", - "MT" => "Malta", - "MH" => "Marshall Islands", - "MQ" => "Martinique", - "MR" => "Mauritania", - "MU" => "Mauritius", - "YT" => "Mayotte", - "MX" => "Mexico", - "FM" => "Micronesia", - "MD" => "Moldova", - "MC" => "Monaco", - "MN" => "Mongolia", - "ME" => "Montenegro", - "MS" => "Montserrat", - "MA" => "Morocco", - "MZ" => "Mozambique", - "MM" => "Myanmar (Burma)", - "NA" => "Namibia", - "NR" => "Nauru", - "NP" => "Nepal", - "NL" => "Netherlands", - "NC" => "New Caledonia", - "NZ" => "New Zealand", - "NI" => "Nicaragua", - "NE" => "Niger", - "NG" => "Nigeria", - "NU" => "Niue", - "NF" => "Norfolk Island", - "KP" => "North Korea", - "MK" => "North Macedonia", - "MP" => "Northern Mariana Islands", - "NO" => "Norway", - "OM" => "Oman", - "PK" => "Pakistan", - "PW" => "Palau", - "PS" => "Palestine", - "PA" => "Panama", - "PG" => "Papua New Guinea", - "PY" => "Paraguay", - "PE" => "Peru", - "PH" => "Philippines", - "PN" => "Pitcairn Islands", - "PL" => "Poland", - "PT" => "Portugal", - "PR" => "Puerto Rico", - "QA" => "Qatar", - "RE" => "Reunion", - "RO" => "Romania", - "RU" => "Russia", - "RW" => "Rwanda", - "BL" => "Saint Barthelemy", - "SH" => "Saint Helena, Ascension and Tristan da Cunha", - "KN" => "Saint Kitts And Nevis", - "LC" => "Saint Lucia", - "MF" => "Saint Martin", - "VC" => "Saint Vincent and the Grenadines", - "PM" => "Saint Pierre And Miquelon", - "WS" => "Samoa", - "SM" => "San Marino", - "ST" => "Sao Tome And Principe", - "SA" => "Saudi Arabia", - "SN" => "Senegal", - "RS" => "Serbia", - "SC" => "Seychelles", - "SL" => "Sierra Leone", - "SG" => "Singapore", - "SX" => "Sint Maarten", - "SK" => "Slovakia", - "SI" => "Slovenia", - "SB" => "Solomon Islands", - "SO" => "Somalia", - "ZA" => "South Africa", - "GS" => "South Georgia and the South Sandwich Islands", - "SS" => "South Sudan", - "KR" => "South Korea", - "ES" => "Spain", - "LK" => "Sri Lanka", - "SD" => "Sudan", - "SR" => "Suriname", - "SJ" => "Svalbard and Jan Mayen", - "SE" => "Sweden", - "CH" => "Switzerland", - "SY" => "Syria", - "TW" => "Taiwan", - "TJ" => "Tajikistan", - "TZ" => "Tanzania", - "TH" => "Thailand", - "TP" => "Timor-Leste", - "TG" => "Togo", - "TK" => "Tokelau", - "TO" => "Tonga", - "TT" => "Trinidad and Tobago", - "TN" => "Tunisia", - "TR" => "Turkey", - "TM" => "Turkmenistan", - "TC" => "Turks and Caicos Islands", - "TV" => "Tuvalu", - "UG" => "Uganda", - "UA" => "Ukraine", - "AE" => "United Arab Emirates", - "GB" => "United Kingdom", - "US" => "United States", - "UM" => "United States Minor Outlying Islands", - "UY" => "Uruguay", - "UZ" => "Uzbekistan", - "VU" => "Vanuatu", - "VA" => "Vatican City", - "VE" => "Venezuela", - "VN" => "Vietnam", - "VI" => "Virgin Islands (U.S.)", - "WF" => "Wallis and Futuna", - "EH" => "Western Sahara", - "YE" => "Yemen", - "ZM" => "Zambia", - "ZW" => "Zimbabwe" - ); + // default countries + $countries = [ + 'AF' => 'Afghanistan', + 'AX' => 'Aland Islands', + 'AL' => 'Albania', + 'DZ' => 'Algeria', + 'AS' => 'American Samoa', + 'AD' => 'Andorra', + 'AO' => 'Angola', + 'AI' => 'Anguilla', + 'AQ' => 'Antarctica', + 'AG' => 'Antigua and Barbuda', + 'AR' => 'Argentina', + 'AM' => 'Armenia', + 'AW' => 'Aruba', + 'AU' => 'Australia', + 'AT' => 'Austria', + 'AZ' => 'Azerbaijan', + 'BS' => 'Bahamas', + 'BH' => 'Bahrain', + 'BD' => 'Bangladesh', + 'BB' => 'Barbados', + 'BY' => 'Belarus', + 'BE' => 'Belgium', + 'BZ' => 'Belize', + 'BJ' => 'Benin', + 'BM' => 'Bermuda', + 'BT' => 'Bhutan', + 'BO' => 'Bolivia', + 'BQ' => 'Bonaire, Sint Eustatius and Saba', + 'BA' => 'Bosnia and Herzegovina', + 'BW' => 'Botswana', + 'BR' => 'Brazil', + 'IO' => 'British Indian Ocean Territory', + 'VG' => 'British Virgin Islands', + 'BN' => 'Brunei', + 'BG' => 'Bulgaria', + 'BF' => 'Burkina Faso', + 'BI' => 'Burundi', + 'CV' => 'Cabo Verde', + 'KH' => 'Cambodia', + 'CM' => 'Cameroon', + 'CA' => 'Canada', + 'KY' => 'Cayman Islands', + 'CF' => 'Central African Republic', + 'TD' => 'Chad', + 'CL' => 'Chile', + 'CN' => 'China', + 'CX' => 'Christmas Island', + 'CC' => 'Cocos (Keeling) Islands', + 'CO' => 'Colombia', + 'KM' => 'Comoros', + 'CD' => 'Congo (Democratic Republic of the)', + 'CG' => 'Congo (Republic of the)', + 'CK' => 'Cook Islands', + 'CR' => 'Costa Rica', + 'CI' => "Cote D'Ivoire", + 'HR' => 'Croatia', + 'CU' => 'Cuba', + 'CW' => 'Curacao', + 'CY' => 'Cyprus', + 'CZ' => 'Czechia', + 'DK' => 'Denmark', + 'DJ' => 'Djibouti', + 'DM' => 'Dominica', + 'DO' => 'Dominican Republic', + 'EC' => 'Ecuador', + 'EG' => 'Egypt', + 'SV' => 'El Salvador', + 'GQ' => 'Equatorial Guinea', + 'ER' => 'Eritrea', + 'EE' => 'Estonia', + 'SZ' => 'Eswatini', + 'ET' => 'Ethiopia', + 'FK' => 'Falkland Islands (Islas Malvinas)', + 'FO' => 'Faroe Islands', + 'FJ' => 'Fiji', + 'FI' => 'Finland', + 'FR' => 'France', + 'GF' => 'French Guiana', + 'PF' => 'French Polynesia', + 'TF' => 'French Southern Territories', + 'GA' => 'Gabon', + 'GM' => 'Gambia', + 'GE' => 'Georgia', + 'DE' => 'Germany', + 'GH' => 'Ghana', + 'GI' => 'Gibraltar', + 'GR' => 'Greece', + 'GL' => 'Greenland', + 'GD' => 'Grenada', + 'GP' => 'Guadeloupe', + 'GU' => 'Guam', + 'GT' => 'Guatemala', + 'GG' => 'Guernsey', + 'GN' => 'Guinea', + 'GW' => 'Guinea-Bissau', + 'GY' => 'Guyana', + 'HT' => 'Haiti', + 'HN' => 'Honduras', + 'HK' => 'Hong Kong', + 'HU' => 'Hungary', + 'IS' => 'Iceland', + 'IN' => 'India', + 'ID' => 'Indonesia', + 'IR' => 'Iran', + 'IQ' => 'Iraq', + 'IE' => 'Ireland', + 'IM' => 'Isle of Man', + 'IL' => 'Israel', + 'IT' => 'Italy', + 'JM' => 'Jamaica', + 'JP' => 'Japan', + 'JE' => 'Jersey', + 'JO' => 'Jordan', + 'KZ' => 'Kazakhstan', + 'KE' => 'Kenya', + 'KI' => 'Kiribati', + 'KW' => 'Kuwait', + 'KG' => 'Kyrgyzstan', + 'LA' => 'Laos', + 'LV' => 'Latvia', + 'LB' => 'Lebanon', + 'LS' => 'Lesotho', + 'LR' => 'Liberia', + 'LY' => 'Libya', + 'LI' => 'Liechtenstein', + 'LT' => 'Lithuania', + 'LU' => 'Luxembourg', + 'MO' => 'Macau', + 'MG' => 'Madagascar', + 'MW' => 'Malawi', + 'MY' => 'Malaysia', + 'MV' => 'Maldives', + 'ML' => 'Mali', + 'MT' => 'Malta', + 'MH' => 'Marshall Islands', + 'MQ' => 'Martinique', + 'MR' => 'Mauritania', + 'MU' => 'Mauritius', + 'YT' => 'Mayotte', + 'MX' => 'Mexico', + 'FM' => 'Micronesia', + 'MD' => 'Moldova', + 'MC' => 'Monaco', + 'MN' => 'Mongolia', + 'ME' => 'Montenegro', + 'MS' => 'Montserrat', + 'MA' => 'Morocco', + 'MZ' => 'Mozambique', + 'MM' => 'Myanmar (Burma)', + 'NA' => 'Namibia', + 'NR' => 'Nauru', + 'NP' => 'Nepal', + 'NL' => 'Netherlands', + 'NC' => 'New Caledonia', + 'NZ' => 'New Zealand', + 'NI' => 'Nicaragua', + 'NE' => 'Niger', + 'NG' => 'Nigeria', + 'NU' => 'Niue', + 'NF' => 'Norfolk Island', + 'KP' => 'North Korea', + 'MK' => 'North Macedonia', + 'MP' => 'Northern Mariana Islands', + 'NO' => 'Norway', + 'OM' => 'Oman', + 'PK' => 'Pakistan', + 'PW' => 'Palau', + 'PS' => 'Palestine', + 'PA' => 'Panama', + 'PG' => 'Papua New Guinea', + 'PY' => 'Paraguay', + 'PE' => 'Peru', + 'PH' => 'Philippines', + 'PN' => 'Pitcairn Islands', + 'PL' => 'Poland', + 'PT' => 'Portugal', + 'PR' => 'Puerto Rico', + 'QA' => 'Qatar', + 'RE' => 'Reunion', + 'RO' => 'Romania', + 'RU' => 'Russia', + 'RW' => 'Rwanda', + 'BL' => 'Saint Barthelemy', + 'SH' => 'Saint Helena, Ascension and Tristan da Cunha', + 'KN' => 'Saint Kitts And Nevis', + 'LC' => 'Saint Lucia', + 'MF' => 'Saint Martin', + 'VC' => 'Saint Vincent and the Grenadines', + 'PM' => 'Saint Pierre And Miquelon', + 'WS' => 'Samoa', + 'SM' => 'San Marino', + 'ST' => 'Sao Tome And Principe', + 'SA' => 'Saudi Arabia', + 'SN' => 'Senegal', + 'RS' => 'Serbia', + 'SC' => 'Seychelles', + 'SL' => 'Sierra Leone', + 'SG' => 'Singapore', + 'SX' => 'Sint Maarten', + 'SK' => 'Slovakia', + 'SI' => 'Slovenia', + 'SB' => 'Solomon Islands', + 'SO' => 'Somalia', + 'ZA' => 'South Africa', + 'GS' => 'South Georgia and the South Sandwich Islands', + 'SS' => 'South Sudan', + 'KR' => 'South Korea', + 'ES' => 'Spain', + 'LK' => 'Sri Lanka', + 'SD' => 'Sudan', + 'SR' => 'Suriname', + 'SJ' => 'Svalbard and Jan Mayen', + 'SE' => 'Sweden', + 'CH' => 'Switzerland', + 'SY' => 'Syria', + 'TW' => 'Taiwan', + 'TJ' => 'Tajikistan', + 'TZ' => 'Tanzania', + 'TH' => 'Thailand', + 'TP' => 'Timor-Leste', + 'TG' => 'Togo', + 'TK' => 'Tokelau', + 'TO' => 'Tonga', + 'TT' => 'Trinidad and Tobago', + 'TN' => 'Tunisia', + 'TR' => 'Turkey', + 'TM' => 'Turkmenistan', + 'TC' => 'Turks and Caicos Islands', + 'TV' => 'Tuvalu', + 'UG' => 'Uganda', + 'UA' => 'Ukraine', + 'AE' => 'United Arab Emirates', + 'GB' => 'United Kingdom', + 'US' => 'United States', + 'UM' => 'United States Minor Outlying Islands', + 'UY' => 'Uruguay', + 'UZ' => 'Uzbekistan', + 'VU' => 'Vanuatu', + 'VA' => 'Vatican City', + 'VE' => 'Venezuela', + 'VN' => 'Vietnam', + 'VI' => 'Virgin Islands (U.S.)', + 'WF' => 'Wallis and Futuna', + 'EH' => 'Western Sahara', + 'YE' => 'Yemen', + 'ZM' => 'Zambia', + 'ZW' => 'Zimbabwe', + ]; - $mod = $this->di['mod']('system'); + $mod = $this->di['mod']('system'); $config = $mod->getConfig(); if (isset($config['countries'])) { preg_match_all('#([A-Z]{2})=(.+)#', $config['countries'], $matches); if (isset($matches[1]) && !empty($matches[1]) && isset($matches[2]) && !empty($matches[2])) { - if (count($matches[1] == count($matches[2]))){ + if (count($matches[1] == count($matches[2]))) { $countries = array_combine($matches[1], $matches[2]); } } @@ -923,55 +928,58 @@ class Service public function getEuCountries() { - $list = array( + $list = [ 'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', - 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'); + 'PL', 'PT', 'RO', 'SE', 'SI', 'SK', ]; $c = $this->getCountries(); - $res = array(); + $res = []; foreach ($list as $code) { - if (!isset($c[$code])) { continue;}; + if (!isset($c[$code])) { + continue; + } $res[$code] = $c[$code]; } + return $res; } public function getEuVat() { - return array( - 'AT' => 20, //Austria - 'BE' => 21, //Belgium - 'BG' => 20, //Bulgaria - 'HR' => 25, //Croatia - 'CY' => 19, //Cyprus - 'CZ' => 21, //Czech Republic - 'DK' => 25, //Denmark - 'EE' => 20, //Estonia - 'FI' => 24, //Finland - 'FR' => 20, //France - 'DE' => 19, //Germany - 'GR' => 24, //Greece - 'HU' => 27, //Hungary - 'IE' => 23, //Ireland - 'IT' => 22, //Italy - 'LV' => 21, //Latvia - 'LT' => 21, //Lithuania - 'LU' => 17, //Luxembourg - 'MT' => 18, //Malta - 'NL' => 21, //Netherlands - 'PL' => 23, //Poland - 'PT' => 23, //Portugal - 'RO' => 19, //Romania - 'SK' => 20, //Slovakia - 'SI' => 22, //Slovenia - 'ES' => 21, //Spain - 'SE' => 25, //Sweden - ); + return [ + 'AT' => 20, // Austria + 'BE' => 21, // Belgium + 'BG' => 20, // Bulgaria + 'HR' => 25, // Croatia + 'CY' => 19, // Cyprus + 'CZ' => 21, // Czech Republic + 'DK' => 25, // Denmark + 'EE' => 20, // Estonia + 'FI' => 24, // Finland + 'FR' => 20, // France + 'DE' => 19, // Germany + 'GR' => 24, // Greece + 'HU' => 27, // Hungary + 'IE' => 23, // Ireland + 'IT' => 22, // Italy + 'LV' => 21, // Latvia + 'LT' => 21, // Lithuania + 'LU' => 17, // Luxembourg + 'MT' => 18, // Malta + 'NL' => 21, // Netherlands + 'PL' => 23, // Poland + 'PT' => 23, // Portugal + 'RO' => 19, // Romania + 'SK' => 20, // Slovakia + 'SI' => 22, // Slovenia + 'ES' => 21, // Spain + 'SE' => 25, // Sweden + ]; } public function getStates() { - return array ( + return [ 'AK' => 'Alaska', 'AL' => 'Alabama', 'AR' => 'Arkansas', @@ -1022,12 +1030,12 @@ class Service 'WI' => 'Wisconsin', 'WV' => 'West Virginia', 'WY' => 'Wyoming', - ); + ]; } public function getPhoneCodes($data) { - $codes = array( + $codes = [ 'AF' => '93', 'AL' => '355', 'DZ' => '213', @@ -1268,17 +1276,17 @@ class Service 'YE' => '967', 'ZM' => '260', 'ZW' => '263', - ); + ]; - if(isset($data['country'])) { - if(array_key_exists($data['country'], $codes)) { + if (isset($data['country'])) { + if (array_key_exists($data['country'], $codes)) { return $codes[$data['country']]; } else { - throw new \Box_Exception('Country :code phone code is not registered', array(':code'=>$data['country'])); + throw new \Box_Exception('Country :code phone code is not registered', [':code' => $data['country']]); } } - return array( + return [ '7940' => 'Abkhazia +7940', '99544' => 'Abkhazia +99544', '93' => 'Afghanistan +93', @@ -1529,15 +1537,14 @@ class Service '260' => 'Zambia +260', '255' => 'Zanzibar +255', '263' => 'Zimbabwe +263', - ); + ]; } /** - * Call this method in API to check limits for entries + * Call this method in API to check limits for entries. */ public function checkLimits($model, $limit = 2) { - } public function getNameservers() @@ -1556,8 +1563,8 @@ class Service { $messages = $this->di['session']->get('pending_messages'); - if (!is_array($messages)){ - return array(); + if (!is_array($messages)) { + return []; } return $messages; @@ -1568,12 +1575,14 @@ class Service $messages = $this->getPendingMessages(); array_push($messages, $msg); $this->di['session']->set('pending_messages', $messages); + return true; } public function clearPendingMessages() { $this->di['session']->delete('pending_messages'); + return true; } } diff --git a/src/bb-modules/Theme/Api/Admin.php b/src/bb-modules/Theme/Api/Admin.php index e63b3fd17..50a621d5e 100644 --- a/src/bb-modules/Theme/Api/Admin.php +++ b/src/bb-modules/Theme/Api/Admin.php @@ -1,6 +1,6 @@ getService()->getThemes(); - return array('list'=>$themes); + + return ['list' => $themes]; } - + /** - * Get list of available admin area themes - * - * @return array + * Get list of available admin area themes. + * + * @return array */ public function get_admin_list($data) { $themes = $this->getService()->getThemes(false); - return array('list'=>$themes); + + return ['list' => $themes]; } /** - * Get theme by code - * + * Get theme by code. + * * @param string $code - theme code - * - * @return array + * + * @return array */ public function get($data) { - $required = array( - 'code' => 'Theme code is missing', - ); + $required = [ + 'code' => 'Theme code is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); return $this->getService()->loadTheme($data['code']); } /** - * Set new theme as default - * + * Set new theme as default. + * * @param string $code - theme code + * * @return bool */ public function select($data) { - $required = array( - 'code' => 'Theme code is missing', - ); + $required = [ + 'code' => 'Theme code is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $theme = $this->getService()->getTheme($data['code']); $systemService = $this->di['mod_service']('system'); - if($theme->isAdminAreaTheme()) { + if ($theme->isAdminAreaTheme()) { $systemService->setParamValue('admin_theme', $data['code']); } else { $systemService->setParamValue('theme', $data['code']); } $this->di['logger']->info('Changed default theme'); + return true; } /** - * Delete theme preset + * Delete theme preset. * - * @param string $code - theme code + * @param string $code - theme code * @param string $preset - theme preset code * * @return bool */ public function preset_delete($data) { - $required = array( - 'code' => 'Theme code is missing', - 'preset' => 'Theme preset name is missing', - ); + $required = [ + 'code' => 'Theme code is missing', + 'preset' => 'Theme preset name is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); @@ -104,19 +108,19 @@ class Admin extends \Api_Abstract } /** - * Select new theme preset + * Select new theme preset. * - * @param string $code - theme code + * @param string $code - theme code * @param string $preset - theme preset code * * @return bool */ public function preset_select($data) { - $required = array( - 'code' => 'Theme code is missing', - 'preset' => 'Theme preset name is missing', - ); + $required = [ + 'code' => 'Theme code is missing', + 'preset' => 'Theme preset name is missing', + ]; $this->di['validator']->checkRequiredParamsForArray($required, $data); $service = $this->getService(); @@ -125,4 +129,4 @@ class Admin extends \Api_Abstract return true; } -} \ No newline at end of file +} diff --git a/src/bb-modules/Theme/Controller/Admin.php b/src/bb-modules/Theme/Controller/Admin.php index cbb100d26..a5aef1191 100644 --- a/src/bb-modules/Theme/Controller/Admin.php +++ b/src/bb-modules/Theme/Controller/Admin.php @@ -1,6 +1,6 @@ get('/theme/:theme', 'get_theme', array('theme' => '[a-z0-9-_]+'), get_class($this)); - $app->post('/theme/:theme', 'save_theme_settings', array('theme' => '[a-z0-9-_]+'), get_class($this)); + $app->get('/theme/:theme', 'get_theme', ['theme' => '[a-z0-9-_]+'], get_class($this)); + $app->post('/theme/:theme', 'save_theme_settings', ['theme' => '[a-z0-9-_]+'], get_class($this)); } /** - * Save theme settings + * Save theme settings. * * @param string $code - client area theme code + * * @return array */ public function save_theme_settings(\Box_App $app, $theme) { - $this->di['events_manager']->fire(array('event' => 'onBeforeThemeSettingsSave', 'params' => $_POST)); + $this->di['events_manager']->fire(['event' => 'onBeforeThemeSettingsSave', 'params' => $_POST]); $api = $this->di['api_admin']; @@ -55,41 +55,40 @@ class Admin implements \Box\InjectionAwareInterface $service = $mod->getService(); $t = $service->getTheme($theme); - $isNewPreset = isset($_POST['save-current-setting']) ? (bool)$_POST['save-current-setting'] : false; + $isNewPreset = isset($_POST['save-current-setting']) ? (bool) $_POST['save-current-setting'] : false; $preset = $service->getCurrentThemePreset($t); - if($isNewPreset && isset($_POST['save-current-setting-preset']) && !empty($_POST['save-current-setting-preset'])) { + if ($isNewPreset && isset($_POST['save-current-setting-preset']) && !empty($_POST['save-current-setting-preset'])) { $preset = $_POST['save-current-setting-preset']; - $preset = str_replace(" ", "", $preset); + $preset = str_replace(' ', '', $preset); $service->setCurrentThemePreset($t, $preset); } unset($_POST['save-current-setting-preset']); unset($_POST['save-current-setting']); - $error = null; try { - if(!$t->isAssetsPathWritable()) { - throw new \Box_Exception('Theme ":name" assets folder is not writable. Files can not be uploaded and settings can not be saved. Set folder permissions to 777', array(':name'=>$t->getName())); + if (!$t->isAssetsPathWritable()) { + throw new \Box_Exception('Theme ":name" assets folder is not writable. Files can not be uploaded and settings can not be saved. Set folder permissions to 777', [':name' => $t->getName()]); } $service->updateSettings($t, $preset, $_POST); $service->uploadAssets($t, $_FILES); $service->regenerateThemeCssAndJsFiles($t, $preset, $api); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e); $error = $e->getMessage(); } - //optional data file + // optional data file try { $service->regenerateThemeSettingsDataFile($t); - } catch(\Exception $e) { + } catch (\Exception $e) { error_log($e); $error = $e->getMessage(); } $red_url = '/theme/'.$theme; - if($error) { + if ($error) { $red_url .= '?error='.$error; } $app->redirect($red_url); @@ -106,27 +105,26 @@ class Admin implements \Box\InjectionAwareInterface $html = $t->getSettingsPageHtml($theme); $info = null; - if(!$t->isAssetsPathWritable()) { - $info = __('Theme ":name" assets folder is not writable. Set folder :folder permissions to 777', array(':name'=>$t->getName(), ':folder'=>$t->getPathAssets())); + if (!$t->isAssetsPathWritable()) { + $info = __('Theme ":name" assets folder is not writable. Set folder :folder permissions to 777', [':name' => $t->getName(), ':folder' => $t->getPathAssets()]); } - if(empty($html)) { - $info = __('Theme ":name" is not configurable', array(':name'=>$t->getName())); + if (empty($html)) { + $info = __('Theme ":name" is not configurable', [':name' => $t->getName()]); } - - $data = array( - 'info' => $info, - 'error' => $this->di['array_get']($_GET, 'error', null), - 'theme_code' => $t->getName(), + $data = [ + 'info' => $info, + 'error' => $this->di['array_get']($_GET, 'error', null), + 'theme_code' => $t->getName(), 'settings_html' => $html, - 'uploaded' => $t->getUploadedAssets($theme), - 'settings' => $service->getThemeSettings($t, $preset), - 'current_preset'=> $preset, - 'presets' => $service->getThemePresets($t), - 'snippets' => $t->getSnippets(), - ); + 'uploaded' => $t->getUploadedAssets($theme), + 'settings' => $service->getThemeSettings($t, $preset), + 'current_preset' => $preset, + 'presets' => $service->getThemePresets($t), + 'snippets' => $t->getSnippets(), + ]; return $app->render('mod_theme_preset', $data); } -} \ No newline at end of file +} diff --git a/src/bb-modules/Theme/Model/Theme.php b/src/bb-modules/Theme/Model/Theme.php index 4997fb4ba..1ac03c36b 100644 --- a/src/bb-modules/Theme/Model/Theme.php +++ b/src/bb-modules/Theme/Model/Theme.php @@ -1,6 +1,6 @@ name = $name; - if(!file_exists($this->getPath())) { - throw new \Box_Exception('Theme ":name" does not exists', array(':name'=>$name)); + if (!file_exists($this->getPath())) { + throw new \Box_Exception('Theme ":name" does not exists', [':name' => $name]); } } @@ -33,7 +32,7 @@ class Theme public function isAdminAreaTheme() { - return (strpos($this->name, 'admin_') !== false); + return false !== strpos($this->name, 'admin_'); } public function isAssetsPathWritable() @@ -44,11 +43,12 @@ class Theme public function getSnippets() { $path = $this->getPathHtml(); - $snippets = glob($path .DIRECTORY_SEPARATOR. 'snippet_*.phtml'); - $result = array(); - foreach($snippets as $snippet) { - $result[basename($snippet)] = str_replace('snippet_','', pathinfo($snippet, PATHINFO_FILENAME)); + $snippets = glob($path.DIRECTORY_SEPARATOR.'snippet_*.phtml'); + $result = []; + foreach ($snippets as $snippet) { + $result[basename($snippet)] = str_replace('snippet_', '', pathinfo($snippet, PATHINFO_FILENAME)); } + return $result; } @@ -56,33 +56,35 @@ class Theme { $assets_folder = $this->getPathAssets(); $files = $this->getSettingsPageFiles(); - $uploaded = array(); - foreach($files as $file) { - if(file_exists($assets_folder .DIRECTORY_SEPARATOR. $file)) { - $uploaded[] = array( - 'name' => $file, - 'url' => $this->getUrl().'/assets/'.$file, - ); + $uploaded = []; + foreach ($files as $file) { + if (file_exists($assets_folder.DIRECTORY_SEPARATOR.$file)) { + $uploaded[] = [ + 'name' => $file, + 'url' => $this->getUrl().'/assets/'.$file, + ]; } } + return $uploaded; } private function getSettingsPageFiles() { $str = $this->getSettingsPageHtml(); - if(empty($str)) { - return array(); + if (empty($str)) { + return []; } $dom = new \DOMDocument(); $dom->loadHTML($str); $xpath = new \DOMXPath($dom); $nodes = $xpath->query("//input[@type='file']/@name"); - $files = array(); - foreach($nodes as $node) { + $files = []; + foreach ($nodes as $node) { $files[] = $node->textContent; } + return $files; } @@ -91,20 +93,21 @@ class Theme */ public function getSettingsPageHtml() { - $spp = $this->getPathConfig() .DIRECTORY_SEPARATOR. 'settings.html'; - if(!file_exists($spp)) { - error_log('Theme '. $this->getName() .' does not have settings page'); + $spp = $this->getPathConfig().DIRECTORY_SEPARATOR.'settings.html'; + if (!file_exists($spp)) { + error_log('Theme '.$this->getName().' does not have settings page'); + return ''; } $settings_page = file_get_contents($spp); $settings_page = $this->strip_tags_content($settings_page, '