From a76adb3bc4d36ab6793aae2819eed352856c8383 Mon Sep 17 00:00:00 2001 From: afayadas Date: Wed, 29 Dec 2021 15:25:05 +0100 Subject: [PATCH 01/15] refs #32038 : update totclasslib to 2.3.1 version --- 202/classlib.yml | 2 +- vendor/totpsclasslib/index.php | 33 +++ .../src/Actions/ActionsHandler.php | 49 ++-- .../src/Actions/DefaultActions.php | 2 +- vendor/totpsclasslib/src/Db/DbSchema.php | 5 +- vendor/totpsclasslib/src/Db/DbTable.php | 4 +- .../src/Db/DbTableDefinitionModel.php | 2 +- .../src/Db/DbTableDefinitionRelation.php | 33 ++- .../src/Db/ObjectModelDefinition.php | 2 +- .../src/Db/ObjectModelExtension.php | 2 +- .../Extensions/AbstractModuleExtension.php | 101 ++++++- .../Classes/ProcessLoggerObjectModel.php | 15 +- .../Admin/AdminProcessLoggerController.php | 9 +- .../ProcessLogger/ProcessLoggerExtension.php | 2 +- .../ProcessLogger/ProcessLoggerHandler.php | 42 ++- .../totpsclasslib/src/Hook/AbstractHook.php | 48 ++++ .../src/Hook/AbstractHookDispatcher.php | 119 ++++++++ .../src/Install/ExtensionInstaller.php | 12 + vendor/totpsclasslib/src/Module.php | 267 ++++++++++++++++++ vendor/totpsclasslib/src/Registry.php | 2 +- .../src/Utils/Translate/TranslateTrait.php | 57 ++++ 21 files changed, 719 insertions(+), 89 deletions(-) create mode 100644 vendor/totpsclasslib/index.php create mode 100644 vendor/totpsclasslib/src/Hook/AbstractHook.php create mode 100644 vendor/totpsclasslib/src/Hook/AbstractHookDispatcher.php create mode 100644 vendor/totpsclasslib/src/Module.php create mode 100644 vendor/totpsclasslib/src/Utils/Translate/TranslateTrait.php diff --git a/202/classlib.yml b/202/classlib.yml index 822ebb09..5b4d50b3 100755 --- a/202/classlib.yml +++ b/202/classlib.yml @@ -1 +1 @@ -version: release/2.1.1 +version: release/2.3.1 diff --git a/vendor/totpsclasslib/index.php b/vendor/totpsclasslib/index.php new file mode 100644 index 00000000..a0ac27b3 --- /dev/null +++ b/vendor/totpsclasslib/index.php @@ -0,0 +1,33 @@ + + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + */ + +header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); +header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); + +header("Cache-Control: no-store, no-cache, must-revalidate"); +header("Cache-Control: post-check=0, pre-check=0", false); +header("Pragma: no-cache"); + +header("Location: ../"); +exit; diff --git a/vendor/totpsclasslib/src/Actions/ActionsHandler.php b/vendor/totpsclasslib/src/Actions/ActionsHandler.php index a68a50a8..23f25126 100644 --- a/vendor/totpsclasslib/src/Actions/ActionsHandler.php +++ b/vendor/totpsclasslib/src/Actions/ActionsHandler.php @@ -20,11 +20,14 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Actions; +use \Hook; +use \Module; +use \ObjectModel; use \Tools; /** @@ -32,6 +35,7 @@ */ class ActionsHandler { + const PROCESS_OVERRIDE_HOOK = 'actionStripe_officialActionsHandler'; /** * @var ObjectModel $modelObject */ @@ -102,31 +106,40 @@ public function addActions($actions) /** * Process the action call back of cross modules * - * @param string $chain Name of the actions chain + * @param string $className Name of the actions chain / Namespaced classname * @return bool + * @throws \Exception */ - public function process($chain) + public function process($className) { - $className = Tools::ucfirst($chain).'Actions'; - if (!preg_match("/^[a-zA-Z]+$/", $className)) { - throw new \Exception($className .'" class name not valid "'); + if (!class_exists($className)) { + $className = Tools::ucfirst($className) . 'Actions'; + if (!preg_match("/^[a-zA-Z]+$/", $className)) { + throw new \Exception($className . '" class name not valid "'); + } + include_once _PS_MODULE_DIR_ . 'stripe_official/classes/actions/' . $className . '.php'; + + $overridePath = _PS_OVERRIDE_DIR_ . 'modules/stripe_official/classes/actions/' . $className . '.php'; + if (file_exists($overridePath)) { + $className .= 'Override'; + include_once $overridePath; + } } - include_once _PS_MODULE_DIR_.'stripe_official/classes/actions/'.$className.'.php'; - - $overridePath = _PS_OVERRIDE_DIR_.'modules/stripe_official/classes/actions/'.$className.'.php'; - if (file_exists($overridePath)) { - $className .= 'Override'; - include_once $overridePath; + + $moduleId = Module::getModuleIdByName('stripe_official'); + $hookResult = Hook::exec(self::PROCESS_OVERRIDE_HOOK, array('className' => $className), $moduleId, true, false); + if (!empty($hookResult) && !empty($hookResult['stripe_official'])) { + $className = $hookResult['stripe_official']; } - + if (class_exists($className)) { - /** @var Stripe_officialDefaultActions $classAction */ + /** @var DefaultActions $classAction */ $classAction = new $className; $classAction->setModelObject($this->modelObject); $classAction->setConveyor($this->conveyor); - + foreach ($this->actions as $action) { - if (!is_callable(array($classAction, $action), false, $callable_name)) { + if (!is_callable(array($classAction, $action), false, $callableName)) { continue; } if (!call_user_func_array(array($classAction, $action), array())) { @@ -134,10 +147,10 @@ public function process($chain) return false; } } - + $this->setConveyor($classAction->getConveyor()); } else { - throw new \Exception($className .'" class not defined "'); + throw new \Exception($className . '" class not defined "'); } return true; diff --git a/vendor/totpsclasslib/src/Actions/DefaultActions.php b/vendor/totpsclasslib/src/Actions/DefaultActions.php index 32dce042..1770ef71 100644 --- a/vendor/totpsclasslib/src/Actions/DefaultActions.php +++ b/vendor/totpsclasslib/src/Actions/DefaultActions.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Actions; diff --git a/vendor/totpsclasslib/src/Db/DbSchema.php b/vendor/totpsclasslib/src/Db/DbSchema.php index f0803b30..7837ab5d 100644 --- a/vendor/totpsclasslib/src/Db/DbSchema.php +++ b/vendor/totpsclasslib/src/Db/DbSchema.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Db; @@ -67,8 +67,7 @@ public function map($table) ->setKeysSimple($this->def->getKeysSimple($this->id)) ->setKeysUnique($this->def->getKeysUnique($this->id)) ->setKeysFulltext($this->def->getKeysFulltext($this->id)) - // @todo: fix foreign key with lang table not InnoDb - //->setKeysForeign($this->def->getKeysForeign($this->id)) + ->setKeysForeign($this->def->getKeysForeign($this->id)) ; } } diff --git a/vendor/totpsclasslib/src/Db/DbTable.php b/vendor/totpsclasslib/src/Db/DbTable.php index f5410f43..8f772f9a 100644 --- a/vendor/totpsclasslib/src/Db/DbTable.php +++ b/vendor/totpsclasslib/src/Db/DbTable.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Db; @@ -369,7 +369,7 @@ protected function setKey($columns, $type = null) case static::FOREIGN: list($table, $columns) = explode('.', $name); $this->keys[] = "FOREIGN KEY (`$columns`) REFERENCES $table (`$columns`) - ON UPDATE CASCADE ON DELETE CASCADE"; + ON UPDATE CASCADE ON DELETE CASCADE"; break; case static::UNIQUE: $this->keys[] = "UNIQUE KEY (`$columns`)"; diff --git a/vendor/totpsclasslib/src/Db/DbTableDefinitionModel.php b/vendor/totpsclasslib/src/Db/DbTableDefinitionModel.php index a9d42eb4..40adb28f 100644 --- a/vendor/totpsclasslib/src/Db/DbTableDefinitionModel.php +++ b/vendor/totpsclasslib/src/Db/DbTableDefinitionModel.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Db; diff --git a/vendor/totpsclasslib/src/Db/DbTableDefinitionRelation.php b/vendor/totpsclasslib/src/Db/DbTableDefinitionRelation.php index bf1493fc..489b35df 100644 --- a/vendor/totpsclasslib/src/Db/DbTableDefinitionRelation.php +++ b/vendor/totpsclasslib/src/Db/DbTableDefinitionRelation.php @@ -20,13 +20,12 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Db; use Stripe_officialClasslib\Db\ObjectModelDefinition; -use Stripe_officialClasslib\Db\DbTableDefinitionRelation; use \ObjectModel; @@ -196,8 +195,8 @@ public function getKeysForeign() public function getKeysSimple() { switch ($this->id) { - case DbTableDefinitionRelation::ID_LANG: - case DbTableDefinitionRelation::ID_SHOP: + case self::ID_LANG: + case self::ID_SHOP: return array(); default: return array_filter( @@ -216,8 +215,8 @@ public function getKeysSimple() public function getKeysUnique() { switch ($this->id) { - case DbTableDefinitionRelation::ID_LANG: - case DbTableDefinitionRelation::ID_SHOP: + case self::ID_LANG: + case self::ID_SHOP: return array(); default: return array_filter( @@ -236,8 +235,8 @@ public function getKeysUnique() public function getKeysFulltext() { switch ($this->id) { - case DbTableDefinitionRelation::ID_LANG: - case DbTableDefinitionRelation::ID_SHOP: + case self::ID_LANG: + case self::ID_SHOP: return array(); default: return array_filter( @@ -256,8 +255,8 @@ public function getKeysFulltext() public function getType() { switch ($this->id) { - case DbTableDefinitionRelation::ID_LANG: - case DbTableDefinitionRelation::ID_SHOP: + case self::ID_LANG: + case self::ID_SHOP: return ObjectModel::HAS_MANY; default: return (int)$this->get('type'); @@ -305,8 +304,8 @@ protected function getFieldsPrimary() protected function getFieldsCommon() { switch ($this->id) { - case DbTableDefinitionRelation::ID_LANG: - case DbTableDefinitionRelation::ID_SHOP: + case self::ID_LANG: + case self::ID_SHOP: return array_filter( $this->def->get('fields'), array( @@ -327,9 +326,9 @@ protected function getFieldsCommon() protected function getForeignTable() { switch ($this->id) { - case DbTableDefinitionRelation::ID_LANG: + case self::ID_LANG: return _DB_PREFIX_ . 'lang'; - case DbTableDefinitionRelation::ID_SHOP: + case self::ID_SHOP: return _DB_PREFIX_ . 'shop'; default: return _DB_PREFIX_ . $this->getForeignModelTableName(); @@ -358,7 +357,7 @@ protected function getForeignModelTableName() protected function hasMany($relation) { switch ($this->id) { - case DbTableDefinitionRelation::ID_LANG: + case self::ID_LANG: return !empty($this->def->get("multilang_$relation")); default: return !empty($this->get("multi$relation")); @@ -374,9 +373,9 @@ protected function hasMany($relation) protected function hasField($field, $name) { switch ($this->id) { - case DbTableDefinitionRelation::ID_LANG: + case self::ID_LANG: return !empty($field['lang']); - case DbTableDefinitionRelation::ID_SHOP: + case self::ID_SHOP: return !empty($field['shop']); default: return isset($this->get('fields')[$name]); diff --git a/vendor/totpsclasslib/src/Db/ObjectModelDefinition.php b/vendor/totpsclasslib/src/Db/ObjectModelDefinition.php index d9821402..9faae36e 100644 --- a/vendor/totpsclasslib/src/Db/ObjectModelDefinition.php +++ b/vendor/totpsclasslib/src/Db/ObjectModelDefinition.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Db; diff --git a/vendor/totpsclasslib/src/Db/ObjectModelExtension.php b/vendor/totpsclasslib/src/Db/ObjectModelExtension.php index 05aa2f2b..d2a1bd16 100644 --- a/vendor/totpsclasslib/src/Db/ObjectModelExtension.php +++ b/vendor/totpsclasslib/src/Db/ObjectModelExtension.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Db; diff --git a/vendor/totpsclasslib/src/Extensions/AbstractModuleExtension.php b/vendor/totpsclasslib/src/Extensions/AbstractModuleExtension.php index 2ebf1a6a..6f432b54 100644 --- a/vendor/totpsclasslib/src/Extensions/AbstractModuleExtension.php +++ b/vendor/totpsclasslib/src/Extensions/AbstractModuleExtension.php @@ -1,12 +1,41 @@ + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + */ + namespace Stripe_officialClasslib\Extensions; +use Stripe_officialClasslib\Hook\AbstractHookDispatcher; +use Stripe_officialClasslib\Module; + abstract class AbstractModuleExtension { //region Fields public $name; + /** + * @var \Module + */ public $module; public $objectModels = array(); @@ -19,10 +48,23 @@ abstract class AbstractModuleExtension public $cronTasks = array(); //TODO + /** + * @var AbstractHookDispatcher + */ + protected $hookDispatcher = null; + //endregion + public function __construct($module = null) + { + $this->module = $module; + } + + /** + * Set the module object for the extension * @param Module $module + * @return AbstractModuleExtension */ public function setModule($module) { @@ -30,4 +72,61 @@ public function setModule($module) return $this; } -} \ No newline at end of file + + /** + * Fetch Smarty template + * @todo Maybe this method should belong to classlib Module class + * so we'd have a unified way of calling the fetch method + * doing `$this->module->fetch(...)` + * + * @param $templatePath + * @param null $cache_id + * @param null $compile_id + * @return mixed|string + * @throws \SmartyException + */ + public function fetch($templatePath, $cache_id = null, $compile_id = null) + { + if (version_compare(_PS_VERSION_, '1.7', '>')) { + return $this->module->fetch($templatePath, $cache_id, $compile_id); + } else { + return \Context::getContext()->smarty->fetch($templatePath, $cache_id, $compile_id); + } + } + + /** + * Do shmth while each initialisation of extension, must be overrided in nested classes + * @return void + */ + public function initExtension() + { + + } + + /** + * Do smth during the installation process + * @return bool + */ + public function install() + { + return true; + } + + /** + * Do smth during the uninstall action + * @return bool + */ + public function uninstall() + { + return true; + } + + /** + * Helps to manage hooks and widgets + * @return AbstractHookDispatcher + */ + public function getHookDispatcher() + { + return $this->hookDispatcher; + } +} diff --git a/vendor/totpsclasslib/src/Extensions/ProcessLogger/Classes/ProcessLoggerObjectModel.php b/vendor/totpsclasslib/src/Extensions/ProcessLogger/Classes/ProcessLoggerObjectModel.php index 3b05a130..82af9ac5 100644 --- a/vendor/totpsclasslib/src/Extensions/ProcessLogger/Classes/ProcessLoggerObjectModel.php +++ b/vendor/totpsclasslib/src/Extensions/ProcessLogger/Classes/ProcessLoggerObjectModel.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Extensions\ProcessLogger\Classes; @@ -35,7 +35,7 @@ class ProcessLoggerObjectModel extends ObjectModel /** @var string Message to display */ public $msg; - /** @var string level (success|failed|info) */ + /** @var string level (success|error|info|deprecated) */ public $level; /** @var string Name of ObjectModel associated if needed */ @@ -44,11 +44,6 @@ class ProcessLoggerObjectModel extends ObjectModel /** @var int|null Identifier of resource announced with ObjectModel if needed */ public $object_id; - /** - * @var int|null - */ - public $id_session; - /** @var string Date */ public $date_add; @@ -67,7 +62,6 @@ class ProcessLoggerObjectModel extends ObjectModel 'msg' => array( 'type' => ObjectModel::TYPE_HTML, 'validate' => 'isGenericName', - 'size' => 255, ), 'level' => array( 'type' => ObjectModel::TYPE_STRING, @@ -84,11 +78,6 @@ class ProcessLoggerObjectModel extends ObjectModel 'validate' => 'isUnsigned', 'allow_null' => true, ), - 'id_session' => array( - 'type' => ObjectModel::TYPE_STRING, - 'validate' => 'isString', - 'allow_null' => true, - ), 'date_add' => array( 'type' => ObjectModel::TYPE_DATE, 'validate' => 'isDate', diff --git a/vendor/totpsclasslib/src/Extensions/ProcessLogger/Controllers/Admin/AdminProcessLoggerController.php b/vendor/totpsclasslib/src/Extensions/ProcessLogger/Controllers/Admin/AdminProcessLoggerController.php index 75de75a6..7e4dc284 100644 --- a/vendor/totpsclasslib/src/Extensions/ProcessLogger/Controllers/Admin/AdminProcessLoggerController.php +++ b/vendor/totpsclasslib/src/Extensions/ProcessLogger/Controllers/Admin/AdminProcessLoggerController.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Extensions\ProcessLogger\Controllers\Admin; @@ -30,6 +30,7 @@ use \Db; use \Tools; use \Configuration; +use \Shop; class AdminProcessLoggerController extends \ModuleAdminController { @@ -102,9 +103,6 @@ public function __construct() 'title' => $this->module->l('Object ID', 'AdminProcessLoggerController'), 'callback' => 'getObjectId', ), - 'id_session' => array( - 'title' => $this->module->l('Session ID', 'AdminProcessLoggerController'), - ), 'date_add' => array( 'title' => $this->module->l('Date', 'AdminProcessLoggerController'), ), @@ -183,6 +181,9 @@ public function getLevel($echo, $tr) case 'error': $echo = ''.$echo.''; break; + case 'deprecated': + $echo = ''.$echo.''; + break; } return $echo; } diff --git a/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerExtension.php b/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerExtension.php index 520e36d3..46d5de2c 100644 --- a/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerExtension.php +++ b/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerExtension.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Extensions\ProcessLogger; diff --git a/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerHandler.php b/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerHandler.php index 69b62d59..74a23cf0 100644 --- a/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerHandler.php +++ b/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerHandler.php @@ -20,15 +20,14 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib\Extensions\ProcessLogger; -use Db; -use Configuration; -use Hook; -use Tools; +use \Db; +use \Configuration; +use \Hook; class ProcessLoggerHandler { @@ -81,7 +80,6 @@ public static function addLog($msg, $objectModel = null, $objectId = null, $name 'object_name' => pSQL($objectModel), 'object_id' => (int)$objectId, 'date_add' => date("Y-m-d H:i:s"), - 'id_session' => self::getSessionId(), ); if (100 === count(self::$logs)) { @@ -131,6 +129,20 @@ public static function logInfo($msg, $objectModel = null, $objectId = null, $nam self::addLog($msg, $objectModel, $objectId, $name, 'info'); } + /** + * @param string $msg + * @param string|null $objectModel + * @param int|null $objectId + * @param string $name + */ + public static function logDeprecated($msg, $objectModel = null, $objectId = null, $name = 'default') + { + if (self::$process != null) { + $name = self::$process->getProcessName(); + } + self::addLog($msg, $objectModel, $objectId, $name, 'deprecated'); + } + /** * @return bool */ @@ -268,22 +280,4 @@ protected static function getSkippingHooksResult() { return true; } - - protected static function getSessionId() - { - $values = array(); - $remoteAddr = Tools::getRemoteAddr(); - $values[] = $remoteAddr; - if (!empty($_SERVER['REQUEST_TIME'])) { - $values[] = $_SERVER['REQUEST_TIME']; - } elseif (!empty($_SERVER['REQUEST_TIME_FLOAT'])) { - $values[] = $_SERVER['REQUEST_TIME_FLOAT']; - } - - if (!empty($_SERVER['REMOTE_PORT'])) { - $values[] = $_SERVER['REMOTE_PORT']; - } - - return sprintf('%08x', abs(crc32(implode('', $values)))); - } } diff --git a/vendor/totpsclasslib/src/Hook/AbstractHook.php b/vendor/totpsclasslib/src/Hook/AbstractHook.php new file mode 100644 index 00000000..fb35353e --- /dev/null +++ b/vendor/totpsclasslib/src/Hook/AbstractHook.php @@ -0,0 +1,48 @@ +module = $module; + } + + /** + * Get all available hooks for current object + * @return array + */ + public function getAvailableHooks() + { + return static::AVAILABLE_HOOKS; + } + + /** + * Remove first 4 letters of hook function and replace the first letter by lower case + * TODO maybe we should delete this function, because it isn't used + * @param $functionName + * @return string + */ + protected function getHookNameFromFunction($functionName) + { + return lcfirst(substr($functionName, 4, strlen($functionName))); + } +} \ No newline at end of file diff --git a/vendor/totpsclasslib/src/Hook/AbstractHookDispatcher.php b/vendor/totpsclasslib/src/Hook/AbstractHookDispatcher.php new file mode 100644 index 00000000..2b42bc7e --- /dev/null +++ b/vendor/totpsclasslib/src/Hook/AbstractHookDispatcher.php @@ -0,0 +1,119 @@ +module = $module; + + foreach ($this->hookClasses as $hookClass) { + /** @var AbstractHook $hook */ + $hook = new $hookClass($this->module); + $this->availableHooks = array_merge($this->availableHooks, $hook->getAvailableHooks()); + $this->hooks[] = $hook; + } + + foreach ($this->widgetClasses as $widgetClass) { + /** @var AbstractWidget $widgetClass */ + $widget = new $widgetClass($this->module); + $this->widgets[] = $widget; + } + } + + /** + * Get available hooks + * + * @return string[] + */ + public function getAvailableHooks() + { + return $this->availableHooks; + } + + /** + * Find hook or widget and dispatch it + * + * @param string $hookName + * @param array $params + * + * @return mixed|void + */ + public function dispatch($hookName, array $params = array()) + { + $hookName = preg_replace('~^hook~', '', $hookName); + + if (!empty($hookName)) { + foreach ($this->hooks as $hook) { + if (is_callable(array($hook, $hookName))) { + return call_user_func(array($hook, $hookName), $params); + } + } + } + + foreach ($this->widgets as $widget) { + if (!isset($params['action'])) { + continue; + } + + if (is_callable(array($widget, $params['action']))) { + return call_user_func(array($widget, $params['action']), $hookName, $params); + } + } + + return null; + } + + /** + * Get hook classes + * @return array + */ + public function getHookClasses() + { + return $this->hookClasses; + } + + /** + * Get widget classes + * @return array + */ + public function getWidgetClasses() + { + return $this->widgetClasses; + } +} \ No newline at end of file diff --git a/vendor/totpsclasslib/src/Install/ExtensionInstaller.php b/vendor/totpsclasslib/src/Install/ExtensionInstaller.php index c161b054..4ad5a851 100644 --- a/vendor/totpsclasslib/src/Install/ExtensionInstaller.php +++ b/vendor/totpsclasslib/src/Install/ExtensionInstaller.php @@ -31,6 +31,18 @@ public function __construct($module, $extension = null) $this->extension = $extension; } + public function install() + { + return parent::install() && $this->extension->install(); + } + + public function uninstall() + { + return parent::uninstall() && $this->extension->uninstall(); + } + + + //region Get-Set diff --git a/vendor/totpsclasslib/src/Module.php b/vendor/totpsclasslib/src/Module.php new file mode 100644 index 00000000..312ee22a --- /dev/null +++ b/vendor/totpsclasslib/src/Module.php @@ -0,0 +1,267 @@ + + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + * @version develop + */ + +namespace Stripe_officialClasslib; + +use Stripe_officialClasslib\Hook\AbstractHookDispatcher; +use PrestaShop\PrestaShop\Core\Module\WidgetInterface; +use \ReflectionClass; +use \Tools; +use Stripe_officialClasslib\Install\ModuleInstaller; +use Stripe_officialClasslib\Extensions\AbstractModuleExtension; + +class Module extends \Module +{ + //region Fields + + /** + * List of objectModel used in this Module + * @var array $objectModels + */ + public $objectModels = array(); + + /** + * List of hooks used in this Module + * @var array $hooks + */ + public $hooks = array(); + + public $extensions = array(); + + /** + * @var AbstractHookDispatcher + */ + protected $hookDispatcher = null; + + /** + * List of AdminControllers used in this Module + * @var array $moduleAdminControllers + */ + public $moduleAdminControllers = array(); + + //endregion + + /** + * Module constructor. + */ + public function __construct() + { + parent::__construct(); + foreach ($this->extensions as $extensionName) { + /** @var AbstractModuleExtension $extension */ + $extension = new $extensionName(); + $extension->setModule($this); + $extension->initExtension(); + } + } + + /** + * Install Module + * + * @return bool + * @throws \PrestaShopException + */ + public function install() + { + $installer = new ModuleInstaller($this); + + $isPhpVersionCompliant = false; + try { + $isPhpVersionCompliant = $installer->checkPhpVersion(); + } catch (\Exception $e) { + $this->_errors[] = Tools::displayError($e->getMessage()); + } + + return $isPhpVersionCompliant && parent::install() && $installer->install(); + } + + /** + * Uninstall Module + * + * @return bool + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException + */ + public function uninstall() + { + $installer = new ModuleInstaller($this); + + return parent::uninstall() && $installer->uninstall(); + } + + /** + * @TODO Reset Module only if merchant choose to keep data on modal + * + * @return bool + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException + */ + public function reset() + { + $installer = new ModuleInstaller($this); + + return $installer->reset($this); + } + + /** + * Handle module extension hook call + * + * @param $hookName + * @param $params + * @return array|bool|string + */ + public function handleExtensionsHook($hookName, $params) + { + $result = false; + + // execute module hooks + if ($this->getHookDispatcher() != null) { + $moduleHookResult = $this->getHookDispatcher()->dispatch($hookName, $params); + if ($moduleHookResult != null) { + $result = $moduleHookResult; + } + } + + //execute extension's hooks + if (!isset($this->extensions) || empty($this->extensions)) { + if (!$result) { + return false; + } + } + + foreach ($this->extensions as $extension) { + /** @var AbstractModuleExtension $extension */ + $extension = new $extension($this); + $hookResult = null; + if (is_callable(array($extension, $hookName))) { + $hookResult = $extension->{$hookName}($params); + //TODO + } else if (is_callable(array($extension, 'getHookDispatcher')) && $extension->getHookDispatcher() != null) { + $hookResult = $extension->getHookDispatcher()->dispatch($hookName, $params); + } + if ($hookResult != null) { + if ($result === false) { + $result = $hookResult; + } elseif (is_array($hookResult) && $result !== false) { + $result = array_merge($result, $hookResult); + } else { + $result .= $hookResult; + } + } + } + + return $result; + } + + /** + * Handle module widget call + * + * @param $action + * @param $method + * @param $hookName + * @param $configuration + * @return bool + * @throws \ReflectionException + * @deprecated use render widget function + */ + public function handleWidget($action, $method, $hookName, $configuration) + { + if (!isset($this->extensions) || empty($this->extensions)) { + return false; + } + + foreach ($this->extensions as $extension) { + /** @var AbstractModuleExtension $extension */ + $extension = new $extension(); + if (!($extension instanceof WidgetInterface)) { + continue; + } + $extensionClass = (new ReflectionClass($extension))->getShortName(); + if ($extensionClass != $action) { + continue; + } + $extension->setModule($this); + if (is_callable(array($extension, $method))) { + return $extension->{$method}($hookName, $configuration); + } + } + + return false; + + } + + /** + * @param $hookName + * @param array $configuration + * @return bool + * @throws \ReflectionException + */ + public function renderWidget($hookName, array $configuration) + { + // render module widgets + if ($this->getHookDispatcher() != null) { + $moduleWidgetResult = $this->getHookDispatcher()->dispatch($hookName, $configuration); + if ($moduleWidgetResult != null) { + return $moduleWidgetResult; + } + } + + // render extensions widget if module widget isn't found + if (!isset($this->extensions) || empty($this->extensions)) { + return false; + } + + foreach ($this->extensions as $extension) { + /** @var AbstractModuleExtension $extension */ + $extension = new $extension($this); + + if (is_callable(array($extension, 'getHookDispatcher')) && $extension->getHookDispatcher() != null) { + return $extension->getHookDispatcher()->dispatch($hookName, $configuration); + } + } + + //if we want to use an old approach + return $this->handleWidget($configuration['action'], __FUNCTION__, $hookName, $configuration); + } + + /** + * @param $hookName + * @param array $configuration + * @return array|bool + */ + public function getWidgetVariables($hookName, array $configuration) + { + return array(); + } + + /** + * Get the current module hook/widget dispatcher + * @return null + */ + public function getHookDispatcher() + { + return $this->hookDispatcher; + } +} diff --git a/vendor/totpsclasslib/src/Registry.php b/vendor/totpsclasslib/src/Registry.php index 73b94f70..46349409 100644 --- a/vendor/totpsclasslib/src/Registry.php +++ b/vendor/totpsclasslib/src/Registry.php @@ -20,7 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version release/2.1.1 + * @version release/2.3.1 */ namespace Stripe_officialClasslib; diff --git a/vendor/totpsclasslib/src/Utils/Translate/TranslateTrait.php b/vendor/totpsclasslib/src/Utils/Translate/TranslateTrait.php new file mode 100644 index 00000000..978e94ca --- /dev/null +++ b/vendor/totpsclasslib/src/Utils/Translate/TranslateTrait.php @@ -0,0 +1,57 @@ + + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + * @version release/2.3.1 + */ + +namespace Stripe_officialClasslib\Utils\Translate; + +use \Translate; + +trait TranslateTrait +{ + + /** + * Translation method for classes that use this trait + * @param $textToTranslate + * @param string $class + * @param bool $addslashes + * @param bool $htmlentities + * @return mixed + */ + protected function l($textToTranslate, $class = '', $addslashes = false, $htmlentities = true) + { + if (empty($class) === true) { + $class = $this->getClassShortName(); + } + return Translate::getModuleTranslation('tomrewardseditor', $textToTranslate, $class); + } + + /** + * @return string + * @throws \ReflectionException + */ + protected function getClassShortName() + { + return (new \ReflectionClass($this))->getShortName(); + } +} From 590b36413f129626a11bc41b9c0e9683feccab79 Mon Sep 17 00:00:00 2001 From: afayadas Date: Wed, 29 Dec 2021 15:55:12 +0100 Subject: [PATCH 02/15] refs #30764 : change customer secure_key passed to validateOrder method by cart secure_key + refactoring code in createOrder method --- classes/actions/ValidationOrderActions.php | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/classes/actions/ValidationOrderActions.php b/classes/actions/ValidationOrderActions.php index fdfa9daf..283fa110 100755 --- a/classes/actions/ValidationOrderActions.php +++ b/classes/actions/ValidationOrderActions.php @@ -302,14 +302,6 @@ public function createOrder() $this->conveyor['cart'] = new Cart((int)$this->conveyor['id_cart']); - $customer = new Customer($this->conveyor['cart']->id_customer); - - if (isset($customer->secure_key)) { - $this->conveyor['secure_key'] = $customer->secure_key; - } else { - $this->conveyor['secure_key'] = false; - } - $paid = $this->conveyor['amount']; /* Add transaction on Prestashop back Office (Order) */ @@ -344,7 +336,7 @@ public function createOrder() $this->context->country = new Country($addressDelivery->id_country); $this->module->validateOrder( - (int)$this->conveyor['id_cart'], + $this->conveyor['cart']->id, (int)$orderStatus, $paid, $this->module->l(Tools::ucfirst(Stripe_official::$paymentMethods[$this->conveyor['datas']['type']]['name']).' via Stripe', 'ValidationOrderActions'), @@ -352,7 +344,7 @@ public function createOrder() array(), null, false, - $this->conveyor['secure_key'] + $this->conveyor['cart']->secure_key ); ProcessLoggerHandler::logInfo( @@ -362,7 +354,7 @@ public function createOrder() 'ValidationOrderActions - createOrder' ); - $idOrder = Order::getOrderByCartId((int)$this->conveyor['id_cart']); + $idOrder = Order::getOrderByCartId($this->conveyor['cart']->id); $order = new Order($idOrder); // capture payment for card if no catch and authorize enabled @@ -419,7 +411,7 @@ public function createOrder() if ($this->conveyor['status'] == 'requires_capture') { $stripeCapture = new StripeCapture(); $stripeCapture->id_payment_intent = $this->conveyor['paymentIntent']; - $stripeCapture->id_order = Order::getOrderByCartId((int)$this->conveyor['cart']->id); + $stripeCapture->id_order = Order::getOrderByCartId($this->conveyor['cart']->id); $stripeCapture->expired = 0; $stripeCapture->date_catch = date('Y-m-d H:i:s'); $stripeCapture->save(); From 6912d99df04f45b5e981e0819ea400302a937384 Mon Sep 17 00:00:00 2001 From: afayadas Date: Wed, 29 Dec 2021 16:18:29 +0100 Subject: [PATCH 03/15] refs #30641 : added the missing sepa debit logo on the checkout payment page --- views/img/sepa_debit.png | Bin 0 -> 4042 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 views/img/sepa_debit.png diff --git a/views/img/sepa_debit.png b/views/img/sepa_debit.png new file mode 100644 index 0000000000000000000000000000000000000000..9a6f2f602bbe34031035a7fea645e88f8d325e72 GIT binary patch literal 4042 zcmbW4*E<^k8^z5Qv8k=HqIS(%MQg8GHB*Wjv9+jGv5CD$v}#2q z_OAK$d%pkRyEyN8&c*v)y%*;fs|Qu5qF|#SARwU9)KD?_=K=o}*`0q=#$IajpAmW+ zsDlZrM>)3s1rkSP9c2Q7x@5qW4e7s3?x|tsO+Y~1{a+FGdz9G|5YSj_swf);z;-MF z2}U!lumn*x{4+SSA2T^k3Iegfzl{{^I^5?RKcp`=wip*Qpqzdj!DOPXN;GVjFDRsO zp#NBl_-SF(3s<*S3@(%K#5&RRl0H*5jEY57m59P}w)gI*=A-5Q;a}N&Be##N;k(yk z&B=T6H@AwL?sV@u;UX-Qcm59>;6xx0n-aspwyW!nKU~l_TWJ#=ypb7j2rnQsf|@1SY2^xplaU&lJ9$UA)|dwU{0C)l^$Z z?$+OAA8qcnC}pQQwfXIBPw2$*cCYk4RZ!P*DSBs@(^9mmP}yRy=AmM|2LM85@O`-Q zYyYyi|q?i09hsr3qZcz!<9o*YWvqI=Z%r9CCQD^bC~!c(b?O^NNzK1<5BD zbH6DO>2sdIuibUvQ8r{BDFcuii&Sz94W$++uns+({5$xk4{x139Q>LCH`0XqofWnF zJ(!FrYqCr%G^Sk7c#TWa?OM`_( zU3v!NmbZ^2Lc8gnB%tcn%UXJdaI=Eb)(h4znBuOZ>(5kImIGu`SofC;S2ac3f_dEc zLuw^b&pnMmSeH?zxd3yk(R-c=(EC7LhC4l1@%Ll?PP>Iph3)$<`OTF`pFO{_obv+C zda?JdRS&S`NUA0jOR-9NkP1h!9UR>?6VaaV+3{d;DNRd*D|L%$NV83iPD;cvnO zD}YfSm&+qKZWE`;Nr0VuZ0_5ED;N zxVm=6SB90mHab!XA2ig^r@)XUs@yy0-icMKvG2`qNqZEbVM!7SV(1__gkReO8mha7 z{Eo_B=v5ty{9YlKYyt6VRO&Wu#m)MQ%C9zYg%5!bw(4t%$7?5?%IoNuyRB?I`Wv zXlym+-?edVtygwD&~0UfLI?N%tvH%wGYu9q*c5F!qQ5>!(ACe#V&v%nHGc7^I`O{slZ=S?@^$@R>M=~4&vQI>6U!}^{#EMMqvf8~Wc9k6A{&`OW4xvP*K8VR+ z;OyqXd<)n(qT)MyHhUA)iqch(T2pAXYP6g_==yR<=tc&Hzt`mDt+O_C(Bauja6Dbv zwC`#3bQiGDnbzFk(|C}wvY|s0?Ox?}+sMklO|+IJ%L%$73-;0;dsgX-iRES7{743 z+f~bI!HPr~A=D)u2xzNy$oA@IV4;Z^sqYiRx2Sk^TVm1)t@fyou0ZSs)Hj=FJ-rU* z!YoDB1yNsBv3g7#Nzam0%7Ip>H_6JMsd6B|ZyB-bOeeYkkG8`jUsK*&!vyC3mbAU3 zZj+9A)K%dwYOj#|0-Lc*BKqw!G$1C+PQWVye#`4^ohiK+1}0Bfxk_yemzkDHbI;|W zO)_wJ&f{u~{R?sMZhHY@wAPa@Fk4tUqHwMGelbD1pDN%LH8d41tW_BL#*iBL9%Z|G z^~9hOw(!K$QhV=!Jo7{W;$@40ing_0s=4O^>^;CwybJg8O2g(X4cU_Jzx#<_P`3r78L6;YapQyz0iR@ase4_Bh^(MR7)dggZ&}Vs^unNsA zi|gG7`?$`)n3AxSZ72WhQorz(n4j&okw>)a#GYVumt3`x;x&0*93Rx6C+F!QI_90S ztF!9iasoX;531`^wIba1+T2Qt0rsgro7b1fT+jL8sem!eP|ggBdM5Zvcjn)lrg1*m zU9#CtI0h7JbHSSa{K?4}5>)R?Mum!*!IZXjXAm@npUa0{b_LaO3t7FX^kj@Kq{&hl ziu8o7MgVJsG>L8q8vf9L1M-d#aAu`45)V$uZPW|^@VIs>HgMBx~SnxUjeqrnVHms_5FLIoSH&bcGg&v_s zSv7XfT|$VYPD^5Er<*e%jj-1Q-86?RjFQi@?DC1l*j$!cCElVksn6pGRRS4?-c5^G zJB2IoQYg!pik*>Mk=5waCn{x^LINk>JlBuFj^0sJ((QYBQc!Od$;iSRZ*q#3{N@$r zxkzo`YsN@b09?{^Z1_MmI2V_?#I@~X!~9#-Mp{iMzskv0SVE0hJQ&@C8sO6N%~4^} z%f3{5r5sbOJ9UBq7WZDc-#t;CDEtsrghjiCed)WLTUtyOL3Ji@ann0TdD%F8F%weZv55VlVX2Y#*7J1d zb9?;N(3V6H1@O~=vMeq8Ebb^sF-b=3+SmE5X^1xXK-CWu7uEA%H3VTTrB5Fx^bLb4 z??{90tf1wSM|OD_7ez`$pDDjUhSdOzb%1=FMwROeLyKkx>>-v+QsIacBmcP`bc}%B zW&Jh7ar3I)^Ei7l7FV={Z~zK#1VS@p^Dm}PYBW@OFumyvO4C;fN6(>jMI9I9WvvRP%c;oZNW z*Td%UWlY$ISAvuFr->|An``G}aDO)pvX0X+-n+#HeOj=H7#GdyO==m zYZ58x0q;W5t+5vks9woB!^vS%bNEt?ti5tR11BEf3xvQK%FBT#P?Db=@?H!q`#_|09ez?zWLHgp7(29$bF}Ux<7&rBm+*+YxSb$jg&P7 zg>UFR9o=fMso^%4Kh_`lwj;kXPySTzf+JxA?ZYGZj`IQTL%t#QP+cQ}5wu}hvTK&i zWd55`JRc&VrG5TchGlcr!N?Ge@s#7|ZZ2L#BN zm7t7A${m^xszPS3)|r(l@^&k>zccqwl8!!nfwQ*>=MH!7nq7KkArfA-0@?j>HuY{T ze!aWwN-FS^!l`()(^4hkB?ofz*+czlZuY#UKO_R4kJHiv-46~o{5#CyF~3hZu(VXs znhabY@s96>KX)UEDDt$d;{a$**3eCOKxY7p@gDhK6ve`DXCNMk8?{W)N>Xa1;w3pz z*NtFgIjWY;oStK&4+wxVfrZ--z(HH2bf9~#rK4LXeXeI9xX-7b>HXQr&dob!>aBw?LL4 z7Dy7NA=@aq2@h$fob9Vri9Rh>p5})gCZ!)`1PXjN5hwhdQh}mXUcTG-i}LBM>R8TE zF-TZdWJkQr*3gBTTD3!BY$!@R-2+r)cYHr@!5rQ#VVS-I=>cc)5 zlqrS)X3YJ8BU~{$>|)2SY|7{NbIPK-jt1w9r}|*BhpL{uxc60$Y8mP-UiSPACr^O! zx%+%ZoC8EX1=F)hd-4|5 Date: Wed, 29 Dec 2021 16:36:53 +0100 Subject: [PATCH 04/15] refs #32846 : fix empty id_customer context on payment card saving --- classes/actions/ValidationOrderActions.php | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/classes/actions/ValidationOrderActions.php b/classes/actions/ValidationOrderActions.php index 283fa110..c47774ca 100755 --- a/classes/actions/ValidationOrderActions.php +++ b/classes/actions/ValidationOrderActions.php @@ -514,29 +514,30 @@ public function saveCard() return true; } + $cartCustomer = new Customer($this->conveyor['cart']->id_customer); + $stripeAccount = \Stripe\Account::retrieve(); $stripeCustomer = new StripeCustomer(); - $stripeCustomer = $stripeCustomer->getCustomerById($this->context->customer->id, $stripeAccount->id); + $stripeCustomer = $stripeCustomer->getCustomerById($cartCustomer->id, $stripeAccount->id); - if ($stripeCustomer->id == null) { + if (empty($stripeCustomer->id)) { $customer = \Stripe\Customer::create([ 'description' => 'Customer created from Prestashop Stripe module', - 'email' => $this->context->customer->email, - 'name' => $this->context->customer->firstname.' '.$this->context->customer->lastname, + 'email' => $cartCustomer->email, + 'name' => $cartCustomer->firstname.' '.$cartCustomer->lastname, ]); - $stripeCustomer->id_customer = $this->context->customer->id; + $stripeCustomer->id_customer = $cartCustomer->id; $stripeCustomer->stripe_customer_key = $customer->id; $stripeCustomer->id_account = $stripeAccount->id; $stripeCustomer->save(); } - $customer = \Stripe\Customer::retrieve($stripeCustomer->stripe_customer_key); - $stripeCard = new StripeCard(); - $stripeCard->stripe_customer_key = $customer->id; + $stripeCard->stripe_customer_key = $stripeCustomer->stripe_customer_key; $stripeCard->payment_method = $this->conveyor['token']; + if (!$stripeCard->save()) { ProcessLoggerHandler::logError( 'Error during save card, card has not been registered', From 7fc8cc92202cbd6c0bb5aeef98b1ef68248b260a Mon Sep 17 00:00:00 2001 From: afayadas Date: Wed, 29 Dec 2021 16:48:50 +0100 Subject: [PATCH 05/15] refs #32848 : fix changing amount cart in AJAX --- stripe_official.php | 95 ++++++++++++++++++++++++--------------------- 1 file changed, 50 insertions(+), 45 deletions(-) diff --git a/stripe_official.php b/stripe_official.php index b8862b42..e97d7361 100755 --- a/stripe_official.php +++ b/stripe_official.php @@ -30,30 +30,30 @@ require_once dirname(__FILE__) . '/vendor/autoload.php'; /** -* Stripe object model -*/ + * Stripe object model + */ // use PrestaShop\PrestaShop\Core\Payment\PaymentOption; /** -* Stripe official PrestaShop module main class extends payment class -* Please note this module use _202 PrestaShop Classlib Project_ (202 classlib) a library developed by "202 ecommerce" -* This library provide utils common features as DB installer, internal logger, chain of responsibility design pattern -* -* To let module compatible with Prestashop 1.6 please keep this following line commented in PrestaShop 1.6: -* // use Stripe_officialClasslib\Install\ModuleInstaller; -* // use Stripe_officialClasslib\Actions\ActionsHandler; -* // use Stripe_officialClasslib\Extensions\ProcessLogger\ProcessLoggerExtension; -* -* Developers use declarative method to define objects, parameters, controllers... needed in this module -*/ + * Stripe official PrestaShop module main class extends payment class + * Please note this module use _202 PrestaShop Classlib Project_ (202 classlib) a library developed by "202 ecommerce" + * This library provide utils common features as DB installer, internal logger, chain of responsibility design pattern + * + * To let module compatible with Prestashop 1.6 please keep this following line commented in PrestaShop 1.6: + * // use Stripe_officialClasslib\Install\ModuleInstaller; + * // use Stripe_officialClasslib\Actions\ActionsHandler; + * // use Stripe_officialClasslib\Extensions\ProcessLogger\ProcessLoggerExtension; + * + * Developers use declarative method to define objects, parameters, controllers... needed in this module + */ class Stripe_official extends PaymentModule { /** - * Stripe Prestashop configuration - * use Configuration::get(Stripe_official::CONST_NAME) to return a value - */ + * Stripe Prestashop configuration + * use Configuration::get(Stripe_official::CONST_NAME) to return a value + */ const KEY = 'STRIPE_KEY'; const TEST_KEY = 'STRIPE_TEST_KEY'; const PUBLISHABLE = 'STRIPE_PUBLISHABLE'; @@ -113,16 +113,16 @@ class Stripe_official extends PaymentModule ); /** - * List of _202 classlib_ extentions - * @var array - */ + * List of _202 classlib_ extentions + * @var array + */ public $extensions = array( Stripe_officialClasslib\Extensions\ProcessLogger\ProcessLoggerExtension::class, ); /** - * To be retrocompatible with PS 1.7, admin tab (controllers) are defined in moduleAdminControllers - */ + * To be retrocompatible with PS 1.7, admin tab (controllers) are defined in moduleAdminControllers + */ public $moduleAdminControllers = array( array( 'name' => array( @@ -148,17 +148,17 @@ class Stripe_official extends PaymentModule * List of ModuleFrontController used in this Module * Module::install() register it, after that you can edit it in BO (for rewrite if needed) * @var array - */ + */ public $controllers = array( 'orderFailure', 'stripeCards', ); /** - * List of hooks needed in this module - * _202 classlib_ extentions will plugged automatically hooks - * @var array - */ + * List of hooks needed in this module + * _202 classlib_ extentions will plugged automatically hooks + * @var array + */ public $hooks = array( 'header', 'orderConfirmation', @@ -857,9 +857,9 @@ public function getContent() if (Tools::isSubmit('submit_login')) { $handler = new Stripe_officialClasslib\Actions\ActionsHandler(); $handler->setConveyor(array( - 'context' => $this->context, - 'module' => $this - )); + 'context' => $this->context, + 'module' => $this + )); $handler->addActions( 'registerKeys', @@ -1118,7 +1118,7 @@ public function addAppleDomainAssociation($secret_key) } else { \Stripe\Stripe::setApiKey($secret_key); \Stripe\ApplePayDomain::create(array( - 'domain_name' => $this->context->shop->domain + 'domain_name' => $this->context->shop->domain )); $curl = curl_init(Tools::getShopDomainSsl(true, true).'/.well-known/apple-developer-merchantid-domain-association'); @@ -1605,11 +1605,14 @@ public function hookHeader() return; } - $currency = $this->context->currency->iso_code; - $address = new Address($this->context->cart->id_address_invoice); - $amount = $this->context->cart->getOrderTotal(); + $cart = $this->context->cart; + + $address = new Address($cart->id_address_invoice); + $currency = new Currency($cart->id_currency); + $amount = $cart->getOrderTotal(); $amount = Tools::ps_round($amount, 2); - $amount = $this->isZeroDecimalCurrency($currency) ? $amount : $amount * 100; + $amount = $this->isZeroDecimalCurrency($currency->iso_code) ? $amount : $amount * 100; + $amount = Tools::ps_round($amount); if ($amount == 0) { return; @@ -1744,12 +1747,13 @@ public function hookPayment($params) // The hookHeader isn't triggered when updating the cart or the carrier // on PS1.6 with OPC; so we need to update the PaymentIntent here - $currency = new Currency($params['cart']->id_currency); - $currency_iso_code = Tools::strtolower($currency->iso_code); - $address = new Address($params['cart']->id_address_invoice); - $amount = $this->context->cart->getOrderTotal(); + $cart = $params['cart']; + $address = new Address($cart->id_address_invoice); + $currency = new Currency($cart->id_currency); + $amount = $cart->getOrderTotal(); $amount = Tools::ps_round($amount, 2); - $amount = $this->isZeroDecimalCurrency($currency_iso_code) ? $amount : $amount * 100; + $amount = $this->isZeroDecimalCurrency($currency->iso_code) ? $amount : $amount * 100; + $amount = Tools::ps_round($amount); if (Configuration::get(self::POSTCODE) == null) { $stripe_reinsurance_enabled = 'off'; @@ -1794,6 +1798,7 @@ public function hookPayment($params) } // Check for currency support + $currency_iso_code = Tools::strtolower($currency->iso_code); if (isset($paymentMethod['currencies']) && !in_array($currency_iso_code, $paymentMethod['currencies'])) { continue; } @@ -1867,7 +1872,7 @@ public function hookDisplayPaymentEU($params) /** * Hook Stripe Payment for PS 1.7 - */ + */ public function hookPaymentOptions($params) { if (!self::isWellConfigured() || !$this->active) { @@ -1936,9 +1941,9 @@ public function hookPaymentOptions($params) // The customer can potientially use this payment method $option = new \PrestaShop\PrestaShop\Core\Payment\PaymentOption(); $option - ->setModuleName($this->name) - //->setLogo(Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/views/img/'.$cc_img)) - ->setCallToActionText($this->button_label[$name]); + ->setModuleName($this->name) + //->setLogo(Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/views/img/'.$cc_img)) + ->setCallToActionText($this->button_label[$name]); // Display additional information for redirect and receiver based payment methods if (in_array($paymentMethod['flow'], array('redirect', 'receiver'))) { @@ -1989,8 +1994,8 @@ public function hookPaymentOptions($params) $option = new \PrestaShop\PrestaShop\Core\Payment\PaymentOption(); $option - ->setModuleName($this->name) - ->setCallToActionText($this->button_label['save_card'].' : '.Tools::ucfirst($card->card->brand).' **** **** **** '.$card->card->last4); + ->setModuleName($this->name) + ->setCallToActionText($this->button_label['save_card'].' : '.Tools::ucfirst($card->card->brand).' **** **** **** '.$card->card->last4); $this->context->smarty->assign(array( 'id_payment_method' => $card->id From 2d0c1d67457060911f04abac86c4e6f482f35900 Mon Sep 17 00:00:00 2001 From: afayadas Date: Mon, 3 Jan 2022 14:38:17 +0100 Subject: [PATCH 06/15] refs #30670 #32649 : catch api error when save Apple Pay configuration --- stripe_official.php | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/stripe_official.php b/stripe_official.php index e97d7361..c200d675 100755 --- a/stripe_official.php +++ b/stripe_official.php @@ -1116,23 +1116,27 @@ public function addAppleDomainAssociation($secret_key) if (!$this->copyAppleDomainFile()) { $this->warning[] = $this->l('Your host does not authorize us to add your domain to use ApplePay. To add your domain manually please follow the subject "Add my domain ApplePay manually from my dashboard" which is located in the tab F.A.Q of the module.'); } else { - \Stripe\Stripe::setApiKey($secret_key); - \Stripe\ApplePayDomain::create(array( - 'domain_name' => $this->context->shop->domain - )); - - $curl = curl_init(Tools::getShopDomainSsl(true, true).'/.well-known/apple-developer-merchantid-domain-association'); - curl_setopt($curl, CURLOPT_FAILONERROR, true); - curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); - $result = curl_exec($curl); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - curl_close($curl); - - if ($httpcode != 200 || !$result) { - $this->warning[] = $this->l('The configurations has been saved, however your host does not authorize us to add your domain to use ApplePay. To add your domain manually please follow the subject "Add my domain ApplePay manually from my dashboard in order to use ApplePay" which is located in the tab F.A.Q of the module.'); + try { + \Stripe\Stripe::setApiKey($secret_key); + \Stripe\ApplePayDomain::create(array( + 'domain_name' => $this->context->shop->domain + )); + + $curl = curl_init(Tools::getShopDomainSsl(true, true) . '/.well-known/apple-developer-merchantid-domain-association'); + curl_setopt($curl, CURLOPT_FAILONERROR, true); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + $result = curl_exec($curl); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close($curl); + + if ($httpcode != 200 || !$result) { + $this->warning[] = $this->l('The configurations has been saved, however your host does not authorize us to add your domain to use ApplePay. To add your domain manually please follow the subject "Add my domain ApplePay manually from my dashboard in order to use ApplePay" which is located in the tab F.A.Q of the module.'); + } + } catch (\Stripe\Exception\ApiErrorException $e) { + $this->warning[] = $e->getMessage(); } } } From e1ac260eb0246ba23a4dad6c4fa54d6f12e53aba Mon Sep 17 00:00:00 2001 From: afayadas Date: Mon, 3 Jan 2022 15:39:17 +0100 Subject: [PATCH 07/15] refs #32215 : fix payment method with redirection on PS 1.7.8 + refactoring OrderSuccess controller code --- controllers/front/orderSuccess.php | 169 ++++++++++++++++------------- controllers/front/webhook.php | 18 ++- 2 files changed, 103 insertions(+), 84 deletions(-) diff --git a/controllers/front/orderSuccess.php b/controllers/front/orderSuccess.php index 4343c378..3b587200 100644 --- a/controllers/front/orderSuccess.php +++ b/controllers/front/orderSuccess.php @@ -36,10 +36,18 @@ public function initContent() { parent::initContent(); - $payment_intent = Tools::getValue('payment_intent'); - $payment_method = Tools::getValue('payment_method'); + $intent = $this->retrievePaymentIntent(); + + if ($this->registerStripeEvent($intent)) + $this->handleWebhookActions($intent); + + $this->displayOrderConfirmation($intent->id); + } + private function retrievePaymentIntent() + { try { + $payment_intent = Tools::getValue('payment_intent'); $intent = \Stripe\PaymentIntent::retrieve($payment_intent); } catch (\Stripe\Exception\ApiErrorException $e) { $intent = null; @@ -47,7 +55,7 @@ public function initContent() 'Retrieve payment intent : ' . $e->getMessage(), null, null, - 'orderSuccess - registerStripeEvent' + 'orderSuccess - retrievePaymentIntent' ); } @@ -55,76 +63,13 @@ public function initContent() 'Retrieve payment intent : '.$intent, null, null, - 'orderSuccess - registerStripeEvent' + 'orderSuccess - retrievePaymentIntent' ); - if ($this->registerStripeEvent($intent)) { - - $conveyorData = [ - 'module' => $this->module, - 'context' => $this->context, - 'paymentIntent' => $payment_intent, - ]; - - if ($payment_method == 'oxxo') { - $conveyorData['voucher_url'] = $intent->next_action->oxxo_display_details->hosted_voucher_url; - $conveyorData['voucher_expire'] = $intent->next_action->oxxo_display_details->expires_after; - } - - $handler = new ActionsHandler(); - $handler->setConveyor($conveyorData); - - if ($payment_method == 'card' - || $payment_method == 'sepa_debit' - || $payment_method == 'oxxo') { - ProcessLoggerHandler::logInfo( - 'Payment method flow without redirection', - null, - null, - 'orderSuccess - initContent' - ); - $handler->addActions( - 'prepareFlowNone', - 'updatePaymentIntent', - 'createOrder', - 'sendMail', - 'saveCard', - 'addTentative' - ); - } elseif ($payment_method == 'sofort' - || $payment_method == 'fpx' - || $payment_method == 'giropay') { - ProcessLoggerHandler::logInfo( - 'Payment method flow with redirection', - null, - null, - 'orderSuccess - initContent' - ); - $handler->addActions( - 'prepareFlowRedirectPaymentIntent', - 'updatePaymentIntent', - 'createOrder', - 'sendMail', - 'saveCard', - 'addTentative' - ); - } - - if (!$handler->process('ValidationOrder')) { - // Handle error - ProcessLoggerHandler::logError( - 'Order creation process disrupted.', - null, - null, - 'orderSuccess - initContent' - ); - } - } - - $this->displayOrderConfirmation($intent->id); + return $intent; } - private function registerStripeEvent($paymentIntent) + private function checkEventStatus($paymentIntent) { $eventCharge = isset($paymentIntent->charges->data[0]) ? $paymentIntent->charges->data[0] : $paymentIntent; @@ -135,7 +80,7 @@ private function registerStripeEvent($paymentIntent) 'Charge event does not need to be processed : '.$eventCharge->status, null, null, - 'webhook - checkEventStatus' + 'orderSuccess - checkEventStatus' ); ProcessLoggerHandler::closeLogger(); return false; @@ -148,7 +93,7 @@ private function registerStripeEvent($paymentIntent) 'Last registered event => ID : ' . $lastRegisteredEvent->id, null, null, - 'orderSuccess - registerStripeEvent' + 'orderSuccess - checkEventStatus' ); if ($lastRegisteredEvent->date_add != null) { @@ -160,7 +105,7 @@ private function registerStripeEvent($paymentIntent) 'This charge event come too late to be processed [Last event : ' . $lastRegisteredEventDate->format('Y-m-d H:m:s') . ' | Current event : ' . $currentEventDate->format('Y-m-d H:m:s') . '].', null, null, - 'orderSuccess - registerStripeEvent' + 'orderSuccess - checkEventStatus' ); ProcessLoggerHandler::closeLogger(); return false; @@ -172,12 +117,21 @@ private function registerStripeEvent($paymentIntent) 'This Stripe module event "' . $stripeEventStatus . '" cannot be processed because [Last event status: ' . $lastRegisteredEvent->status . ' | Processed : ' . ($lastRegisteredEvent->isProcessed() ? 'Yes' : 'No') . '].', 'StripeEvent', $lastRegisteredEvent->id, - 'orderSuccess - registerStripeEvent' + 'orderSuccess - checkEventStatus' ); ProcessLoggerHandler::closeLogger(); return false; } + return $stripeEventStatus; + } + + private function registerStripeEvent($paymentIntent) + { + $eventCharge = isset($paymentIntent->charges->data[0]) ? $paymentIntent->charges->data[0] : $paymentIntent; + + $stripeEventStatus = $this->checkEventStatus($paymentIntent); + $stripeEventDate = new DateTime(); $stripeEventDate = $stripeEventDate->setTimestamp($eventCharge->created); @@ -202,6 +156,75 @@ private function registerStripeEvent($paymentIntent) } } + private function handleWebhookActions($intent) + { + $eventCharge = isset($intent->charges->data[0]) ? $intent->charges->data[0] : $intent; + $eventType = $eventCharge->status; + + $payment_method = Tools::getValue('payment_method'); + + $conveyorData = [ + 'module' => $this->module, + 'context' => $this->context, + 'paymentIntent' => $intent->id, + ]; + + if ($payment_method == 'oxxo') { + $conveyorData['voucher_url'] = $intent->next_action->oxxo_display_details->hosted_voucher_url; + $conveyorData['voucher_expire'] = $intent->next_action->oxxo_display_details->expires_after; + } + + $handler = new ActionsHandler(); + $handler->setConveyor($conveyorData); + + if (($eventType == 'succeeded' && $payment_method == 'card') + || ($eventType == 'pending' && $payment_method == 'sepa_debit') + || ($eventType == 'requires_action' && $payment_method == 'oxxo') + ) { + ProcessLoggerHandler::logInfo( + 'Payment method flow without redirection', + null, + null, + 'orderSuccess - handleWebhookActions' + ); + $handler->addActions( + 'prepareFlowNone', + 'updatePaymentIntent', + 'createOrder', + 'sendMail', + 'saveCard', + 'addTentative' + ); + } elseif (($eventType == 'pending' && $payment_method == 'sofort') + || (($eventType == 'succeeded' || $eventType == 'requires_action') && $payment_method != 'sofort') + ) { + ProcessLoggerHandler::logInfo( + 'Payment method flow with redirection', + null, + null, + 'orderSuccess - handleWebhookActions' + ); + $handler->addActions( + 'prepareFlowRedirectPaymentIntent', + 'updatePaymentIntent', + 'createOrder', + 'sendMail', + 'saveCard', + 'addTentative' + ); + } + + if (!$handler->process('ValidationOrder')) { + // Handle error + ProcessLoggerHandler::logError( + 'Order creation process disrupted.', + null, + null, + 'orderSuccess - handleWebhookActions' + ); + } + } + private function displayOrderConfirmation($id_intent) { ProcessLoggerHandler::logInfo( diff --git a/controllers/front/webhook.php b/controllers/front/webhook.php index 71e0996c..50a67e1c 100755 --- a/controllers/front/webhook.php +++ b/controllers/front/webhook.php @@ -530,12 +530,10 @@ private function handleWebhookActions($handler, $event) else $paymentMethodType = null; - if (($eventType == 'charge.succeeded' - && $paymentMethodType == 'card') - || ($eventType == 'charge.pending' - && $paymentMethodType == 'sepa_debit') - || ($eventType == 'payment_intent.requires_action' - && $paymentMethodType == 'oxxo')) { + if (($eventType == 'charge.succeeded' && $paymentMethodType == 'card') + || ($eventType == 'charge.pending' && $paymentMethodType == 'sepa_debit') + || ($eventType == 'payment_intent.requires_action' && $paymentMethodType == 'oxxo') + ) { ProcessLoggerHandler::logInfo( 'Payment method flow without redirection', null, @@ -550,11 +548,9 @@ private function handleWebhookActions($handler, $event) 'saveCard', 'addTentative' ); - } elseif (($eventType == 'charge.succeeded' - && $paymentMethodType != 'sofort' - && Stripe_official::$paymentMethods[$paymentMethodType]['flow'] == 'redirect') - || ($eventType == 'charge.pending' - && $paymentMethodType == 'sofort')) { + } elseif (($eventType == 'charge.pending' && $paymentMethodType == 'sofort') + || (($eventType == 'charge.succeeded' || $eventType == 'payment_intent.requires_action') && $paymentMethodType != 'sofort') + ) { ProcessLoggerHandler::logInfo( 'Payment method flow with redirection', null, From 30a46eaefe923459dd621ab90cf5bae4c6dc47eb Mon Sep 17 00:00:00 2001 From: afayadas Date: Mon, 3 Jan 2022 15:41:33 +0100 Subject: [PATCH 08/15] refs #32038 : truncate process logger table in upgrade 2.4.2 + remove use statement in upgrade 2.4.1 --- upgrade/Upgrade-2.4.1.php | 2 -- upgrade/Upgrade-2.4.2.php | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 upgrade/Upgrade-2.4.2.php diff --git a/upgrade/Upgrade-2.4.1.php b/upgrade/Upgrade-2.4.1.php index 3ac76264..f31d0b76 100644 --- a/upgrade/Upgrade-2.4.1.php +++ b/upgrade/Upgrade-2.4.1.php @@ -24,8 +24,6 @@ * @license Commercial license */ -use Stripe_officialClasslib\Extensions\ProcessLogger\ProcessLoggerHandler; - if (!defined('_PS_VERSION_')) { exit; } diff --git a/upgrade/Upgrade-2.4.2.php b/upgrade/Upgrade-2.4.2.php new file mode 100644 index 00000000..551514bb --- /dev/null +++ b/upgrade/Upgrade-2.4.2.php @@ -0,0 +1,37 @@ + + * @copyright Copyright (c) Stripe + * @license Commercial license + */ + +if (!defined('_PS_VERSION_')) { + exit; +} + +function upgrade_module_2_4_2($module) +{ + $sql = "TRUNCATE `" . _DB_PREFIX_ . "stripe_event`;"; + + return Db::getInstance()->execute($sql); +} From f5aad55842c8d6b4c17a0c702e99eddf2a32cd3f Mon Sep 17 00:00:00 2001 From: afayadas Date: Mon, 3 Jan 2022 15:45:11 +0100 Subject: [PATCH 09/15] refs #32864 : bump 2.4.2 --- 202/build.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/202/build.xml b/202/build.xml index 9aeafcce..e55bbc7b 100644 --- a/202/build.xml +++ b/202/build.xml @@ -5,7 +5,7 @@ - + From 72e0ec922874fcea6392a0722775c51db8e2cdd5 Mon Sep 17 00:00:00 2001 From: afayadas Date: Tue, 4 Jan 2022 10:27:20 +0100 Subject: [PATCH 10/15] refs #32038 : update totclasslib 2.3.1 with last modifications --- .../src/Actions/ActionsHandler.php | 36 ++-- .../src/Actions/DefaultActions.php | 21 +- .../Classes/ProcessLoggerObjectModel.php | 67 +++--- .../Admin/AdminProcessLoggerController.php | 198 ++++++++++-------- .../ProcessLogger/ProcessLoggerExtension.php | 40 +++- .../ProcessLogger/ProcessLoggerHandler.php | 143 ++++++++----- .../Classes/ProcessMonitorObjectModel.php | 113 ++++++++++ .../ProcessMonitor/ProcessMonitorHandler.php | 191 +++++++++++++++++ .../totpsclasslib/src/Hook/AbstractHook.php | 36 +++- .../src/Hook/AbstractHookDispatcher.php | 50 +++-- .../src/Install/AbstractInstaller.php | 54 ++++- .../src/Install/ExtensionInstaller.php | 33 ++- .../src/Install/ModuleInstaller.php | 44 +++- vendor/totpsclasslib/src/Module.php | 118 +++++++---- vendor/totpsclasslib/src/Registry.php | 35 ++-- .../src/Utils/Translate/TranslateTrait.php | 11 +- 16 files changed, 913 insertions(+), 277 deletions(-) create mode 100644 vendor/totpsclasslib/src/Extensions/ProcessMonitor/Classes/ProcessMonitorObjectModel.php create mode 100644 vendor/totpsclasslib/src/Extensions/ProcessMonitor/ProcessMonitorHandler.php diff --git a/vendor/totpsclasslib/src/Actions/ActionsHandler.php b/vendor/totpsclasslib/src/Actions/ActionsHandler.php index 23f25126..61aa9826 100644 --- a/vendor/totpsclasslib/src/Actions/ActionsHandler.php +++ b/vendor/totpsclasslib/src/Actions/ActionsHandler.php @@ -20,15 +20,16 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license + * * @version release/2.3.1 */ namespace Stripe_officialClasslib\Actions; -use \Hook; -use \Module; -use \ObjectModel; -use \Tools; +use Hook; +use Module; +use ObjectModel; +use Tools; /** * Actions Handler @@ -36,22 +37,23 @@ class ActionsHandler { const PROCESS_OVERRIDE_HOOK = 'actionStripe_officialActionsHandler'; + /** - * @var ObjectModel $modelObject + * @var ObjectModel */ protected $modelObject; /** * Values conveyored by the classes * - * @var array $conveyor + * @var array */ - protected $conveyor = array(); + protected $conveyor = []; /** * List of actions * - * @var array $actions + * @var array */ protected $actions; @@ -59,6 +61,7 @@ class ActionsHandler * Set an modelObject * * @param ObjectModel $modelObject + * * @return $this */ public function setModelObject($modelObject) @@ -72,6 +75,7 @@ public function setModelObject($modelObject) * Set the conveyor * * @param array $conveyorData + * * @return $this */ public function setConveyor($conveyorData) @@ -95,11 +99,13 @@ public function getConveyor() * Call sevral actions * * @param mixed $actions + * * @return $this */ public function addActions($actions) { $this->actions = func_get_args(); + return $this; } @@ -107,14 +113,16 @@ public function addActions($actions) * Process the action call back of cross modules * * @param string $className Name of the actions chain / Namespaced classname + * * @return bool + * * @throws \Exception */ public function process($className) { if (!class_exists($className)) { $className = Tools::ucfirst($className) . 'Actions'; - if (!preg_match("/^[a-zA-Z]+$/", $className)) { + if (!preg_match('/^[a-zA-Z]+$/', $className)) { throw new \Exception($className . '" class name not valid "'); } include_once _PS_MODULE_DIR_ . 'stripe_official/classes/actions/' . $className . '.php'; @@ -127,23 +135,25 @@ public function process($className) } $moduleId = Module::getModuleIdByName('stripe_official'); - $hookResult = Hook::exec(self::PROCESS_OVERRIDE_HOOK, array('className' => $className), $moduleId, true, false); + /** @var array $hookResult */ + $hookResult = Hook::exec(self::PROCESS_OVERRIDE_HOOK, ['className' => $className], $moduleId, true, false); if (!empty($hookResult) && !empty($hookResult['stripe_official'])) { $className = $hookResult['stripe_official']; } if (class_exists($className)) { /** @var DefaultActions $classAction */ - $classAction = new $className; + $classAction = new $className(); $classAction->setModelObject($this->modelObject); $classAction->setConveyor($this->conveyor); foreach ($this->actions as $action) { - if (!is_callable(array($classAction, $action), false, $callableName)) { + if (!is_callable([$classAction, $action], false, $callableName)) { continue; } - if (!call_user_func_array(array($classAction, $action), array())) { + if (!call_user_func_array([$classAction, $action], [])) { $this->setConveyor($classAction->getConveyor()); + return false; } } diff --git a/vendor/totpsclasslib/src/Actions/DefaultActions.php b/vendor/totpsclasslib/src/Actions/DefaultActions.php index 1770ef71..e8f52368 100644 --- a/vendor/totpsclasslib/src/Actions/DefaultActions.php +++ b/vendor/totpsclasslib/src/Actions/DefaultActions.php @@ -20,12 +20,13 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license + * * @version release/2.3.1 */ namespace Stripe_officialClasslib\Actions; -use \Translate; +use Translate; /** * DefaultActions @@ -33,21 +34,22 @@ class DefaultActions { /** - * @var \ObjectModel $modelObject + * @var \ObjectModel */ protected $modelObject; /** * Values conveyored by the classes * - * @var array $conveyor + * @var array */ - protected $conveyor = array(); + protected $conveyor = []; /** * Set the modelObject * * @param \ObjectModel $modelObject + * * @return $this */ public function setModelObject($modelObject) @@ -61,6 +63,7 @@ public function setModelObject($modelObject) * Set the conveyor * * @param array $conveyorData + * * @return $this */ public function setConveyor($conveyorData) @@ -84,24 +87,28 @@ public function getConveyor() * Call next action call back of cross modules * * @param mixed $action Name of the actions chain + * * @return bool */ protected function forward($action) { - if (!is_callable(array($this, $action), false)) { - echo $action.' not defined'; + if (!is_callable([$this, $action], false)) { + echo $action . ' not defined'; exit; } - if (!call_user_func_array(array($this, $action), array())) { + if (!call_user_func_array([$this, $action], [])) { return false; } + return true; } /** * Translation function; needed so PS will properly parse the file + * * @param string $string the string to translate * @param string $source the file with the translation; should always be the current file + * * @return mixed|string */ protected function l($string, $source) diff --git a/vendor/totpsclasslib/src/Extensions/ProcessLogger/Classes/ProcessLoggerObjectModel.php b/vendor/totpsclasslib/src/Extensions/ProcessLogger/Classes/ProcessLoggerObjectModel.php index 82af9ac5..6fb6a2af 100644 --- a/vendor/totpsclasslib/src/Extensions/ProcessLogger/Classes/ProcessLoggerObjectModel.php +++ b/vendor/totpsclasslib/src/Extensions/ProcessLogger/Classes/ProcessLoggerObjectModel.php @@ -20,12 +20,13 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license + * * @version release/2.3.1 */ namespace Stripe_officialClasslib\Extensions\ProcessLogger\Classes; -use \ObjectModel; +use ObjectModel; class ProcessLoggerObjectModel extends ObjectModel { @@ -44,45 +45,55 @@ class ProcessLoggerObjectModel extends ObjectModel /** @var int|null Identifier of resource announced with ObjectModel if needed */ public $object_id; + /** + * @var int|null + */ + public $id_session; + /** @var string Date */ public $date_add; /** * @see \ObjectModel::$definition */ - public static $definition = array( - 'table' => 'stripe_official_processlogger', - 'primary' => 'id_stripe_official_processlogger', - 'fields' => array( - 'name' => array( - 'type' => ObjectModel::TYPE_STRING, + public static $definition = [ + 'table' => 'stripe_official_processlogger', + 'primary' => 'id_stripe_official_processlogger', + 'fields' => [ + 'name' => [ + 'type' => ObjectModel::TYPE_STRING, 'validate' => 'isGenericName', - 'size' => 100, - ), - 'msg' => array( - 'type' => ObjectModel::TYPE_HTML, + 'size' => 100, + ], + 'msg' => [ + 'type' => ObjectModel::TYPE_HTML, 'validate' => 'isGenericName', - ), - 'level' => array( - 'type' => ObjectModel::TYPE_STRING, + ], + 'level' => [ + 'type' => ObjectModel::TYPE_STRING, 'validate' => 'isGenericName', - 'size' => 10, - ), - 'object_name' => array( - 'type' => ObjectModel::TYPE_STRING, + 'size' => 10, + ], + 'object_name' => [ + 'type' => ObjectModel::TYPE_STRING, 'validate' => 'isGenericName', - 'size' => 100, - ), - 'object_id' => array( + 'size' => 100, + ], + 'object_id' => [ 'type' => ObjectModel::TYPE_INT, 'validate' => 'isUnsigned', 'allow_null' => true, - ), - 'date_add' => array( - 'type' => ObjectModel::TYPE_DATE, - 'validate' => 'isDate', + ], + 'id_session' => [ + 'type' => ObjectModel::TYPE_STRING, + 'validate' => 'isString', + 'allow_null' => true, + ], + 'date_add' => [ + 'type' => ObjectModel::TYPE_DATE, + 'validate' => 'isDate', 'copy_post' => false, - ), - ), - ); + ], + ], + ]; } diff --git a/vendor/totpsclasslib/src/Extensions/ProcessLogger/Controllers/Admin/AdminProcessLoggerController.php b/vendor/totpsclasslib/src/Extensions/ProcessLogger/Controllers/Admin/AdminProcessLoggerController.php index 7e4dc284..7f7ff624 100644 --- a/vendor/totpsclasslib/src/Extensions/ProcessLogger/Controllers/Admin/AdminProcessLoggerController.php +++ b/vendor/totpsclasslib/src/Extensions/ProcessLogger/Controllers/Admin/AdminProcessLoggerController.php @@ -20,21 +20,22 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license + * * @version release/2.3.1 */ namespace Stripe_officialClasslib\Extensions\ProcessLogger\Controllers\Admin; use Stripe_officialClasslib\Extensions\ProcessLogger\Classes\ProcessLoggerObjectModel; - -use \Db; -use \Tools; -use \Configuration; -use \Shop; +use Stripe_officialClasslib\Extensions\ProcessLogger\ProcessLoggerExtension; +use Configuration; +use Db; +use Shop; +use Tools; class AdminProcessLoggerController extends \ModuleAdminController { - /** @var bool $bootstrap Active bootstrap for Prestashop 1.6 */ + /** @var bool Active bootstrap for Prestashop 1.6 */ public $bootstrap = true; /** @var \Module Instance of your module automatically set by ModuleAdminController */ @@ -49,10 +50,10 @@ class AdminProcessLoggerController extends \ModuleAdminController /** @var string|false Object identifier inside the associated table */ public $identifier = 'id_stripe_official_processlogger'; - /** @var string Default ORDER BY clause when $_orderBy is not defined */ + /** @var string Default ORDER BY clause when is not defined */ protected $_defaultOrderBy = 'id_stripe_official_processlogger'; - /** @var string Default ORDER WAY clause when $_orderWay is not defined */ + /** @var string Default ORDER WAY clause when is not defined */ protected $_defaultOrderWay = 'DESC'; /** @var bool List content lines are clickable if true */ @@ -69,103 +70,123 @@ public function __construct() $this->addRowAction('delete'); - $this->bulk_actions = array( - 'delete' => array( + $this->bulk_actions = [ + 'delete' => [ 'text' => $this->module->l('Delete selected', 'AdminProcessLoggerController'), 'confirm' => $this->module->l( 'Would you like to delete the selected items?', 'AdminProcessLoggerController' ), - ) - ); - - $this->fields_list = array( - 'id_stripe_official_processlogger' => array( - 'title' => $this->module->l('ID', 'AdminProcessLoggerController'), - 'align' => 'center', - 'class' => 'fixed-width-xs', + ], + ]; + + $this->fields_list = [ + 'id_stripe_official_processlogger' => [ + 'title' => $this->module->l('ID', 'AdminProcessLoggerController'), + 'align' => 'center', + 'class' => 'fixed-width-xs', 'search' => true, - ), - 'name' => array( + ], + 'name' => [ 'title' => $this->module->l('Name', 'AdminProcessLoggerController'), - ), - 'msg' => array( + ], + 'msg' => [ 'title' => $this->module->l('Message', 'AdminProcessLoggerController'), - ), - 'level' => array( - 'title' => $this->module->l('Level', 'AdminProcessLoggerController'), + ], + 'level' => [ + 'title' => $this->module->l('Level', 'AdminProcessLoggerController'), 'callback' => 'getLevel', - ), - 'object_name' => array( + ], + 'object_name' => [ 'title' => $this->module->l('Object Name', 'AdminProcessLoggerController'), - ), - 'object_id' => array( - 'title' => $this->module->l('Object ID', 'AdminProcessLoggerController'), + ], + 'object_id' => [ + 'title' => $this->module->l('Object ID', 'AdminProcessLoggerController'), 'callback' => 'getObjectId', - ), - 'date_add' => array( + ], + 'id_session' => [ + 'title' => $this->module->l('Session ID', 'AdminProcessLoggerController'), + ], + 'date_add' => [ 'title' => $this->module->l('Date', 'AdminProcessLoggerController'), - ), - ); + ], + ]; - $this->fields_options = array( - 'processLogger' => array( - 'image' => '../img/admin/cog.gif', - 'title' => $this->module->l('Process Logger Settings', 'AdminProcessLoggerController'), + $this->fields_options = [ + 'processLogger' => [ + 'image' => '../img/admin/cog.gif', + 'title' => $this->module->l('Process Logger Settings', 'AdminProcessLoggerController'), 'description' => $this->module->l( 'Here you can change the default configuration for this Process Logger', 'AdminProcessLoggerController' ), - 'fields' => array( - 'STRIPE_OFFICIAL_EXTLOGS_ERASING_DISABLED' => array( - 'title' => $this->module->l( + 'fields' => [ + ProcessLoggerExtension::QUIET_MODE => [ + 'title' => $this->module->l( + 'Activate quiet mode', + 'AdminProcessLoggerController' + ), + 'hint' => $this->module->l( + 'If quiet mode is activated, only success and error logs are saved. Logs with a level info are not saved.', + 'AdminProcessLoggerController' + ), + 'validation' => 'isBool', + 'cast' => 'intval', + 'type' => 'bool', + ], + ProcessLoggerExtension::ERASING_DISABLED => [ + 'title' => $this->module->l( 'Disable auto erasing', 'AdminProcessLoggerController' ), - 'hint' => $this->module->l( + 'hint' => $this->module->l( 'If disabled, logs will be automatically erased after the delay', 'AdminProcessLoggerController' ), - 'validation' => 'isBool', - 'cast' => 'intval', - 'type' => 'bool', - ), - 'STRIPE_OFFICIAL_EXTLOGS_ERASING_DAYSMAX' => array( - 'title' => $this->module->l( + 'validation' => 'isBool', + 'cast' => 'intval', + 'type' => 'bool', + ], + ProcessLoggerExtension::ERASING_DAYSMAX => [ + 'title' => $this->module->l( 'Auto erasing delay (in days)', 'AdminProcessLoggerController' ), - 'hint' => $this->module->l( + 'hint' => $this->module->l( 'Choose the number of days you want to keep logs in database', 'AdminProcessLoggerController' ), - 'validation' => 'isInt', - 'cast' => 'intval', - 'type' => 'text', + 'validation' => 'isInt', + 'cast' => 'intval', + 'type' => 'text', 'defaultValue' => 5, - ), - ), - 'submit' => array( + ], + ], + 'submit' => [ 'title' => $this->module->l('Save', 'AdminProcessLoggerController'), - 'name' => 'submitSaveConf'), - ), - ); + 'name' => 'submitSaveConf', + ], + ], + ]; } /** - * @param $echo string Value of field - * @param $tr array All data of the row + * @param string $echo Value of field + * @param array $tr All data of the row + * * @return string */ public function getObjectId($echo, $tr) { unset($tr); + return empty($echo) ? '' : $echo; } /** - * @param $echo string Value of field - * @param $tr array All data of the row + * @param string $echo Value of field + * @param array $tr All data of the row + * * @return string */ public function getLevel($echo, $tr) @@ -173,18 +194,19 @@ public function getLevel($echo, $tr) unset($tr); switch ($echo) { case 'info': - $echo = ''.$echo.''; + $echo = '' . $echo . ''; break; case 'success': - $echo = ''.$echo.''; + $echo = '' . $echo . ''; break; case 'error': - $echo = ''.$echo.''; + $echo = '' . $echo . ''; break; case 'deprecated': - $echo = ''.$echo.''; + $echo = '' . $echo . ''; break; } + return $echo; } @@ -206,13 +228,13 @@ public function initToolbar() parent::initToolbar(); // Remove the add new item button unset($this->toolbar_btn['new']); - $this->toolbar_btn['delete'] = array( + $this->toolbar_btn['delete'] = [ 'short' => 'Erase', 'desc' => $this->module->l('Erase all'), - 'js' => 'if (confirm(\''. - $this->module->l('Are you sure?', 'AdminProcessLoggerController'). - '\')) document.location = \''.self::$currentIndex.'&token='.$this->token.'&action=erase\';' - ); + 'js' => 'if (confirm(\'' . + $this->module->l('Are you sure?', 'AdminProcessLoggerController') . + '\')) document.location = \'' . self::$currentIndex . '&token=' . $this->token . '&action=erase\';', + ]; } /** @@ -242,31 +264,41 @@ public function postProcess() public function saveConfiguration() { - $shops = \Shop::getShops(); - foreach ($shops as $shop) { - $extlogs_erasing_daysmax = Tools::getValue('STRIPE_OFFICIAL_EXTLOGS_ERASING_DAYSMAX'); - $extlogs_erasing_disabled = Tools::getValue('STRIPE_OFFICIAL_EXTLOGS_ERASING_DISABLED'); - + $shops = \Shop::getShops(false, null, true); + $shops[] = 0; + foreach ($shops as $idShop) { + $extlogsQuietMode = Tools::getValue(ProcessLoggerExtension::QUIET_MODE); + $extlogsErasingDaysmax = Tools::getValue(ProcessLoggerExtension::ERASING_DAYSMAX); + $extlogsErasingDisabled = Tools::getValue(ProcessLoggerExtension::ERASING_DISABLED); + + Configuration::updateValue( + ProcessLoggerExtension::QUIET_MODE, + (bool)$extlogsQuietMode, + false, + null, + $idShop + ); + Configuration::updateValue( - 'STRIPE_OFFICIAL_EXTLOGS_ERASING_DISABLED', - ($extlogs_erasing_disabled ? true : false), + ProcessLoggerExtension::ERASING_DISABLED, + (bool)$extlogsErasingDisabled, false, null, - $shop['id_shop'] + $idShop ); - if (!is_numeric($extlogs_erasing_daysmax)) { + if (!is_numeric($extlogsErasingDaysmax)) { $this->errors[] = $this->module->l( 'You must specify a valid \"Auto erasing delay (in days)\" number.', 'AdminProcessLoggerController' ); } else { Configuration::updateValue( - 'STRIPE_OFFICIAL_EXTLOGS_ERASING_DAYSMAX', - $extlogs_erasing_daysmax, + ProcessLoggerExtension::ERASING_DAYSMAX, + $extlogsErasingDaysmax, false, null, - $shop['id_shop'] + $idShop ); $this->confirmations[] = $this->module->l( 'Log parameters are successfully updated!', diff --git a/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerExtension.php b/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerExtension.php index 46d5de2c..ad324d76 100644 --- a/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerExtension.php +++ b/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerExtension.php @@ -20,31 +20,49 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license + * * @version release/2.3.1 */ + namespace Stripe_officialClasslib\Extensions\ProcessLogger; use Stripe_officialClasslib\Extensions\AbstractModuleExtension; -use Stripe_officialClasslib\Extensions\ProcessLogger\Controllers\Admin\AdminProcessLoggerController; use Stripe_officialClasslib\Extensions\ProcessLogger\Classes\ProcessLoggerObjectModel; +use Stripe_officialClasslib\Extensions\ProcessLogger\Controllers\Admin\AdminProcessLoggerController; +use Configuration; class ProcessLoggerExtension extends AbstractModuleExtension { public $name = 'process_logger'; - public $extensionAdminControllers = array( - array( - 'name' => array( + public $extensionAdminControllers = [ + [ + 'name' => [ 'en' => 'Logger Stripe_official', 'fr' => 'Logger Stripe_official', - ), + ], 'class_name' => 'AdminStripe_officialProcessLogger', 'parent_class_name' => 'stripe_official', 'visible' => true, - ), - ); + ], + ]; + + public $objectModels = [ + ProcessLoggerObjectModel::class, + ]; + + const QUIET_MODE = 'STRIPE_OFFICIAL_PROCESS_LOGGER_QUIET_MODE'; + + const ERASING_DISABLED = 'STRIPE_OFFICIAL_EXTLOGS_ERASING_DISABLED'; + + const ERASING_DAYSMAX = 'STRIPE_OFFICIAL_EXTLOGS_ERASING_DAYSMAX'; + + public function install() + { + Configuration::updateGlobalValue(self::QUIET_MODE, 0); + Configuration::updateGlobalValue(self::ERASING_DISABLED, 0); + Configuration::updateGlobalValue(self::ERASING_DAYSMAX, 5); - public $objectModels = array( - ProcessLoggerObjectModel::class - ); -} \ No newline at end of file + return parent::install(); + } +} diff --git a/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerHandler.php b/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerHandler.php index 74a23cf0..26fd8141 100644 --- a/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerHandler.php +++ b/vendor/totpsclasslib/src/Extensions/ProcessLogger/ProcessLoggerHandler.php @@ -20,32 +20,35 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license + * * @version release/2.3.1 */ namespace Stripe_officialClasslib\Extensions\ProcessLogger; -use \Db; -use \Configuration; -use \Hook; +use Stripe_officialClasslib\Extensions\ProcessMonitor\ProcessMonitorHandler; +use Configuration; +use Db; +use Hook; +use Tools; class ProcessLoggerHandler { /** - * @var Stripe_officialClasslib\Extensions\ProcessMonitor\ProcessMonitorHandler - * Instance of ProcessMonitorHandler + * @var ProcessMonitorHandler + * Instance of ProcessMonitorHandler */ private static $process; /** * @var array logs */ - private static $logs = array(); + private static $logs = []; /** * Set process name and remove oldest logs * - * @param Stripe_officialClasslib\Extensions\ProcessMonitor\ProcessMonitorHandler|null $process + * @param ProcessMonitorHandler|null $process */ public static function openLogger($process = null) { @@ -55,6 +58,9 @@ public static function openLogger($process = null) /** * @param string|null $msg + * + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException */ public static function closeLogger($msg = null) { @@ -70,17 +76,26 @@ public static function closeLogger($msg = null) * @param int|null $objectId * @param string|null $name * @param string $level + * + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException */ public static function addLog($msg, $objectModel = null, $objectId = null, $name = null, $level = 'info') { - self::$logs[] = array( + $isQuietMode = Configuration::get(ProcessLoggerExtension::QUIET_MODE); + if ($isQuietMode && $level == 'info') { + return; + } + + self::$logs[] = [ 'name' => pSQL($name), 'msg' => pSQL($msg), 'level' => pSQL($level), 'object_name' => pSQL($objectModel), 'object_id' => (int)$objectId, - 'date_add' => date("Y-m-d H:i:s"), - ); + 'date_add' => date('Y-m-d H:i:s'), + 'id_session' => self::getSessionId(), + ]; if (100 === count(self::$logs)) { self::saveLogsInDb(); @@ -92,6 +107,9 @@ public static function addLog($msg, $objectModel = null, $objectId = null, $name * @param string|null $objectModel * @param int|null $objectId * @param string $name + * + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException */ public static function logSuccess($msg, $objectModel = null, $objectId = null, $name = 'default') { @@ -106,6 +124,9 @@ public static function logSuccess($msg, $objectModel = null, $objectId = null, $ * @param string|null $objectModel * @param int|null $objectId * @param string $name + * + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException */ public static function logError($msg, $objectModel = null, $objectId = null, $name = 'default') { @@ -120,6 +141,9 @@ public static function logError($msg, $objectModel = null, $objectId = null, $na * @param string|null $objectModel * @param int|null $objectId * @param string $name + * + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException */ public static function logInfo($msg, $objectModel = null, $objectId = null, $name = 'default') { @@ -134,6 +158,9 @@ public static function logInfo($msg, $objectModel = null, $objectId = null, $nam * @param string|null $objectModel * @param int|null $objectId * @param string $name + * + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException */ public static function logDeprecated($msg, $objectModel = null, $objectId = null, $name = 'default') { @@ -145,36 +172,38 @@ public static function logDeprecated($msg, $objectModel = null, $objectId = null /** * @return bool + * + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException */ public static function saveLogsInDb() { $result = true; if (false === empty(self::$logs) && self::getSkippingHooksResult()) { - Hook::exec( - 'actionProcessLoggerSave', - array( - 'logs' => &self::$logs, - ), - null, - true + 'actionProcessLoggerSave', + [ + 'logs' => &self::$logs, + ], + null, + true ); Hook::exec( - 'actionStripe_officialProcessLoggerSave', - array( - 'logs' => &self::$logs, - ), - null, - true + 'actionStripe_officialProcessLoggerSave', + [ + 'logs' => &self::$logs, + ], + null, + true ); - + $result = Db::getInstance()->insert( 'stripe_official_processlogger', self::$logs ); if ($result) { - self::$logs = array(); + self::$logs = []; } } @@ -220,32 +249,34 @@ public static function getAutoErasingDelayInDays() return (int)$numberOfDays; } - + /** * Executes the hooks used to skip a ProcessLogger save. This will return * false if any module hooked to either 'actionSkipProcessLoggerSave' or * 'actionSkipStripe_officialProcessLoggerSave' returns false (weak comparison) - * + * * @return bool + * + * @throws \PrestaShopException */ - protected static function getSkippingHooksResult() { - + protected static function getSkippingHooksResult() + { if (Hook::getIdByName('actionSkipProcessLoggerSave')) { $hookProcessLoggerReturnArray = Hook::exec( - 'actionSkipProcessLoggerSave', - array( - 'logs' => self::$logs, - ), - null, - true + 'actionSkipProcessLoggerSave', + [ + 'logs' => self::$logs, + ], + null, + true ); if (!is_array($hookProcessLoggerReturnArray)) { return false; } - + if (!empty($hookProcessLoggerReturnArray)) { - $hookReturn = array_reduce($hookProcessLoggerReturnArray, function($and, $hookReturn) { + $hookReturn = array_reduce($hookProcessLoggerReturnArray, function ($and, $hookReturn) { return $and && (bool)$hookReturn; }); if (!$hookReturn) { @@ -253,23 +284,23 @@ protected static function getSkippingHooksResult() { } } } - + if (Hook::getIdByName('actionSkipStripe_officialProcessLoggerSave')) { $hookModuleProcessLoggerReturnArray = Hook::exec( - 'actionSkipStripe_officialProcessLoggerSave', - array( - 'logs' => self::$logs, - ), - null, - true + 'actionSkipStripe_officialProcessLoggerSave', + [ + 'logs' => self::$logs, + ], + null, + true ); if (!is_array($hookModuleProcessLoggerReturnArray)) { return false; } - + if (!empty($hookModuleProcessLoggerReturnArray)) { - $hookReturn = array_reduce($hookModuleProcessLoggerReturnArray, function($and, $hookReturn) { + $hookReturn = array_reduce($hookModuleProcessLoggerReturnArray, function ($and, $hookReturn) { return $and && (bool)$hookReturn; }); if (!$hookReturn) { @@ -277,7 +308,25 @@ protected static function getSkippingHooksResult() { } } } - + return true; } + + protected static function getSessionId() + { + $values = []; + $remoteAddr = Tools::getRemoteAddr(); + $values[] = $remoteAddr; + if (!empty($_SERVER['REQUEST_TIME'])) { + $values[] = $_SERVER['REQUEST_TIME']; + } elseif (!empty($_SERVER['REQUEST_TIME_FLOAT'])) { + $values[] = $_SERVER['REQUEST_TIME_FLOAT']; + } + + if (!empty($_SERVER['REMOTE_PORT'])) { + $values[] = $_SERVER['REMOTE_PORT']; + } + + return sprintf('%08x', abs(crc32(implode('', $values)))); + } } diff --git a/vendor/totpsclasslib/src/Extensions/ProcessMonitor/Classes/ProcessMonitorObjectModel.php b/vendor/totpsclasslib/src/Extensions/ProcessMonitor/Classes/ProcessMonitorObjectModel.php new file mode 100644 index 00000000..72ae964a --- /dev/null +++ b/vendor/totpsclasslib/src/Extensions/ProcessMonitor/Classes/ProcessMonitorObjectModel.php @@ -0,0 +1,113 @@ + + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + * @version release/2.3.1 + */ + +namespace Stripe_officialClasslib\Extensions\ProcessMonitor\Classes; + +use \Db; +use \DbQuery; +use \ObjectModel; + +class ProcessMonitorObjectModel extends ObjectModel +{ + /** @var string name of process */ + public $name; + + /** @var int PHP's process ID associated with process */ + public $pid = null; + + /** @var string Some useful data about process execution */ + public $data; + + /** @var float */ + public $duration = 0; + + /** @var string Date */ + public $last_update; + + /** @var string Boolean */ + public $active = true; + + /** + * @see ObjectModel::$definition + */ + public static $definition = array( + 'table' => 'stripe_official_processmonitor', + 'primary' => 'id_stripe_official_processmonitor', + 'fields' => array( + 'name' => array( + 'type' => ObjectModel::TYPE_STRING, + 'validate' => 'isGenericName', + 'size' => 100, + 'unique' => true, + 'required' => true, + ), + 'pid' => array( + 'type' => ObjectModel::TYPE_INT, + 'validate' => 'isUnsignedId', + 'allow_null' => true, + ), + 'data' => array( + 'type' => ObjectModel::TYPE_STRING, + ), + 'duration' => array( + 'type' => ObjectModel::TYPE_FLOAT, + 'validate' => 'isUnsignedFloat', + 'size' => 10, + 'scale' => 6, + ), + 'active' => array( + 'type' => ObjectModel::TYPE_BOOL, + 'validate' => 'isBool', + 'required' => true + ), + 'last_update' => array( + 'type' => ObjectModel::TYPE_DATE, + ), + ), + ); + + /** + * @param $name + * + * @return mixed + */ + public function findOneByName($name) + { + $query = new DbQuery(); + $query->select('*'); + $query->from(self::$definition['table'], 'p'); + $query->where('p.name = \''.pSQL($name).'\''); + + $data = Db::getInstance()->getRow($query); + + if (empty($data)) { + return $this; + } + + $this->hydrate($data); + + return $this; + } +} diff --git a/vendor/totpsclasslib/src/Extensions/ProcessMonitor/ProcessMonitorHandler.php b/vendor/totpsclasslib/src/Extensions/ProcessMonitor/ProcessMonitorHandler.php new file mode 100644 index 00000000..05b6ee52 --- /dev/null +++ b/vendor/totpsclasslib/src/Extensions/ProcessMonitor/ProcessMonitorHandler.php @@ -0,0 +1,191 @@ + + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + * @version release/2.3.1 + */ + +namespace Stripe_officialClasslib\Extensions\ProcessMonitor; + +use Stripe_officialClasslib\Extensions\ProcessMonitor\Classes\ProcessMonitorObjectModel; + +use \Tools; +use \Db; +use \ObjectModel; + +class ProcessMonitorHandler +{ + /** + * @var Stripe_officialProcessMonitorObjectModel $process + */ + protected $process; + + /** + * @var float $startTime microtime + */ + public $startTime; + + /** + * Lock process + * + * @param string $name + * @return bool|mixed + * @throws \PrestaShopDatabaseException + * @throws \PrestaShopException + */ + public function lock($name) + { + $this->startTime = $this->microtimeFloat(); + $processMonitorObjectModel = new ProcessMonitorObjectModel(); + $this->process = $processMonitorObjectModel->findOneByName($name); + if (empty($this->process->id)) { + $this->process = new ProcessMonitorObjectModel(); + $this->process->name = $name; + $this->process->data = Tools::jsonEncode(array()); + $this->process->date_add = date('Y-m-d H:i:s'); + } + if (!empty($this->process->pid)) { + $last_update = new \DateTime($this->process->last_update); + $data_now = new \DateTime('NOW'); + $diff = $data_now->diff($last_update); + $hours = $diff->h; + $hours = $hours + ($diff->days*24); + if ($hours < 1) { + return false; + } + } + + $this->process->last_update = date('Y-m-d H:i:s'); + $this->process->pid = getmypid(); + + $this->date_upd = date('Y-m-d H:i:s'); + + /** + * We can't use the ObjectModel's "save", "add" or "update" methods. + * PS will natively call ObjectModel hooks, using the class name of the + * ObjectModel. On PS 1.6, the namespace is not escaped from the class name, + * resulting in an invalid hook name, e.g. : + * actionObjectShoppingfeedClasslib\Extensions\ProcessMonitor\ProcessMonitorObjectModelUpdateBefore + */ + $definition = ObjectModel::getDefinition($this->process); + if (empty($this->process->id)) { + Db::getInstance()->insert( + $definition['table'], + $this->process->getFields(), + false + ); + $this->process->id = Db::getInstance()->Insert_ID(); + } else { + Db::getInstance()->update( + $definition['table'], + $this->process->getFields(), + '`'.pSQL($definition['primary']).'` = '.(int)$this->process->id, + 0, + false + ); + } + + return Tools::jsonDecode($this->process->data, true); + } + + /** + * UnLock process + * + * @param array $data + * @return bool + * @throws \PrestaShopException + */ + public function unlock($data = array()) + { + if (empty($this->process)) { + return false; + } + + if (false === empty($data)) { + $this->process->data = Tools::jsonEncode($data); + } + $this->process->last_update = date('Y-m-d H:i:s'); + $endTime = $this->microtimeFloat(); + $duration = number_format(($endTime - $this->startTime), 3); + $this->process->duration = $duration; + $this->process->pid = null; + + /** + * We can't use the ObjectModel's "save", "add" or "update" methods. + * PS will natively call ObjectModel hooks, using the class name of the + * ObjectModel. On PS 1.6, the namespace is not escaped from the class name, + * resulting in an invalid hook name, e.g. : + * actionObjectShoppingfeedClasslib\Extensions\ProcessMonitor\ProcessMonitorObjectModelUpdateBefore + */ + $definition = ObjectModel::getDefinition($this->process); + return Db::getInstance()->update( + $definition['table'], + $this->process->getFields(), + '`'.pSQL($definition['primary']).'` = '.(int)$this->process->id, + 0, + false + ); + } + + /** + * Get microtime in float value + * + * @return float + */ + public function microtimeFloat() + { + list($usec, $sec) = explode(" ", microtime()); + return ((float)$usec + (float)$sec); + } + + /** + * @return null|string + */ + public function getProcessObjectModelName() + { + if (empty($this->process)) { + return null; + } + return get_class($this->process); + } + + /** + * @return int|null + */ + public function getProcessObjectModelId() + { + if (empty($this->process)) { + return null; + } + return (int)$this->process->id; + } + + /** + * @return null|string + */ + public function getProcessName() + { + if (empty($this->process)) { + return null; + } + return $this->process->name; + } +} diff --git a/vendor/totpsclasslib/src/Hook/AbstractHook.php b/vendor/totpsclasslib/src/Hook/AbstractHook.php index fb35353e..f0df37d7 100644 --- a/vendor/totpsclasslib/src/Hook/AbstractHook.php +++ b/vendor/totpsclasslib/src/Hook/AbstractHook.php @@ -1,8 +1,31 @@ + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + * + * @version release/2.3.1 + */ namespace Stripe_officialClasslib\Hook; - use Stripe_officialClasslib\Extensions\AbstractModuleExtension; use Stripe_officialClasslib\Module; use Stripe_officialClasslib\Utils\Translate\TranslateTrait; @@ -10,7 +33,8 @@ abstract class AbstractHook { use TranslateTrait; - const AVAILABLE_HOOKS = array(); + + const AVAILABLE_HOOKS = []; /** * @var Module @@ -19,6 +43,7 @@ abstract class AbstractHook /** * AbstractExtensionHook constructor. + * * @param Module $module */ public function __construct($module) @@ -28,6 +53,7 @@ public function __construct($module) /** * Get all available hooks for current object + * * @return array */ public function getAvailableHooks() @@ -38,11 +64,13 @@ public function getAvailableHooks() /** * Remove first 4 letters of hook function and replace the first letter by lower case * TODO maybe we should delete this function, because it isn't used - * @param $functionName + * + * @param string $functionName + * * @return string */ protected function getHookNameFromFunction($functionName) { return lcfirst(substr($functionName, 4, strlen($functionName))); } -} \ No newline at end of file +} diff --git a/vendor/totpsclasslib/src/Hook/AbstractHookDispatcher.php b/vendor/totpsclasslib/src/Hook/AbstractHookDispatcher.php index 2b42bc7e..f9ac1443 100644 --- a/vendor/totpsclasslib/src/Hook/AbstractHookDispatcher.php +++ b/vendor/totpsclasslib/src/Hook/AbstractHookDispatcher.php @@ -1,4 +1,28 @@ + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + * + * @version release/2.3.1 + */ namespace Stripe_officialClasslib\Hook; @@ -7,24 +31,23 @@ abstract class AbstractHookDispatcher { - protected $hookClasses = array(); + protected $hookClasses = []; - protected $widgetClasses = array(); + protected $widgetClasses = []; /** * List of available hooks * * @var string[] */ - protected $availableHooks = array(); + protected $availableHooks = []; /** * Hook classes - * */ - protected $hooks = array(); + protected $hooks = []; - protected $widgets = array(); + protected $widgets = []; /** * Module @@ -74,14 +97,15 @@ public function getAvailableHooks() * * @return mixed|void */ - public function dispatch($hookName, array $params = array()) + public function dispatch($hookName, array $params = []) { $hookName = preg_replace('~^hook~', '', $hookName); + $hookName = lcfirst($hookName); if (!empty($hookName)) { foreach ($this->hooks as $hook) { - if (is_callable(array($hook, $hookName))) { - return call_user_func(array($hook, $hookName), $params); + if (is_callable([$hook, $hookName])) { + return call_user_func([$hook, $hookName], $params); } } } @@ -91,8 +115,8 @@ public function dispatch($hookName, array $params = array()) continue; } - if (is_callable(array($widget, $params['action']))) { - return call_user_func(array($widget, $params['action']), $hookName, $params); + if (is_callable([$widget, $params['action']])) { + return call_user_func([$widget, $params['action']], $hookName, $params); } } @@ -101,6 +125,7 @@ public function dispatch($hookName, array $params = array()) /** * Get hook classes + * * @return array */ public function getHookClasses() @@ -110,10 +135,11 @@ public function getHookClasses() /** * Get widget classes + * * @return array */ public function getWidgetClasses() { return $this->widgetClasses; } -} \ No newline at end of file +} diff --git a/vendor/totpsclasslib/src/Install/AbstractInstaller.php b/vendor/totpsclasslib/src/Install/AbstractInstaller.php index a2246ab8..5f6e11d4 100644 --- a/vendor/totpsclasslib/src/Install/AbstractInstaller.php +++ b/vendor/totpsclasslib/src/Install/AbstractInstaller.php @@ -1,4 +1,28 @@ + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + * + * @version release/2.3.1 + */ namespace Stripe_officialClasslib\Install; @@ -16,7 +40,7 @@ abstract class AbstractInstaller //region Fields /** - * @var \Stripe_official + * @var Module */ protected $module; @@ -44,24 +68,28 @@ public function __construct($module) /** * Get hooks used in module/extension + * * @return array */ abstract public function getHooks(); /** * Get admin controllers used in module/extension + * * @return array */ abstract public function getAdminControllers(); /** * Get object models used in module/extension + * * @return array */ abstract public function getObjectModels(); /** - * @param \Stripe_official $module + * @param Module $module + * * @return $this */ public function setModule($module) @@ -73,6 +101,7 @@ public function setModule($module) /** * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -87,6 +116,7 @@ public function install() /** * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -99,11 +129,14 @@ public function uninstall() } //TODO + /** * Used only if merchant choose to keep data on modal in Prestashop 1.6 * - * @param Stripe_official $module + * @param Module $module + * * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -120,6 +153,7 @@ public function reset($module) /** * Register hooks used by our module + * * @return bool */ public function registerHooks() @@ -128,14 +162,16 @@ public function registerHooks() return true; } - return array_product(array_map(array($this->module, 'registerHook'), $this->getHooks())); + return array_product(array_map([$this->module, 'registerHook'], $this->getHooks())); } //TODO + /** * Clear hooks used by our module * * @return bool + * * @throws \PrestaShopException */ public function clearHookUsed() @@ -150,7 +186,7 @@ public function clearHookUsed() if (false === is_array($this->getHooks())) { // If $module->hooks is not defined or is not an array - $this->hooks = array(); + $this->hooks = []; } foreach ($this->getHooks() as $hook) { @@ -175,6 +211,7 @@ public function clearHookUsed() * Retrieve hooks used by our module * * @return array + * * @throws \PrestaShopDatabaseException */ public function getHooksUsed() @@ -189,7 +226,7 @@ public function getHooksUsed() $results = Db::getInstance()->executeS($query); if (empty($results)) { - return array(); + return []; } return array_column($results, 'name'); @@ -199,6 +236,7 @@ public function getHooksUsed() * Add Tabs for our ModuleAdminController * * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -222,7 +260,7 @@ public function installAdminControllers() $parentClassName = 'AdminPreferences'; } /** 3 levels available on 1.7+ */ - $defaultTabLevel1 = array('SELL', 'IMPROVE', 'CONFIGURE', 'DEFAULT'); + $defaultTabLevel1 = ['SELL', 'IMPROVE', 'CONFIGURE', 'DEFAULT']; if (in_array($parentClassName, $defaultTabLevel1) && version_compare(_PS_VERSION_, '1.7', '<')) { continue; } @@ -274,7 +312,7 @@ public function uninstallModuleAdminControllers() $query = new DbQuery(); $query->select('*'); $query->from('tab'); - $query->where('module = \''.pSQL($this->module->name).'\''); + $query->where('module = \'' . pSQL($this->module->name) . '\''); $tabs = Db::getInstance()->executeS($query); diff --git a/vendor/totpsclasslib/src/Install/ExtensionInstaller.php b/vendor/totpsclasslib/src/Install/ExtensionInstaller.php index 4ad5a851..683c7b64 100644 --- a/vendor/totpsclasslib/src/Install/ExtensionInstaller.php +++ b/vendor/totpsclasslib/src/Install/ExtensionInstaller.php @@ -1,4 +1,28 @@ + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + * + * @version release/2.3.1 + */ namespace Stripe_officialClasslib\Install; @@ -41,13 +65,11 @@ public function uninstall() return parent::uninstall() && $this->extension->uninstall(); } - - - //region Get-Set /** * @return array + * * @throws PrestaShopException */ public function getHooks() @@ -61,6 +83,7 @@ public function getHooks() /** * @return array + * * @throws PrestaShopException */ public function getAdminControllers() @@ -74,6 +97,7 @@ public function getAdminControllers() /** * @return array + * * @throws PrestaShopException */ public function getObjectModels() @@ -95,6 +119,7 @@ public function getExtension() /** * @param AbstractModuleExtension $extension + * * @return ExtensionInstaller */ public function setExtension($extension) @@ -105,4 +130,4 @@ public function setExtension($extension) } //endregion -} \ No newline at end of file +} diff --git a/vendor/totpsclasslib/src/Install/ModuleInstaller.php b/vendor/totpsclasslib/src/Install/ModuleInstaller.php index 95128232..218576e3 100644 --- a/vendor/totpsclasslib/src/Install/ModuleInstaller.php +++ b/vendor/totpsclasslib/src/Install/ModuleInstaller.php @@ -1,4 +1,28 @@ + * ........................................................................... + * + * @author 202-ecommerce + * @copyright Copyright (c) 202-ecommerce + * @license Commercial license + * + * @version release/2.3.1 + */ namespace Stripe_officialClasslib\Install; @@ -15,6 +39,7 @@ class ModuleInstaller extends AbstractInstaller { /** * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -29,6 +54,7 @@ public function install() /** * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -44,6 +70,7 @@ public function uninstall() /** * @return bool + * * @throws \Exception */ public function checkPhpVersion() @@ -69,6 +96,7 @@ public function checkPhpVersion() * Uninstall Configuration (with or without language management) * * @return bool + * * @throws \PrestaShopDatabaseException */ public function uninstallConfiguration() @@ -98,6 +126,7 @@ public function uninstallConfiguration() * Register Order State : create new order state for this module * * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -136,6 +165,7 @@ public function registerOrderStates() * Unregister Order State : mark them as deleted * * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -183,12 +213,14 @@ public function installExtensions() return true; } - return array_product(array_map(array($this, 'installExtension'), $this->module->extensions)); + return array_product(array_map([$this, 'installExtension'], $this->module->extensions)); } /** - * @param $extensionName + * @param string $extensionName + * * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -206,12 +238,14 @@ public function uninstallExtensions() return true; } - return array_product(array_map(array($this, 'uninstallExtension'), $this->module->extensions)); + return array_product(array_map([$this, 'uninstallExtension'], $this->module->extensions)); } /** - * @param $extensionName + * @param string $extensionName + * * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -243,4 +277,4 @@ public function getObjectModels() } //endregion -} \ No newline at end of file +} diff --git a/vendor/totpsclasslib/src/Module.php b/vendor/totpsclasslib/src/Module.php index 312ee22a..ed16cb6e 100644 --- a/vendor/totpsclasslib/src/Module.php +++ b/vendor/totpsclasslib/src/Module.php @@ -2,17 +2,17 @@ /** * NOTICE OF LICENSE * - * This source file is subject to a commercial license from SARL 202 ecommence + * This source file is subject to a commercial license from SARL 202 ecommerce * Use, copy, modification or distribution of this source file without written - * license agreement from the SARL 202 ecommence is strictly forbidden. + * license agreement from the SARL 202 ecommerce is strictly forbidden. * In order to obtain a license, please contact us: tech@202-ecommerce.com * ........................................................................... * INFORMATION SUR LA LICENCE D'UTILISATION * * L'utilisation de ce fichier source est soumise a une licence commerciale - * concedee par la societe 202 ecommence + * concedee par la societe 202 ecommerce * Toute utilisation, reproduction, modification ou distribution du present - * fichier source sans contrat de licence ecrit de la part de la SARL 202 ecommence est + * fichier source sans contrat de licence ecrit de la part de la SARL 202 ecommerce est * expressement interdite. * Pour obtenir une licence, veuillez contacter 202-ecommerce * ........................................................................... @@ -20,17 +20,18 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license - * @version develop + * + * @version release/2.3.1 */ namespace Stripe_officialClasslib; +use Stripe_officialClasslib\Extensions\AbstractModuleExtension; use Stripe_officialClasslib\Hook\AbstractHookDispatcher; -use PrestaShop\PrestaShop\Core\Module\WidgetInterface; -use \ReflectionClass; -use \Tools; use Stripe_officialClasslib\Install\ModuleInstaller; -use Stripe_officialClasslib\Extensions\AbstractModuleExtension; +use PrestaShop\PrestaShop\Core\Module\WidgetInterface; +use ReflectionClass; +use Tools; class Module extends \Module { @@ -38,17 +39,22 @@ class Module extends \Module /** * List of objectModel used in this Module - * @var array $objectModels + * + * @var array */ - public $objectModels = array(); + public $objectModels = []; /** * List of hooks used in this Module - * @var array $hooks + * + * @var array */ - public $hooks = array(); + public $hooks = []; - public $extensions = array(); + /** + * @var array + */ + public $extensions = []; /** * @var AbstractHookDispatcher @@ -57,9 +63,20 @@ class Module extends \Module /** * List of AdminControllers used in this Module - * @var array $moduleAdminControllers + * + * @var array */ - public $moduleAdminControllers = array(); + public $moduleAdminControllers = []; + + /** + * @var string + */ + public $secure_key; + + /** + * @var array + */ + public $cronTasks = []; //endregion @@ -74,6 +91,7 @@ public function __construct() $extension = new $extensionName(); $extension->setModule($this); $extension->initExtension(); + $this->hooks = array_merge($this->hooks, $extension->hooks); } } @@ -81,6 +99,7 @@ public function __construct() * Install Module * * @return bool + * * @throws \PrestaShopException */ public function install() @@ -88,6 +107,7 @@ public function install() $installer = new ModuleInstaller($this); $isPhpVersionCompliant = false; + try { $isPhpVersionCompliant = $installer->checkPhpVersion(); } catch (\Exception $e) { @@ -101,6 +121,7 @@ public function install() * Uninstall Module * * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -115,6 +136,7 @@ public function uninstall() * @TODO Reset Module only if merchant choose to keep data on modal * * @return bool + * * @throws \PrestaShopDatabaseException * @throws \PrestaShopException */ @@ -128,17 +150,19 @@ public function reset() /** * Handle module extension hook call * - * @param $hookName - * @param $params + * @param string $hookName + * @param array $params + * * @return array|bool|string */ public function handleExtensionsHook($hookName, $params) { $result = false; + $hookDispatcher = $this->getHookDispatcher(); // execute module hooks - if ($this->getHookDispatcher() != null) { - $moduleHookResult = $this->getHookDispatcher()->dispatch($hookName, $params); + if ($hookDispatcher != null) { + $moduleHookResult = $hookDispatcher->dispatch($hookName, $params); if ($moduleHookResult != null) { $result = $moduleHookResult; } @@ -155,10 +179,10 @@ public function handleExtensionsHook($hookName, $params) /** @var AbstractModuleExtension $extension */ $extension = new $extension($this); $hookResult = null; - if (is_callable(array($extension, $hookName))) { + if (is_callable([$extension, $hookName])) { $hookResult = $extension->{$hookName}($params); - //TODO - } else if (is_callable(array($extension, 'getHookDispatcher')) && $extension->getHookDispatcher() != null) { + //TODO + } elseif (is_callable([$extension, 'getHookDispatcher']) && $extension->getHookDispatcher() != null) { $hookResult = $extension->getHookDispatcher()->dispatch($hookName, $params); } if ($hookResult != null) { @@ -178,12 +202,15 @@ public function handleExtensionsHook($hookName, $params) /** * Handle module widget call * - * @param $action - * @param $method - * @param $hookName - * @param $configuration + * @param string $action + * @param string $method + * @param string $hookName + * @param array $configuration + * * @return bool + * * @throws \ReflectionException + * * @deprecated use render widget function */ public function handleWidget($action, $method, $hookName, $configuration) @@ -203,26 +230,28 @@ public function handleWidget($action, $method, $hookName, $configuration) continue; } $extension->setModule($this); - if (is_callable(array($extension, $method))) { + if (is_callable([$extension, $method])) { return $extension->{$method}($hookName, $configuration); } } return false; - } /** - * @param $hookName + * @param string $hookName * @param array $configuration + * * @return bool + * * @throws \ReflectionException */ public function renderWidget($hookName, array $configuration) { + $hookDispatcher = $this->getHookDispatcher(); // render module widgets - if ($this->getHookDispatcher() != null) { - $moduleWidgetResult = $this->getHookDispatcher()->dispatch($hookName, $configuration); + if ($hookDispatcher != null) { + $moduleWidgetResult = $hookDispatcher->dispatch($hookName, $configuration); if ($moduleWidgetResult != null) { return $moduleWidgetResult; } @@ -237,8 +266,13 @@ public function renderWidget($hookName, array $configuration) /** @var AbstractModuleExtension $extension */ $extension = new $extension($this); - if (is_callable(array($extension, 'getHookDispatcher')) && $extension->getHookDispatcher() != null) { - return $extension->getHookDispatcher()->dispatch($hookName, $configuration); + if (is_callable([$extension, 'getHookDispatcher']) && $extension->getHookDispatcher() != null) { + $extensionWidgetResult = $extension->getHookDispatcher()->dispatch($hookName, $configuration); + if (is_null($extensionWidgetResult)) { + continue; + } + + return $extensionWidgetResult; } } @@ -247,21 +281,31 @@ public function renderWidget($hookName, array $configuration) } /** - * @param $hookName + * @param string $hookName * @param array $configuration + * * @return array|bool */ public function getWidgetVariables($hookName, array $configuration) { - return array(); + return []; } /** * Get the current module hook/widget dispatcher - * @return null + * + * @return AbstractHookDispatcher|null */ public function getHookDispatcher() { return $this->hookDispatcher; } + + /** + * @return string|null + */ + public function getPath() + { + return $this->_path; + } } diff --git a/vendor/totpsclasslib/src/Registry.php b/vendor/totpsclasslib/src/Registry.php index 46349409..e2de0664 100644 --- a/vendor/totpsclasslib/src/Registry.php +++ b/vendor/totpsclasslib/src/Registry.php @@ -20,6 +20,7 @@ * @author 202-ecommerce * @copyright Copyright (c) 202-ecommerce * @license Commercial license + * * @version release/2.3.1 */ @@ -30,35 +31,36 @@ */ class Registry { - /** - * @var Stripe_officialClasslib\Registry $_registry Instance of this class + * @var Registry Instance of this class */ private static $_registry = null; /** - * @var array $values + * @var array */ - private $values = array(); - + private $values = []; + /** * Get instance of this class * - * @return Stripe_officialClasslib\Registry + * @return Registry */ public static function getInstance() { if (self::$_registry === null) { - self::$_registry = new Registry; + self::$_registry = new Registry(); } + return self::$_registry; } - + /** * Get a variable in the Registry * * @param string $index - * @return bool + * + * @return mixed */ public static function get($index) { @@ -66,25 +68,27 @@ public static function get($index) if (!$instance->offsetExists($index)) { return false; } + return $instance->values[$index]; } - + /** * Set a variable in the Registry * * @param string $index - * @param string $value + * @param string|array $value */ public static function set($index, $value) { $instance = self::getInstance(); - $instance->values[$index]= $value; + $instance->values[$index] = $value; } /** * Check if var exist in the registry * * @param string $index + * * @return bool */ public static function isRegistered($index) @@ -92,6 +96,7 @@ public static function isRegistered($index) if (self::$_registry === null) { return false; } + return self::$_registry->offsetExists($index); } @@ -99,6 +104,7 @@ public static function isRegistered($index) * Check if offsetExists * * @param string $index + * * @return bool */ public function offsetExists($index) @@ -106,9 +112,10 @@ public function offsetExists($index) if (false === isset($this->values)) { return false; } + return array_key_exists($index, $this->values); } - + /** * Increment a counter in the Registry * @@ -124,7 +131,7 @@ public static function increment($index, $value = 1) $instance->values[$index] = $value; } } - + /** * Decrement a counter in the Registry * diff --git a/vendor/totpsclasslib/src/Utils/Translate/TranslateTrait.php b/vendor/totpsclasslib/src/Utils/Translate/TranslateTrait.php index 978e94ca..1b0134e6 100644 --- a/vendor/totpsclasslib/src/Utils/Translate/TranslateTrait.php +++ b/vendor/totpsclasslib/src/Utils/Translate/TranslateTrait.php @@ -25,17 +25,18 @@ namespace Stripe_officialClasslib\Utils\Translate; -use \Translate; +use Translate; trait TranslateTrait { - /** * Translation method for classes that use this trait - * @param $textToTranslate + * + * @param string $textToTranslate * @param string $class * @param bool $addslashes * @param bool $htmlentities + * * @return mixed */ protected function l($textToTranslate, $class = '', $addslashes = false, $htmlentities = true) @@ -43,11 +44,13 @@ protected function l($textToTranslate, $class = '', $addslashes = false, $htmlen if (empty($class) === true) { $class = $this->getClassShortName(); } - return Translate::getModuleTranslation('tomrewardseditor', $textToTranslate, $class); + + return Translate::getModuleTranslation('stripe_official', $textToTranslate, $class); } /** * @return string + * * @throws \ReflectionException */ protected function getClassShortName() From cafce15c725dc5023473d95aa6546915d9591245 Mon Sep 17 00:00:00 2001 From: afayadas Date: Tue, 4 Jan 2022 14:18:32 +0100 Subject: [PATCH 11/15] refs #32846 : add no empty customer condition to saving card payment --- classes/actions/ValidationOrderActions.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/classes/actions/ValidationOrderActions.php b/classes/actions/ValidationOrderActions.php index c47774ca..cb9a249c 100755 --- a/classes/actions/ValidationOrderActions.php +++ b/classes/actions/ValidationOrderActions.php @@ -510,7 +510,7 @@ public function sendMail() public function saveCard() { try { - if ($this->conveyor['saveCard'] == null) { + if (empty($this->conveyor['saveCard']) === true || empty($this->conveyor['cart']->id_customer) === true) { return true; } @@ -521,7 +521,7 @@ public function saveCard() $stripeCustomer = new StripeCustomer(); $stripeCustomer = $stripeCustomer->getCustomerById($cartCustomer->id, $stripeAccount->id); - if (empty($stripeCustomer->id)) { + if (empty($stripeCustomer->id) === true) { $customer = \Stripe\Customer::create([ 'description' => 'Customer created from Prestashop Stripe module', 'email' => $cartCustomer->email, From 5c25188b69ee680ba71dcaa2ab1522f77414cdb4 Mon Sep 17 00:00:00 2001 From: afayadas Date: Tue, 4 Jan 2022 14:18:41 +0100 Subject: [PATCH 12/15] refs #32848 : remove useless round amount --- stripe_official.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/stripe_official.php b/stripe_official.php index c200d675..b80a08c4 100755 --- a/stripe_official.php +++ b/stripe_official.php @@ -1616,7 +1616,6 @@ public function hookHeader() $amount = $cart->getOrderTotal(); $amount = Tools::ps_round($amount, 2); $amount = $this->isZeroDecimalCurrency($currency->iso_code) ? $amount : $amount * 100; - $amount = Tools::ps_round($amount); if ($amount == 0) { return; @@ -1757,7 +1756,6 @@ public function hookPayment($params) $amount = $cart->getOrderTotal(); $amount = Tools::ps_round($amount, 2); $amount = $this->isZeroDecimalCurrency($currency->iso_code) ? $amount : $amount * 100; - $amount = Tools::ps_round($amount); if (Configuration::get(self::POSTCODE) == null) { $stripe_reinsurance_enabled = 'off'; From b77a0cbb28bd08500ea316101f84bb0e621534ca Mon Sep 17 00:00:00 2001 From: afayadas Date: Tue, 4 Jan 2022 15:11:59 +0100 Subject: [PATCH 13/15] refs #32848 : fix changing amount cart in AJAX in createIntent --- classes/StripeIdempotencyKey.php | 33 ++++++++++++++++++++++-------- controllers/front/createIntent.php | 33 ++++++++++++++++++++++-------- 2 files changed, 50 insertions(+), 16 deletions(-) diff --git a/classes/StripeIdempotencyKey.php b/classes/StripeIdempotencyKey.php index b1201234..6bad9b16 100644 --- a/classes/StripeIdempotencyKey.php +++ b/classes/StripeIdempotencyKey.php @@ -125,23 +125,21 @@ public function getByIdPaymentIntent($id_payment_intent) * @throws PrestaShopException * @throws \Stripe\Exception\ApiErrorException */ - public function createNewOne($id_cart, $datasIntent) + public function createNewOne($id_cart, $intentData) { $idempotency_key = $id_cart.'_'.uniqid(); $intent = \Stripe\PaymentIntent::create( - $datasIntent, + $intentData, [ 'idempotency_key' => $idempotency_key ] ); - $stripeIdempotencyKey = new StripeIdempotencyKey(); - $stripeIdempotencyKey->getByIdCart($id_cart); - $stripeIdempotencyKey->id_cart = $id_cart; - $stripeIdempotencyKey->idempotency_key = $idempotency_key; - $stripeIdempotencyKey->id_payment_intent = $intent->id; - $stripeIdempotencyKey->save(); + $this->id_cart = $id_cart; + $this->idempotency_key = $idempotency_key; + $this->id_payment_intent = $intent->id; + $this->save(); $paymentIntent = new StripePaymentIntent(); $paymentIntent->setIdPaymentIntent($intent->id); @@ -154,4 +152,23 @@ public function createNewOne($id_cart, $datasIntent) return $intent; } + + /** + * @throws \Stripe\Exception\ApiErrorException + * @throws PrestaShopException + */ + public function updateIntentData($intentData) + { + $intent = \Stripe\PaymentIntent::update($this->id_payment_intent, $intentData); + + $paymentIntent = new StripePaymentIntent(); + $paymentIntent->findByIdPaymentIntent($this->id_payment_intent); + $paymentIntent->setStatus($intent->status); + $paymentIntent->setAmount($intent->amount); + $paymentIntent->setCurrency($intent->currency); + $paymentIntent->setDateUpd(date("Y-m-d H:i:s")); + $paymentIntent->save(false, false); + + return $intent; + } } diff --git a/controllers/front/createIntent.php b/controllers/front/createIntent.php index 5139211d..095ad6a2 100644 --- a/controllers/front/createIntent.php +++ b/controllers/front/createIntent.php @@ -41,18 +41,35 @@ public function initContent() 'createIntent - intiContent' ); - $amount = Tools::ps_round(Tools::getValue('amount')); - $currency = Tools::getValue('currency'); - $paymentOption = Tools::getValue('payment_option'); - $paymentMethodId = Tools::getValue('id_payment_method'); + try { + $cart = $this->context->cart; + + $currency = new Currency($cart->id_currency); + $amount = $cart->getOrderTotal(); + $amount = Tools::ps_round($amount, 2); + $amount = $this->module->isZeroDecimalCurrency($currency->iso_code) ? $amount : $amount * 100; - $intentData = $this->constructIntentData($amount, $currency, $paymentOption, $paymentMethodId); + $paymentOption = Tools::getValue('payment_option'); + $paymentMethodId = Tools::getValue('id_payment_method'); - $cardData = $this->constructCardData($paymentMethodId); + $intentData = $this->constructIntentData($amount, $currency, $paymentOption, $paymentMethodId); - $intent = $this->createIdempotencyKey($intentData); + $cardData = $this->constructCardData($paymentMethodId); - $this->registerStripeEvent($intent); + $intent = $this->createIdempotencyKey($intentData); + + $this->registerStripeEvent($intent); + } catch (Exception $e) { + ProcessLoggerHandler::logError( + "Retrieve Stripe Account Error => ".$e->getMessage(), + null, + null, + 'createIntent' + ); + ProcessLoggerHandler::closeLogger(); + http_response_code(400); + die('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); + } ProcessLoggerHandler::logInfo( '[ Intent Creation Ending ]', From a3750c921a64fe12e23c25474a34c6132fd775cc Mon Sep 17 00:00:00 2001 From: afayadas Date: Tue, 4 Jan 2022 16:16:39 +0100 Subject: [PATCH 14/15] refs #32848 : change idempotency registration --- classes/StripeIdempotencyKey.php | 4 ++-- controllers/front/createIntent.php | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/classes/StripeIdempotencyKey.php b/classes/StripeIdempotencyKey.php index 6bad9b16..a1ae6a29 100644 --- a/classes/StripeIdempotencyKey.php +++ b/classes/StripeIdempotencyKey.php @@ -125,12 +125,12 @@ public function getByIdPaymentIntent($id_payment_intent) * @throws PrestaShopException * @throws \Stripe\Exception\ApiErrorException */ - public function createNewOne($id_cart, $intentData) + public function createNewOne($id_cart, $datasIntent) { $idempotency_key = $id_cart.'_'.uniqid(); $intent = \Stripe\PaymentIntent::create( - $intentData, + $datasIntent, [ 'idempotency_key' => $idempotency_key ] diff --git a/controllers/front/createIntent.php b/controllers/front/createIntent.php index 095ad6a2..37a1c893 100644 --- a/controllers/front/createIntent.php +++ b/controllers/front/createIntent.php @@ -221,8 +221,15 @@ private function constructCardData($paymentMethodId) private function createIdempotencyKey($intentData) { try { + $cart = $this->context->cart; $stripeIdempotencyKey = new StripeIdempotencyKey(); - $intent = $stripeIdempotencyKey->createNewOne($this->context->cart->id, $intentData); + $stripeIdempotencyKey = $stripeIdempotencyKey->getByIdCart($cart->id); + + if (empty($stripeIdempotencyKey->id) === true) { + $intent = $stripeIdempotencyKey->createNewOne($cart->id, $intentData); + } else { + $intent = $stripeIdempotencyKey->updateIntentData($intentData); + } ProcessLoggerHandler::logInfo( 'Intent => '.$intent, From 8bdca78f31d239d77bc8499a6fddf620cd448a27 Mon Sep 17 00:00:00 2001 From: afayadas Date: Wed, 5 Jan 2022 10:59:09 +0100 Subject: [PATCH 15/15] refs #32848 : replace die by ajaxDie method --- controllers/front/createIntent.php | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/controllers/front/createIntent.php b/controllers/front/createIntent.php index 37a1c893..a2faadc7 100644 --- a/controllers/front/createIntent.php +++ b/controllers/front/createIntent.php @@ -68,7 +68,7 @@ public function initContent() ); ProcessLoggerHandler::closeLogger(); http_response_code(400); - die('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); + $this->ajaxDie('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); } ProcessLoggerHandler::logInfo( @@ -79,11 +79,13 @@ public function initContent() ); ProcessLoggerHandler::closeLogger(); - echo Tools::jsonEncode(array( - 'intent' => $intent, - 'cardPayment' => $cardData['cardPayment'], - 'saveCard' => $cardData['save_card'] - )); + $this->ajaxDie( + json_encode([ + 'intent' => $intent, + 'cardPayment' => $cardData['cardPayment'], + 'saveCard' => $cardData['save_card'] + ]) + ); exit; } @@ -141,7 +143,7 @@ private function constructIntentData($amount, $currency, $paymentOption, $paymen ); ProcessLoggerHandler::closeLogger(); http_response_code(400); - die('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); + $this->ajaxDie('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); } catch (PrestaShopDatabaseException $e) { ProcessLoggerHandler::logError( "Retrieve Prestashop State Error => ".$e->getMessage(), @@ -151,7 +153,7 @@ private function constructIntentData($amount, $currency, $paymentOption, $paymen ); ProcessLoggerHandler::closeLogger(); http_response_code(400); - die('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); + $this->ajaxDie('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); } catch (PrestaShopException $e) { ProcessLoggerHandler::logError( "Retrieve Prestashop State Error => ".$e->getMessage(), @@ -161,7 +163,7 @@ private function constructIntentData($amount, $currency, $paymentOption, $paymen ); ProcessLoggerHandler::closeLogger(); http_response_code(400); - die('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); + $this->ajaxDie('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); } } @@ -248,7 +250,7 @@ private function createIdempotencyKey($intentData) ); ProcessLoggerHandler::closeLogger(); http_response_code(400); - die($e->getMessage()); + $this->ajaxDie($e->getMessage()); } catch (PrestaShopException $e) { ProcessLoggerHandler::logError( "Save Stripe Idempotency Key Error => ".$e->getMessage(), @@ -258,7 +260,7 @@ private function createIdempotencyKey($intentData) ); ProcessLoggerHandler::closeLogger(); http_response_code(400); - die('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); + $this->ajaxDie('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); } catch (PrestaShopException $e) { ProcessLoggerHandler::logError( "Save Stripe Payment Intent Error => ".$e->getMessage(), @@ -268,7 +270,7 @@ private function createIdempotencyKey($intentData) ); ProcessLoggerHandler::closeLogger(); http_response_code(400); - die('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); + $this->ajaxDie('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); } } @@ -297,7 +299,7 @@ private function registerStripeEvent($intent) ); ProcessLoggerHandler::closeLogger(); http_response_code(400); - die('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); + $this->ajaxDie('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); } } catch (PrestaShopException $e) { ProcessLoggerHandler::logError( @@ -308,7 +310,7 @@ private function registerStripeEvent($intent) ); ProcessLoggerHandler::closeLogger(); http_response_code(400); - die('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); + $this->ajaxDie('An unexpected problem has occurred. Please contact the support : https://addons.prestashop.com/en/contact-us?id_product=24922'); } }