diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php
index c16b8b334ec..1ce6de6bdd2 100644
--- a/.php-cs-fixer.dist.php
+++ b/.php-cs-fixer.dist.php
@@ -1,9 +1,7 @@
setRiskyAllowed(true)
@@ -16,6 +14,8 @@
'modernize_types_casting' => true,
// PHP84: Adds or removes ? before single type declarations or |null at the end of union types when parameters have a default null value.
'nullable_type_declaration_for_default_null_value' => true,
+ // Orders the elements of classes/interfaces/traits/enums.
+ 'ordered_class_elements' => true,
// Convert double quotes to single quotes for simple strings.
'single_quote' => true,
// Arguments lists, array destructuring lists, arrays that are multi-line, match-lines and parameters lists must have a trailing comma.
@@ -29,11 +29,13 @@
__DIR__,
])
->exclude([
- 'lib/3Dsecure/',
- 'lib/LinLibertineFont/',
- 'lib/Unserialize/',
+ __DIR__ . 'lib/3Dsecure/',
+ __DIR__ . 'lib/LinLibertineFont/',
+ __DIR__ . 'lib/Unserialize/',
+ __DIR__ . '/shell/translations.php',
+ __DIR__ . '/shell/update-copyright.php',
])
->name('*.php')
->ignoreDotFiles(true)
- ->ignoreVCS(true)
+ ->ignoreVCS(true),
);
diff --git a/app/Mage.php b/app/Mage.php
index ec7df4782f2..c978a64ef67 100644
--- a/app/Mage.php
+++ b/app/Mage.php
@@ -64,6 +64,20 @@
*/
final class Mage
{
+ /**
+ * Magento edition constants
+ */
+ public const EDITION_COMMUNITY = 'Community';
+ public const EDITION_ENTERPRISE = 'Enterprise';
+ public const EDITION_PROFESSIONAL = 'Professional';
+ public const EDITION_GO = 'Go';
+
+ /**
+ * Is allow throw Exception about headers already sent
+ *
+ * @var bool
+ */
+ public static $headersSentThrowsException = true;
/**
* Registry collection
*
@@ -113,13 +127,6 @@ final class Mage
*/
private static $_isDeveloperMode = false;
- /**
- * Is allow throw Exception about headers already sent
- *
- * @var bool
- */
- public static $headersSentThrowsException = true;
-
/**
* Is installed flag
*
@@ -127,14 +134,6 @@ final class Mage
*/
private static $_isInstalled;
- /**
- * Magento edition constants
- */
- public const EDITION_COMMUNITY = 'Community';
- public const EDITION_ENTERPRISE = 'Enterprise';
- public const EDITION_PROFESSIONAL = 'Professional';
- public const EDITION_GO = 'Go';
-
/**
* Current Magento edition.
*
@@ -777,40 +776,6 @@ public static function run($code = '', $type = 'store', $options = [])
}
}
- /**
- * Set application isInstalled flag based on given options
- *
- * @param array $options
- */
- private static function _setIsInstalled($options = [])
- {
- if (isset($options['is_installed']) && $options['is_installed']) {
- self::$_isInstalled = true;
- }
- }
-
- /**
- * Set application Config model
- *
- * @param array $options
- */
- private static function _setConfigModel($options = [])
- {
- if (isset($options['config_model']) && class_exists($options['config_model'])) {
- $alternativeConfigModelName = $options['config_model'];
- unset($options['config_model']);
- $alternativeConfigModel = new $alternativeConfigModelName($options);
- } else {
- $alternativeConfigModel = null;
- }
-
- if (!is_null($alternativeConfigModel) && ($alternativeConfigModel instanceof Mage_Core_Model_Config)) {
- self::$_config = $alternativeConfigModel;
- } else {
- self::$_config = new Mage_Core_Model_Config($options);
- }
- }
-
/**
* Retrieve application installation flag
*
@@ -1059,4 +1024,38 @@ public static function getScriptSystemUrl($folder, $exitIfNot = false)
return $baseUrl;
}
+
+ /**
+ * Set application isInstalled flag based on given options
+ *
+ * @param array $options
+ */
+ private static function _setIsInstalled($options = [])
+ {
+ if (isset($options['is_installed']) && $options['is_installed']) {
+ self::$_isInstalled = true;
+ }
+ }
+
+ /**
+ * Set application Config model
+ *
+ * @param array $options
+ */
+ private static function _setConfigModel($options = [])
+ {
+ if (isset($options['config_model']) && class_exists($options['config_model'])) {
+ $alternativeConfigModelName = $options['config_model'];
+ unset($options['config_model']);
+ $alternativeConfigModel = new $alternativeConfigModelName($options);
+ } else {
+ $alternativeConfigModel = null;
+ }
+
+ if (!is_null($alternativeConfigModel) && ($alternativeConfigModel instanceof Mage_Core_Model_Config)) {
+ self::$_config = $alternativeConfigModel;
+ } else {
+ self::$_config = new Mage_Core_Model_Config($options);
+ }
+ }
}
diff --git a/app/code/core/Mage/Admin/Helper/Data.php b/app/code/core/Mage/Admin/Helper/Data.php
index d1f062fff0c..2287c7d0782 100644
--- a/app/code/core/Mage/Admin/Helper/Data.php
+++ b/app/code/core/Mage/Admin/Helper/Data.php
@@ -22,13 +22,12 @@
*/
class Mage_Admin_Helper_Data extends Mage_Core_Helper_Abstract
{
- protected $_moduleName = 'Mage_Admin';
-
/**
* Configuration path to expiration period of reset password link
*/
public const XML_PATH_ADMIN_RESET_PASSWORD_LINK_EXPIRATION_PERIOD
= 'default/admin/emails/password_reset_link_expiration_period';
+ protected $_moduleName = 'Mage_Admin';
/**
* Generate unique token for reset password confirmation link
diff --git a/app/code/core/Mage/Admin/Helper/Rules/Fallback.php b/app/code/core/Mage/Admin/Helper/Rules/Fallback.php
index fb890134218..bccd985e2aa 100644
--- a/app/code/core/Mage/Admin/Helper/Rules/Fallback.php
+++ b/app/code/core/Mage/Admin/Helper/Rules/Fallback.php
@@ -22,19 +22,6 @@
*/
class Mage_Admin_Helper_Rules_Fallback extends Mage_Core_Helper_Abstract
{
- /**
- * Fallback to resource parent node
- * @param string $resourceId
- *
- * @return string
- */
- protected function _getParentResourceId($resourceId)
- {
- $resourcePathInfo = explode('/', $resourceId);
- array_pop($resourcePathInfo);
- return implode('/', $resourcePathInfo);
- }
-
/**
* Fallback resource permissions similarly to zend_acl
* @param array $resources
@@ -58,4 +45,16 @@ public function fallbackResourcePermissions(
return $resources[$resourceId];
}
+ /**
+ * Fallback to resource parent node
+ * @param string $resourceId
+ *
+ * @return string
+ */
+ protected function _getParentResourceId($resourceId)
+ {
+ $resourcePathInfo = explode('/', $resourceId);
+ array_pop($resourcePathInfo);
+ return implode('/', $resourcePathInfo);
+ }
}
diff --git a/app/code/core/Mage/Admin/Model/Acl.php b/app/code/core/Mage/Admin/Model/Acl.php
index b65e68ddb86..032c786ca20 100644
--- a/app/code/core/Mage/Admin/Model/Acl.php
+++ b/app/code/core/Mage/Admin/Model/Acl.php
@@ -57,19 +57,6 @@ class Mage_Admin_Model_Acl extends Zend_Acl
*/
public const RULE_PERM_ALLOW = 2;
- /**
- * Get role registry object or create one
- *
- * @return Mage_Admin_Model_Acl_Role_Registry
- */
- protected function _getRoleRegistry()
- {
- if ($this->_roleRegistry === null) {
- $this->_roleRegistry = Mage::getModel('admin/acl_role_registry');
- }
- return $this->_roleRegistry;
- }
-
/**
* Add parent to role object
*
@@ -82,4 +69,17 @@ public function addRoleParent($role, $parent)
$this->_getRoleRegistry()->addParent($role, $parent);
return $this;
}
+
+ /**
+ * Get role registry object or create one
+ *
+ * @return Mage_Admin_Model_Acl_Role_Registry
+ */
+ protected function _getRoleRegistry()
+ {
+ if ($this->_roleRegistry === null) {
+ $this->_roleRegistry = Mage::getModel('admin/acl_role_registry');
+ }
+ return $this->_roleRegistry;
+ }
}
diff --git a/app/code/core/Mage/Admin/Model/Block.php b/app/code/core/Mage/Admin/Model/Block.php
index 4db6952bfdb..272aa1102c0 100644
--- a/app/code/core/Mage/Admin/Model/Block.php
+++ b/app/code/core/Mage/Admin/Model/Block.php
@@ -29,14 +29,6 @@
*/
class Mage_Admin_Model_Block extends Mage_Core_Model_Abstract
{
- /**
- * Initialize variable model
- */
- protected function _construct()
- {
- $this->_init('admin/block');
- }
-
/**
* @return array|true
* @throws Exception
@@ -77,4 +69,11 @@ public function isTypeAllowed($type)
{
return Mage::helper('admin/block')->isTypeAllowed($type);
}
+ /**
+ * Initialize variable model
+ */
+ protected function _construct()
+ {
+ $this->_init('admin/block');
+ }
}
diff --git a/app/code/core/Mage/Admin/Model/Resource/Acl.php b/app/code/core/Mage/Admin/Model/Resource/Acl.php
index 33f2540234e..5559d91bb55 100644
--- a/app/code/core/Mage/Admin/Model/Resource/Acl.php
+++ b/app/code/core/Mage/Admin/Model/Resource/Acl.php
@@ -24,15 +24,6 @@ class Mage_Admin_Model_Resource_Acl extends Mage_Core_Model_Resource_Db_Abstract
{
public const ACL_ALL_RULES = 'all';
- /**
- * Initialize resource
- *
- */
- protected function _construct()
- {
- $this->_init('admin/role', 'role_id');
- }
-
/**
* Load ACL for the user
*
@@ -152,4 +143,13 @@ public function loadRules(Mage_Admin_Model_Acl $acl, array $rulesArr)
return $this;
}
+
+ /**
+ * Initialize resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('admin/role', 'role_id');
+ }
}
diff --git a/app/code/core/Mage/Admin/Model/Resource/Block.php b/app/code/core/Mage/Admin/Model/Resource/Block.php
index ada5b4136cb..3d510a0664c 100644
--- a/app/code/core/Mage/Admin/Model/Resource/Block.php
+++ b/app/code/core/Mage/Admin/Model/Resource/Block.php
@@ -34,11 +34,6 @@ class Mage_Admin_Model_Resource_Block extends Mage_Core_Model_Resource_Db_Abstra
*/
protected $disallowedBlockNames = ['install/end'];
- protected function _construct()
- {
- $this->_init('admin/permission_block', 'block_id');
- }
-
/**
* Get allowed types
*
@@ -54,6 +49,21 @@ public function getAllowedTypes()
return Mage::helper('core')->jsonDecode($data);
}
+ /**
+ * Get disallowed names for block
+ *
+ * @return array
+ */
+ public function getDisallowedBlockNames()
+ {
+ return $this->disallowedBlockNames;
+ }
+
+ protected function _construct()
+ {
+ $this->_init('admin/permission_block', 'block_id');
+ }
+
/**
* Regenerate cache
*/
@@ -92,14 +102,4 @@ protected function _afterDelete(Mage_Core_Model_Abstract $object)
$this->_generateCache();
return parent::_afterDelete($object);
}
-
- /**
- * Get disallowed names for block
- *
- * @return array
- */
- public function getDisallowedBlockNames()
- {
- return $this->disallowedBlockNames;
- }
}
diff --git a/app/code/core/Mage/Admin/Model/Resource/Role/Collection.php b/app/code/core/Mage/Admin/Model/Resource/Role/Collection.php
index a8f316c8a2c..a5ff2d197da 100644
--- a/app/code/core/Mage/Admin/Model/Resource/Role/Collection.php
+++ b/app/code/core/Mage/Admin/Model/Resource/Role/Collection.php
@@ -24,11 +24,6 @@
*/
class Mage_Admin_Model_Resource_Role_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('admin/role');
- }
-
/**
* Add user filter
*
@@ -52,4 +47,8 @@ public function setRolesFilter()
$this->addFieldToFilter('role_type', 'G');
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('admin/role');
+ }
}
diff --git a/app/code/core/Mage/Admin/Model/Resource/Roles.php b/app/code/core/Mage/Admin/Model/Resource/Roles.php
index d9157ce4852..21fab045a45 100644
--- a/app/code/core/Mage/Admin/Model/Resource/Roles.php
+++ b/app/code/core/Mage/Admin/Model/Resource/Roles.php
@@ -36,6 +36,22 @@ class Mage_Admin_Model_Resource_Roles extends Mage_Core_Model_Resource_Db_Abstra
*/
protected $_ruleTable;
+ /**
+ * Get role users
+ *
+ * @return array
+ */
+ public function getRoleUsers(Mage_Admin_Model_Roles $role)
+ {
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from($this->getMainTable(), ['user_id'])
+ ->where('parent_id = ?', $role->getId())
+ ->where('role_type = ?', Mage_Admin_Model_Acl::ROLE_TYPE_USER)
+ ->where('user_id > 0');
+ return $adapter->fetchCol($select);
+ }
+
protected function _construct()
{
$this->_init('admin/role', 'role_id');
@@ -107,22 +123,6 @@ protected function _afterDelete(Mage_Core_Model_Abstract $role)
return $this;
}
- /**
- * Get role users
- *
- * @return array
- */
- public function getRoleUsers(Mage_Admin_Model_Roles $role)
- {
- $adapter = $this->_getReadAdapter();
- $select = $adapter->select()
- ->from($this->getMainTable(), ['user_id'])
- ->where('parent_id = ?', $role->getId())
- ->where('role_type = ?', Mage_Admin_Model_Acl::ROLE_TYPE_USER)
- ->where('user_id > 0');
- return $adapter->fetchCol($select);
- }
-
/**
* Update role users
*
diff --git a/app/code/core/Mage/Admin/Model/Resource/Roles/Collection.php b/app/code/core/Mage/Admin/Model/Resource/Roles/Collection.php
index b1c3ddcd517..1ad7d0530df 100644
--- a/app/code/core/Mage/Admin/Model/Resource/Roles/Collection.php
+++ b/app/code/core/Mage/Admin/Model/Resource/Roles/Collection.php
@@ -22,6 +22,15 @@
*/
class Mage_Admin_Model_Resource_Roles_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
+ /**
+ * Convert to option array
+ *
+ * @return array
+ */
+ public function toOptionArray()
+ {
+ return $this->_toOptionArray('role_id', 'role_name');
+ }
protected function _construct()
{
$this->_init('admin/role');
@@ -38,14 +47,4 @@ protected function _initSelect()
return $this;
}
-
- /**
- * Convert to option array
- *
- * @return array
- */
- public function toOptionArray()
- {
- return $this->_toOptionArray('role_id', 'role_name');
- }
}
diff --git a/app/code/core/Mage/Admin/Model/Resource/Rules.php b/app/code/core/Mage/Admin/Model/Resource/Rules.php
index ae3ca90c41f..601d94cddc4 100644
--- a/app/code/core/Mage/Admin/Model/Resource/Rules.php
+++ b/app/code/core/Mage/Admin/Model/Resource/Rules.php
@@ -22,11 +22,6 @@
*/
class Mage_Admin_Model_Resource_Rules extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('admin/rule', 'rule_id');
- }
-
/**
* Save ACL resources
*/
@@ -118,4 +113,8 @@ public function deleteOrphanedResources(array $orphanedIds): int
return $this->_getWriteAdapter()
->delete($this->getMainTable(), ['resource_id IN (?)' => $orphanedIds]);
}
+ protected function _construct()
+ {
+ $this->_init('admin/rule', 'rule_id');
+ }
}
diff --git a/app/code/core/Mage/Admin/Model/Resource/Rules/Collection.php b/app/code/core/Mage/Admin/Model/Resource/Rules/Collection.php
index 575b016b3f4..d7426930264 100644
--- a/app/code/core/Mage/Admin/Model/Resource/Rules/Collection.php
+++ b/app/code/core/Mage/Admin/Model/Resource/Rules/Collection.php
@@ -24,11 +24,6 @@
*/
class Mage_Admin_Model_Resource_Rules_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('admin/rules');
- }
-
/**
* Get rules by role id
*
@@ -68,4 +63,8 @@ public function getResourcesPermissionsArray()
return $resourcesPermissionsArray;
}
+ protected function _construct()
+ {
+ $this->_init('admin/rules');
+ }
}
diff --git a/app/code/core/Mage/Admin/Model/Resource/User.php b/app/code/core/Mage/Admin/Model/Resource/User.php
index 3ef0dfd67e1..ec85e3bd770 100644
--- a/app/code/core/Mage/Admin/Model/Resource/User.php
+++ b/app/code/core/Mage/Admin/Model/Resource/User.php
@@ -22,29 +22,6 @@
*/
class Mage_Admin_Model_Resource_User extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('admin/user', 'user_id');
- }
-
- /**
- * @return $this
- */
- protected function _initUniqueFields()
- {
- $this->_uniqueFields = [
- [
- 'field' => 'email',
- 'title' => Mage::helper('adminhtml')->__('Email'),
- ],
- [
- 'field' => 'username',
- 'title' => Mage::helper('adminhtml')->__('User Name'),
- ],
- ];
- return $this;
- }
-
/**
* Authenticate user by $username and $password
*
@@ -124,43 +101,6 @@ public function hasAssigned2Role($user)
}
}
- /**
- * Set created/modified values before user save
- *
- * @param Mage_Admin_Model_User $user
- * @inheritDoc
- */
- protected function _beforeSave(Mage_Core_Model_Abstract $user)
- {
- if ($user->isObjectNew()) {
- $user->setCreated($this->formatDate(true));
- }
- $user->setModified($this->formatDate(true));
-
- return parent::_beforeSave($user);
- }
-
- /**
- * Unserialize user extra data after user save
- *
- * @return $this
- */
- protected function _afterSave(Mage_Core_Model_Abstract $user)
- {
- $this->_unserializeExtraData($user);
- return $this;
- }
-
- /**
- * Unserialize user extra data after user load
- *
- * @inheritDoc
- */
- protected function _afterLoad(Mage_Core_Model_Abstract $user)
- {
- return parent::_afterLoad($this->_unserializeExtraData($user));
- }
-
/**
* Delete user role record with user
*
@@ -448,6 +388,65 @@ public function saveReloadAclFlag($object, $flag)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('admin/user', 'user_id');
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _initUniqueFields()
+ {
+ $this->_uniqueFields = [
+ [
+ 'field' => 'email',
+ 'title' => Mage::helper('adminhtml')->__('Email'),
+ ],
+ [
+ 'field' => 'username',
+ 'title' => Mage::helper('adminhtml')->__('User Name'),
+ ],
+ ];
+ return $this;
+ }
+
+ /**
+ * Set created/modified values before user save
+ *
+ * @param Mage_Admin_Model_User $user
+ * @inheritDoc
+ */
+ protected function _beforeSave(Mage_Core_Model_Abstract $user)
+ {
+ if ($user->isObjectNew()) {
+ $user->setCreated($this->formatDate(true));
+ }
+ $user->setModified($this->formatDate(true));
+
+ return parent::_beforeSave($user);
+ }
+
+ /**
+ * Unserialize user extra data after user save
+ *
+ * @return $this
+ */
+ protected function _afterSave(Mage_Core_Model_Abstract $user)
+ {
+ $this->_unserializeExtraData($user);
+ return $this;
+ }
+
+ /**
+ * Unserialize user extra data after user load
+ *
+ * @inheritDoc
+ */
+ protected function _afterLoad(Mage_Core_Model_Abstract $user)
+ {
+ return parent::_afterLoad($this->_unserializeExtraData($user));
+ }
/**
* Unserializes user extra data
diff --git a/app/code/core/Mage/Admin/Model/Resource/Variable.php b/app/code/core/Mage/Admin/Model/Resource/Variable.php
index 506ff5942df..0a4ff344a68 100644
--- a/app/code/core/Mage/Admin/Model/Resource/Variable.php
+++ b/app/code/core/Mage/Admin/Model/Resource/Variable.php
@@ -24,6 +24,19 @@ class Mage_Admin_Model_Resource_Variable extends Mage_Core_Model_Resource_Db_Abs
{
public const CACHE_ID = 'permission_variable';
+ /**
+ * Get allowed types
+ */
+ public function getAllowedPaths()
+ {
+ $data = Mage::app()->getCacheInstance()->load(self::CACHE_ID);
+ if ($data === false) {
+ $this->_generateCache();
+ $data = Mage::app()->getCacheInstance()->load(self::CACHE_ID);
+ }
+ return Mage::helper('core')->jsonDecode($data);
+ }
+
protected function _construct()
{
$this->_init('admin/permission_variable', 'variable_id');
@@ -43,19 +56,6 @@ protected function _generateCache()
);
}
- /**
- * Get allowed types
- */
- public function getAllowedPaths()
- {
- $data = Mage::app()->getCacheInstance()->load(self::CACHE_ID);
- if ($data === false) {
- $this->_generateCache();
- $data = Mage::app()->getCacheInstance()->load(self::CACHE_ID);
- }
- return Mage::helper('core')->jsonDecode($data);
- }
-
/**
* @inheritDoc
*/
diff --git a/app/code/core/Mage/Admin/Model/Roles.php b/app/code/core/Mage/Admin/Model/Roles.php
index 43ba99b1ef9..2a45da93191 100644
--- a/app/code/core/Mage/Admin/Model/Roles.php
+++ b/app/code/core/Mage/Admin/Model/Roles.php
@@ -46,11 +46,6 @@ class Mage_Admin_Model_Roles extends Mage_Core_Model_Abstract
*/
protected $_eventPrefix = 'admin_roles';
- protected function _construct()
- {
- $this->_init('admin/roles');
- }
-
/**
* Update object into database
*
@@ -112,6 +107,11 @@ public function getRoleUsers()
return $this->getResource()->getRoleUsers($this);
}
+ protected function _construct()
+ {
+ $this->_init('admin/roles');
+ }
+
/**
* Build resources array process
*
diff --git a/app/code/core/Mage/Admin/Model/Rules.php b/app/code/core/Mage/Admin/Model/Rules.php
index b9f7234f95f..da3e6866e48 100644
--- a/app/code/core/Mage/Admin/Model/Rules.php
+++ b/app/code/core/Mage/Admin/Model/Rules.php
@@ -51,11 +51,6 @@ class Mage_Admin_Model_Rules extends Mage_Core_Model_Abstract
*/
public const RULE_PERMISSION_DENIED = 'deny';
- protected function _construct()
- {
- $this->_init('admin/rules');
- }
-
/**
* Update rules
* @return $this
@@ -101,4 +96,9 @@ public function isDenied()
{
return $this->getPermission() == self::RULE_PERMISSION_DENIED;
}
+
+ protected function _construct()
+ {
+ $this->_init('admin/rules');
+ }
}
diff --git a/app/code/core/Mage/Admin/Model/Session.php b/app/code/core/Mage/Admin/Model/Session.php
index 2f2ba2fb388..ad3ade753f1 100644
--- a/app/code/core/Mage/Admin/Model/Session.php
+++ b/app/code/core/Mage/Admin/Model/Session.php
@@ -115,25 +115,6 @@ public function init($namespace, $sessionName = null)
return $this;
}
- /**
- * Logout user if was logged not from admin
- */
- protected function logoutIndirect()
- {
- $user = $this->getUser();
- if ($user) {
- $extraData = $user->getExtra();
- if (!is_null(Mage::app()->getRequest()->getParam('SID'))
- && !$this->allowAdminSid()
- || isset($extraData['indirect_login'])
- && $this->getIndirectLogin()
- ) {
- $this->unsetData('user');
- $this->setIndirectLogin(false);
- }
- }
- }
-
/**
* Try to login user in admin
*
@@ -284,6 +265,25 @@ public function setIsFirstPageAfterLogin($value)
return $this->setIsFirstVisit($this->_isFirstPageAfterLogin);
}
+ /**
+ * Logout user if was logged not from admin
+ */
+ protected function logoutIndirect()
+ {
+ $user = $this->getUser();
+ if ($user) {
+ $extraData = $user->getExtra();
+ if (!is_null(Mage::app()->getRequest()->getParam('SID'))
+ && !$this->allowAdminSid()
+ || isset($extraData['indirect_login'])
+ && $this->getIndirectLogin()
+ ) {
+ $this->unsetData('user');
+ $this->setIndirectLogin(false);
+ }
+ }
+ }
+
/**
* Custom REQUEST_URI logic
*
diff --git a/app/code/core/Mage/Admin/Model/User.php b/app/code/core/Mage/Admin/Model/User.php
index 9655a4af4e9..43b00835d1f 100644
--- a/app/code/core/Mage/Admin/Model/User.php
+++ b/app/code/core/Mage/Admin/Model/User.php
@@ -124,71 +124,6 @@ class Mage_Admin_Model_User extends Mage_Core_Model_Abstract
*/
protected $_hasAvailableResources = true;
- /**
- * Initialize user model
- */
- protected function _construct()
- {
- $this->_init('admin/user');
- }
-
- /**
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- $data = [
- 'firstname' => $this->getFirstname(),
- 'lastname' => $this->getLastname(),
- 'email' => $this->getEmail(),
- 'modified' => $this->_getDateNow(),
- 'extra' => serialize($this->getExtra()),
- ];
-
- if ($this->getId() > 0) {
- $data['user_id'] = $this->getId();
- }
-
- if ($this->getUsername()) {
- $data['username'] = $this->getUsername();
- }
-
- if ($this->getNewPassword()) {
- // Change user password
- $data['password'] = $this->_getEncodedPassword($this->getNewPassword());
- $data['new_password'] = $data['password'];
- $sessionUser = $this->getSession()->getUser();
- if ($sessionUser && $sessionUser->getId() == $this->getId()) {
- $this->getSession()->setUserPasswordChanged(true);
- }
- } elseif ($this->getPassword() && $this->getPassword() != $this->getOrigData('password')) {
- // New user password
- $data['password'] = $this->_getEncodedPassword($this->getPassword());
- } elseif (!$this->getPassword() && $this->getOrigData('password') // Change user data
- || $this->getPassword() == $this->getOrigData('password') // Retrieve user password
- ) {
- $data['password'] = $this->getOrigData('password');
- }
-
- $this->cleanPasswordsValidationData();
-
- if (!is_null($this->getIsActive())) {
- $data['is_active'] = (int) $this->getIsActive();
- }
-
- $this->addData($data);
-
- return parent::_beforeSave();
- }
-
- /**
- * @return Mage_Admin_Model_Session
-*/
- protected function getSession()
- {
- return Mage::getSingleton('admin/session');
- }
-
/**
* Save admin user extra data (like configuration sections state)
*
@@ -483,28 +418,6 @@ public function hasAssigned2Role($user)
return $this->getResource()->hasAssigned2Role($user);
}
- /**
- * Retrieve encoded password
- *
- * @param string $password
- * @return string
- */
- protected function _getEncodedPassword($password)
- {
- return Mage::helper('core')->getHash($password, self::HASH_SALT_LENGTH);
- }
-
- /**
- * Returns helper instance
- *
- * @param string $helperName
- * @return Mage_Core_Helper_Abstract
- */
- protected function _getHelper($helperName)
- {
- return Mage::helper($helperName);
- }
-
/**
* Find first menu item that user is able to access
*
@@ -729,17 +642,6 @@ public function cleanPasswordsValidationData()
return $this;
}
- /**
- * Simple sql format date
- *
- * @param string|bool $dayOnly
- * @return string
- */
- protected function _getDateNow($dayOnly = false)
- {
- return Varien_Date::now($dayOnly);
- }
-
/**
* Send notification to general Contact and additional emails when new admin user created.
* You can declare additional emails in Mage_Core general/additional_notification_emails/admin_user_create node.
@@ -800,4 +702,102 @@ public function getMinAdminPasswordLength()
$absoluteMinLength = Mage_Core_Model_App::ABSOLUTE_MIN_PASSWORD_LENGTH;
return ($minLength < $absoluteMinLength) ? $absoluteMinLength : $minLength;
}
+
+ /**
+ * Initialize user model
+ */
+ protected function _construct()
+ {
+ $this->_init('admin/user');
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ $data = [
+ 'firstname' => $this->getFirstname(),
+ 'lastname' => $this->getLastname(),
+ 'email' => $this->getEmail(),
+ 'modified' => $this->_getDateNow(),
+ 'extra' => serialize($this->getExtra()),
+ ];
+
+ if ($this->getId() > 0) {
+ $data['user_id'] = $this->getId();
+ }
+
+ if ($this->getUsername()) {
+ $data['username'] = $this->getUsername();
+ }
+
+ if ($this->getNewPassword()) {
+ // Change user password
+ $data['password'] = $this->_getEncodedPassword($this->getNewPassword());
+ $data['new_password'] = $data['password'];
+ $sessionUser = $this->getSession()->getUser();
+ if ($sessionUser && $sessionUser->getId() == $this->getId()) {
+ $this->getSession()->setUserPasswordChanged(true);
+ }
+ } elseif ($this->getPassword() && $this->getPassword() != $this->getOrigData('password')) {
+ // New user password
+ $data['password'] = $this->_getEncodedPassword($this->getPassword());
+ } elseif (!$this->getPassword() && $this->getOrigData('password') // Change user data
+ || $this->getPassword() == $this->getOrigData('password') // Retrieve user password
+ ) {
+ $data['password'] = $this->getOrigData('password');
+ }
+
+ $this->cleanPasswordsValidationData();
+
+ if (!is_null($this->getIsActive())) {
+ $data['is_active'] = (int) $this->getIsActive();
+ }
+
+ $this->addData($data);
+
+ return parent::_beforeSave();
+ }
+
+ /**
+ * @return Mage_Admin_Model_Session
+*/
+ protected function getSession()
+ {
+ return Mage::getSingleton('admin/session');
+ }
+
+ /**
+ * Retrieve encoded password
+ *
+ * @param string $password
+ * @return string
+ */
+ protected function _getEncodedPassword($password)
+ {
+ return Mage::helper('core')->getHash($password, self::HASH_SALT_LENGTH);
+ }
+
+ /**
+ * Returns helper instance
+ *
+ * @param string $helperName
+ * @return Mage_Core_Helper_Abstract
+ */
+ protected function _getHelper($helperName)
+ {
+ return Mage::helper($helperName);
+ }
+
+ /**
+ * Simple sql format date
+ *
+ * @param string|bool $dayOnly
+ * @return string
+ */
+ protected function _getDateNow($dayOnly = false)
+ {
+ return Varien_Date::now($dayOnly);
+ }
}
diff --git a/app/code/core/Mage/Admin/Model/Variable.php b/app/code/core/Mage/Admin/Model/Variable.php
index ef8906dc555..9cdcc9c5648 100644
--- a/app/code/core/Mage/Admin/Model/Variable.php
+++ b/app/code/core/Mage/Admin/Model/Variable.php
@@ -29,14 +29,6 @@
*/
class Mage_Admin_Model_Variable extends Mage_Core_Model_Abstract
{
- /**
- * Initialize variable model
- */
- protected function _construct()
- {
- $this->_init('admin/variable');
- }
-
/**
* @return array|bool
* @throws Exception
@@ -73,4 +65,11 @@ public function isPathAllowed($path)
{
return Mage::helper('admin/variable')->isPathAllowed($path);
}
+ /**
+ * Initialize variable model
+ */
+ protected function _construct()
+ {
+ $this->_init('admin/variable');
+ }
}
diff --git a/app/code/core/Mage/AdminNotification/Model/Feed.php b/app/code/core/Mage/AdminNotification/Model/Feed.php
index 7b72d55b74d..b13d7d8db6b 100644
--- a/app/code/core/Mage/AdminNotification/Model/Feed.php
+++ b/app/code/core/Mage/AdminNotification/Model/Feed.php
@@ -34,12 +34,6 @@ class Mage_AdminNotification_Model_Feed extends Mage_Core_Model_Abstract
*/
protected $_feedUrl;
- /**
- * Init model
- *
- */
- protected function _construct() {}
-
/**
* Retrieve feed url
*
@@ -173,4 +167,10 @@ public function getFeedXml()
return $xml;
}
+
+ /**
+ * Init model
+ *
+ */
+ protected function _construct() {}
}
diff --git a/app/code/core/Mage/AdminNotification/Model/Inbox.php b/app/code/core/Mage/AdminNotification/Model/Inbox.php
index 147e03a09ca..7eda8dcc76f 100644
--- a/app/code/core/Mage/AdminNotification/Model/Inbox.php
+++ b/app/code/core/Mage/AdminNotification/Model/Inbox.php
@@ -45,11 +45,6 @@ class Mage_AdminNotification_Model_Inbox extends Mage_Core_Model_Abstract
public const SEVERITY_MINOR = 3;
public const SEVERITY_NOTICE = 4;
- protected function _construct()
- {
- $this->_init('adminnotification/inbox');
- }
-
/**
* Retrieve Severity collection array
*
@@ -193,4 +188,9 @@ public function addNotice($title, $description, $url = '', $isInternal = true)
$this->add(self::SEVERITY_NOTICE, $title, $description, $url, $isInternal);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('adminnotification/inbox');
+ }
}
diff --git a/app/code/core/Mage/AdminNotification/Model/Resource/Inbox.php b/app/code/core/Mage/AdminNotification/Model/Resource/Inbox.php
index 889afe42d3b..829c3e40fe7 100644
--- a/app/code/core/Mage/AdminNotification/Model/Resource/Inbox.php
+++ b/app/code/core/Mage/AdminNotification/Model/Resource/Inbox.php
@@ -22,15 +22,6 @@
*/
class Mage_AdminNotification_Model_Resource_Inbox extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * AdminNotification Resource initialization
- *
- */
- protected function _construct()
- {
- $this->_init('adminnotification/inbox', 'notification_id');
- }
-
/**
* Load latest notice
*
@@ -103,4 +94,12 @@ public function parse(Mage_AdminNotification_Model_Inbox $object, array $data)
}
}
}
+ /**
+ * AdminNotification Resource initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('adminnotification/inbox', 'notification_id');
+ }
}
diff --git a/app/code/core/Mage/AdminNotification/Model/Resource/Inbox/Collection.php b/app/code/core/Mage/AdminNotification/Model/Resource/Inbox/Collection.php
index 3c0d20328c5..a34d28b0307 100644
--- a/app/code/core/Mage/AdminNotification/Model/Resource/Inbox/Collection.php
+++ b/app/code/core/Mage/AdminNotification/Model/Resource/Inbox/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_AdminNotification_Model_Resource_Inbox_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Resource collection initialization
- *
- */
- protected function _construct()
- {
- $this->_init('adminnotification/inbox');
- }
-
/**
* Add remove filter
*
@@ -42,4 +33,12 @@ public function addRemoveFilter()
->where('is_remove=?', 0);
return $this;
}
+ /**
+ * Resource collection initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('adminnotification/inbox');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Api/Buttons.php b/app/code/core/Mage/Adminhtml/Block/Api/Buttons.php
index 5ba8a1e3c40..51993a7d38c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Api/Buttons.php
+++ b/app/code/core/Mage/Adminhtml/Block/Api/Buttons.php
@@ -26,6 +26,34 @@ public function __construct()
$this->setTemplate('api/userinfo.phtml');
}
+ public function getBackButtonHtml()
+ {
+ return $this->getChildHtml('backButton');
+ }
+
+ public function getResetButtonHtml()
+ {
+ return $this->getChildHtml('resetButton');
+ }
+
+ public function getSaveButtonHtml()
+ {
+ return $this->getChildHtml('saveButton');
+ }
+
+ public function getDeleteButtonHtml()
+ {
+ if ((int) $this->getRequest()->getParam('rid') == 0) {
+ return;
+ }
+ return $this->getChildHtml('deleteButton');
+ }
+
+ public function getUser()
+ {
+ return Mage::registry('user_data');
+ }
+
protected function _prepareLayout()
{
$this->setChild(
@@ -70,32 +98,4 @@ protected function _prepareLayout()
);
return parent::_prepareLayout();
}
-
- public function getBackButtonHtml()
- {
- return $this->getChildHtml('backButton');
- }
-
- public function getResetButtonHtml()
- {
- return $this->getChildHtml('resetButton');
- }
-
- public function getSaveButtonHtml()
- {
- return $this->getChildHtml('saveButton');
- }
-
- public function getDeleteButtonHtml()
- {
- if ((int) $this->getRequest()->getParam('rid') == 0) {
- return;
- }
- return $this->getChildHtml('deleteButton');
- }
-
- public function getUser()
- {
- return Mage::registry('user_data');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Api/Edituser.php b/app/code/core/Mage/Adminhtml/Block/Api/Edituser.php
index 9a85ec2b519..e7d599a9a2d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Api/Edituser.php
+++ b/app/code/core/Mage/Adminhtml/Block/Api/Edituser.php
@@ -27,6 +27,11 @@ public function __construct()
$this->setDestElementId('user_edit_form');
}
+ public function getUser()
+ {
+ return Mage::registry('user_data');
+ }
+
protected function _beforeToHtml()
{
$this->addTab('account', [
@@ -44,9 +49,4 @@ protected function _beforeToHtml()
}
return parent::_beforeToHtml();
}
-
- public function getUser()
- {
- return Mage::registry('user_data');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Api/Grid/Role.php b/app/code/core/Mage/Adminhtml/Block/Api/Grid/Role.php
index e93e15a9f23..df9b00b20f7 100644
--- a/app/code/core/Mage/Adminhtml/Block/Api/Grid/Role.php
+++ b/app/code/core/Mage/Adminhtml/Block/Api/Grid/Role.php
@@ -32,6 +32,16 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/roleGrid', ['_current' => true]);
+ }
+
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/editrole', ['rid' => $row->getRoleId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getModel('api/roles')->getCollection();
@@ -56,14 +66,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getGridUrl()
- {
- return $this->getUrl('*/*/roleGrid', ['_current' => true]);
- }
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/editrole', ['rid' => $row->getRoleId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Api/Role/Grid/User.php b/app/code/core/Mage/Adminhtml/Block/Api/Role/Grid/User.php
index c1c85860bef..8ed82ecb6c7 100644
--- a/app/code/core/Mage/Adminhtml/Block/Api/Role/Grid/User.php
+++ b/app/code/core/Mage/Adminhtml/Block/Api/Role/Grid/User.php
@@ -34,6 +34,16 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * @return string
+ * @throws Exception
+ */
+ public function getGridUrl()
+ {
+ $roleId = $this->getRequest()->getParam('rid');
+ return $this->getUrl('*/*/editrolegrid', ['rid' => $roleId]);
+ }
+
/**
* @param Mage_Adminhtml_Block_Widget_Grid_Column $column
* @return $this
@@ -128,16 +138,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * @return string
- * @throws Exception
- */
- public function getGridUrl()
- {
- $roleId = $this->getRequest()->getParam('rid');
- return $this->getUrl('*/*/editrolegrid', ['rid' => $roleId]);
- }
-
/**
* @param bool $json
* @return array|int|string
diff --git a/app/code/core/Mage/Adminhtml/Block/Api/User/Edit/Tab/Roles.php b/app/code/core/Mage/Adminhtml/Block/Api/User/Edit/Tab/Roles.php
index 2d6f17ce108..a933c9dd3e2 100644
--- a/app/code/core/Mage/Adminhtml/Block/Api/User/Edit/Tab/Roles.php
+++ b/app/code/core/Mage/Adminhtml/Block/Api/User/Edit/Tab/Roles.php
@@ -35,6 +35,14 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/rolesGrid', ['user_id' => Mage::registry('api_user')->getUserId()]);
+ }
+
protected function _addColumnFilterToCollection($column)
{
if ($column->getId() === 'assigned_user_role') {
@@ -89,14 +97,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/rolesGrid', ['user_id' => Mage::registry('api_user')->getUserId()]);
- }
-
/**
* @param bool $json
* @return string
diff --git a/app/code/core/Mage/Adminhtml/Block/Api/User/Grid.php b/app/code/core/Mage/Adminhtml/Block/Api/User/Grid.php
index bd5dbad065a..4bcfe09d53f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Api/User/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Api/User/Grid.php
@@ -31,6 +31,17 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['user_id' => $row->getId()]);
+ }
+
+ public function getGridUrl()
+ {
+ //$uid = $this->getRequest()->getParam('user_id');
+ return $this->getUrl('*/*/roleGrid', []);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('api/user_collection');
@@ -78,15 +89,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['user_id' => $row->getId()]);
- }
-
- public function getGridUrl()
- {
- //$uid = $this->getRequest()->getParam('user_id');
- return $this->getUrl('*/*/roleGrid', []);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Cache/Grid.php b/app/code/core/Mage/Adminhtml/Block/Cache/Grid.php
index 0052b72901d..dd63ed29781 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cache/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cache/Grid.php
@@ -35,6 +35,36 @@ public function __construct()
$this->_invalidatedTypes = Mage::app()->getCacheInstance()->getInvalidatedTypes();
}
+ /**
+ * Decorate status column values
+ *
+ * @return string
+ */
+ public function decorateStatus($value, $row, $column, $isExport)
+ {
+ $class = '';
+ if (isset($this->_invalidatedTypes[$row->getId()])) {
+ $cell = '' . $this->__('Invalidated') . '';
+ } else {
+ if ($row->getStatus()) {
+ $cell = '' . $value . '';
+ } else {
+ $cell = '' . $value . '';
+ }
+ }
+ return $cell;
+ }
+
+ /**
+ * Get row edit url
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return '';
+ }
+
/**
* Prepare grid collection
*/
@@ -98,36 +128,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Decorate status column values
- *
- * @return string
- */
- public function decorateStatus($value, $row, $column, $isExport)
- {
- $class = '';
- if (isset($this->_invalidatedTypes[$row->getId()])) {
- $cell = '' . $this->__('Invalidated') . '';
- } else {
- if ($row->getStatus()) {
- $cell = '' . $value . '';
- } else {
- $cell = '' . $value . '';
- }
- }
- return $cell;
- }
-
- /**
- * Get row edit url
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return '';
- }
-
/**
* Add mass-actions to grid
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Checkboxes/Tree.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Checkboxes/Tree.php
index bc8ad9f2254..ea1559a41c2 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Checkboxes/Tree.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Checkboxes/Tree.php
@@ -24,15 +24,6 @@ class Mage_Adminhtml_Block_Catalog_Category_Checkboxes_Tree extends Mage_Adminht
{
protected $_selectedIds = [];
- /**
- * @return $this
- */
- protected function _prepareLayout()
- {
- $this->setTemplate('catalog/category/checkboxes/tree.phtml');
- return $this;
- }
-
public function getCategoryIds()
{
return $this->_selectedIds;
@@ -49,6 +40,20 @@ public function setCategoryIds($ids)
return $this;
}
+ public function getRoot($parentNodeCategory = null, $recursionLevel = 3)
+ {
+ return $this->getRootByIds($this->getCategoryIds());
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $this->setTemplate('catalog/category/checkboxes/tree.phtml');
+ return $this;
+ }
+
protected function _getNodeJson($node, $level = 1)
{
$item = [];
@@ -84,9 +89,4 @@ protected function _getNodeJson($node, $level = 1)
return $item;
}
-
- public function getRoot($parentNodeCategory = null, $recursionLevel = 3)
- {
- return $this->getRootByIds($this->getCategoryIds());
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit/Form.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit/Form.php
index e02d779aa02..30bd261e71d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit/Form.php
@@ -35,58 +35,6 @@ public function __construct()
$this->setTemplate('catalog/category/edit/form.phtml');
}
- protected function _prepareLayout()
- {
- $category = $this->getCategory();
- $categoryId = (int) $category->getId(); // 0 when we create category, otherwise some value for editing category
-
- $this->setChild(
- 'tabs',
- $this->getLayout()->createBlock('adminhtml/catalog_category_tabs', 'tabs'),
- );
-
- // Save button
- if (!$category->isReadonly()) {
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Save Category'),
- 'onclick' => "categorySubmit('" . $this->getSaveUrl() . "', true)",
- 'class' => 'save',
- ]),
- );
- }
-
- // Delete button
- if (!in_array($categoryId, $this->getRootIds()) && $category->isDeleteable()) {
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Delete Category'),
- 'onclick' => "categoryDelete('" . $this->getUrl('*/*/delete', ['_current' => true]) . "', true, {$categoryId})",
- 'class' => 'delete',
- ]),
- );
- }
-
- // Reset button
- if (!$category->isReadonly()) {
- $resetPath = $categoryId ? '*/*/edit' : '*/*/add';
- $this->setChild(
- 'reset_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Reset'),
- 'onclick' => "categoryReset('" . $this->getUrl($resetPath, ['_current' => true]) . "',true)",
- ]),
- );
- }
-
- return parent::_prepareLayout();
- }
-
public function getStoreConfigurationUrl()
{
$storeId = (int) $this->getRequest()->getParam('store');
@@ -225,4 +173,56 @@ public function isAjax()
{
return Mage::app()->getRequest()->isXmlHttpRequest() || Mage::app()->getRequest()->getParam('isAjax');
}
+
+ protected function _prepareLayout()
+ {
+ $category = $this->getCategory();
+ $categoryId = (int) $category->getId(); // 0 when we create category, otherwise some value for editing category
+
+ $this->setChild(
+ 'tabs',
+ $this->getLayout()->createBlock('adminhtml/catalog_category_tabs', 'tabs'),
+ );
+
+ // Save button
+ if (!$category->isReadonly()) {
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Save Category'),
+ 'onclick' => "categorySubmit('" . $this->getSaveUrl() . "', true)",
+ 'class' => 'save',
+ ]),
+ );
+ }
+
+ // Delete button
+ if (!in_array($categoryId, $this->getRootIds()) && $category->isDeleteable()) {
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Delete Category'),
+ 'onclick' => "categoryDelete('" . $this->getUrl('*/*/delete', ['_current' => true]) . "', true, {$categoryId})",
+ 'class' => 'delete',
+ ]),
+ );
+ }
+
+ // Reset button
+ if (!$category->isReadonly()) {
+ $resetPath = $categoryId ? '*/*/edit' : '*/*/add';
+ $this->setChild(
+ 'reset_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Reset'),
+ 'onclick' => "categoryReset('" . $this->getUrl($resetPath, ['_current' => true]) . "',true)",
+ ]),
+ );
+ }
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Attributes.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Attributes.php
index c0c9f86234a..06950a5e1e7 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Attributes.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Attributes.php
@@ -23,23 +23,22 @@
class Mage_Adminhtml_Block_Catalog_Category_Tab_Attributes extends Mage_Adminhtml_Block_Catalog_Form
{
/**
- * Retrieve Category object
+ * Initialize tab
*
- * @return Mage_Catalog_Model_Category
*/
- public function getCategory()
+ public function __construct()
{
- return Mage::registry('current_category');
+ parent::__construct();
+ $this->setShowGlobalIcon(true);
}
-
/**
- * Initialize tab
+ * Retrieve Category object
*
+ * @return Mage_Catalog_Model_Category
*/
- public function __construct()
+ public function getCategory()
{
- parent::__construct();
- $this->setShowGlobalIcon(true);
+ return Mage::registry('current_category');
}
/**
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Product.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Product.php
index f3cd68a086f..90f8fbade42 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Product.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Product.php
@@ -43,6 +43,14 @@ public function getCategory()
return Mage::registry('category');
}
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
protected function _addColumnFilterToCollection($column)
{
// Set custom filter for in category flag
@@ -206,14 +214,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
-
/**
* @return array
* @throws Exception
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tree.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tree.php
index c717c65b9c4..33159eb33f8 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tree.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tree.php
@@ -32,53 +32,6 @@ public function __construct()
$this->_withProductCount = true;
}
- protected function _prepareLayout()
- {
- $addUrl = $this->getUrl('*/*/add', [
- '_current' => true,
- 'id' => null,
- '_query' => false,
- ]);
-
- $this->setChild(
- 'add_sub_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Add Subcategory'),
- 'onclick' => "addNew('" . $addUrl . "', false)",
- 'class' => 'add',
- 'id' => 'add_subcategory_button',
- 'style' => $this->canAddSubCategory() ? '' : 'display: none;',
- ]),
- );
-
- if ($this->canAddRootCategory()) {
- $this->setChild(
- 'add_root_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Add Root Category'),
- 'onclick' => "addNew('" . $addUrl . "', true)",
- 'class' => 'add',
- 'id' => 'add_root_category_button',
- ]),
- );
- }
-
- $this->setChild(
- 'store_switcher',
- $this->getLayout()->createBlock('adminhtml/store_switcher')
- ->setSwitchUrl($this->getUrl('*/*/*', ['_current' => true, '_query' => false, 'store' => null]))
- ->setTemplate('store/switcher/enhanced.phtml'),
- );
- return parent::_prepareLayout();
- }
-
- protected function _getDefaultStoreId()
- {
- return Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID;
- }
-
public function getCategoryCollection()
{
$storeId = $this->getRequest()->getParam('store', $this->_getDefaultStoreId());
@@ -199,6 +152,118 @@ public function getBreadcrumbsJavascript($path, $javascriptVarName)
. '';
}
+ /**
+ * Get category name
+ *
+ * @param Varien_Object $node
+ * @return string
+ */
+ public function buildNodeName($node)
+ {
+ $result = $this->escapeHtml($node->getName());
+ if ($this->_withProductCount) {
+ $result .= ' (' . $node->getProductCount() . ')';
+ }
+ return $result;
+ }
+
+ /**
+ * Check if page loaded by outside link to category edit
+ *
+ * @return bool
+ */
+ public function isClearEdit()
+ {
+ return (bool) $this->getRequest()->getParam('clear');
+ }
+
+ /**
+ * Check availability of adding root category
+ *
+ * @return bool
+ */
+ public function canAddRootCategory()
+ {
+ $options = new Varien_Object(['is_allow' => true]);
+ Mage::dispatchEvent(
+ 'adminhtml_catalog_category_tree_can_add_root_category',
+ [
+ 'category' => $this->getCategory(),
+ 'options' => $options,
+ 'store' => $this->getStore()->getId(),
+ ],
+ );
+
+ return $options->getIsAllow();
+ }
+
+ /**
+ * Check availability of adding sub category
+ *
+ * @return bool
+ */
+ public function canAddSubCategory()
+ {
+ $options = new Varien_Object(['is_allow' => true]);
+ Mage::dispatchEvent(
+ 'adminhtml_catalog_category_tree_can_add_sub_category',
+ [
+ 'category' => $this->getCategory(),
+ 'options' => $options,
+ 'store' => $this->getStore()->getId(),
+ ],
+ );
+
+ return $options->getIsAllow();
+ }
+
+ protected function _prepareLayout()
+ {
+ $addUrl = $this->getUrl('*/*/add', [
+ '_current' => true,
+ 'id' => null,
+ '_query' => false,
+ ]);
+
+ $this->setChild(
+ 'add_sub_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Add Subcategory'),
+ 'onclick' => "addNew('" . $addUrl . "', false)",
+ 'class' => 'add',
+ 'id' => 'add_subcategory_button',
+ 'style' => $this->canAddSubCategory() ? '' : 'display: none;',
+ ]),
+ );
+
+ if ($this->canAddRootCategory()) {
+ $this->setChild(
+ 'add_root_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Add Root Category'),
+ 'onclick' => "addNew('" . $addUrl . "', true)",
+ 'class' => 'add',
+ 'id' => 'add_root_category_button',
+ ]),
+ );
+ }
+
+ $this->setChild(
+ 'store_switcher',
+ $this->getLayout()->createBlock('adminhtml/store_switcher')
+ ->setSwitchUrl($this->getUrl('*/*/*', ['_current' => true, '_query' => false, 'store' => null]))
+ ->setTemplate('store/switcher/enhanced.phtml'),
+ );
+ return parent::_prepareLayout();
+ }
+
+ protected function _getDefaultStoreId()
+ {
+ return Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID;
+ }
+
/**
* Get JSON of a tree node or an associative array
*
@@ -254,21 +319,6 @@ protected function _getNodeJson($node, $level = 0)
return $item;
}
- /**
- * Get category name
- *
- * @param Varien_Object $node
- * @return string
- */
- public function buildNodeName($node)
- {
- $result = $this->escapeHtml($node->getName());
- if ($this->_withProductCount) {
- $result .= ' (' . $node->getProductCount() . ')';
- }
- return $result;
- }
-
protected function _isCategoryMoveable($node)
{
$options = new Varien_Object([
@@ -295,54 +345,4 @@ protected function _isParentSelectedCategory($node)
return false;
}
-
- /**
- * Check if page loaded by outside link to category edit
- *
- * @return bool
- */
- public function isClearEdit()
- {
- return (bool) $this->getRequest()->getParam('clear');
- }
-
- /**
- * Check availability of adding root category
- *
- * @return bool
- */
- public function canAddRootCategory()
- {
- $options = new Varien_Object(['is_allow' => true]);
- Mage::dispatchEvent(
- 'adminhtml_catalog_category_tree_can_add_root_category',
- [
- 'category' => $this->getCategory(),
- 'options' => $options,
- 'store' => $this->getStore()->getId(),
- ],
- );
-
- return $options->getIsAllow();
- }
-
- /**
- * Check availability of adding sub category
- *
- * @return bool
- */
- public function canAddSubCategory()
- {
- $options = new Varien_Object(['is_allow' => true]);
- Mage::dispatchEvent(
- 'adminhtml_catalog_category_tree_can_add_sub_category',
- [
- 'category' => $this->getCategory(),
- 'options' => $options,
- 'store' => $this->getStore()->getId(),
- ],
- );
-
- return $options->getIsAllow();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Widget/Chooser.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Widget/Chooser.php
index 7a509152b0a..b7e011a70db 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Widget/Chooser.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Widget/Chooser.php
@@ -94,28 +94,6 @@ public function prepareElementHtml(Varien_Data_Form_Element_Abstract $element)
$element->setData('after_element_html', $chooser->toHtml());
return $element;
}
-
- /**
- * Retrieve model attribute value
- *
- * @param string $modelType Model Type
- * @param string $attributeName Attribute Name
- * @param string $entityId Form Entity ID
- * @return string
- */
- protected function _getModelAttributeByEntityId($modelType, $attributeName, $entityId)
- {
- $result = '';
- $model = Mage::getModel($modelType)
- ->getCollection()
- ->addAttributeToSelect($attributeName)
- ->addAttributeToFilter('entity_id', $entityId)
- ->getFirstItem();
- if ($model) {
- $result = $model->getData($attributeName);
- }
- return $result;
- }
/**
* Category Tree node onClick listener js function
*
@@ -147,24 +125,6 @@ function (node, e) {
return $js;
}
- /**
- * Get JSON of a tree node or an associative array
- *
- * @param Varien_Data_Tree_Node|array $node
- * @param int $level
- * @return array
- */
- protected function _getNodeJson($node, $level = 0)
- {
- $item = parent::_getNodeJson($node, $level);
- if (in_array($node->getId(), $this->getSelectedCategories())) {
- $item['checked'] = true;
- }
- $item['is_anchor'] = (int) $node->getIsAnchor();
- $item['url_key'] = $node->getData('url_key');
- return $item;
- }
-
/**
* Adds some extra params to categories collection
*
@@ -188,4 +148,44 @@ public function getLoadTreeUrl($expanded = null)
'use_massaction' => $this->getUseMassaction(),
]);
}
+
+ /**
+ * Retrieve model attribute value
+ *
+ * @param string $modelType Model Type
+ * @param string $attributeName Attribute Name
+ * @param string $entityId Form Entity ID
+ * @return string
+ */
+ protected function _getModelAttributeByEntityId($modelType, $attributeName, $entityId)
+ {
+ $result = '';
+ $model = Mage::getModel($modelType)
+ ->getCollection()
+ ->addAttributeToSelect($attributeName)
+ ->addAttributeToFilter('entity_id', $entityId)
+ ->getFirstItem();
+ if ($model) {
+ $result = $model->getData($attributeName);
+ }
+ return $result;
+ }
+
+ /**
+ * Get JSON of a tree node or an associative array
+ *
+ * @param Varien_Data_Tree_Node|array $node
+ * @param int $level
+ * @return array
+ */
+ protected function _getNodeJson($node, $level = 0)
+ {
+ $item = parent::_getNodeJson($node, $level);
+ if (in_array($node->getId(), $this->getSelectedCategories())) {
+ $item['checked'] = true;
+ }
+ $item['is_anchor'] = (int) $node->getIsAnchor();
+ $item['url_key'] = $node->getData('url_key');
+ return $item;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Form/Renderer/Fieldset/Element.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Form/Renderer/Fieldset/Element.php
index 542f63add12..2f058ab9c8d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Form/Renderer/Fieldset/Element.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Form/Renderer/Fieldset/Element.php
@@ -22,14 +22,6 @@
*/
class Mage_Adminhtml_Block_Catalog_Form_Renderer_Fieldset_Element extends Mage_Adminhtml_Block_Widget_Form_Renderer_Fieldset_Element
{
- /**
- * Initialize block template
- */
- protected function _construct()
- {
- $this->setTemplate('catalog/form/renderer/fieldset/element.phtml');
- }
-
/**
* Retrieve data object related with form
*
@@ -177,6 +169,13 @@ public function getElementHtml()
{
return $this->getElement()->getElementHtml();
}
+ /**
+ * Initialize block template
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('catalog/form/renderer/fieldset/element.phtml');
+ }
/**
* Default sore ID getter
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product.php
index b8e1734ebeb..c4cb4ce86ba 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product.php
@@ -32,21 +32,6 @@ public function __construct()
$this->setTemplate('catalog/product.phtml');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->_addButton('add_new', [
- 'label' => Mage::helper('catalog')->__('Add Product'),
- 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/new')),
- 'class' => 'add',
- ]);
-
- $this->setChild('grid', $this->getLayout()->createBlock('adminhtml/catalog_product_grid', 'product.grid'));
- return parent::_prepareLayout();
- }
-
/**
* @deprecated since 1.3.2
*
@@ -79,4 +64,19 @@ public function isSingleStoreMode()
}
return true;
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->_addButton('add_new', [
+ 'label' => Mage::helper('catalog')->__('Add Product'),
+ 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/new')),
+ 'class' => 'add',
+ ]);
+
+ $this->setChild('grid', $this->getLayout()->createBlock('adminhtml/catalog_product_grid', 'product.grid'));
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/New/Product/Created.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/New/Product/Created.php
index a32bd85c0e6..1855634552a 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/New/Product/Created.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/New/Product/Created.php
@@ -31,6 +31,27 @@ public function __construct()
$this->setTemplate('catalog/product/attribute/new/created.phtml');
}
+ /**
+ * @return string
+ */
+ public function getCloseButtonHtml()
+ {
+ return $this->getChildHtml('close_button');
+ }
+
+ /**
+ * @return string
+ * @throws Exception
+ */
+ public function getAttributesBlockJson()
+ {
+ $result = [
+ $this->getRequest()->getParam('tab') => $this->getChildHtml('attributes'),
+ ];
+
+ return Mage::helper('core')->jsonEncode($result);
+ }
+
/**
* @return $this
* @throws Exception
@@ -71,25 +92,4 @@ protected function _getGroupAttributes()
}
return $attributes;
}
-
- /**
- * @return string
- */
- public function getCloseButtonHtml()
- {
- return $this->getChildHtml('close_button');
- }
-
- /**
- * @return string
- * @throws Exception
- */
- public function getAttributesBlockJson()
- {
- $result = [
- $this->getRequest()->getParam('tab') => $this->getChildHtml('attributes'),
- ];
-
- return Mage::helper('core')->jsonEncode($result);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Grid.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Grid.php
index ec8279413f6..c680a137519 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Grid.php
@@ -29,6 +29,15 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getAttributeSetId()]);
+ }
+
/**
* @inheritDoc
*/
@@ -55,13 +64,4 @@ protected function _prepareColumns()
return $this;
}
-
- /**
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getAttributeSetId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Main.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Main.php
index d9ba08a360f..3293e0e94ba 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Main.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Main.php
@@ -22,100 +22,6 @@
*/
class Mage_Adminhtml_Block_Catalog_Product_Attribute_Set_Main extends Mage_Adminhtml_Block_Template
{
- /**
- * Initialize template
- */
- protected function _construct()
- {
- $this->setTemplate('catalog/product/attribute/set/main.phtml');
- }
-
- /**
- * Prepare Global Layout
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- $setId = $this->_getSetId();
-
- $this->setChild(
- 'group_tree',
- $this->getLayout()->createBlock('adminhtml/catalog_product_attribute_set_main_tree_group'),
- );
-
- $this->setChild(
- 'edit_set_form',
- $this->getLayout()->createBlock('adminhtml/catalog_product_attribute_set_main_formset'),
- );
-
- $this->setChild(
- 'delete_group_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('catalog')->__('Delete Selected Group'),
- 'onclick' => 'editSet.submit();',
- 'class' => 'delete',
- ]),
- );
-
- $this->setChild(
- 'add_group_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('catalog')->__('Add New'),
- 'onclick' => 'editSet.addGroup();',
- 'class' => 'add',
- ]),
- );
-
- $this->setChild(
- 'back_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('catalog')->__('Back'),
- 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/')),
- 'class' => 'back',
- ]),
- );
-
- $this->setChild(
- 'reset_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('catalog')->__('Reset'),
- 'onclick' => 'window.location.reload()',
- ]),
- );
-
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('catalog')->__('Save Attribute Set'),
- 'onclick' => 'editSet.save();',
- 'class' => 'save',
- ]),
- );
-
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('catalog')->__('Delete Attribute Set'),
- 'onclick' => Mage::helper('core/js')->getDeleteConfirmJs(
- $this->getUrlSecure('*/*/delete', ['id' => $setId]),
- Mage::helper('catalog')->__('All products of this set will be deleted! Are you sure you want to delete this attribute set?'),
- ),
- 'class' => 'delete',
- ]),
- );
-
- $this->setChild(
- 'rename_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('catalog')->__('New Set Name'),
- 'onclick' => 'editSet.rename()',
- ]),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* Retrieve Attribute Set Group Tree HTML
*
@@ -136,16 +42,6 @@ public function getSetFormHtml()
return $this->getChildHtml('edit_set_form');
}
- /**
- * Retrieve Block Header Text
- *
- * @return string
- */
- protected function _getHeader()
- {
- return Mage::helper('catalog')->__("Edit Attribute Set '%s'", $this->_getAttributeSet()->getAttributeSetName());
- }
-
/**
* Retrieve Attribute Set Save URL
*
@@ -355,6 +251,127 @@ public function getRenameButton()
return $this->getChildHtml('rename_button');
}
+ /**
+ * Check Current Attribute Set is a default
+ *
+ * @return bool
+ */
+ public function getIsCurrentSetDefault()
+ {
+ $isDefault = $this->getData('is_current_set_default');
+ if (is_null($isDefault)) {
+ $defaultSetId = Mage::getSingleton('eav/config')
+ ->getEntityType(Mage::registry('entityType'))
+ ->getDefaultAttributeSetId();
+ $isDefault = $this->_getSetId() == $defaultSetId;
+ $this->setData('is_current_set_default', $isDefault);
+ }
+ return $isDefault;
+ }
+ /**
+ * Initialize template
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('catalog/product/attribute/set/main.phtml');
+ }
+
+ /**
+ * Prepare Global Layout
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $setId = $this->_getSetId();
+
+ $this->setChild(
+ 'group_tree',
+ $this->getLayout()->createBlock('adminhtml/catalog_product_attribute_set_main_tree_group'),
+ );
+
+ $this->setChild(
+ 'edit_set_form',
+ $this->getLayout()->createBlock('adminhtml/catalog_product_attribute_set_main_formset'),
+ );
+
+ $this->setChild(
+ 'delete_group_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('catalog')->__('Delete Selected Group'),
+ 'onclick' => 'editSet.submit();',
+ 'class' => 'delete',
+ ]),
+ );
+
+ $this->setChild(
+ 'add_group_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('catalog')->__('Add New'),
+ 'onclick' => 'editSet.addGroup();',
+ 'class' => 'add',
+ ]),
+ );
+
+ $this->setChild(
+ 'back_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('catalog')->__('Back'),
+ 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/')),
+ 'class' => 'back',
+ ]),
+ );
+
+ $this->setChild(
+ 'reset_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('catalog')->__('Reset'),
+ 'onclick' => 'window.location.reload()',
+ ]),
+ );
+
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('catalog')->__('Save Attribute Set'),
+ 'onclick' => 'editSet.save();',
+ 'class' => 'save',
+ ]),
+ );
+
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('catalog')->__('Delete Attribute Set'),
+ 'onclick' => Mage::helper('core/js')->getDeleteConfirmJs(
+ $this->getUrlSecure('*/*/delete', ['id' => $setId]),
+ Mage::helper('catalog')->__('All products of this set will be deleted! Are you sure you want to delete this attribute set?'),
+ ),
+ 'class' => 'delete',
+ ]),
+ );
+
+ $this->setChild(
+ 'rename_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('catalog')->__('New Set Name'),
+ 'onclick' => 'editSet.rename()',
+ ]),
+ );
+
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Retrieve Block Header Text
+ *
+ * @return string
+ */
+ protected function _getHeader()
+ {
+ return Mage::helper('catalog')->__("Edit Attribute Set '%s'", $this->_getAttributeSet()->getAttributeSetName());
+ }
+
/**
* Retrieve current Attribute Set object
*
@@ -375,24 +392,6 @@ protected function _getSetId()
return $this->_getAttributeSet()->getId();
}
- /**
- * Check Current Attribute Set is a default
- *
- * @return bool
- */
- public function getIsCurrentSetDefault()
- {
- $isDefault = $this->getData('is_current_set_default');
- if (is_null($isDefault)) {
- $defaultSetId = Mage::getSingleton('eav/config')
- ->getEntityType(Mage::registry('entityType'))
- ->getDefaultAttributeSetId();
- $isDefault = $this->_getSetId() == $defaultSetId;
- $this->setData('is_current_set_default', $isDefault);
- }
- return $isDefault;
- }
-
/**
* Retrieve current Attribute Set object
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Configure.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Configure.php
index cada40cf485..b68264c5ad6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Configure.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Configure.php
@@ -24,14 +24,6 @@ class Mage_Adminhtml_Block_Catalog_Product_Composite_Configure extends Mage_Admi
{
protected $_product;
- /**
- * Set template
- */
- protected function _construct()
- {
- $this->setTemplate('catalog/product/composite/configure.phtml');
- }
-
/**
* Retrieve product object
*
@@ -59,4 +51,12 @@ public function setProduct(?Mage_Catalog_Model_Product $product = null)
$this->_product = $product;
return $this;
}
+
+ /**
+ * Set template
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('catalog/product/composite/configure.phtml');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Fieldset/Grouped.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Fieldset/Grouped.php
index 94c99f14383..f0f17d21c14 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Fieldset/Grouped.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Fieldset/Grouped.php
@@ -22,23 +22,6 @@
*/
class Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset_Grouped extends Mage_Catalog_Block_Product_View_Type_Grouped
{
- /**
- * Redefine default price block
- * Set current customer to tax calculation
- */
- protected function _construct()
- {
- parent::_construct();
-
- $this->_block = 'adminhtml/catalog_product_price';
- $this->_useLinkForAsLowAs = false;
-
- $taxCalculation = Mage::getSingleton('tax/calculation');
- if (!$taxCalculation->getCustomer() && Mage::registry('current_customer')) {
- $taxCalculation->setCustomer(Mage::registry('current_customer'));
- }
- }
-
/**
* Retrieve product
*
@@ -140,4 +123,20 @@ public function getCurrencyPrice($price)
$store = $this->getProduct()->getStore();
return $helper::currencyByStore($price, $store, false);
}
+ /**
+ * Redefine default price block
+ * Set current customer to tax calculation
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+
+ $this->_block = 'adminhtml/catalog_product_price';
+ $this->_useLinkForAsLowAs = false;
+
+ $taxCalculation = Mage::getSingleton('tax/calculation');
+ if (!$taxCalculation->getCustomer() && Mage::registry('current_customer')) {
+ $taxCalculation->setCustomer(Mage::registry('current_customer'));
+ }
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Created.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Created.php
index 14fa017279a..e2529847724 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Created.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Created.php
@@ -31,19 +31,6 @@ public function __construct()
$this->setTemplate('catalog/product/created.phtml');
}
- protected function _prepareLayout()
- {
- $this->setChild(
- 'close_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Close Window'),
- 'onclick' => 'addProduct(true)',
- ]),
- );
- return $this;
- }
-
public function getCloseButtonHtml()
{
return $this->getChildHtml('close_button');
@@ -139,4 +126,17 @@ public function getProduct()
}
return $this->_product;
}
+
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'close_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Close Window'),
+ 'onclick' => 'addProduct(true)',
+ ]),
+ );
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit.php
index efabda28fc2..ee7c94e4ad8 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit.php
@@ -40,94 +40,6 @@ public function getProduct()
return Mage::registry('current_product');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- if (!$this->getRequest()->getParam('popup')) {
- $this->setChild(
- 'back_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Back'),
- 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/', ['store' => $this->getRequest()->getParam('store', 0)])),
- 'class' => 'back',
- ]),
- );
- } else {
- $this->setChild(
- 'back_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Close Window'),
- 'onclick' => 'window.close()',
- 'class' => 'cancel',
- ]),
- );
- }
-
- if (!$this->getProduct()->isReadonly()) {
- $this->setChild(
- 'reset_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Reset'),
- 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/*', ['_current' => true])),
- ]),
- );
-
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Save'),
- 'onclick' => 'productForm.submit()',
- 'class' => 'save',
- ]),
- );
- }
-
- if (!$this->getRequest()->getParam('popup')) {
- if (!$this->getProduct()->isReadonly()) {
- $this->setChild(
- 'save_and_edit_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Save and Continue Edit'),
- 'onclick' => Mage::helper('core/js')->getSaveAndContinueEditJs($this->getSaveAndContinueUrl()),
- 'class' => 'save',
- ]),
- );
- }
- if ($this->getProduct()->isDeleteable()) {
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Delete'),
- 'onclick' => Mage::helper('core/js')->getConfirmSetLocationJs($this->getDeleteUrl()),
- 'class' => 'delete',
- ]),
- );
- }
-
- if ($this->getProduct()->isDuplicable()) {
- $this->setChild(
- 'duplicate_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Duplicate'),
- 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getDuplicateUrl()),
- 'class' => 'add',
- ]),
- );
- }
- }
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -297,4 +209,92 @@ public function getSelectedTabId()
{
return addslashes(htmlspecialchars($this->getRequest()->getParam('tab', '')));
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ if (!$this->getRequest()->getParam('popup')) {
+ $this->setChild(
+ 'back_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Back'),
+ 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/', ['store' => $this->getRequest()->getParam('store', 0)])),
+ 'class' => 'back',
+ ]),
+ );
+ } else {
+ $this->setChild(
+ 'back_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Close Window'),
+ 'onclick' => 'window.close()',
+ 'class' => 'cancel',
+ ]),
+ );
+ }
+
+ if (!$this->getProduct()->isReadonly()) {
+ $this->setChild(
+ 'reset_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Reset'),
+ 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/*', ['_current' => true])),
+ ]),
+ );
+
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Save'),
+ 'onclick' => 'productForm.submit()',
+ 'class' => 'save',
+ ]),
+ );
+ }
+
+ if (!$this->getRequest()->getParam('popup')) {
+ if (!$this->getProduct()->isReadonly()) {
+ $this->setChild(
+ 'save_and_edit_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Save and Continue Edit'),
+ 'onclick' => Mage::helper('core/js')->getSaveAndContinueEditJs($this->getSaveAndContinueUrl()),
+ 'class' => 'save',
+ ]),
+ );
+ }
+ if ($this->getProduct()->isDeleteable()) {
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Delete'),
+ 'onclick' => Mage::helper('core/js')->getConfirmSetLocationJs($this->getDeleteUrl()),
+ 'class' => 'delete',
+ ]),
+ );
+ }
+
+ if ($this->getProduct()->isDuplicable()) {
+ $this->setChild(
+ 'duplicate_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Duplicate'),
+ 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getDuplicateUrl()),
+ 'class' => 'add',
+ ]),
+ );
+ }
+ }
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute.php
index c9e4eeda697..bdb3f28fb0b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute.php
@@ -22,44 +22,6 @@
*/
class Mage_Adminhtml_Block_Catalog_Product_Edit_Action_Attribute extends Mage_Adminhtml_Block_Widget
{
- protected function _prepareLayout()
- {
- $this->setChild(
- 'back_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Back'),
- 'onclick' => Mage::helper('core/js')->getSetLocationJs(
- $this->getUrl(
- '*/catalog_product/',
- ['store' => $this->getRequest()->getParam('store', 0)],
- ),
- ),
- 'class' => 'back',
- ]),
- );
-
- $this->setChild(
- 'reset_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Reset'),
- 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/*', ['_current' => true])),
- ]),
- );
-
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Save'),
- 'onclick' => 'attributesForm.submit()',
- 'class' => 'save',
- ]),
- );
- return $this;
- }
-
/**
* Retrieve selected products for update
*
@@ -70,16 +32,6 @@ public function getProducts()
return $this->_getHelper()->getProducts();
}
- /**
- * Retrieve block attributes update helper
- *
- * @return Mage_Adminhtml_Helper_Catalog_Product_Edit_Action_Attribute
- */
- protected function _getHelper()
- {
- return $this->helper('adminhtml/catalog_product_edit_action_attribute');
- }
-
/**
* Retrieve back button html code
*
@@ -129,4 +81,51 @@ public function getValidationUrl()
{
return $this->getUrl('*/*/validate', ['_current' => true]);
}
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'back_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Back'),
+ 'onclick' => Mage::helper('core/js')->getSetLocationJs(
+ $this->getUrl(
+ '*/catalog_product/',
+ ['store' => $this->getRequest()->getParam('store', 0)],
+ ),
+ ),
+ 'class' => 'back',
+ ]),
+ );
+
+ $this->setChild(
+ 'reset_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Reset'),
+ 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/*', ['_current' => true])),
+ ]),
+ );
+
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Save'),
+ 'onclick' => 'attributesForm.submit()',
+ 'class' => 'save',
+ ]),
+ );
+ return $this;
+ }
+
+ /**
+ * Retrieve block attributes update helper
+ *
+ * @return Mage_Adminhtml_Helper_Catalog_Product_Edit_Action_Attribute
+ */
+ protected function _getHelper()
+ {
+ return $this->helper('adminhtml/catalog_product_edit_action_attribute');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute/Tab/Attributes.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute/Tab/Attributes.php
index 6180a319d2e..e515b3c4028 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute/Tab/Attributes.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute/Tab/Attributes.php
@@ -22,6 +22,49 @@
*/
class Mage_Adminhtml_Block_Catalog_Product_Edit_Action_Attribute_Tab_Attributes extends Mage_Adminhtml_Block_Catalog_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
+ /**
+ * Retrieve attributes for product massupdate
+ *
+ * @return array
+ */
+ public function getAttributes()
+ {
+ /** @var Mage_Adminhtml_Helper_Catalog_Product_Edit_Action_Attribute $helper */
+ $helper = $this->helper('adminhtml/catalog_product_edit_action_attribute');
+ return $helper->getAttributes()->getItems();
+ }
+
+ /**
+ * @return string
+ */
+ public function getTabLabel()
+ {
+ return Mage::helper('catalog')->__('Attributes');
+ }
+
+ /**
+ * @return string
+ */
+ public function getTabTitle()
+ {
+ return Mage::helper('catalog')->__('Attributes');
+ }
+
+ /**
+ * @return true
+ */
+ public function canShowTab()
+ {
+ return true;
+ }
+
+ /**
+ * @return false
+ */
+ public function isHidden()
+ {
+ return false;
+ }
protected function _construct()
{
parent::_construct();
@@ -52,18 +95,6 @@ protected function _prepareForm()
return $this;
}
- /**
- * Retrieve attributes for product massupdate
- *
- * @return array
- */
- public function getAttributes()
- {
- /** @var Mage_Adminhtml_Helper_Catalog_Product_Edit_Action_Attribute $helper */
- $helper = $this->helper('adminhtml/catalog_product_edit_action_attribute');
- return $helper->getAttributes()->getItems();
- }
-
/**
* Additional element types for product attributes
*
@@ -96,36 +127,4 @@ protected function _getAdditionalElementHtml($element)
. '
';
}
-
- /**
- * @return string
- */
- public function getTabLabel()
- {
- return Mage::helper('catalog')->__('Attributes');
- }
-
- /**
- * @return string
- */
- public function getTabTitle()
- {
- return Mage::helper('catalog')->__('Attributes');
- }
-
- /**
- * @return true
- */
- public function canShowTab()
- {
- return true;
- }
-
- /**
- * @return false
- */
- public function isHidden()
- {
- return false;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts.php
index ff4bccc4d4c..5d7a396e7ee 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts.php
@@ -31,6 +31,14 @@ public function __construct()
$this->setTemplate('catalog/product/tab/alert.phtml');
}
+ /**
+ * @return string
+ */
+ public function getAccordionHtml()
+ {
+ return $this->getChildHtml('accordion');
+ }
+
/**
* @inheritDoc
*/
@@ -62,12 +70,4 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
-
- /**
- * @return string
- */
- public function getAccordionHtml()
- {
- return $this->getChildHtml('accordion');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts/Price.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts/Price.php
index ae4a7b6116d..3d815fbdc2f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts/Price.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts/Price.php
@@ -34,6 +34,19 @@ public function __construct()
$this->setEmptyText(Mage::helper('catalog')->__('There are no customers for this alert'));
}
+ public function getGridUrl()
+ {
+ $productId = $this->getRequest()->getParam('id');
+ $storeId = $this->getRequest()->getParam('store', 0);
+ if ($storeId) {
+ $storeId = Mage::app()->getStore($storeId)->getId();
+ }
+ return $this->getUrl('*/catalog_product/alertsPriceGrid', [
+ 'id' => $productId,
+ 'store' => $storeId,
+ ]);
+ }
+
protected function _prepareCollection()
{
$productId = $this->getRequest()->getParam('id');
@@ -97,17 +110,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getGridUrl()
- {
- $productId = $this->getRequest()->getParam('id');
- $storeId = $this->getRequest()->getParam('store', 0);
- if ($storeId) {
- $storeId = Mage::app()->getStore($storeId)->getId();
- }
- return $this->getUrl('*/catalog_product/alertsPriceGrid', [
- 'id' => $productId,
- 'store' => $storeId,
- ]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts/Stock.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts/Stock.php
index be96f5db39f..0bcb70f3c02 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts/Stock.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Alerts/Stock.php
@@ -34,6 +34,19 @@ public function __construct()
$this->setEmptyText(Mage::helper('catalog')->__('There are no customers for this alert.'));
}
+ public function getGridUrl()
+ {
+ $productId = $this->getRequest()->getParam('id');
+ $storeId = $this->getRequest()->getParam('store', 0);
+ if ($storeId) {
+ $storeId = Mage::app()->getStore($storeId)->getId();
+ }
+ return $this->getUrl('*/catalog_product/alertsStockGrid', [
+ 'id' => $productId,
+ 'store' => $storeId,
+ ]);
+ }
+
protected function _prepareCollection()
{
$productId = $this->getRequest()->getParam('id');
@@ -91,17 +104,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getGridUrl()
- {
- $productId = $this->getRequest()->getParam('id');
- $storeId = $this->getRequest()->getParam('store', 0);
- if ($storeId) {
- $storeId = Mage::app()->getStore($storeId)->getId();
- }
- return $this->getUrl('*/catalog_product/alertsStockGrid', [
- 'id' => $productId,
- 'store' => $storeId,
- ]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Attributes/Create.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Attributes/Create.php
index cff01a3a849..a8eddb31c8e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Attributes/Create.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Attributes/Create.php
@@ -43,6 +43,14 @@ public function getConfig()
return $this->_config;
}
+ /**
+ * @return string
+ */
+ public function getJsObjectName()
+ {
+ return $this->getId() . 'JsObject';
+ }
+
/**
* @inheritDoc
*/
@@ -89,12 +97,4 @@ protected function _toHtml()
. "{$this->getJsObjectName()}.setConfig(" . Mage::helper('core')->jsonEncode($this->getConfig()->getData()) . ");\n",
);
}
-
- /**
- * @return string
- */
- public function getJsObjectName()
- {
- return $this->getId() . 'JsObject';
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Categories.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Categories.php
index a3262d765d8..b9ccf52b070 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Categories.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Categories.php
@@ -54,16 +54,6 @@ public function isReadonly()
return $this->getProduct()->getCategoriesReadonly();
}
- /**
- * Return array with category IDs which the product is assigned to
- *
- * @return array
- */
- protected function getCategoryIds()
- {
- return $this->getProduct()->getCategoryIds();
- }
-
/**
* Forms string out of getCategoryIds()
*
@@ -138,72 +128,6 @@ public function getRoot($parentNodeCategory = null, $recursionLevel = 3)
return $root;
}
- /**
- * Returns array with configuration of current node
- *
- * @param Varien_Data_Tree_Node $node
- * @param int $level How deep is the node in the tree
- * @return array
- */
- protected function _getNodeJson($node, $level = 1)
- {
- $item = parent::_getNodeJson($node, $level);
-
- if ($this->_isParentSelectedCategory($node)) {
- $item['expanded'] = true;
- }
-
- if (in_array($node->getId(), $this->getCategoryIds())) {
- $item['checked'] = true;
- }
-
- if ($this->isReadonly()) {
- $item['disabled'] = true;
- }
-
- return $item;
- }
-
- /**
- * Returns whether $node is a parent (not exactly direct) of a selected node
- *
- * @param Varien_Data_Tree_Node $node
- * @return bool
- */
- protected function _isParentSelectedCategory($node)
- {
- foreach ($this->_getSelectedNodes() as $selected) {
- if ($selected) {
- $pathIds = explode('/', $selected->getPathId());
- if (in_array($node->getId(), $pathIds)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Returns array with nodes those are selected (contain current product)
- *
- * @return array
- */
- protected function _getSelectedNodes()
- {
- if ($this->_selectedNodes === null) {
- $this->_selectedNodes = [];
- $root = $this->getRoot();
- foreach ($this->getCategoryIds() as $categoryId) {
- if ($root) {
- $this->_selectedNodes[] = $root->getTree()->getNodeById($categoryId);
- }
- }
- }
-
- return $this->_selectedNodes;
- }
-
/**
* Returns JSON-encoded array of category children
*
@@ -274,4 +198,80 @@ public function getSelectedCategoriesPathIds($rootId = false)
}
return $ids;
}
+
+ /**
+ * Return array with category IDs which the product is assigned to
+ *
+ * @return array
+ */
+ protected function getCategoryIds()
+ {
+ return $this->getProduct()->getCategoryIds();
+ }
+
+ /**
+ * Returns array with configuration of current node
+ *
+ * @param Varien_Data_Tree_Node $node
+ * @param int $level How deep is the node in the tree
+ * @return array
+ */
+ protected function _getNodeJson($node, $level = 1)
+ {
+ $item = parent::_getNodeJson($node, $level);
+
+ if ($this->_isParentSelectedCategory($node)) {
+ $item['expanded'] = true;
+ }
+
+ if (in_array($node->getId(), $this->getCategoryIds())) {
+ $item['checked'] = true;
+ }
+
+ if ($this->isReadonly()) {
+ $item['disabled'] = true;
+ }
+
+ return $item;
+ }
+
+ /**
+ * Returns whether $node is a parent (not exactly direct) of a selected node
+ *
+ * @param Varien_Data_Tree_Node $node
+ * @return bool
+ */
+ protected function _isParentSelectedCategory($node)
+ {
+ foreach ($this->_getSelectedNodes() as $selected) {
+ if ($selected) {
+ $pathIds = explode('/', $selected->getPathId());
+ if (in_array($node->getId(), $pathIds)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Returns array with nodes those are selected (contain current product)
+ *
+ * @return array
+ */
+ protected function _getSelectedNodes()
+ {
+ if ($this->_selectedNodes === null) {
+ $this->_selectedNodes = [];
+ $root = $this->getRoot();
+ foreach ($this->getCategoryIds() as $categoryId) {
+ if ($root) {
+ $this->_selectedNodes[] = $root->getTree()->getNodeById($categoryId);
+ }
+ }
+ }
+
+ return $this->_selectedNodes;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Crosssell.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Crosssell.php
index 2ad459c4a6c..80f81735cf4 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Crosssell.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Crosssell.php
@@ -42,6 +42,40 @@ public function __construct()
}
}
+ /**
+ * Checks when this block is readonly
+ *
+ * @return bool
+ */
+ public function isReadonly()
+ {
+ return $this->_getProduct()->getCrosssellReadonly();
+ }
+
+ /**
+ * Rerieve grid URL
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->_getData('grid_url') ?: $this->getUrl('*/*/crosssellGrid', ['_current' => true]);
+ }
+
+ /**
+ * Retrieve crosssell products
+ *
+ * @return array
+ */
+ public function getSelectedCrossSellProducts()
+ {
+ $products = [];
+ foreach (Mage::registry('current_product')->getCrossSellProducts() as $product) {
+ $products[$product->getId()] = ['position' => $product->getPosition()];
+ }
+ return $products;
+ }
+
/**
* Retrieve currently edited product model
*
@@ -101,16 +135,6 @@ protected function _prepareCollection()
return parent::_prepareCollection();
}
- /**
- * Checks when this block is readonly
- *
- * @return bool
- */
- public function isReadonly()
- {
- return $this->_getProduct()->getCrosssellReadonly();
- }
-
/**
* @inheritDoc
*/
@@ -200,16 +224,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Rerieve grid URL
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->_getData('grid_url') ?: $this->getUrl('*/*/crosssellGrid', ['_current' => true]);
- }
-
/**
* Retrieve selected crosssell products
*
@@ -223,18 +237,4 @@ protected function _getSelectedProducts()
}
return $products;
}
-
- /**
- * Retrieve crosssell products
- *
- * @return array
- */
- public function getSelectedCrossSellProducts()
- {
- $products = [];
- foreach (Mage::registry('current_product')->getCrossSellProducts() as $product) {
- $products[$product->getId()] = ['position' => $product->getPosition()];
- }
- return $products;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options.php
index 3c898d367d8..e208e5d6f97 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options.php
@@ -28,6 +28,16 @@ public function __construct()
$this->setTemplate('catalog/product/edit/options.phtml');
}
+ public function getAddButtonHtml()
+ {
+ return $this->getChildHtml('add_button');
+ }
+
+ public function getOptionsBoxHtml()
+ {
+ return $this->getChildHtml('options_box');
+ }
+
protected function _prepareLayout()
{
$this->setChild(
@@ -47,14 +57,4 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
-
- public function getAddButtonHtml()
- {
- return $this->getChildHtml('add_button');
- }
-
- public function getOptionsBoxHtml()
- {
- return $this->getChildHtml('options_box');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Option.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Option.php
index c6423611956..6984efbddc1 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Option.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Option.php
@@ -106,31 +106,6 @@ public function isReadonly()
return $this->getProduct()->getOptionsReadonly();
}
- protected function _prepareLayout()
- {
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Delete Option'),
- 'class' => 'delete delete-product-option ',
- ]),
- );
-
- $path = 'global/catalog/product/options/custom/groups';
-
- foreach (Mage::getConfig()->getNode($path)->children() as $group) {
- $this->setChild(
- $group->getName() . '_option_type',
- $this->getLayout()->createBlock(
- (string) Mage::getConfig()->getNode($path . '/' . $group->getName() . '/render'),
- ),
- );
- }
-
- return parent::_prepareLayout();
- }
-
public function getAddButtonId()
{
return $this->getLayout()
@@ -337,4 +312,29 @@ public function getPriceValue($value, $type)
return number_format($value, 2, null, '');
}
}
+
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Delete Option'),
+ 'class' => 'delete delete-product-option ',
+ ]),
+ );
+
+ $path = 'global/catalog/product/options/custom/groups';
+
+ foreach (Mage::getConfig()->getNode($path)->children() as $group) {
+ $this->setChild(
+ $group->getName() . '_option_type',
+ $this->getLayout()->createBlock(
+ (string) Mage::getConfig()->getNode($path . '/' . $group->getName() . '/render'),
+ ),
+ );
+ }
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Abstract.php
index c99c9e4eab0..f4d70b29946 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Abstract.php
@@ -24,6 +24,19 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Type_Abstract extend
{
protected $_name = 'abstract';
+ /**
+ * Get html of Price Type select element
+ *
+ * @return string
+ */
+ public function getPriceTypeSelectHtml()
+ {
+ if ($this->getCanEditPrice() === false) {
+ $this->getChild('option_price_type')->setExtraParams('disabled="disabled"');
+ }
+ return $this->getChildHtml('option_price_type');
+ }
+
protected function _prepareLayout()
{
$this->setChild(
@@ -41,17 +54,4 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
-
- /**
- * Get html of Price Type select element
- *
- * @return string
- */
- public function getPriceTypeSelectHtml()
- {
- if ($this->getCanEditPrice() === false) {
- $this->getChild('option_price_type')->setExtraParams('disabled="disabled"');
- }
- return $this->getChildHtml('option_price_type');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Select.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Select.php
index 10281119e8a..cc04c134ab0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Select.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Select.php
@@ -33,6 +33,25 @@ public function __construct()
$this->setCanReadPrice(true);
}
+ public function getAddButtonHtml()
+ {
+ return $this->getChildHtml('add_select_row_button');
+ }
+
+ public function getDeleteButtonHtml()
+ {
+ return $this->getChildHtml('delete_select_row_button');
+ }
+
+ public function getPriceTypeSelectHtml()
+ {
+ $this->getChild('option_price_type')
+ ->setData('id', 'product_option_{{id}}_select_{{select_id}}_price_type')
+ ->setName('product[options][{{id}}][values][{{select_id}}][price_type]');
+
+ return parent::getPriceTypeSelectHtml();
+ }
+
protected function _prepareLayout()
{
$this->setChild(
@@ -57,23 +76,4 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
-
- public function getAddButtonHtml()
- {
- return $this->getChildHtml('add_select_row_button');
- }
-
- public function getDeleteButtonHtml()
- {
- return $this->getChildHtml('delete_select_row_button');
- }
-
- public function getPriceTypeSelectHtml()
- {
- $this->getChild('option_price_type')
- ->setData('id', 'product_option_{{id}}_select_{{select_id}}_price_type')
- ->setName('product[options][{{id}}][values][{{select_id}}][price_type]');
-
- return parent::getPriceTypeSelectHtml();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Price/Group.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Price/Group.php
index 17d455b04c5..f1448fabb6f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Price/Group.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Price/Group.php
@@ -30,6 +30,16 @@ public function __construct()
$this->setTemplate('catalog/product/edit/price/group.phtml');
}
+ /**
+ * Get is percent flag
+ *
+ * @return int
+ */
+ public function getIsPercent()
+ {
+ return $this->getData('is_percent') ? $this->getData('is_percent') : 0;
+ }
+
/**
* Sort values
*
@@ -80,14 +90,4 @@ protected function _prepareLayout()
$this->setChild('add_button', $button);
return parent::_prepareLayout();
}
-
- /**
- * Get is percent flag
- *
- * @return int
- */
- public function getIsPercent()
- {
- return $this->getData('is_percent') ? $this->getData('is_percent') : 0;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Price/Group/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Price/Group/Abstract.php
index 74385fb3319..430a4133117 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Price/Group/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Price/Group/Abstract.php
@@ -108,17 +108,6 @@ public function getValues()
return $values;
}
- /**
- * Sort values
- *
- * @param array $data
- * @return array
- */
- protected function _sortValues($data)
- {
- return $data;
- }
-
/**
* Retrieve allowed customer groups
*
@@ -147,16 +136,6 @@ public function getCustomerGroups($groupId = null)
return $this->_customerGroups;
}
- /**
- * Retrieve list of initial customer groups
- *
- * @return array
- */
- protected function _getInitialCustomerGroups()
- {
- return [];
- }
-
/**
* Retrieve number of websites
*
@@ -326,4 +305,25 @@ public function isAllowChangeWebsite()
}
return true;
}
+
+ /**
+ * Sort values
+ *
+ * @param array $data
+ * @return array
+ */
+ protected function _sortValues($data)
+ {
+ return $data;
+ }
+
+ /**
+ * Retrieve list of initial customer groups
+ *
+ * @return array
+ */
+ protected function _getInitialCustomerGroups()
+ {
+ return [];
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Related.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Related.php
index a4f16e00e45..87284764e5b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Related.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Related.php
@@ -42,6 +42,40 @@ public function __construct()
}
}
+ /**
+ * Checks when this block is readonly
+ *
+ * @return bool
+ */
+ public function isReadonly()
+ {
+ return $this->_getProduct()->getRelatedReadonly();
+ }
+
+ /**
+ * Rerieve grid URL
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getData('grid_url') ?: $this->getUrl('*/*/relatedGrid', ['_current' => true]);
+ }
+
+ /**
+ * Retrieve related products
+ *
+ * @return array
+ */
+ public function getSelectedRelatedProducts()
+ {
+ $products = [];
+ foreach (Mage::registry('current_product')->getRelatedProducts() as $product) {
+ $products[$product->getId()] = ['position' => $product->getPosition()];
+ }
+ return $products;
+ }
+
/**
* Retrieve currently edited product model
*
@@ -101,16 +135,6 @@ protected function _prepareCollection()
return parent::_prepareCollection();
}
- /**
- * Checks when this block is readonly
- *
- * @return bool
- */
- public function isReadonly()
- {
- return $this->_getProduct()->getRelatedReadonly();
- }
-
/**
* Add columns to grid
*
@@ -202,16 +226,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Rerieve grid URL
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getData('grid_url') ?: $this->getUrl('*/*/relatedGrid', ['_current' => true]);
- }
-
/**
* Retrieve selected related products
*
@@ -225,18 +239,4 @@ protected function _getSelectedProducts()
}
return $products;
}
-
- /**
- * Retrieve related products
- *
- * @return array
- */
- public function getSelectedRelatedProducts()
- {
- $products = [];
- foreach (Mage::registry('current_product')->getRelatedProducts() as $product) {
- $products[$product->getId()] = ['position' => $product->getPosition()];
- }
- return $products;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Reviews.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Reviews.php
index 4e2d97161e1..4440e37e8ac 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Reviews.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Reviews.php
@@ -23,22 +23,21 @@
class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Reviews extends Mage_Adminhtml_Block_Review_Grid
{
/**
- * Hide grid mass action elements
+ * Determine ajax url for grid refresh
*
- * @return $this
+ * @return string
*/
- protected function _prepareMassaction()
+ public function getGridUrl()
{
- return $this;
+ return $this->getUrl('*/*/reviews', ['_current' => true]);
}
-
/**
- * Determine ajax url for grid refresh
+ * Hide grid mass action elements
*
- * @return string
+ * @return $this
*/
- public function getGridUrl()
+ protected function _prepareMassaction()
{
- return $this->getUrl('*/*/reviews', ['_current' => true]);
+ return $this;
}
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Settings.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Settings.php
index e98bfb370e1..b13e6d66e87 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Settings.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Settings.php
@@ -22,6 +22,14 @@
*/
class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Settings extends Mage_Adminhtml_Block_Widget_Form
{
+ public function getContinueUrl()
+ {
+ return $this->getUrl('*/*/new', [
+ '_current' => true,
+ 'set' => '{{attribute_set}}',
+ 'type' => '{{type}}',
+ ]);
+ }
protected function _prepareLayout()
{
$this->setChild(
@@ -70,13 +78,4 @@ protected function _prepareForm()
$this->setForm($form);
return $this;
}
-
- public function getContinueUrl()
- {
- return $this->getUrl('*/*/new', [
- '_current' => true,
- 'set' => '{{attribute_set}}',
- 'type' => '{{type}}',
- ]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config.php
index 4c066da32b3..f3dbc77a0cf 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config.php
@@ -77,64 +77,6 @@ public function isAttributesPricesReadonly()
(Mage::helper('catalog')->isPriceGlobal() && $this->isReadonly());
}
- /**
- * Prepare Layout data
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'grid',
- $this->getLayout()->createBlock(
- 'adminhtml/catalog_product_edit_tab_super_config_grid',
- 'admin.product.edit.tab.super.config.grid',
- ),
- );
-
- $this->setChild(
- 'create_empty',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Create Empty'),
- 'class' => 'add',
- 'onclick' => 'superProduct.createEmptyProduct()',
- ]),
- );
-
- if ($this->_getProduct()->getId()) {
- $this->setChild(
- 'simple',
- $this->getLayout()->createBlock(
- 'adminhtml/catalog_product_edit_tab_super_config_simple',
- 'catalog.product.edit.tab.super.config.simple',
- ),
- );
-
- $this->setChild(
- 'create_from_configurable',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Copy From Configurable'),
- 'class' => 'add',
- 'onclick' => 'superProduct.createNewProduct()',
- ]),
- );
- }
-
- return parent::_prepareLayout();
- }
-
- /**
- * Retrieve currently edited product object
- *
- * @return Mage_Catalog_Model_Product
- */
- protected function _getProduct()
- {
- return Mage::registry('current_product');
- }
-
/**
* Retrieve attributes data in JSON format
*
@@ -283,24 +225,6 @@ public function getQuickCreationUrl()
);
}
- /**
- * Retrieve Required attributes Ids (comma separated)
- *
- * @return string
- */
- protected function _getRequiredAttributesIds()
- {
- $attributesIds = [];
- /** @var Mage_Catalog_Model_Product_Type_Configurable $productType */
- $productType = $this->_getProduct()->getTypeInstance(true);
- $configurableAttributes = $productType->getConfigurableAttributes($this->_getProduct());
- foreach ($configurableAttributes as $attribute) {
- $attributesIds[] = $attribute->getProductAttribute()->getId();
- }
-
- return implode(',', $attributesIds);
- }
-
/**
* Escape JavaScript string
*
@@ -362,4 +286,80 @@ public function getShowUseDefaultPrice()
return !Mage::helper('catalog')->isPriceGlobal()
&& $this->_getProduct()->getStoreId();
}
+
+ /**
+ * Prepare Layout data
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'grid',
+ $this->getLayout()->createBlock(
+ 'adminhtml/catalog_product_edit_tab_super_config_grid',
+ 'admin.product.edit.tab.super.config.grid',
+ ),
+ );
+
+ $this->setChild(
+ 'create_empty',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Create Empty'),
+ 'class' => 'add',
+ 'onclick' => 'superProduct.createEmptyProduct()',
+ ]),
+ );
+
+ if ($this->_getProduct()->getId()) {
+ $this->setChild(
+ 'simple',
+ $this->getLayout()->createBlock(
+ 'adminhtml/catalog_product_edit_tab_super_config_simple',
+ 'catalog.product.edit.tab.super.config.simple',
+ ),
+ );
+
+ $this->setChild(
+ 'create_from_configurable',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Copy From Configurable'),
+ 'class' => 'add',
+ 'onclick' => 'superProduct.createNewProduct()',
+ ]),
+ );
+ }
+
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Retrieve currently edited product object
+ *
+ * @return Mage_Catalog_Model_Product
+ */
+ protected function _getProduct()
+ {
+ return Mage::registry('current_product');
+ }
+
+ /**
+ * Retrieve Required attributes Ids (comma separated)
+ *
+ * @return string
+ */
+ protected function _getRequiredAttributesIds()
+ {
+ $attributesIds = [];
+ /** @var Mage_Catalog_Model_Product_Type_Configurable $productType */
+ $productType = $this->_getProduct()->getTypeInstance(true);
+ $configurableAttributes = $productType->getConfigurableAttributes($this->_getProduct());
+ foreach ($configurableAttributes as $attribute) {
+ $attributesIds[] = $attribute->getProductAttribute()->getId();
+ }
+
+ return implode(',', $attributesIds);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config/Grid.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config/Grid.php
index 2f6d383abd1..9a8259c9c32 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config/Grid.php
@@ -42,6 +42,51 @@ public function __construct()
}
}
+ /**
+ * Check block is readonly
+ *
+ * @return bool
+ */
+ public function isReadonly()
+ {
+ if ($this->hasData('is_readonly')) {
+ return $this->getData('is_readonly');
+ }
+ return $this->_getProduct()->getCompositeReadonly();
+ }
+
+ /**
+ * @return array
+ */
+ public function getEditParamsForAssociated()
+ {
+ return [
+ 'base' => '*/*/edit',
+ 'params' => [
+ 'required' => $this->_getRequiredAttributesIds(),
+ 'popup' => 1,
+ 'product' => $this->_getProduct()->getId(),
+ ],
+ ];
+ }
+
+ public function getOptions($attribute)
+ {
+ $result = [];
+ foreach ($attribute->getProductAttribute()->getSource()->getAllOptions() as $option) {
+ if ($option['value'] != '') {
+ $result[$option['value']] = $option['label'];
+ }
+ }
+
+ return $result;
+ }
+
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/superConfig', ['_current' => true]);
+ }
+
/**
* Retrieve currently edited product object
*
@@ -160,19 +205,6 @@ protected function _getSelectedProducts()
return $products;
}
- /**
- * Check block is readonly
- *
- * @return bool
- */
- public function isReadonly()
- {
- if ($this->hasData('is_readonly')) {
- return $this->getData('is_readonly');
- }
- return $this->_getProduct()->getCompositeReadonly();
- }
-
/**
* @inheritDoc
* @throws Mage_Core_Exception
@@ -270,21 +302,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * @return array
- */
- public function getEditParamsForAssociated()
- {
- return [
- 'base' => '*/*/edit',
- 'params' => [
- 'required' => $this->_getRequiredAttributesIds(),
- 'popup' => 1,
- 'product' => $this->_getProduct()->getId(),
- ],
- ];
- }
-
/**
* Retrieve Required attributes Ids (comma separated)
*
@@ -302,23 +319,6 @@ protected function _getRequiredAttributesIds()
return implode(',', $attributesIds);
}
- public function getOptions($attribute)
- {
- $result = [];
- foreach ($attribute->getProductAttribute()->getSource()->getAllOptions() as $option) {
- if ($option['value'] != '') {
- $result[$option['value']] = $option['label'];
- }
- }
-
- return $result;
- }
-
- public function getGridUrl()
- {
- return $this->getUrl('*/*/superConfig', ['_current' => true]);
- }
-
/**
* Retrieving configurable attributes
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Group.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Group.php
index a244739fd56..eb213a47660 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Group.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Group.php
@@ -55,6 +55,52 @@ public function getTabClass()
return 'ajax';
}
+ /**
+ * Get Grid Url
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->_getData('grid_url') ?: $this->getUrl('*/*/superGroupGridOnly', ['_current' => true]);
+ }
+
+ /**
+ * Retrieve grouped products
+ *
+ * @return array
+ */
+ public function getSelectedGroupedProducts()
+ {
+ $associatedProducts = Mage::registry('current_product')->getTypeInstance(true)
+ ->getAssociatedProducts(Mage::registry('current_product'));
+ $products = [];
+ foreach ($associatedProducts as $product) {
+ $products[$product->getId()] = [
+ 'qty' => $product->getQty(),
+ 'position' => $product->getPosition(),
+ ];
+ }
+ return $products;
+ }
+
+ public function getTabLabel()
+ {
+ return Mage::helper('catalog')->__('Associated Products');
+ }
+ public function getTabTitle()
+ {
+ return Mage::helper('catalog')->__('Associated Products');
+ }
+ public function canShowTab()
+ {
+ return true;
+ }
+ public function isHidden()
+ {
+ return false;
+ }
+
/**
* Retrieve currently edited product model
*
@@ -194,16 +240,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Get Grid Url
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->_getData('grid_url') ?: $this->getUrl('*/*/superGroupGridOnly', ['_current' => true]);
- }
-
/**
* Retrieve selected grouped products
*
@@ -217,40 +253,4 @@ protected function _getSelectedProducts()
}
return $products;
}
-
- /**
- * Retrieve grouped products
- *
- * @return array
- */
- public function getSelectedGroupedProducts()
- {
- $associatedProducts = Mage::registry('current_product')->getTypeInstance(true)
- ->getAssociatedProducts(Mage::registry('current_product'));
- $products = [];
- foreach ($associatedProducts as $product) {
- $products[$product->getId()] = [
- 'qty' => $product->getQty(),
- 'position' => $product->getPosition(),
- ];
- }
- return $products;
- }
-
- public function getTabLabel()
- {
- return Mage::helper('catalog')->__('Associated Products');
- }
- public function getTabTitle()
- {
- return Mage::helper('catalog')->__('Associated Products');
- }
- public function canShowTab()
- {
- return true;
- }
- public function isHidden()
- {
- return false;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Settings.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Settings.php
index 10d8eda58a2..da67f5a49a6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Settings.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Settings.php
@@ -22,6 +22,28 @@
*/
class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Settings extends Mage_Adminhtml_Block_Widget_Form
{
+ /**
+ * Retrieve Continue URL
+ *
+ * @return string
+ */
+ public function getContinueUrl()
+ {
+ return $this->getUrl('*/*/new', [
+ '_current' => true,
+ 'attributes' => '{{attributes}}',
+ ]);
+ }
+
+ /**
+ * Retrieve Back URL
+ *
+ * @return string
+ */
+ public function getBackUrl()
+ {
+ return $this->getUrl('*/*/new', ['set' => null, 'type' => null]);
+ }
/**
* Prepare block children and data
*/
@@ -122,27 +144,4 @@ protected function _prepareForm()
return parent::_prepareForm();
}
-
- /**
- * Retrieve Continue URL
- *
- * @return string
- */
- public function getContinueUrl()
- {
- return $this->getUrl('*/*/new', [
- '_current' => true,
- 'attributes' => '{{attributes}}',
- ]);
- }
-
- /**
- * Retrieve Back URL
- *
- * @return string
- */
- public function getBackUrl()
- {
- return $this->getUrl('*/*/new', ['set' => null, 'type' => null]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Tag.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Tag.php
index a87638959b6..3c31acb0fe0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Tag.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Tag.php
@@ -31,6 +31,23 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/tag/edit', [
+ 'tag_id' => $row->getId(),
+ 'product_id' => $this->getProductId(),
+ ]);
+ }
+
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/catalog_product/tagGrid', [
+ '_current' => true,
+ 'id' => $this->getProductId(),
+ 'product_id' => $this->getProductId(),
+ ]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getModel('tag/tag')
@@ -75,21 +92,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/tag/edit', [
- 'tag_id' => $row->getId(),
- 'product_id' => $this->getProductId(),
- ]);
- }
-
- public function getGridUrl()
- {
- return $this->getUrl('*/catalog_product/tagGrid', [
- '_current' => true,
- 'id' => $this->getProductId(),
- 'product_id' => $this->getProductId(),
- ]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Tag/Customer.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Tag/Customer.php
index 90eddacc241..9eee024795e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Tag/Customer.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Tag/Customer.php
@@ -31,6 +31,20 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/customer/edit', ['id' => $row->getEntityId()]);
+ }
+
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/catalog_product/tagCustomerGrid', [
+ '_current' => true,
+ 'id' => $this->getProductId(),
+ 'product_id' => $this->getProductId(),
+ ]);
+ }
+
protected function _prepareCollection()
{
if ($this->isModuleEnabled('Mage_Tag', 'catalog')) {
@@ -79,18 +93,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/customer/edit', ['id' => $row->getEntityId()]);
- }
-
- public function getGridUrl()
- {
- return $this->getUrl('*/catalog_product/tagCustomerGrid', [
- '_current' => true,
- 'id' => $this->getProductId(),
- 'product_id' => $this->getProductId(),
- ]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Upsell.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Upsell.php
index da667665293..30565343510 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Upsell.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Upsell.php
@@ -42,6 +42,40 @@ public function __construct()
}
}
+ /**
+ * Checks when this block is readonly
+ *
+ * @return bool
+ */
+ public function isReadonly()
+ {
+ return $this->_getProduct()->getUpsellReadonly();
+ }
+
+ /**
+ * Rerieve grid URL
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->_getData('grid_url') ?: $this->getUrl('*/*/upsellGrid', ['_current' => true]);
+ }
+
+ /**
+ * Retrieve upsell products
+ *
+ * @return array
+ */
+ public function getSelectedUpsellProducts()
+ {
+ $products = [];
+ foreach (Mage::registry('current_product')->getUpSellProducts() as $product) {
+ $products[$product->getId()] = ['position' => $product->getPosition()];
+ }
+ return $products;
+ }
+
/**
* Retrieve currently edited product model
*
@@ -77,16 +111,6 @@ protected function _addColumnFilterToCollection($column)
return $this;
}
- /**
- * Checks when this block is readonly
- *
- * @return bool
- */
- public function isReadonly()
- {
- return $this->_getProduct()->getUpsellReadonly();
- }
-
/**
* Prepare collection
*
@@ -201,16 +225,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Rerieve grid URL
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->_getData('grid_url') ?: $this->getUrl('*/*/upsellGrid', ['_current' => true]);
- }
-
/**
* Retrieve selected upsell products
*
@@ -224,18 +238,4 @@ protected function _getSelectedProducts()
}
return $products;
}
-
- /**
- * Retrieve upsell products
- *
- * @return array
- */
- public function getSelectedUpsellProducts()
- {
- $products = [];
- foreach (Mage::registry('current_product')->getUpSellProducts() as $product) {
- $products[$product->getId()] = ['position' => $product->getPosition()];
- }
- return $products;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tabs.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tabs.php
index 896aabe6f15..f2dfda25cfb 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tabs.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tabs.php
@@ -32,6 +32,38 @@ public function __construct()
$this->setTitle(Mage::helper('catalog')->__('Product Information'));
}
+ /**
+ * Retrieve product object from object if not from registry
+ *
+ * @return Mage_Catalog_Model_Product
+ */
+ public function getProduct()
+ {
+ if (!($this->getData('product') instanceof Mage_Catalog_Model_Product)) {
+ $this->setData('product', Mage::registry('product'));
+ }
+ return $this->getData('product');
+ }
+
+ /**
+ * Getting attribute block name for tabs
+ *
+ * @return string|null
+ */
+ public function getAttributeTabBlock()
+ {
+ if (is_null(Mage::helper('adminhtml/catalog')->getAttributeTabBlock())) {
+ return $this->_attributeTabBlock;
+ }
+ return Mage::helper('adminhtml/catalog')->getAttributeTabBlock();
+ }
+
+ public function setAttributeTabBlock($attributeTabBlock)
+ {
+ $this->_attributeTabBlock = $attributeTabBlock;
+ return $this;
+ }
+
protected function _prepareLayout()
{
$product = $this->getProduct();
@@ -180,38 +212,6 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
- /**
- * Retrieve product object from object if not from registry
- *
- * @return Mage_Catalog_Model_Product
- */
- public function getProduct()
- {
- if (!($this->getData('product') instanceof Mage_Catalog_Model_Product)) {
- $this->setData('product', Mage::registry('product'));
- }
- return $this->getData('product');
- }
-
- /**
- * Getting attribute block name for tabs
- *
- * @return string|null
- */
- public function getAttributeTabBlock()
- {
- if (is_null(Mage::helper('adminhtml/catalog')->getAttributeTabBlock())) {
- return $this->_attributeTabBlock;
- }
- return Mage::helper('adminhtml/catalog')->getAttributeTabBlock();
- }
-
- public function setAttributeTabBlock($attributeTabBlock)
- {
- $this->_attributeTabBlock = $attributeTabBlock;
- return $this;
- }
-
/**
* Translate html content
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php
index 5b59c1ed066..14281f9196d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php
@@ -37,6 +37,25 @@ public function __construct()
$this->setVarNameFilter('product_filter');
}
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
+ /**
+ * @param Mage_Catalog_Model_Product $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', [
+ 'store' => $this->getRequest()->getParam('store'),
+ 'id' => $row->getId()]);
+ }
+
protected function _getStore()
{
$storeId = (int) $this->getRequest()->getParam('store', 0);
@@ -333,23 +352,4 @@ protected function _prepareMassaction()
Mage::dispatchEvent('adminhtml_catalog_product_grid_prepare_massaction', ['block' => $this]);
return $this;
}
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
-
- /**
- * @param Mage_Catalog_Model_Product $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', [
- 'store' => $this->getRequest()->getParam('store'),
- 'id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php
index bca3ab6517c..350bd1fdcb6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php
@@ -35,34 +35,6 @@ public function __construct()
$this->setTemplate('catalog/product/helper/gallery.phtml');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'uploader',
- $this->getLayout()->createBlock($this->_uploaderType),
- );
-
- $this->getUploader()->getUploaderConfig()
- ->setFileParameterName('image')
- ->setTarget(Mage::getModel('adminhtml/url')->addSessionParam()->getUrl(
- '*/catalog_product_gallery/upload',
- ['_query' => false],
- ));
-
- $browseConfig = $this->getUploader()->getButtonConfig();
- $browseConfig
- ->setAttributes([
- 'accept' => $browseConfig->getMimeTypesByExtensions(Varien_Io_File::ALLOWED_IMAGES_EXTENSIONS),
- ]);
-
- Mage::dispatchEvent('catalog_product_gallery_prepare_layout', ['block' => $this]);
-
- return parent::_prepareLayout();
- }
-
/**
* Retrieve uploader block
*
@@ -182,4 +154,32 @@ public function getImageTypesJson()
{
return Mage::helper('core')->jsonEncode($this->getImageTypes());
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'uploader',
+ $this->getLayout()->createBlock($this->_uploaderType),
+ );
+
+ $this->getUploader()->getUploaderConfig()
+ ->setFileParameterName('image')
+ ->setTarget(Mage::getModel('adminhtml/url')->addSessionParam()->getUrl(
+ '*/catalog_product_gallery/upload',
+ ['_query' => false],
+ ));
+
+ $browseConfig = $this->getUploader()->getButtonConfig();
+ $browseConfig
+ ->setAttributes([
+ 'accept' => $browseConfig->getMimeTypesByExtensions(Varien_Io_File::ALLOWED_IMAGES_EXTENSIONS),
+ ]);
+
+ Mage::dispatchEvent('catalog_product_gallery_prepare_layout', ['block' => $this]);
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Price.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Price.php
index c6d36600d8d..70d8bb25d72 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Price.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Price.php
@@ -62,17 +62,6 @@ public function getAfterElementHtml()
return $html;
}
- /**
- * @param $attribute
- * @return string
- */
- protected function _getTaxObservingCode($attribute)
- {
- $spanId = "dynamic-tax-{$attribute->getAttributeCode()}";
-
- return "";
- }
-
/**
* @param null $index deprecated
* @return string|null
@@ -87,4 +76,15 @@ public function getEscapedValue($index = null)
return number_format((float) $value, 2, null, '');
}
+
+ /**
+ * @param $attribute
+ * @return string
+ */
+ protected function _getTaxObservingCode($attribute)
+ {
+ $spanId = "dynamic-tax-{$attribute->getAttributeCode()}";
+
+ return "";
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Widget/Chooser.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Widget/Chooser.php
index 9a3d3e94b00..dfc9dfa3f19 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Widget/Chooser.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Widget/Chooser.php
@@ -147,6 +147,47 @@ function (node, e) {
return str_replace('{jsObject}', $this->getJsObjectName(), $js);
}
+ /**
+ * Adds additional parameter to URL for loading only products grid
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/catalog_product_widget/chooser', [
+ 'products_grid' => true,
+ '_current' => true,
+ 'uniq_id' => $this->getId(),
+ 'use_massaction' => $this->getUseMassaction(),
+ 'product_type_id' => $this->getProductTypeId(),
+ ]);
+ }
+
+ /**
+ * Setter
+ *
+ * @param array $selectedProducts
+ * @return $this
+ */
+ public function setSelectedProducts($selectedProducts)
+ {
+ $this->_selectedProducts = $selectedProducts;
+ return $this;
+ }
+
+ /**
+ * Getter
+ *
+ * @return array
+ */
+ public function getSelectedProducts()
+ {
+ if ($selectedProducts = $this->getRequest()->getParam('selected_products', null)) {
+ $this->setSelectedProducts($selectedProducts);
+ }
+ return $this->_selectedProducts;
+ }
+
/**
* Filter checked/unchecked rows in grid
*
@@ -240,45 +281,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Adds additional parameter to URL for loading only products grid
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/catalog_product_widget/chooser', [
- 'products_grid' => true,
- '_current' => true,
- 'uniq_id' => $this->getId(),
- 'use_massaction' => $this->getUseMassaction(),
- 'product_type_id' => $this->getProductTypeId(),
- ]);
- }
-
- /**
- * Setter
- *
- * @param array $selectedProducts
- * @return $this
- */
- public function setSelectedProducts($selectedProducts)
- {
- $this->_selectedProducts = $selectedProducts;
- return $this;
- }
-
- /**
- * Getter
- *
- * @return array
- */
- public function getSelectedProducts()
- {
- if ($selectedProducts = $this->getRequest()->getParam('selected_products', null)) {
- $this->setSelectedProducts($selectedProducts);
- }
- return $this->_selectedProducts;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Search/Grid.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Search/Grid.php
index 6a6cb806392..1c64f5ea145 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Search/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Search/Grid.php
@@ -34,6 +34,17 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * Retrieve Row Click callback URL
+ *
+ * @param Mage_CatalogSearch_Model_Query $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
/**
* Prepare collection for Grid
*
@@ -149,15 +160,4 @@ protected function _prepareMassaction()
return parent::_prepareMassaction();
}
-
- /**
- * Retrieve Row Click callback URL
- *
- * @param Mage_CatalogSearch_Model_Query $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Checkout/Agreement/Grid.php b/app/code/core/Mage/Adminhtml/Block/Checkout/Agreement/Grid.php
index 8d29d5dfbf6..d80e9ee86e8 100644
--- a/app/code/core/Mage/Adminhtml/Block/Checkout/Agreement/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Checkout/Agreement/Grid.php
@@ -36,6 +36,15 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * @param Mage_Checkout_Model_Agreement $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
/**
* @inheritDoc
*/
@@ -123,13 +132,4 @@ protected function _filterStoreCondition($collection, $column)
$collection->addStoreFilter($value);
}
}
-
- /**
- * @param Mage_Checkout_Model_Agreement $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Cms/Block/Grid.php b/app/code/core/Mage/Adminhtml/Block/Cms/Block/Grid.php
index e8f912ef815..12d6543d44f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cms/Block/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cms/Block/Grid.php
@@ -30,6 +30,16 @@ public function __construct()
$this->setDefaultDir('ASC');
}
+ /**
+ * Row click url
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['block_id' => $row->getId()]);
+ }
+
/**
* @inheritDoc
* @throws Exception
@@ -116,14 +126,4 @@ protected function _filterStoreCondition($collection, $column)
$collection->addStoreFilter($value);
}
}
-
- /**
- * Row click url
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['block_id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Cms/Block/Widget/Chooser.php b/app/code/core/Mage/Adminhtml/Block/Cms/Block/Widget/Chooser.php
index 2c65be2272c..0423f09d7ce 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cms/Block/Widget/Chooser.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cms/Block/Widget/Chooser.php
@@ -86,6 +86,11 @@ function (grid, event) {
';
}
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/cms_block_widget/chooser', ['_current' => true]);
+ }
+
/**
* Prepare Cms static blocks collection
*
@@ -137,9 +142,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getGridUrl()
- {
- return $this->getUrl('*/cms_block_widget/chooser', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php
index 25800b26c8e..1968c7c98d9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php
@@ -22,6 +22,45 @@
*/
class Mage_Adminhtml_Block_Cms_Page_Edit_Tab_Content extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
+ /**
+ * Prepare label for tab
+ *
+ * @return string
+ */
+ public function getTabLabel()
+ {
+ return Mage::helper('cms')->__('Content');
+ }
+
+ /**
+ * Prepare title for tab
+ *
+ * @return string
+ */
+ public function getTabTitle()
+ {
+ return Mage::helper('cms')->__('Content');
+ }
+
+ /**
+ * Returns status flag about this tab can be shown or not
+ *
+ * @return true
+ */
+ public function canShowTab()
+ {
+ return true;
+ }
+
+ /**
+ * Returns status flag about this tab hidden or not
+ *
+ * @return false
+ */
+ public function isHidden()
+ {
+ return false;
+ }
/**
* Load Wysiwyg on demand and Prepare layout
*/
@@ -89,46 +128,6 @@ protected function _prepareForm()
return parent::_prepareForm();
}
- /**
- * Prepare label for tab
- *
- * @return string
- */
- public function getTabLabel()
- {
- return Mage::helper('cms')->__('Content');
- }
-
- /**
- * Prepare title for tab
- *
- * @return string
- */
- public function getTabTitle()
- {
- return Mage::helper('cms')->__('Content');
- }
-
- /**
- * Returns status flag about this tab can be shown or not
- *
- * @return true
- */
- public function canShowTab()
- {
- return true;
- }
-
- /**
- * Returns status flag about this tab hidden or not
- *
- * @return false
- */
- public function isHidden()
- {
- return false;
- }
-
/**
* Check permission for passed action
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Design.php b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Design.php
index 08663208973..688f02cf35f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Design.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Design.php
@@ -29,6 +29,46 @@ public function __construct()
$this->setShowGlobalIcon(true);
}
+ /**
+ * Prepare label for tab
+ *
+ * @return string
+ */
+ public function getTabLabel()
+ {
+ return Mage::helper('cms')->__('Design');
+ }
+
+ /**
+ * Prepare title for tab
+ *
+ * @return string
+ */
+ public function getTabTitle()
+ {
+ return Mage::helper('cms')->__('Design');
+ }
+
+ /**
+ * Returns status flag about this tab can be showen or not
+ *
+ * @return true
+ */
+ public function canShowTab()
+ {
+ return true;
+ }
+
+ /**
+ * Returns status flag about this tab hidden or not
+ *
+ * @return false
+ */
+ public function isHidden()
+ {
+ return false;
+ }
+
/**
* @inheritDoc
*/
@@ -131,46 +171,6 @@ protected function _prepareForm()
return parent::_prepareForm();
}
- /**
- * Prepare label for tab
- *
- * @return string
- */
- public function getTabLabel()
- {
- return Mage::helper('cms')->__('Design');
- }
-
- /**
- * Prepare title for tab
- *
- * @return string
- */
- public function getTabTitle()
- {
- return Mage::helper('cms')->__('Design');
- }
-
- /**
- * Returns status flag about this tab can be showen or not
- *
- * @return true
- */
- public function canShowTab()
- {
- return true;
- }
-
- /**
- * Returns status flag about this tab hidden or not
- *
- * @return false
- */
- public function isHidden()
- {
- return false;
- }
-
/**
* Check permission for passed action
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Main.php b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Main.php
index cdf5aae7639..fd3da94ef01 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Main.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Main.php
@@ -22,6 +22,45 @@
*/
class Mage_Adminhtml_Block_Cms_Page_Edit_Tab_Main extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
+ /**
+ * Prepare label for tab
+ *
+ * @return string
+ */
+ public function getTabLabel()
+ {
+ return Mage::helper('cms')->__('Page Information');
+ }
+
+ /**
+ * Prepare title for tab
+ *
+ * @return string
+ */
+ public function getTabTitle()
+ {
+ return Mage::helper('cms')->__('Page Information');
+ }
+
+ /**
+ * Returns status flag about this tab can be shown or not
+ *
+ * @return true
+ */
+ public function canShowTab()
+ {
+ return true;
+ }
+
+ /**
+ * Returns status flag about this tab hidden or not
+ *
+ * @return false
+ */
+ public function isHidden()
+ {
+ return false;
+ }
/**
* @inheritDoc
*/
@@ -111,46 +150,6 @@ protected function _prepareForm()
return parent::_prepareForm();
}
- /**
- * Prepare label for tab
- *
- * @return string
- */
- public function getTabLabel()
- {
- return Mage::helper('cms')->__('Page Information');
- }
-
- /**
- * Prepare title for tab
- *
- * @return string
- */
- public function getTabTitle()
- {
- return Mage::helper('cms')->__('Page Information');
- }
-
- /**
- * Returns status flag about this tab can be shown or not
- *
- * @return true
- */
- public function canShowTab()
- {
- return true;
- }
-
- /**
- * Returns status flag about this tab hidden or not
- *
- * @return false
- */
- public function isHidden()
- {
- return false;
- }
-
/**
* Check permission for passed action
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Meta.php b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Meta.php
index e99f8ef6ff5..216b0330427 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Meta.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Meta.php
@@ -22,6 +22,45 @@
*/
class Mage_Adminhtml_Block_Cms_Page_Edit_Tab_Meta extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
+ /**
+ * Prepare label for tab
+ *
+ * @return string
+ */
+ public function getTabLabel()
+ {
+ return Mage::helper('cms')->__('Meta Data');
+ }
+
+ /**
+ * Prepare title for tab
+ *
+ * @return string
+ */
+ public function getTabTitle()
+ {
+ return Mage::helper('cms')->__('Meta Data');
+ }
+
+ /**
+ * Returns status flag about this tab can be showen or not
+ *
+ * @return true
+ */
+ public function canShowTab()
+ {
+ return true;
+ }
+
+ /**
+ * Returns status flag about this tab hidden or not
+ *
+ * @return false
+ */
+ public function isHidden()
+ {
+ return false;
+ }
/**
* @inheritDoc
*/
@@ -67,46 +106,6 @@ protected function _prepareForm()
return parent::_prepareForm();
}
- /**
- * Prepare label for tab
- *
- * @return string
- */
- public function getTabLabel()
- {
- return Mage::helper('cms')->__('Meta Data');
- }
-
- /**
- * Prepare title for tab
- *
- * @return string
- */
- public function getTabTitle()
- {
- return Mage::helper('cms')->__('Meta Data');
- }
-
- /**
- * Returns status flag about this tab can be showen or not
- *
- * @return true
- */
- public function canShowTab()
- {
- return true;
- }
-
- /**
- * Returns status flag about this tab hidden or not
- *
- * @return false
- */
- public function isHidden()
- {
- return false;
- }
-
/**
* Check permission for passed action
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Grid.php b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Grid.php
index 0518e73408c..f6fcaedef38 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Grid.php
@@ -30,6 +30,16 @@ public function __construct()
$this->setDefaultDir('ASC');
}
+ /**
+ * Row click url
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['page_id' => $row->getId()]);
+ }
+
/**
* @inheritDoc
* @throws Exception
@@ -131,14 +141,4 @@ protected function _filterStoreCondition($collection, $column)
$collection->addStoreFilter($value);
}
}
-
- /**
- * Row click url
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['page_id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Widget/Chooser.php b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Widget/Chooser.php
index f06f9ea700b..45c1f7536ed 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cms/Page/Widget/Chooser.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cms/Page/Widget/Chooser.php
@@ -85,6 +85,11 @@ function (grid, event) {
';
}
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/cms_page_widget/chooser', ['_current' => true]);
+ }
+
/**
* Prepare pages collection
*
@@ -144,9 +149,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getGridUrl()
- {
- return $this->getUrl('*/cms_page_widget/chooser', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Cms/Wysiwyg/Images/Content.php b/app/code/core/Mage/Adminhtml/Block/Cms/Wysiwyg/Images/Content.php
index ff906c875ef..53ec4670e70 100644
--- a/app/code/core/Mage/Adminhtml/Block/Cms/Wysiwyg/Images/Content.php
+++ b/app/code/core/Mage/Adminhtml/Block/Cms/Wysiwyg/Images/Content.php
@@ -107,16 +107,6 @@ public function getNewfolderUrl()
return $this->getUrl('*/*/newFolder');
}
- /**
- * Delete directory action target URL
- *
- * @return string
- */
- protected function getDeletefolderUrl()
- {
- return $this->getUrl('*/*/deleteFolder');
- }
-
/**
* @return string
*/
@@ -144,4 +134,14 @@ public function getTargetElementId()
{
return $this->getRequest()->getParam('target_element_id');
}
+
+ /**
+ * Delete directory action target URL
+ *
+ * @return string
+ */
+ protected function getDeletefolderUrl()
+ {
+ return $this->getUrl('*/*/deleteFolder');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Renderer/Attribute/Group.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Renderer/Attribute/Group.php
index 9da80b38d33..b07f43350e6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Renderer/Attribute/Group.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Renderer/Attribute/Group.php
@@ -22,25 +22,6 @@
*/
class Mage_Adminhtml_Block_Customer_Edit_Renderer_Attribute_Group extends Mage_Adminhtml_Block_Widget_Form_Renderer_Fieldset_Element
{
- /**
- * Override parent constructor just for setting custom template
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('customer/edit/tab/account/form/renderer/group.phtml');
- }
-
- /**
- * Retrieve disable auto group change element HTML ID
- *
- * @return string
- */
- protected function _getDisableAutoGroupChangeElementHtmlId()
- {
- return $this->getDisableAutoGroupChangeAttribute()->getAttributeCode();
- }
-
/**
* Retrieve disable auto group change checkbox label text
*
@@ -90,4 +71,22 @@ public function getDisableAutoGroupChangeCheckboxElementId()
{
return $this->_getDisableAutoGroupChangeElementHtmlId();
}
+ /**
+ * Override parent constructor just for setting custom template
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('customer/edit/tab/account/form/renderer/group.phtml');
+ }
+
+ /**
+ * Retrieve disable auto group change element HTML ID
+ *
+ * @return string
+ */
+ protected function _getDisableAutoGroupChangeElementHtmlId()
+ {
+ return $this->getDisableAutoGroupChangeAttribute()->getAttributeCode();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Addresses.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Addresses.php
index a7d23728e64..8436618eadc 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Addresses.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Addresses.php
@@ -39,51 +39,6 @@ public function getRegionsUrl()
return $this->getUrl('*/json/countryRegion');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('customer')->__('Delete Address'),
- 'name' => 'delete_address',
- 'element_name' => 'delete_address',
- 'disabled' => $this->isReadonly(),
- 'class' => 'delete' . ($this->isReadonly() ? ' disabled' : ''),
- ]),
- );
- $this->setChild(
- 'add_address_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('customer')->__('Add New Address'),
- 'id' => 'add_address_button',
- 'name' => 'add_address_button',
- 'element_name' => 'add_address_button',
- 'disabled' => $this->isReadonly(),
- 'class' => 'add' . ($this->isReadonly() ? ' disabled' : ''),
- 'onclick' => 'customerAddresses.addNewAddress()',
- ]),
- );
- $this->setChild(
- 'cancel_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('customer')->__('Cancel'),
- 'id' => 'cancel_add_address' . $this->getTemplatePrefix(),
- 'name' => 'cancel_address',
- 'element_name' => 'cancel_address',
- 'class' => 'cancel delete-address' . ($this->isReadonly() ? ' disabled' : ''),
- 'disabled' => $this->isReadonly(),
- 'onclick' => 'customerAddresses.cancelAdd(this)',
- ]),
- );
- return parent::_prepareLayout();
- }
-
/**
* Check block is readonly.
*
@@ -235,20 +190,6 @@ public function getTemplatePrefix()
return '_template_';
}
- /**
- * Return predefined additional element types
- *
- * @return array
- */
- protected function _getAdditionalElementTypes()
- {
- return [
- 'file' => Mage::getConfig()->getBlockClassName('adminhtml/customer_form_element_file'),
- 'image' => Mage::getConfig()->getBlockClassName('adminhtml/customer_form_element_image'),
- 'boolean' => Mage::getConfig()->getBlockClassName('adminhtml/customer_form_element_boolean'),
- ];
- }
-
/**
* Return JSON object with countries associated to possible websites
*
@@ -296,6 +237,65 @@ public function addValuesToNameSuffixElement($values)
return $this;
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('customer')->__('Delete Address'),
+ 'name' => 'delete_address',
+ 'element_name' => 'delete_address',
+ 'disabled' => $this->isReadonly(),
+ 'class' => 'delete' . ($this->isReadonly() ? ' disabled' : ''),
+ ]),
+ );
+ $this->setChild(
+ 'add_address_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('customer')->__('Add New Address'),
+ 'id' => 'add_address_button',
+ 'name' => 'add_address_button',
+ 'element_name' => 'add_address_button',
+ 'disabled' => $this->isReadonly(),
+ 'class' => 'add' . ($this->isReadonly() ? ' disabled' : ''),
+ 'onclick' => 'customerAddresses.addNewAddress()',
+ ]),
+ );
+ $this->setChild(
+ 'cancel_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('customer')->__('Cancel'),
+ 'id' => 'cancel_add_address' . $this->getTemplatePrefix(),
+ 'name' => 'cancel_address',
+ 'element_name' => 'cancel_address',
+ 'class' => 'cancel delete-address' . ($this->isReadonly() ? ' disabled' : ''),
+ 'disabled' => $this->isReadonly(),
+ 'onclick' => 'customerAddresses.cancelAdd(this)',
+ ]),
+ );
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Return predefined additional element types
+ *
+ * @return array
+ */
+ protected function _getAdditionalElementTypes()
+ {
+ return [
+ 'file' => Mage::getConfig()->getBlockClassName('adminhtml/customer_form_element_file'),
+ 'image' => Mage::getConfig()->getBlockClassName('adminhtml/customer_form_element_image'),
+ 'boolean' => Mage::getConfig()->getBlockClassName('adminhtml/customer_form_element_boolean'),
+ ];
+ }
+
protected function getRegistryCurrentCustomer(): ?Mage_Customer_Model_Customer
{
return Mage::registry('current_customer');
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Cart.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Cart.php
index 0655ea751c8..88b28170d92 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Cart.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Cart.php
@@ -39,6 +39,39 @@ public function __construct($attributes = [])
$this->setTemplate('customer/tab/cart.phtml');
}
+ /**
+ * Gets customer assigned to this block
+ *
+ * @return Mage_Customer_Model_Customer
+ */
+ public function getCustomer()
+ {
+ return Mage::registry('current_customer');
+ }
+
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/cart', ['_current' => true, 'website_id' => $this->getWebsiteId()]);
+ }
+
+ /**
+ * @return string
+ * @throws Exception
+ */
+ public function getGridParentHtml()
+ {
+ $templateName = Mage::getDesign()->getTemplateFilename($this->_parentTemplate, ['_relative' => true]);
+ return $this->fetchView($templateName);
+ }
+
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
+ }
+
/**
* @inheritDoc
*/
@@ -135,37 +168,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Gets customer assigned to this block
- *
- * @return Mage_Customer_Model_Customer
- */
- public function getCustomer()
- {
- return Mage::registry('current_customer');
- }
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/cart', ['_current' => true, 'website_id' => $this->getWebsiteId()]);
- }
-
- /**
- * @return string
- * @throws Exception
- */
- public function getGridParentHtml()
- {
- $templateName = Mage::getDesign()->getTemplateFilename($this->_parentTemplate, ['_relative' => true]);
- return $this->fetchView($templateName);
- }
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Newsletter/Grid/Filter/Status.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Newsletter/Grid/Filter/Status.php
index c8ff1509bbb..b8899f92113 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Newsletter/Grid/Filter/Status.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Newsletter/Grid/Filter/Status.php
@@ -38,27 +38,27 @@ public function __construct()
}
/**
- * @return array
+ * @return array|null
*/
- protected function _getOptions()
+ public function getCondition()
{
- $result = [];
- foreach (self::$_statuses as $code => $label) {
- $result[] = ['value' => $code, 'label' => Mage::helper('customer')->__($label)];
+ if (is_null($this->getValue())) {
+ return null;
}
- return $result;
+ return ['eq' => $this->getValue()];
}
/**
- * @return array|null
+ * @return array
*/
- public function getCondition()
+ protected function _getOptions()
{
- if (is_null($this->getValue())) {
- return null;
+ $result = [];
+ foreach (self::$_statuses as $code => $label) {
+ $result[] = ['value' => $code, 'label' => Mage::helper('customer')->__($label)];
}
- return ['eq' => $this->getValue()];
+ return $result;
}
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Orders.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Orders.php
index 9c978133018..2d362f4a344 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Orders.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Orders.php
@@ -34,6 +34,23 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
+ }
+
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/orders', ['_current' => true]);
+ }
+
/**
* @inheritDoc
*/
@@ -118,21 +135,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
- }
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/orders', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Reviews.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Reviews.php
index 5d692441193..40868af1295 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Reviews.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Reviews.php
@@ -23,22 +23,21 @@
class Mage_Adminhtml_Block_Customer_Edit_Tab_Reviews extends Mage_Adminhtml_Block_Review_Grid
{
/**
- * Hide grid mass action elements
+ * Determine ajax url for grid refresh
*
- * @return $this
+ * @return string
*/
- protected function _prepareMassaction()
+ public function getGridUrl()
{
- return $this;
+ return $this->getUrl('*/*/productReviews', ['_current' => true]);
}
-
/**
- * Determine ajax url for grid refresh
+ * Hide grid mass action elements
*
- * @return string
+ * @return $this
*/
- public function getGridUrl()
+ protected function _prepareMassaction()
{
- return $this->getUrl('*/*/productReviews', ['_current' => true]);
+ return $this;
}
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Tag.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Tag.php
index a81d8206954..c8c158214f8 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Tag.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Tag.php
@@ -34,6 +34,25 @@ public function __construct()
$this->setFilterVisibility(false);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/tag/edit', [
+ 'tag_id' => $row->getTagId(),
+ 'customer_id' => $this->getCustomerId(),
+ ]);
+ }
+
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/customer/tagGrid', [
+ '_current' => true,
+ 'id' => $this->getCustomerId(),
+ ]);
+ }
+
protected function _prepareCollection()
{
$tagId = Mage::registry('tagId');
@@ -99,23 +118,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/tag/edit', [
- 'tag_id' => $row->getTagId(),
- 'customer_id' => $this->getCustomerId(),
- ]);
- }
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/customer/tagGrid', [
- '_current' => true,
- 'id' => $this->getCustomerId(),
- ]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Tags.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Tags.php
index ddba5fdfc24..c4820fb9afe 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Tags.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Tags.php
@@ -29,6 +29,11 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/index', ['_current' => true]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('customer/customer_collection')
@@ -97,9 +102,4 @@ protected function _prepareColumns()
$this->addExportType('*/*/exportXml', Mage::helper('customer')->__('Excel XML'));
return parent::_prepareColumns();
}
-
- public function getGridUrl()
- {
- return $this->getUrl('*/*/index', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Cart.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Cart.php
index 959baaba179..682bb113143 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Cart.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Cart.php
@@ -37,6 +37,27 @@ public function __construct()
$this->setEmptyText(Mage::helper('customer')->__('There are no items in customer\'s shopping cart at the moment'));
}
+ /**
+ * Retrieve row url
+ *
+ * @param Mage_Sales_Model_Quote_Item $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
+ }
+
+ /**
+ * Check weather header should be shown
+ *
+ * @return bool
+ */
+ public function getHeadersVisibility()
+ {
+ return ($this->getCollection()->getSize() > 0);
+ }
+
/**
* @inheritDoc
* @throws Mage_Core_Exception
@@ -94,25 +115,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Retrieve row url
- *
- * @param Mage_Sales_Model_Quote_Item $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
- }
-
- /**
- * Check weather header should be shown
- *
- * @return bool
- */
- public function getHeadersVisibility()
- {
- return ($this->getCollection()->getSize() > 0);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Grid/Renderer/Item.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Grid/Renderer/Item.php
index 57e44005a24..ba32254148d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Grid/Renderer/Item.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Grid/Renderer/Item.php
@@ -22,6 +22,26 @@
*/
class Mage_Adminhtml_Block_Customer_Edit_Tab_View_Grid_Renderer_Item extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
+ /**
+ * Returns product associated with this block
+ *
+ * @return Mage_Catalog_Model_Product
+ */
+ public function getProduct()
+ {
+ return $this->getItem()->getProduct();
+ }
+
+ /**
+ * Renders item product name and its configuration
+ *
+ * @return string
+ */
+ public function render(Varien_Object $item)
+ {
+ $this->setItem($item);
+ return $this->toHtml();
+ }
/**
* Constructor to set default template
*
@@ -67,16 +87,6 @@ protected function _getProductHelper($product)
return $helper;
}
- /**
- * Returns product associated with this block
- *
- * @return Mage_Catalog_Model_Product
- */
- public function getProduct()
- {
- return $this->getItem()->getProduct();
- }
-
/**
* Returns list of options and their values for product configuration
*
@@ -103,15 +113,4 @@ protected function getFormattedOptionValue($option)
];
return Mage::helper('catalog/product_configuration')->getFormattedOptionValue($option, $params);
}
-
- /**
- * Renders item product name and its configuration
- *
- * @return string
- */
- public function render(Varien_Object $item)
- {
- $this->setItem($item);
- return $this->toHtml();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Orders.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Orders.php
index da206b22640..431a8fc05f4 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Orders.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Orders.php
@@ -36,6 +36,23 @@ public function __construct()
$this->setFilterVisibility(false);
}
+ /**
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getHeadersVisibility()
+ {
+ return ($this->getCollection()->getSize() > 0);
+ }
+
protected function _preparePage()
{
$this->getCollection()
@@ -107,21 +124,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
- }
-
- /**
- * @return bool
- */
- public function getHeadersVisibility()
- {
- return ($this->getCollection()->getSize() > 0);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Wishlist.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Wishlist.php
index 401ddb53c45..ac43093802e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Wishlist.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Wishlist.php
@@ -32,6 +32,27 @@ public function __construct()
$this->setEmptyText(Mage::helper('customer')->__("There are no items in customer's wishlist at the moment"));
}
+ /**
+ * Get headers visibility
+ *
+ * @return bool
+ */
+ public function getHeadersVisibility()
+ {
+ return ($this->getCollection()->getSize() > 0);
+ }
+
+ /**
+ * Get row url
+ *
+ * @param Mage_Wishlist_Model_Item $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
+ }
+
/**
* Prepare collection
*
@@ -92,25 +113,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Get headers visibility
- *
- * @return bool
- */
- public function getHeadersVisibility()
- {
- return ($this->getCollection()->getSize() > 0);
- }
-
- /**
- * Get row url
- *
- * @param Mage_Wishlist_Model_Item $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Wishlist.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Wishlist.php
index 58811c4c9fd..05def6c654c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Wishlist.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Wishlist.php
@@ -59,6 +59,61 @@ public function __construct()
$this->addProductConfigurationHelper('default', 'catalog/product_configuration');
}
+ /**
+ * Retrieve Grid URL
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/wishlist', ['_current' => true]);
+ }
+
+ /**
+ * Retrieve Grid Parent Block HTML
+ *
+ * @return string
+ */
+ public function getGridParentHtml()
+ {
+ $templateName = Mage::getDesign()->getTemplateFilename($this->_parentTemplate, ['_relative' => true]);
+ return $this->fetchView($templateName);
+ }
+
+ /**
+ * Retrieve Row click URL
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
+ }
+
+ /**
+ * Adds product type helper depended on product type (used to show options in item cell)
+ *
+ * @param string $productType
+ * @param string $helperName
+ *
+ * @return $this
+ */
+ public function addProductConfigurationHelper($productType, $helperName)
+ {
+ $this->_productHelpers[$productType] = $helperName;
+ return $this;
+ }
+
+ /**
+ * Returns array of product configuration helpers
+ *
+ * @return array
+ */
+ public function getProductConfigurationHelpers()
+ {
+ return $this->_productHelpers;
+ }
+
/**
* Retrieve current customer object
*
@@ -164,16 +219,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Retrieve Grid URL
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/wishlist', ['_current' => true]);
- }
-
/**
* Add column filter to collection
*
@@ -224,49 +269,4 @@ protected function _setCollectionOrder($column)
}
return $this;
}
-
- /**
- * Retrieve Grid Parent Block HTML
- *
- * @return string
- */
- public function getGridParentHtml()
- {
- $templateName = Mage::getDesign()->getTemplateFilename($this->_parentTemplate, ['_relative' => true]);
- return $this->fetchView($templateName);
- }
-
- /**
- * Retrieve Row click URL
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
- }
-
- /**
- * Adds product type helper depended on product type (used to show options in item cell)
- *
- * @param string $productType
- * @param string $helperName
- *
- * @return $this
- */
- public function addProductConfigurationHelper($productType, $helperName)
- {
- $this->_productHelpers[$productType] = $helperName;
- return $this;
- }
-
- /**
- * Returns array of product configuration helpers
- *
- * @return array
- */
- public function getProductConfigurationHelpers()
- {
- return $this->_productHelpers;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Form/Element/File.php b/app/code/core/Mage/Adminhtml/Block/Customer/Form/Element/File.php
index 5e01121321a..e307fa3fb74 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Form/Element/File.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Form/Element/File.php
@@ -58,6 +58,26 @@ public function getElementHtml()
return $this->_getPreviewHtml() . $element . $this->_getDeleteCheckboxHtml();
}
+ /**
+ * Return escaped value
+ *
+ * @param string|null $index
+ * @return false|string
+ */
+ public function getEscapedValue($index = null)
+ {
+ $value = $this->getValue();
+ if (is_array($value)) {
+ return false;
+ }
+
+ if (is_null($index)) {
+ $index = 'value';
+ }
+
+ return parent::getEscapedValue($index);
+ }
+
/**
* Return Delete File CheckBox HTML
*
@@ -178,24 +198,4 @@ protected function _drawElementHtml($element, array $attributes, $closed = true)
return sprintf('<%s %s%s>', $element, implode(' ', $parts), $closed ? ' /' : '');
}
-
- /**
- * Return escaped value
- *
- * @param string|null $index
- * @return false|string
- */
- public function getEscapedValue($index = null)
- {
- $value = $this->getValue();
- if (is_array($value)) {
- return false;
- }
-
- if (is_null($index)) {
- $index = 'value';
- }
-
- return parent::getEscapedValue($index);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Grid.php b/app/code/core/Mage/Adminhtml/Block/Customer/Grid.php
index 74c4ae8cfd5..0e1fda83f29 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Grid.php
@@ -36,6 +36,23 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
+ /**
+ * @param Mage_Customer_Model_Customer $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
/**
* @inheritDoc
* @throws Mage_Core_Exception
@@ -203,21 +220,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
-
- /**
- * @param Mage_Customer_Model_Customer $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Group/Grid.php b/app/code/core/Mage/Adminhtml/Block/Customer/Group/Grid.php
index d293915900d..73287d2b242 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Group/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Group/Grid.php
@@ -31,6 +31,11 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
/**
* Init customer groups collection
* @inheritDoc
@@ -69,9 +74,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Online.php b/app/code/core/Mage/Adminhtml/Block/Customer/Online.php
index ae245fbb83a..3f27a759366 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Online.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Online.php
@@ -34,14 +34,14 @@ public function _beforeToHtml()
return parent::_beforeToHtml();
}
- protected function _prepareLayout()
+ public function getFilterFormHtml()
{
- $this->setChild('filterForm', $this->getLayout()->createBlock('adminhtml/customer_online_filter'));
- return parent::_prepareLayout();
+ return $this->getChild('filterForm')->toHtml();
}
- public function getFilterFormHtml()
+ protected function _prepareLayout()
{
- return $this->getChild('filterForm')->toHtml();
+ $this->setChild('filterForm', $this->getLayout()->createBlock('adminhtml/customer_online_filter'));
+ return parent::_prepareLayout();
}
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Online/Grid.php b/app/code/core/Mage/Adminhtml/Block/Customer/Online/Grid.php
index 41dc00ee9c8..b67aadfd475 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Online/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Online/Grid.php
@@ -35,6 +35,18 @@ public function __construct()
$this->setDefaultDir('DESC');
}
+ /**
+ * Retrieve Row URL
+ *
+ * @param Mage_Core_Model_Abstract $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return (Mage::getSingleton('admin/session')->isAllowed('customer/manage') && $row->getCustomerId())
+ ? $this->getUrl('*/customer/edit', ['id' => $row->getCustomerId()]) : '';
+ }
+
/**
* Prepare collection for grid
*
@@ -141,16 +153,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Retrieve Row URL
- *
- * @param Mage_Core_Model_Abstract $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return (Mage::getSingleton('admin/session')->isAllowed('customer/manage') && $row->getCustomerId())
- ? $this->getUrl('*/customer/edit', ['id' => $row->getCustomerId()]) : '';
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Sales/Order/Address/Form/Renderer/Vat.php b/app/code/core/Mage/Adminhtml/Block/Customer/Sales/Order/Address/Form/Renderer/Vat.php
index 9a9bbe8f2f9..9ba74b53376 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Sales/Order/Address/Form/Renderer/Vat.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Sales/Order/Address/Form/Renderer/Vat.php
@@ -29,14 +29,6 @@ class Mage_Adminhtml_Block_Customer_Sales_Order_Address_Form_Renderer_Vat extend
*/
protected $_validateButton = null;
- /**
- * Set custom template for 'VAT number'
- */
- protected function _construct()
- {
- $this->setTemplate('customer/sales/order/create/address/form/renderer/vat.phtml');
- }
-
/**
* Retrieve validate button block
*
@@ -86,4 +78,12 @@ public function getValidateButton()
}
return $this->_validateButton;
}
+
+ /**
+ * Set custom template for 'VAT number'
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('customer/sales/order/create/address/form/renderer/vat.phtml');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/System/Config/Validatevat.php b/app/code/core/Mage/Adminhtml/Block/Customer/System/Config/Validatevat.php
index eced84bfc3b..b5fb05f9158 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/System/Config/Validatevat.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/System/Config/Validatevat.php
@@ -22,6 +22,16 @@
*/
class Mage_Adminhtml_Block_Customer_System_Config_Validatevat extends Mage_Adminhtml_Block_System_Config_Form_Field
{
+ /**
+ * Unset some non-related element parameters
+ *
+ * @return string
+ */
+ public function render(Varien_Data_Form_Element_Abstract $element)
+ {
+ $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
+ return parent::render($element);
+ }
/**
* Set template to itself
*
@@ -36,17 +46,6 @@ protected function _prepareLayout()
return $this;
}
- /**
- * Unset some non-related element parameters
- *
- * @return string
- */
- public function render(Varien_Data_Form_Element_Abstract $element)
- {
- $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
- return parent::render($element);
- }
-
/**
* Get the button and scripts contents
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard.php b/app/code/core/Mage/Adminhtml/Block/Dashboard.php
index 73a86b54ad5..62aaf4e0d30 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard.php
@@ -20,12 +20,11 @@
*/
class Mage_Adminhtml_Block_Dashboard extends Mage_Adminhtml_Block_Template
{
- protected $_locale;
-
/**
* Location of the "Enable Chart" config param
*/
public const XML_PATH_ENABLE_CHARTS = 'admin/dashboard/enable_charts';
+ protected $_locale;
public function __construct()
{
@@ -33,6 +32,14 @@ public function __construct()
$this->setTemplate('dashboard/index.phtml');
}
+ public function getSwitchUrl()
+ {
+ if ($url = $this->getData('switch_url')) {
+ return $url;
+ }
+ return $this->getUrl('*/*/*', ['_current' => true, 'period' => null]);
+ }
+
protected function _prepareLayout()
{
$this->setChild(
@@ -76,12 +83,4 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
-
- public function getSwitchUrl()
- {
- if ($url = $this->getData('switch_url')) {
- return $url;
- }
- return $this->getUrl('*/*/*', ['_current' => true, 'period' => null]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Bar.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Bar.php
index aad136187a1..2795403894d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Bar.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Bar.php
@@ -30,17 +30,6 @@ class Mage_Adminhtml_Block_Dashboard_Bar extends Mage_Adminhtml_Block_Dashboard_
*/
protected $_currency;
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('dashboard/bar.phtml');
- }
-
- protected function getTotals()
- {
- return $this->_totals;
- }
-
public function addTotal($label, $value, $isQuantity = false)
{
if (!$isQuantity) {
@@ -98,4 +87,15 @@ public function getCurrency()
return $this->_currentCurrencyCode;
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('dashboard/bar.phtml');
+ }
+
+ protected function getTotals()
+ {
+ return $this->_totals;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Graph.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Graph.php
index 108de96bb23..64360b43630 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Graph.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Graph.php
@@ -111,16 +111,6 @@ public function __construct()
$this->setTemplate('dashboard/graph.phtml');
}
- /**
- * Get tab template
- *
- * @return string
- */
- protected function _getTabTemplate()
- {
- return 'dashboard/graph.phtml';
- }
-
/**
* Set data rows
*
@@ -403,29 +393,6 @@ public function getChartUrl($directUrl = true)
return $this->getUrl('*/*/tunnel', ['_query' => $params]);
}
- /**
- * Get rows data
- *
- * @param array $attributes
- * @param bool $single
- * @return array
- */
- protected function getRowsData($attributes, $single = false)
- {
- $items = $this->getCollection()->getItems();
- $options = [];
- foreach ($items as $item) {
- if ($single) {
- $options[] = max(0, $item->getData($attributes));
- } else {
- foreach ((array) $attributes as $attr) {
- $options[$attr][] = max(0, $item->getData($attr));
- }
- }
- }
- return $options;
- }
-
/**
* Set axis labels
*
@@ -457,6 +424,39 @@ public function getHtmlId()
return $this->_htmlId;
}
+ /**
+ * Get tab template
+ *
+ * @return string
+ */
+ protected function _getTabTemplate()
+ {
+ return 'dashboard/graph.phtml';
+ }
+
+ /**
+ * Get rows data
+ *
+ * @param array $attributes
+ * @param bool $single
+ * @return array
+ */
+ protected function getRowsData($attributes, $single = false)
+ {
+ $items = $this->getCollection()->getItems();
+ $options = [];
+ foreach ($items as $item) {
+ if ($single) {
+ $options[] = max(0, $item->getData($attributes));
+ } else {
+ foreach ((array) $attributes as $attr) {
+ $options[$attr][] = max(0, $item->getData($attr));
+ }
+ }
+ }
+ return $options;
+ }
+
/**
* Return pow
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Orders/Grid.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Orders/Grid.php
index 17fbb1d79d9..aa9c6e46ea9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Orders/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Orders/Grid.php
@@ -28,6 +28,15 @@ public function __construct()
$this->setId('lastOrdersGrid');
}
+ /**
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
if (!$this->isModuleEnabled('Mage_Reports')) {
@@ -102,13 +111,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Searches/Last.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Searches/Last.php
index c12440aaeb4..4b09bf8b18e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Searches/Last.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Searches/Last.php
@@ -30,6 +30,11 @@ public function __construct()
$this->setId('lastSearchGrid');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_search/edit', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
if (!$this->isModuleEnabled('Mage_CatalogSearch')) {
@@ -82,9 +87,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_search/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Searches/Top.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Searches/Top.php
index a2e67fe7114..ea447f8f682 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Searches/Top.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Searches/Top.php
@@ -30,6 +30,11 @@ public function __construct()
$this->setId('topSearchGrid');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_search/edit', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
if (!$this->isModuleEnabled('Mage_CatalogSearch')) {
@@ -84,9 +89,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_search/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Customers/Most.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Customers/Most.php
index 12cad5b7f23..d3e7df30ebf 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Customers/Most.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Customers/Most.php
@@ -28,6 +28,11 @@ public function __construct()
$this->setId('customersMostGrid');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/customer/edit', ['id' => $row->getCustomerId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('reports/order_collection');
@@ -95,9 +100,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/customer/edit', ['id' => $row->getCustomerId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Customers/Newest.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Customers/Newest.php
index 53754202529..be2c51f78b3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Customers/Newest.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Customers/Newest.php
@@ -28,6 +28,11 @@ public function __construct()
$this->setId('customersNewestGrid');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/customer/edit', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('reports/customer_collection')
@@ -93,9 +98,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/customer/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products/Ordered.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products/Ordered.php
index 4a55b0efa96..aedfe7f8213 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products/Ordered.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products/Ordered.php
@@ -28,6 +28,30 @@ public function __construct()
$this->setId('productsOrderedGrid');
}
+ /**
+ * Returns row url to show in admin dashboard
+ * $row is bestseller row wrapped in Product model
+ *
+ * @param Mage_Catalog_Model_Product $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ // getId() would return id of bestseller row, and product id we get by getProductId()
+ $productId = $row->getProductId();
+
+ // No url is possible for non-existing products
+ if (!$productId) {
+ return '';
+ }
+
+ $params = ['id' => $productId];
+ if ($this->getRequest()->getParam('store')) {
+ $params['store'] = $this->getRequest()->getParam('store');
+ }
+ return $this->getUrl('*/catalog_product/edit', $params);
+ }
+
protected function _prepareCollection()
{
if (!$this->isModuleEnabled('Mage_Sales')) {
@@ -83,28 +107,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Returns row url to show in admin dashboard
- * $row is bestseller row wrapped in Product model
- *
- * @param Mage_Catalog_Model_Product $row
- * @return string
- */
- public function getRowUrl($row)
- {
- // getId() would return id of bestseller row, and product id we get by getProductId()
- $productId = $row->getProductId();
-
- // No url is possible for non-existing products
- if (!$productId) {
- return '';
- }
-
- $params = ['id' => $productId];
- if ($this->getRequest()->getParam('store')) {
- $params['store'] = $this->getRequest()->getParam('store');
- }
- return $this->getUrl('*/catalog_product/edit', $params);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products/Viewed.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products/Viewed.php
index d7854276e48..57d647bfb7b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products/Viewed.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products/Viewed.php
@@ -28,6 +28,15 @@ public function __construct()
$this->setId('productsReviewedGrid');
}
+ public function getRowUrl($row)
+ {
+ $params = ['id' => $row->getId()];
+ if ($this->getRequest()->getParam('store')) {
+ $params['store'] = $this->getRequest()->getParam('store');
+ }
+ return $this->getUrl('*/catalog_product/edit', $params);
+ }
+
protected function _prepareCollection()
{
if ($this->getParam('website')) {
@@ -77,13 +86,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- $params = ['id' => $row->getId()];
- if ($this->getRequest()->getParam('store')) {
- $params['store'] = $this->getRequest()->getParam('store');
- }
- return $this->getUrl('*/catalog_product/edit', $params);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Newsletter/Problem.php b/app/code/core/Mage/Adminhtml/Block/Newsletter/Problem.php
index 56de0be7d0b..137023d82c6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Newsletter/Problem.php
+++ b/app/code/core/Mage/Adminhtml/Block/Newsletter/Problem.php
@@ -31,6 +31,21 @@ public function __construct()
->addQueueInfo();
}
+ public function getUnsubscribeButtonHtml()
+ {
+ return $this->getChildHtml('unsubscribeButton');
+ }
+
+ public function getDeleteButtonHtml()
+ {
+ return $this->getChildHtml('deleteButton');
+ }
+
+ public function getShowButtons()
+ {
+ return Mage::getResourceSingleton('newsletter/problem_collection')->getSize() > 0;
+ }
+
protected function _prepareLayout()
{
$this->setChild(
@@ -61,19 +76,4 @@ protected function _prepareLayout()
);
return parent::_prepareLayout();
}
-
- public function getUnsubscribeButtonHtml()
- {
- return $this->getChildHtml('unsubscribeButton');
- }
-
- public function getDeleteButtonHtml()
- {
- return $this->getChildHtml('deleteButton');
- }
-
- public function getShowButtons()
- {
- return Mage::getResourceSingleton('newsletter/problem_collection')->getSize() > 0;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Newsletter/Queue/Edit.php b/app/code/core/Mage/Adminhtml/Block/Newsletter/Queue/Edit.php
index b8ed29ea1bd..78be99d3770 100644
--- a/app/code/core/Mage/Adminhtml/Block/Newsletter/Queue/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Newsletter/Queue/Edit.php
@@ -22,18 +22,6 @@
*/
class Mage_Adminhtml_Block_Newsletter_Queue_Edit extends Mage_Adminhtml_Block_Template
{
- /**
- * Check for template Id in request
- */
- protected function _construct()
- {
- parent::_construct();
- $templateId = $this->getRequest()->getParam('template_id');
- if ($templateId) {
- $this->setTemplateId($templateId);
- }
- }
-
/**
* Retrieve current Newsletter Queue Object
*
@@ -44,21 +32,6 @@ public function getQueue()
return Mage::registry('current_queue');
}
- /**
- * @inheritDoc
- */
- protected function _beforeToHtml()
- {
- $this->setTemplate('newsletter/queue/edit.phtml');
-
- $this->setChild(
- 'form',
- $this->getLayout()->createBlock('adminhtml/newsletter_queue_edit_form', 'form'),
- );
-
- return parent::_beforeToHtml();
- }
-
/**
* @return string
* @throws Exception
@@ -73,72 +46,6 @@ public function getSaveUrl()
return $this->getUrl('*/*/save', $params);
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- // Load Wysiwyg on demand and Prepare layout
- if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
- $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
- }
-
- $this->setChild(
- 'preview_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Preview Template'),
- 'onclick' => 'queueControl.preview();',
- 'class' => 'task',
- ]),
- );
-
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Save Newsletter'),
- 'onclick' => 'queueControl.save()',
- 'class' => 'save',
- ]),
- );
-
- $this->setChild(
- 'save_and_resume',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Save and Resume'),
- 'onclick' => 'queueControl.resume()',
- 'class' => 'save',
- ]),
- );
-
- $this->setChild(
- 'reset_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Reset'),
- 'onclick' => 'window.location = window.location',
- ]),
- );
-
- $this->setChild(
- 'back_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('newsletter')->__('Back'),
- 'onclick' => "window.location.href = '" . $this->getUrl((
- $this->getTemplateId() ? '*/newsletter_template/' : '*/*'
- )) . "'",
- 'class' => 'back',
- ],
- ),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* Return preview action url for form
*
@@ -213,52 +120,144 @@ public function getIsPreview()
}
/**
- * Getter for single store mode check
+ * Getter for check is this newsletter the plain text.
*
* @return bool
*/
- protected function isSingleStoreMode()
+ public function getIsTextType()
{
- return Mage::app()->isSingleStoreMode();
+ return $this->getQueue()->isPlain();
}
/**
- * Getter for id of current store (the only one in single-store mode and current in multi-stores mode)
+ * Getter for availability resume action
*
- * @return int
+ * @return bool
*/
- protected function getStoreId()
+ public function getCanResume()
{
- return Mage::app()->getStore(true)->getId();
+ return $this->getQueue()->getQueueStatus() == Mage_Newsletter_Model_Queue::STATUS_PAUSE;
}
/**
- * Getter for check is this newsletter the plain text.
+ * Getter for header text
*
- * @return bool
+ * @return string
*/
- public function getIsTextType()
+ public function getHeaderText()
{
- return $this->getQueue()->isPlain();
+ return ($this->getIsPreview() ? Mage::helper('newsletter')->__('View Newsletter') : Mage::helper('newsletter')->__('Edit Newsletter'));
+ }
+ /**
+ * Check for template Id in request
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $templateId = $this->getRequest()->getParam('template_id');
+ if ($templateId) {
+ $this->setTemplateId($templateId);
+ }
}
/**
- * Getter for availability resume action
+ * @inheritDoc
+ */
+ protected function _beforeToHtml()
+ {
+ $this->setTemplate('newsletter/queue/edit.phtml');
+
+ $this->setChild(
+ 'form',
+ $this->getLayout()->createBlock('adminhtml/newsletter_queue_edit_form', 'form'),
+ );
+
+ return parent::_beforeToHtml();
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ // Load Wysiwyg on demand and Prepare layout
+ if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
+ $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
+ }
+
+ $this->setChild(
+ 'preview_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Preview Template'),
+ 'onclick' => 'queueControl.preview();',
+ 'class' => 'task',
+ ]),
+ );
+
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Save Newsletter'),
+ 'onclick' => 'queueControl.save()',
+ 'class' => 'save',
+ ]),
+ );
+
+ $this->setChild(
+ 'save_and_resume',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Save and Resume'),
+ 'onclick' => 'queueControl.resume()',
+ 'class' => 'save',
+ ]),
+ );
+
+ $this->setChild(
+ 'reset_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Reset'),
+ 'onclick' => 'window.location = window.location',
+ ]),
+ );
+
+ $this->setChild(
+ 'back_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('newsletter')->__('Back'),
+ 'onclick' => "window.location.href = '" . $this->getUrl((
+ $this->getTemplateId() ? '*/newsletter_template/' : '*/*'
+ )) . "'",
+ 'class' => 'back',
+ ],
+ ),
+ );
+
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Getter for single store mode check
*
* @return bool
*/
- public function getCanResume()
+ protected function isSingleStoreMode()
{
- return $this->getQueue()->getQueueStatus() == Mage_Newsletter_Model_Queue::STATUS_PAUSE;
+ return Mage::app()->isSingleStoreMode();
}
/**
- * Getter for header text
+ * Getter for id of current store (the only one in single-store mode and current in multi-stores mode)
*
- * @return string
+ * @return int
*/
- public function getHeaderText()
+ protected function getStoreId()
{
- return ($this->getIsPreview() ? Mage::helper('newsletter')->__('View Newsletter') : Mage::helper('newsletter')->__('Edit Newsletter'));
+ return Mage::app()->getStore(true)->getId();
}
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Newsletter/Queue/Grid.php b/app/code/core/Mage/Adminhtml/Block/Newsletter/Queue/Grid.php
index 0c460c231c5..ec0fb8d42d8 100644
--- a/app/code/core/Mage/Adminhtml/Block/Newsletter/Queue/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Newsletter/Queue/Grid.php
@@ -32,6 +32,11 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('newsletter/queue_collection')
@@ -106,9 +111,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber.php b/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber.php
index 33fb0a541db..49159a8a81c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber.php
+++ b/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber.php
@@ -32,17 +32,6 @@ public function __construct()
$this->setTemplate('newsletter/subscriber/list.phtml');
}
- /**
- * Prepares block to render
- *
- * @return $this
- */
- protected function _beforeToHtml()
- {
- $this->setChild('grid', $this->getLayout()->createBlock('adminhtml/newsletter_subscriber_grid', 'grid'));
- return parent::_beforeToHtml();
- }
-
/**
* Return queue collection with loaded neversent queues
*
@@ -74,4 +63,15 @@ public function getQueueAsOptions()
{
return $this->getQueueCollection()->toOptionArray();
}
+
+ /**
+ * Prepares block to render
+ *
+ * @return $this
+ */
+ protected function _beforeToHtml()
+ {
+ $this->setChild('grid', $this->getLayout()->createBlock('adminhtml/newsletter_subscriber_grid', 'grid'));
+ return parent::_beforeToHtml();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber/Grid/Filter/Website.php b/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber/Grid/Filter/Website.php
index 3e2080f9ca5..2aaf8c0eac3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber/Grid/Filter/Website.php
+++ b/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber/Grid/Filter/Website.php
@@ -27,16 +27,6 @@ class Mage_Adminhtml_Block_Newsletter_Subscriber_Grid_Filter_Website extends Mag
*/
protected $_websiteCollection = null;
- /**
- * @return array[]
- */
- protected function _getOptions()
- {
- $result = $this->getCollection()->toOptionArray();
- array_unshift($result, ['label' => null, 'value' => null]);
- return $result;
- }
-
/**
* @return Mage_Core_Model_Resource_Website_Collection
* @throws Mage_Core_Exception
@@ -68,4 +58,14 @@ public function getCondition()
return ['in' => $website->getStoresIds(true)];
}
+
+ /**
+ * @return array[]
+ */
+ protected function _getOptions()
+ {
+ $result = $this->getCollection()->toOptionArray();
+ array_unshift($result, ['label' => null, 'value' => null]);
+ return $result;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Newsletter/Template.php b/app/code/core/Mage/Adminhtml/Block/Newsletter/Template.php
index 60f2cb2465b..b890bfa1655 100644
--- a/app/code/core/Mage/Adminhtml/Block/Newsletter/Template.php
+++ b/app/code/core/Mage/Adminhtml/Block/Newsletter/Template.php
@@ -28,15 +28,6 @@ public function __construct()
$this->setTemplate('newsletter/template/list.phtml');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild('grid', $this->getLayout()->createBlock('adminhtml/newsletter_template_grid', 'newsletter.template.grid'));
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -52,4 +43,13 @@ public function getHeaderText()
{
return Mage::helper('newsletter')->__('Newsletter Templates');
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild('grid', $this->getLayout()->createBlock('adminhtml/newsletter_template_grid', 'newsletter.template.grid'));
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Newsletter/Template/Edit.php b/app/code/core/Mage/Adminhtml/Block/Newsletter/Template/Edit.php
index 8ef89df2ed2..f26263e32c4 100644
--- a/app/code/core/Mage/Adminhtml/Block/Newsletter/Template/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Newsletter/Template/Edit.php
@@ -39,101 +39,6 @@ public function getModel()
return Mage::registry('_current_template');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- // Load Wysiwyg on demand and Prepare layout
- if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled() && ($block = $this->getLayout()->getBlock('head'))) {
- $block->setCanLoadTinyMce(true);
- }
-
- $this->setChild(
- 'back_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Back'),
- 'onclick' => "window.location.href = '" . $this->getUrl('*/*') . "'",
- 'class' => 'back',
- ]),
- );
-
- $this->setChild(
- 'reset_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Reset'),
- 'onclick' => 'window.location.href = window.location.href',
- ]),
- );
-
- $this->setChild(
- 'to_plain_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Convert to Plain Text'),
- 'onclick' => 'templateControl.stripTags();',
- 'id' => 'convert_button',
- 'class' => 'task',
- ]),
- );
-
- $this->setChild(
- 'to_html_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Return HTML Version'),
- 'onclick' => 'templateControl.unStripTags();',
- 'id' => 'convert_button_back',
- 'style' => 'display:none',
- 'class' => 'task',
- ]),
- );
-
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Save Template'),
- 'onclick' => 'templateControl.save();',
- 'class' => 'save',
- ]),
- );
-
- $this->setChild(
- 'save_as_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Save As'),
- 'onclick' => 'templateControl.saveAs();',
- 'class' => 'save',
- ]),
- );
-
- $this->setChild(
- 'preview_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Preview Template'),
- 'onclick' => 'templateControl.preview();',
- 'class' => 'task',
- ]),
- );
-
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('newsletter')->__('Delete Template'),
- 'onclick' => 'templateControl.deleteTemplate();',
- 'class' => 'delete',
- ]),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* Retrieve Back Button HTML
*
@@ -324,6 +229,101 @@ public function getSaveAsFlag()
return $this->getRequest()->getParam('_save_as_flag') ? '1' : '';
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ // Load Wysiwyg on demand and Prepare layout
+ if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled() && ($block = $this->getLayout()->getBlock('head'))) {
+ $block->setCanLoadTinyMce(true);
+ }
+
+ $this->setChild(
+ 'back_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Back'),
+ 'onclick' => "window.location.href = '" . $this->getUrl('*/*') . "'",
+ 'class' => 'back',
+ ]),
+ );
+
+ $this->setChild(
+ 'reset_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Reset'),
+ 'onclick' => 'window.location.href = window.location.href',
+ ]),
+ );
+
+ $this->setChild(
+ 'to_plain_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Convert to Plain Text'),
+ 'onclick' => 'templateControl.stripTags();',
+ 'id' => 'convert_button',
+ 'class' => 'task',
+ ]),
+ );
+
+ $this->setChild(
+ 'to_html_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Return HTML Version'),
+ 'onclick' => 'templateControl.unStripTags();',
+ 'id' => 'convert_button_back',
+ 'style' => 'display:none',
+ 'class' => 'task',
+ ]),
+ );
+
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Save Template'),
+ 'onclick' => 'templateControl.save();',
+ 'class' => 'save',
+ ]),
+ );
+
+ $this->setChild(
+ 'save_as_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Save As'),
+ 'onclick' => 'templateControl.saveAs();',
+ 'class' => 'save',
+ ]),
+ );
+
+ $this->setChild(
+ 'preview_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Preview Template'),
+ 'onclick' => 'templateControl.preview();',
+ 'class' => 'task',
+ ]),
+ );
+
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('newsletter')->__('Delete Template'),
+ 'onclick' => 'templateControl.deleteTemplate();',
+ 'class' => 'delete',
+ ]),
+ );
+
+ return parent::_prepareLayout();
+ }
+
/**
* Getter for single store mode check
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Newsletter/Template/Grid.php b/app/code/core/Mage/Adminhtml/Block/Newsletter/Template/Grid.php
index f7cfb06e3d4..b461bfc2adf 100644
--- a/app/code/core/Mage/Adminhtml/Block/Newsletter/Template/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Newsletter/Template/Grid.php
@@ -32,6 +32,11 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
protected function _construct()
{
$this->setEmptyText(Mage::helper('newsletter')->__('No Templates Found'));
@@ -124,9 +129,4 @@ protected function _prepareColumns()
return $this;
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Notification/Curl.php b/app/code/core/Mage/Adminhtml/Block/Notification/Curl.php
index 1596f2b06e4..5004280a23a 100644
--- a/app/code/core/Mage/Adminhtml/Block/Notification/Curl.php
+++ b/app/code/core/Mage/Adminhtml/Block/Notification/Curl.php
@@ -39,6 +39,20 @@ public function __construct()
$this->_curlVersion = curl_version();
}
+ /**
+ * Returns a message that should be displayed.
+ *
+ * @return string
+ */
+ public function getMessage()
+ {
+ return $this->helper('adminhtml')->__(
+ 'Your current version of cURL php5 module is %s, which can prevent services that require TLS v1.2 from working correctly. It is recommended to update your cURL php5 module to version %s or higher.',
+ $this->_curlVersion['version'],
+ $this::REQUIRED_CURL_VERSION,
+ );
+ }
+
/**
* Check cURL version and return true if system must show notification message.
*
@@ -56,20 +70,6 @@ protected function _canShow()
return $result;
}
- /**
- * Returns a message that should be displayed.
- *
- * @return string
- */
- public function getMessage()
- {
- return $this->helper('adminhtml')->__(
- 'Your current version of cURL php5 module is %s, which can prevent services that require TLS v1.2 from working correctly. It is recommended to update your cURL php5 module to version %s or higher.',
- $this->_curlVersion['version'],
- $this::REQUIRED_CURL_VERSION,
- );
- }
-
/**
* Prepare html output.
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Notification/Grid.php b/app/code/core/Mage/Adminhtml/Block/Notification/Grid.php
index 783b684b160..f4b4b1848ee 100644
--- a/app/code/core/Mage/Adminhtml/Block/Notification/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Notification/Grid.php
@@ -24,6 +24,22 @@
*/
class Mage_Adminhtml_Block_Notification_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
+ /**
+ * @param Mage_AdminNotification_Model_Inbox $row
+ * @return string
+ */
+ public function getRowClass(Varien_Object $row)
+ {
+ return $row->getIsRead() ? 'read' : 'unread';
+ }
+
+ /**
+ * @return false
+ */
+ public function getRowClickCallback()
+ {
+ return false;
+ }
protected function _construct()
{
$this->setSaveParametersInSession(true);
@@ -103,21 +119,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * @param Mage_AdminNotification_Model_Inbox $row
- * @return string
- */
- public function getRowClass(Varien_Object $row)
- {
- return $row->getIsRead() ? 'read' : 'unread';
- }
-
- /**
- * @return false
- */
- public function getRowClickCallback()
- {
- return false;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Notification/Toolbar.php b/app/code/core/Mage/Adminhtml/Block/Notification/Toolbar.php
index de15c9dd06b..031717661d1 100644
--- a/app/code/core/Mage/Adminhtml/Block/Notification/Toolbar.php
+++ b/app/code/core/Mage/Adminhtml/Block/Notification/Toolbar.php
@@ -22,22 +22,6 @@
*/
class Mage_Adminhtml_Block_Notification_Toolbar extends Mage_Adminhtml_Block_Template
{
- /**
- * Initialize Toolbar block
- *
- */
- protected function _construct() {}
-
- /**
- * Retrieve helper
- *
- * @return Mage_AdminNotification_Helper_Data
- */
- protected function _getHelper()
- {
- return Mage::helper('adminnotification');
- }
-
/**
* Check is show toolbar
*
@@ -150,4 +134,19 @@ public function isMessageWindowAvailable()
}
return false;
}
+ /**
+ * Initialize Toolbar block
+ *
+ */
+ protected function _construct() {}
+
+ /**
+ * Retrieve helper
+ *
+ * @return Mage_AdminNotification_Helper_Data
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('adminnotification');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Notification/Window.php b/app/code/core/Mage/Adminhtml/Block/Notification/Window.php
index 4f00b756d3a..2cd3f2c71b9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Notification/Window.php
+++ b/app/code/core/Mage/Adminhtml/Block/Notification/Window.php
@@ -39,43 +39,6 @@ class Mage_Adminhtml_Block_Notification_Window extends Mage_Adminhtml_Block_Noti
*/
protected $_available = null;
- /**
- * Initialize block window
- */
- protected function _construct()
- {
- parent::_construct();
-
- $this->setHeaderText($this->escapeHtml($this->__('Incoming Message')));
- $this->setCloseText($this->escapeHtml($this->__('close')));
- $this->setReadDetailsText($this->escapeHtml($this->__('Read details')));
- $this->setNoticeText($this->escapeHtml($this->__('NOTICE')));
- $this->setMinorText($this->escapeHtml($this->__('MINOR')));
- $this->setMajorText($this->escapeHtml($this->__('MAJOR')));
- $this->setCriticalText($this->escapeHtml($this->__('CRITICAL')));
-
- $this->setNoticeMessageText($this->escapeHtml($this->getLastNotice()->getTitle()));
- $this->setNoticeMessageUrl($this->escapeUrl($this->getLastNotice()->getUrl()));
-
- switch ($this->getLastNotice()->getSeverity()) {
- default:
- case Mage_AdminNotification_Model_Inbox::SEVERITY_NOTICE:
- $severity = 'SEVERITY_NOTICE';
- break;
- case Mage_AdminNotification_Model_Inbox::SEVERITY_MINOR:
- $severity = 'SEVERITY_MINOR';
- break;
- case Mage_AdminNotification_Model_Inbox::SEVERITY_MAJOR:
- $severity = 'SEVERITY_MAJOR';
- break;
- case Mage_AdminNotification_Model_Inbox::SEVERITY_CRITICAL:
- $severity = 'SEVERITY_CRITICAL';
- break;
- }
-
- $this->setNoticeSeverity($severity);
- }
-
/**
* Can we show notification window
*
@@ -159,6 +122,43 @@ public function getSeverityText()
return strtolower(str_replace('SEVERITY_', '', $this->getNoticeSeverity()));
}
+ /**
+ * Initialize block window
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+
+ $this->setHeaderText($this->escapeHtml($this->__('Incoming Message')));
+ $this->setCloseText($this->escapeHtml($this->__('close')));
+ $this->setReadDetailsText($this->escapeHtml($this->__('Read details')));
+ $this->setNoticeText($this->escapeHtml($this->__('NOTICE')));
+ $this->setMinorText($this->escapeHtml($this->__('MINOR')));
+ $this->setMajorText($this->escapeHtml($this->__('MAJOR')));
+ $this->setCriticalText($this->escapeHtml($this->__('CRITICAL')));
+
+ $this->setNoticeMessageText($this->escapeHtml($this->getLastNotice()->getTitle()));
+ $this->setNoticeMessageUrl($this->escapeUrl($this->getLastNotice()->getUrl()));
+
+ switch ($this->getLastNotice()->getSeverity()) {
+ default:
+ case Mage_AdminNotification_Model_Inbox::SEVERITY_NOTICE:
+ $severity = 'SEVERITY_NOTICE';
+ break;
+ case Mage_AdminNotification_Model_Inbox::SEVERITY_MINOR:
+ $severity = 'SEVERITY_MINOR';
+ break;
+ case Mage_AdminNotification_Model_Inbox::SEVERITY_MAJOR:
+ $severity = 'SEVERITY_MAJOR';
+ break;
+ case Mage_AdminNotification_Model_Inbox::SEVERITY_CRITICAL:
+ $severity = 'SEVERITY_CRITICAL';
+ break;
+ }
+
+ $this->setNoticeSeverity($severity);
+ }
+
/**
* Check if current block allowed in ACL
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Page/Footer.php b/app/code/core/Mage/Adminhtml/Block/Page/Footer.php
index bb0f4957e46..9cf3fe6404c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Page/Footer.php
+++ b/app/code/core/Mage/Adminhtml/Block/Page/Footer.php
@@ -26,12 +26,6 @@ class Mage_Adminhtml_Block_Page_Footer extends Mage_Adminhtml_Block_Template
public const LOCALE_CACHE_KEY = 'footer_locale';
public const LOCALE_CACHE_TAG = 'adminhtml';
- protected function _construct()
- {
- $this->setTemplate('page/footer.phtml');
- $this->setShowProfiler(true);
- }
-
/**
* @return string
*/
@@ -139,4 +133,10 @@ public function getOpenMageProjectUrl(): string
{
return (string) $this->_getData('openmage_project_url');
}
+
+ protected function _construct()
+ {
+ $this->setTemplate('page/footer.phtml');
+ $this->setShowProfiler(true);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Page/Head.php b/app/code/core/Mage/Adminhtml/Block/Page/Head.php
index 65d04040146..92dd9291bcb 100644
--- a/app/code/core/Mage/Adminhtml/Block/Page/Head.php
+++ b/app/code/core/Mage/Adminhtml/Block/Page/Head.php
@@ -22,14 +22,6 @@
*/
class Mage_Adminhtml_Block_Page_Head extends Mage_Page_Block_Html_Head
{
- /**
- * @return string
- */
- protected function _getUrlModelClass()
- {
- return 'adminhtml/url';
- }
-
/**
* Retrieve Session Form Key
*
@@ -50,4 +42,11 @@ public function getLoadingTimeout()
{
return Mage::getStoreConfigAsInt('admin/design/loading_timeout');
}
+ /**
+ * @return string
+ */
+ protected function _getUrlModelClass()
+ {
+ return 'adminhtml/url';
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Page/Menu.php b/app/code/core/Mage/Adminhtml/Block/Page/Menu.php
index 7b6c531d7d8..7503f387ebc 100644
--- a/app/code/core/Mage/Adminhtml/Block/Page/Menu.php
+++ b/app/code/core/Mage/Adminhtml/Block/Page/Menu.php
@@ -34,18 +34,6 @@ class Mage_Adminhtml_Block_Page_Menu extends Mage_Adminhtml_Block_Template
*/
protected $_url;
- /**
- * Initialize template and cache settings
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('page/menu.phtml');
- $this->_url = Mage::getModel('adminhtml/url');
- $this->setCacheTags([self::CACHE_TAGS]);
- }
-
/**
* Retrieve cache lifetime
*
@@ -89,6 +77,52 @@ public function getMenuArray()
return $this->_buildMenuArray($parent);
}
+ /**
+ * Get menu level HTML code
+ *
+ * @param array $menu
+ * @param int $level
+ * @return string
+ */
+ public function getMenuLevel($menu, $level = 0)
+ {
+ $html = '
' . PHP_EOL;
+ foreach ($menu as $item) {
+ if ((empty($item['url']) || ($item['url'] == '#')) && empty($item['children'])) {
+ continue; // for example hide System/Tools when empty
+ }
+ $html .= '- '
+ . $this->escapeHtml($item['label']) . '' . PHP_EOL;
+ if (!empty($item['children'])) {
+ $html .= $this->getMenuLevel($item['children'], $level + 1);
+ }
+ $html .= '
' . PHP_EOL;
+ }
+
+ return $html . ('
' . PHP_EOL);
+ }
+
+ /**
+ * Initialize template and cache settings
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('page/menu.phtml');
+ $this->_url = Mage::getModel('adminhtml/url');
+ $this->setCacheTags([self::CACHE_TAGS]);
+ }
+
/**
* Retrieve Title value for menu node
*
@@ -249,40 +283,6 @@ protected function _callbackSecretKey($match)
. $this->_url->getSecretKey($match[1], $match[2]);
}
- /**
- * Get menu level HTML code
- *
- * @param array $menu
- * @param int $level
- * @return string
- */
- public function getMenuLevel($menu, $level = 0)
- {
- $html = '' . PHP_EOL;
- foreach ($menu as $item) {
- if ((empty($item['url']) || ($item['url'] == '#')) && empty($item['children'])) {
- continue; // for example hide System/Tools when empty
- }
- $html .= '- '
- . $this->escapeHtml($item['label']) . '' . PHP_EOL;
- if (!empty($item['children'])) {
- $html .= $this->getMenuLevel($item['children'], $level + 1);
- }
- $html .= '
' . PHP_EOL;
- }
-
- return $html . ('
' . PHP_EOL);
- }
-
/**
* Check is module output enabled
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Block/Grid.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Block/Grid.php
index 02e1e016e46..7ee04adc4b5 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Block/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Block/Grid.php
@@ -31,6 +31,23 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * @param Mage_Admin_Model_Block $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['block_id' => $row->getId()]);
+ }
+
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/blockGrid', []);
+ }
+
/**
* @return Mage_Adminhtml_Block_Widget_Grid
*/
@@ -68,21 +85,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * @param Mage_Admin_Model_Block $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['block_id' => $row->getId()]);
- }
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/blockGrid', []);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Buttons.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Buttons.php
index 00eed767092..45d981113c6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Buttons.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Buttons.php
@@ -26,6 +26,34 @@ public function __construct()
$this->setTemplate('permissions/userinfo.phtml');
}
+ public function getBackButtonHtml()
+ {
+ return $this->getChildHtml('backButton');
+ }
+
+ public function getResetButtonHtml()
+ {
+ return $this->getChildHtml('resetButton');
+ }
+
+ public function getSaveButtonHtml()
+ {
+ return $this->getChildHtml('saveButton');
+ }
+
+ public function getDeleteButtonHtml()
+ {
+ if ((int) $this->getRequest()->getParam('rid') == 0) {
+ return;
+ }
+ return $this->getChildHtml('deleteButton');
+ }
+
+ public function getUser()
+ {
+ return Mage::registry('user_data');
+ }
+
protected function _prepareLayout()
{
$this->setChild(
@@ -70,32 +98,4 @@ protected function _prepareLayout()
);
return parent::_prepareLayout();
}
-
- public function getBackButtonHtml()
- {
- return $this->getChildHtml('backButton');
- }
-
- public function getResetButtonHtml()
- {
- return $this->getChildHtml('resetButton');
- }
-
- public function getSaveButtonHtml()
- {
- return $this->getChildHtml('saveButton');
- }
-
- public function getDeleteButtonHtml()
- {
- if ((int) $this->getRequest()->getParam('rid') == 0) {
- return;
- }
- return $this->getChildHtml('deleteButton');
- }
-
- public function getUser()
- {
- return Mage::registry('user_data');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Edituser.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Edituser.php
index f93e970b8c1..26f3cc53208 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Edituser.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Edituser.php
@@ -27,6 +27,11 @@ public function __construct()
$this->setDestElementId('user_edit_form');
}
+ public function getUser()
+ {
+ return Mage::registry('user_data');
+ }
+
protected function _beforeToHtml()
{
$this->addTab('account', [
@@ -44,9 +49,4 @@ protected function _beforeToHtml()
}
return parent::_beforeToHtml();
}
-
- public function getUser()
- {
- return Mage::registry('user_data');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Grid/Role.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Grid/Role.php
index d6df41c1101..0bdc3d64d3b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Grid/Role.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Grid/Role.php
@@ -32,6 +32,16 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/roleGrid', ['_current' => true]);
+ }
+
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/editrole', ['rid' => $row->getRoleId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getModel('admin/roles')->getCollection();
@@ -56,14 +66,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getGridUrl()
- {
- return $this->getUrl('*/*/roleGrid', ['_current' => true]);
- }
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/editrole', ['rid' => $row->getRoleId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Grid/User.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Grid/User.php
index a261791c5fb..e2464aa8f4a 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Grid/User.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Grid/User.php
@@ -31,6 +31,11 @@ public function __construct()
$this->setDefaultDir('asc');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edituser', ['id' => $row->getUserId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getModel('permissions/users')->getCollection();
@@ -68,9 +73,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edituser', ['id' => $row->getUserId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/OrphanedResource/Grid.php b/app/code/core/Mage/Adminhtml/Block/Permissions/OrphanedResource/Grid.php
index 143a2dd87e2..4a06dfcc479 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/OrphanedResource/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/OrphanedResource/Grid.php
@@ -31,6 +31,11 @@ public function __construct()
$this->setDefaultDir('asc');
}
+ public function getRowUrl($row): string
+ {
+ return '';
+ }
+
/**
* @inheritdoc
*/
@@ -83,9 +88,4 @@ protected function _prepareMassaction()
return $this;
}
-
- public function getRowUrl($row): string
- {
- return '';
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Role/Grid/User.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Role/Grid/User.php
index 962bc53d342..0667ca9819b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Role/Grid/User.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Role/Grid/User.php
@@ -32,6 +32,12 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getGridUrl()
+ {
+ $roleId = $this->getRequest()->getParam('rid');
+ return $this->getUrl('*/*/editrolegrid', ['rid' => $roleId]);
+ }
+
protected function _addColumnFilterToCollection($column)
{
if ($column->getId() == 'in_role_users') {
@@ -133,12 +139,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- public function getGridUrl()
- {
- $roleId = $this->getRequest()->getParam('rid');
- return $this->getUrl('*/*/editrolegrid', ['rid' => $roleId]);
- }
-
protected function _getUsers($json = false)
{
if ($this->getRequest()->getParam('in_role_user') != '') {
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Tab/Rolesedit.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Tab/Rolesedit.php
index cd821660852..4e9c627fb53 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Tab/Rolesedit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Tab/Rolesedit.php
@@ -22,55 +22,6 @@
*/
class Mage_Adminhtml_Block_Permissions_Tab_Rolesedit extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
- /**
- * Retrieve an instance of the fallback helper
- * @return Mage_Admin_Helper_Rules_Fallback
- */
- protected function _getFallbackHelper()
- {
- return Mage::helper('admin/rules_fallback');
- }
-
- /**
- * Get tab label
- *
- * @return string
- */
- public function getTabLabel()
- {
- return Mage::helper('adminhtml')->__('Role Resources');
- }
-
- /**
- * Get tab title
- *
- * @return string
- */
- public function getTabTitle()
- {
- return $this->getTabLabel();
- }
-
- /**
- * Whether tab is available
- *
- * @return bool
- */
- public function canShowTab()
- {
- return true;
- }
-
- /**
- * Whether tab is visible
- *
- * @return bool
- */
- public function isHidden()
- {
- return false;
- }
-
/**
* Class constructor
*
@@ -117,6 +68,46 @@ public function __construct()
$this->setTemplate('permissions/rolesedit.phtml');
}
+ /**
+ * Get tab label
+ *
+ * @return string
+ */
+ public function getTabLabel()
+ {
+ return Mage::helper('adminhtml')->__('Role Resources');
+ }
+
+ /**
+ * Get tab title
+ *
+ * @return string
+ */
+ public function getTabTitle()
+ {
+ return $this->getTabLabel();
+ }
+
+ /**
+ * Whether tab is available
+ *
+ * @return bool
+ */
+ public function canShowTab()
+ {
+ return true;
+ }
+
+ /**
+ * Whether tab is visible
+ *
+ * @return bool
+ */
+ public function isHidden()
+ {
+ return false;
+ }
+
/**
* Check if everything is allowed
*
@@ -141,6 +132,14 @@ public function getResTreeJson()
return Mage::helper('core')->jsonEncode($rootArray['children'] ?? []);
}
+ /**
+ * Retrieve an instance of the fallback helper
+ * @return Mage_Admin_Helper_Rules_Fallback
+ */
+ protected function _getFallbackHelper()
+ {
+ return Mage::helper('admin/rules_fallback');
+ }
/**
* Compare two nodes of the Resource Tree
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/User/Edit/Tab/Roles.php b/app/code/core/Mage/Adminhtml/Block/Permissions/User/Edit/Tab/Roles.php
index f6b7eb5b1a9..87bb956285d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/User/Edit/Tab/Roles.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/User/Edit/Tab/Roles.php
@@ -31,6 +31,11 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/rolesGrid', ['user_id' => Mage::registry('permissions_user')->getUserId()]);
+ }
+
protected function _addColumnFilterToCollection($column)
{
if ($column->getId() == 'assigned_user_role') {
@@ -86,11 +91,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- public function getGridUrl()
- {
- return $this->getUrl('*/*/rolesGrid', ['user_id' => Mage::registry('permissions_user')->getUserId()]);
- }
-
protected function _getSelectedRoles($json = false)
{
if ($this->getRequest()->getParam('user_roles') != '') {
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/User/Grid.php b/app/code/core/Mage/Adminhtml/Block/Permissions/User/Grid.php
index 875fa0fe6ee..82af91a3120 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/User/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/User/Grid.php
@@ -31,6 +31,17 @@ public function __construct()
$this->setUseAjax(true);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['user_id' => $row->getId()]);
+ }
+
+ public function getGridUrl()
+ {
+ //$uid = $this->getRequest()->getParam('user_id');
+ return $this->getUrl('*/*/roleGrid', []);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('admin/user_collection');
@@ -78,15 +89,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['user_id' => $row->getId()]);
- }
-
- public function getGridUrl()
- {
- //$uid = $this->getRequest()->getParam('user_id');
- return $this->getUrl('*/*/roleGrid', []);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Grid.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Grid.php
index 31c3f96d210..c18830e2928 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Grid.php
@@ -31,6 +31,23 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * @param Mage_Admin_Model_Variable $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['variable_id' => $row->getId()]);
+ }
+
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/variableGrid', []);
+ }
+
/**
* @return Mage_Adminhtml_Block_Widget_Grid
*/
@@ -68,21 +85,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * @param Mage_Admin_Model_Variable $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['variable_id' => $row->getId()]);
- }
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/variableGrid', []);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Grid.php b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Grid.php
index 67f603ac549..0a566c4c028 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Grid.php
@@ -35,6 +35,18 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * Retrieve row click URL
+ *
+ * @param Mage_CatalogRule_Model_Rule $row
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getRuleId()]);
+ }
+
/**
* Add websites to catalog rules collection
* Set collection
@@ -115,16 +127,4 @@ protected function _prepareColumns()
parent::_prepareColumns();
return $this;
}
-
- /**
- * Retrieve row click URL
- *
- * @param Mage_CatalogRule_Model_Rule $row
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getRuleId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Form.php b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Form.php
index 4e25baae23a..666bf6a1d24 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Form.php
@@ -22,6 +22,15 @@
*/
class Mage_Adminhtml_Block_Promo_Quote_Edit_Tab_Coupons_Form extends Mage_Adminhtml_Block_Widget_Form
{
+ /**
+ * Retrieve URL to Generate Action
+ *
+ * @return string
+ */
+ public function getGenerateUrl()
+ {
+ return $this->getUrl('*/*/generate');
+ }
/**
* Prepare coupon codes generation parameters form
*
@@ -121,14 +130,4 @@ protected function _prepareForm()
return parent::_prepareForm();
}
-
- /**
- * Retrieve URL to Generate Action
- *
- * @return string
- */
- public function getGenerateUrl()
- {
- return $this->getUrl('*/*/generate');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Grid.php b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Grid.php
index 375b3bc1ff6..cc59c8715cc 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Grid.php
@@ -32,6 +32,24 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * Get grid url
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/couponsGrid', ['_current' => true]);
+ }
+
+ /**
+ * @inheritdoc
+ */
+ public function getRowUrl($row)
+ {
+ return '';
+ }
+
/**
* Prepare collection for grid
*
@@ -120,22 +138,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * Get grid url
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/couponsGrid', ['_current' => true]);
- }
-
- /**
- * @inheritdoc
- */
- public function getRowUrl($row)
- {
- return '';
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Grid.php b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Grid.php
index 1d60508f2c6..75a87c75cbf 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Grid.php
@@ -35,6 +35,18 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * Retrieve row click URL
+ *
+ * @param Varien_Object $row
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getRuleId()]);
+ }
+
/**
* Add websites to sales rules collection
* Set collection
@@ -137,16 +149,4 @@ protected function _prepareColumns()
parent::_prepareColumns();
return $this;
}
-
- /**
- * Retrieve row click URL
- *
- * @param Varien_Object $row
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getRuleId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser.php b/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser.php
index 7f030b56ac4..ca112252ea9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser.php
@@ -85,6 +85,16 @@ function (grid, event) {
';
}
+ /**
+ * Prepare grid URL
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/promo_quote/chooser', ['_current' => true]);
+ }
+
/**
* Prepare rules collection
*
@@ -158,14 +168,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Prepare grid URL
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/promo_quote/chooser', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser/Daterange.php b/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser/Daterange.php
index ca679414d85..316427264cb 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser/Daterange.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser/Daterange.php
@@ -44,42 +44,6 @@ class Mage_Adminhtml_Block_Promo_Widget_Chooser_Daterange extends Mage_Adminhtml
*/
protected $_rangeDelimiter = '...';
- /**
- * Render the chooser HTML
- * Target element should be set.
- *
- * @return string
- */
- protected function _toHtml()
- {
- if (empty($this->_targetElementId)) {
- return '';
- }
-
- $idSuffix = Mage::helper('core')->uniqHash();
- $form = new Varien_Data_Form();
- foreach ([
- 'from' => Mage::helper('adminhtml')->__('From'),
- 'to' => Mage::helper('adminhtml')->__('To')] as $key => $label
- ) {
- $id = "{$key}_{$idSuffix}";
- $element = new Varien_Data_Form_Element_Date([
- 'format' => Varien_Date::DATE_INTERNAL_FORMAT, // hardcode because hardcoded values delimiter
- 'label' => $label,
- 'image' => $this->getSkinUrl('images/grid-cal.gif'),
- 'onchange' => "dateTimeChoose_{$idSuffix}()", // won't work through Event.observe()
- 'value' => $this->_rangeValues[$key],
- ]);
- $element->setId($id);
- $form->addElement($element);
- }
- return $form->toHtml() . "";
- }
-
/**
* Target element ID setter
*
@@ -131,4 +95,40 @@ public function setRangeDelimiter($value)
$this->_rangeDelimiter = (string) $value;
return $this;
}
+
+ /**
+ * Render the chooser HTML
+ * Target element should be set.
+ *
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ if (empty($this->_targetElementId)) {
+ return '';
+ }
+
+ $idSuffix = Mage::helper('core')->uniqHash();
+ $form = new Varien_Data_Form();
+ foreach ([
+ 'from' => Mage::helper('adminhtml')->__('From'),
+ 'to' => Mage::helper('adminhtml')->__('To')] as $key => $label
+ ) {
+ $id = "{$key}_{$idSuffix}";
+ $element = new Varien_Data_Form_Element_Date([
+ 'format' => Varien_Date::DATE_INTERNAL_FORMAT, // hardcode because hardcoded values delimiter
+ 'label' => $label,
+ 'image' => $this->getSkinUrl('images/grid-cal.gif'),
+ 'onchange' => "dateTimeChoose_{$idSuffix}()", // won't work through Event.observe()
+ 'value' => $this->_rangeValues[$key],
+ ]);
+ $element->setId($id);
+ $form->addElement($element);
+ }
+ return $form->toHtml() . "";
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser/Sku.php b/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser/Sku.php
index 60969835410..92f00bdc3b4 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser/Sku.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Widget/Chooser/Sku.php
@@ -59,6 +59,18 @@ public function getStore()
return Mage::app()->getStore();
}
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/chooser', [
+ '_current' => true,
+ 'current_grid_id' => $this->getId(),
+ 'collapse' => null,
+ ]);
+ }
+
/**
* @param Mage_Adminhtml_Block_Widget_Grid_Column $column
* @return $this
@@ -162,18 +174,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/chooser', [
- '_current' => true,
- 'current_grid_id' => $this->getId(),
- 'collapse' => null,
- ]);
- }
-
/**
* @return array
* @throws Exception
diff --git a/app/code/core/Mage/Adminhtml/Block/Rating/Grid.php b/app/code/core/Mage/Adminhtml/Block/Rating/Grid.php
index 109bf93cf9a..7e7dbd47ed7 100644
--- a/app/code/core/Mage/Adminhtml/Block/Rating/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Rating/Grid.php
@@ -29,6 +29,11 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getModel('rating/rating')
@@ -66,9 +71,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Grid.php
index d90c497488a..baadf3654f7 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Grid.php
@@ -72,148 +72,6 @@ public function __construct()
$this->setCountTotals(true);
}
- /**
- * @return $this
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'store_switcher',
- $this->getLayout()->createBlock('adminhtml/store_switcher')
- ->setUseConfirm(false)
- ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
- ->setTemplate('report/store/switcher.phtml'),
- );
-
- $this->setChild(
- 'refresh_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('adminhtml')->__('Refresh'),
- 'onclick' => $this->getRefreshButtonCallback(),
- 'class' => 'task',
- ]),
- );
- parent::_prepareLayout();
- return $this;
- }
-
- /**
- * @inheritDoc
- */
- protected function _prepareColumns()
- {
- foreach ($this->_columns as $_column) {
- $_column->setSortable(false);
- }
-
- return parent::_prepareColumns();
- }
-
- /**
- * @return $this
- */
- protected function _prepareCollection()
- {
- $filter = $this->getParam($this->getVarNameFilter(), null);
-
- if (is_null($filter)) {
- $filter = $this->_defaultFilter;
- }
-
- if (is_string($filter)) {
- $data = [];
- $filter = base64_decode($filter);
- parse_str(urldecode($filter), $data);
-
- if (!isset($data['report_from'])) {
- // getting all reports from 2001 year
- $date = new Zend_Date(mktime(0, 0, 0, 1, 1, 2001));
- $data['report_from'] = $date->toString($this->getLocale()->getDateFormat('short'));
- }
-
- if (!isset($data['report_to'])) {
- // getting all reports from 2001 year
- $date = new Zend_Date();
- $data['report_to'] = $date->toString($this->getLocale()->getDateFormat('short'));
- }
-
- $this->_setFilterValues($data);
- } elseif ($filter && is_array($filter)) {
- $this->_setFilterValues($filter);
- } elseif (count($this->_defaultFilter)) {
- $this->_setFilterValues($this->_defaultFilter);
- }
- /** @var Mage_Reports_Model_Resource_Report_Collection $collection */
- $collection = Mage::getResourceModel('reports/report_collection');
-
- $collection->setPeriod($this->getFilter('report_period'));
-
- if ($this->getFilter('report_from') && $this->getFilter('report_to')) {
- /**
- * Validate from and to date
- */
- try {
- $from = $this->getLocale()->date($this->getFilter('report_from'), Zend_Date::DATE_SHORT, null, false);
- $to = $this->getLocale()->date($this->getFilter('report_to'), Zend_Date::DATE_SHORT, null, false);
-
- $collection->setInterval($from, $to);
- } catch (Exception $e) {
- $this->_errors[] = Mage::helper('reports')->__('Invalid date specified.');
- }
- }
-
- /**
- * Getting and saving store ids for website & group
- */
- $storeIds = [];
- if ($this->getRequest()->getParam('store')) {
- $storeIds = [$this->getParam('store')];
- } elseif ($this->getRequest()->getParam('website')) {
- $storeIds = Mage::app()->getWebsite($this->getRequest()->getParam('website'))->getStoreIds();
- } elseif ($this->getRequest()->getParam('group')) {
- $storeIds = Mage::app()->getGroup($this->getRequest()->getParam('group'))->getStoreIds();
- }
-
- // By default storeIds array contains only allowed stores
- $allowedStoreIds = array_keys(Mage::app()->getStores());
- // And then array_intersect with post data for prevent unauthorized stores reports
- $storeIds = array_intersect($allowedStoreIds, $storeIds);
- // If selected all websites or unauthorized stores use only allowed
- if (empty($storeIds)) {
- $storeIds = $allowedStoreIds;
- }
- // reset array keys
- $storeIds = array_values($storeIds);
-
- $collection->setStoreIds($storeIds);
-
- if ($this->getSubReportSize() !== null) {
- $collection->setPageSize($this->getSubReportSize());
- }
-
- $this->setCollection($collection);
-
- Mage::dispatchEvent(
- 'adminhtml_widget_grid_filter_collection',
- ['collection' => $this->getCollection(), 'filter_values' => $this->_filterValues],
- );
-
- return $this;
- }
-
- /**
- * @param array $data
- * @return $this
- */
- protected function _setFilterValues($data)
- {
- foreach (array_keys($data) as $name) {
- $this->setFilter($name, $data[$name]);
- }
- return $this;
- }
-
/**
* Set visibility of store switcher
*
@@ -650,4 +508,146 @@ public function getRate($toCurrency)
{
return Mage::app()->getStore()->getBaseCurrency()->getRate($toCurrency);
}
+
+ /**
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'store_switcher',
+ $this->getLayout()->createBlock('adminhtml/store_switcher')
+ ->setUseConfirm(false)
+ ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
+ ->setTemplate('report/store/switcher.phtml'),
+ );
+
+ $this->setChild(
+ 'refresh_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('adminhtml')->__('Refresh'),
+ 'onclick' => $this->getRefreshButtonCallback(),
+ 'class' => 'task',
+ ]),
+ );
+ parent::_prepareLayout();
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareColumns()
+ {
+ foreach ($this->_columns as $_column) {
+ $_column->setSortable(false);
+ }
+
+ return parent::_prepareColumns();
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _prepareCollection()
+ {
+ $filter = $this->getParam($this->getVarNameFilter(), null);
+
+ if (is_null($filter)) {
+ $filter = $this->_defaultFilter;
+ }
+
+ if (is_string($filter)) {
+ $data = [];
+ $filter = base64_decode($filter);
+ parse_str(urldecode($filter), $data);
+
+ if (!isset($data['report_from'])) {
+ // getting all reports from 2001 year
+ $date = new Zend_Date(mktime(0, 0, 0, 1, 1, 2001));
+ $data['report_from'] = $date->toString($this->getLocale()->getDateFormat('short'));
+ }
+
+ if (!isset($data['report_to'])) {
+ // getting all reports from 2001 year
+ $date = new Zend_Date();
+ $data['report_to'] = $date->toString($this->getLocale()->getDateFormat('short'));
+ }
+
+ $this->_setFilterValues($data);
+ } elseif ($filter && is_array($filter)) {
+ $this->_setFilterValues($filter);
+ } elseif (count($this->_defaultFilter)) {
+ $this->_setFilterValues($this->_defaultFilter);
+ }
+ /** @var Mage_Reports_Model_Resource_Report_Collection $collection */
+ $collection = Mage::getResourceModel('reports/report_collection');
+
+ $collection->setPeriod($this->getFilter('report_period'));
+
+ if ($this->getFilter('report_from') && $this->getFilter('report_to')) {
+ /**
+ * Validate from and to date
+ */
+ try {
+ $from = $this->getLocale()->date($this->getFilter('report_from'), Zend_Date::DATE_SHORT, null, false);
+ $to = $this->getLocale()->date($this->getFilter('report_to'), Zend_Date::DATE_SHORT, null, false);
+
+ $collection->setInterval($from, $to);
+ } catch (Exception $e) {
+ $this->_errors[] = Mage::helper('reports')->__('Invalid date specified.');
+ }
+ }
+
+ /**
+ * Getting and saving store ids for website & group
+ */
+ $storeIds = [];
+ if ($this->getRequest()->getParam('store')) {
+ $storeIds = [$this->getParam('store')];
+ } elseif ($this->getRequest()->getParam('website')) {
+ $storeIds = Mage::app()->getWebsite($this->getRequest()->getParam('website'))->getStoreIds();
+ } elseif ($this->getRequest()->getParam('group')) {
+ $storeIds = Mage::app()->getGroup($this->getRequest()->getParam('group'))->getStoreIds();
+ }
+
+ // By default storeIds array contains only allowed stores
+ $allowedStoreIds = array_keys(Mage::app()->getStores());
+ // And then array_intersect with post data for prevent unauthorized stores reports
+ $storeIds = array_intersect($allowedStoreIds, $storeIds);
+ // If selected all websites or unauthorized stores use only allowed
+ if (empty($storeIds)) {
+ $storeIds = $allowedStoreIds;
+ }
+ // reset array keys
+ $storeIds = array_values($storeIds);
+
+ $collection->setStoreIds($storeIds);
+
+ if ($this->getSubReportSize() !== null) {
+ $collection->setPageSize($this->getSubReportSize());
+ }
+
+ $this->setCollection($collection);
+
+ Mage::dispatchEvent(
+ 'adminhtml_widget_grid_filter_collection',
+ ['collection' => $this->getCollection(), 'filter_values' => $this->_filterValues],
+ );
+
+ return $this;
+ }
+
+ /**
+ * @param array $data
+ * @return $this
+ */
+ protected function _setFilterValues($data)
+ {
+ foreach (array_keys($data) as $name) {
+ $this->setFilter($name, $data[$name]);
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Grid/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Report/Grid/Abstract.php
index 0ca6a38a784..c9faaefd543 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Grid/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Grid/Abstract.php
@@ -67,24 +67,6 @@ public function getCollection()
return $this->_collection;
}
- /**
- * @return array
- */
- protected function _getAggregatedColumns()
- {
- if (is_null($this->_aggregatedColumns)) {
- foreach ($this->getColumns() as $column) {
- if (!is_array($this->_aggregatedColumns)) {
- $this->_aggregatedColumns = [];
- }
- if ($column->hasTotal()) {
- $this->_aggregatedColumns[$column->getId()] = "{$column->getTotal()}({$column->getIndex()})";
- }
- }
- }
- return $this->_aggregatedColumns;
- }
-
/**
* Add column to grid
* Overridden to add support for visibility_filter column option
@@ -121,6 +103,98 @@ public function addColumn($columnId, $column)
return parent::addColumn($columnId, $column);
}
+ public function getCountTotals()
+ {
+ if (!$this->getTotals()) {
+ $filterData = $this->getFilterData();
+ /** @var Mage_Sales_Model_Resource_Report_Collection_Abstract $totalsCollection */
+ $totalsCollection = Mage::getResourceModel($this->getResourceCollectionName());
+ $totalsCollection
+ ->setPeriod($filterData->getData('period_type'))
+ ->setDateRange($filterData->getData('from', null), $filterData->getData('to', null))
+ ->addStoreFilter($this->_getStoreIds())
+ ->setAggregatedColumns($this->_getAggregatedColumns())
+ ->isTotals(true);
+
+ $this->_addOrderStatusFilter($totalsCollection, $filterData);
+ $this->_addCustomFilter($totalsCollection, $filterData);
+
+ if (count($totalsCollection->getItems()) < 1 || !$filterData->getData('from')) {
+ $this->setTotals(new Varien_Object());
+ } else {
+ foreach ($totalsCollection->getItems() as $item) {
+ $this->setTotals($item);
+ break;
+ }
+ }
+ }
+ return parent::getCountTotals();
+ }
+
+ public function getSubTotals()
+ {
+ $filterData = $this->getFilterData();
+ /** @var Mage_Sales_Model_Resource_Report_Collection_Abstract $subTotalsCollection */
+ $subTotalsCollection = Mage::getResourceModel($this->getResourceCollectionName());
+ $subTotalsCollection
+ ->setPeriod($filterData->getData('period_type'))
+ ->setDateRange($filterData->getData('from', null), $filterData->getData('to', null))
+ ->addStoreFilter($this->_getStoreIds())
+ ->setAggregatedColumns($this->_getAggregatedColumns())
+ ->isSubTotals(true);
+
+ $this->_addOrderStatusFilter($subTotalsCollection, $filterData);
+ $this->_addCustomFilter($subTotalsCollection, $filterData);
+
+ $this->setSubTotals($subTotalsCollection->getItems());
+ return parent::getSubTotals();
+ }
+
+ public function setStoreIds($storeIds)
+ {
+ $this->_storeIds = $storeIds;
+ return $this;
+ }
+
+ public function getCurrentCurrencyCode()
+ {
+ if (is_null($this->_currentCurrencyCode)) {
+ $this->_currentCurrencyCode = (count($this->_storeIds) > 0)
+ ? Mage::app()->getStore(array_shift($this->_storeIds))->getBaseCurrencyCode()
+ : Mage::app()->getStore()->getBaseCurrencyCode();
+ }
+ return $this->_currentCurrencyCode;
+ }
+
+ /**
+ * Get currency rate (base to given currency)
+ *
+ * @param string|Mage_Directory_Model_Currency $toCurrency
+ * @return double
+ */
+ public function getRate($toCurrency)
+ {
+ return Mage::app()->getStore()->getBaseCurrency()->getRate($toCurrency);
+ }
+
+ /**
+ * @return array
+ */
+ protected function _getAggregatedColumns()
+ {
+ if (is_null($this->_aggregatedColumns)) {
+ foreach ($this->getColumns() as $column) {
+ if (!is_array($this->_aggregatedColumns)) {
+ $this->_aggregatedColumns = [];
+ }
+ if ($column->hasTotal()) {
+ $this->_aggregatedColumns[$column->getId()] = "{$column->getTotal()}({$column->getIndex()})";
+ }
+ }
+ }
+ return $this->_aggregatedColumns;
+ }
+
/**
* Get allowed store ids array intersected with selected scope in store switcher
*
@@ -221,80 +295,6 @@ protected function _prepareCollection()
return parent::_prepareCollection();
}
- public function getCountTotals()
- {
- if (!$this->getTotals()) {
- $filterData = $this->getFilterData();
- /** @var Mage_Sales_Model_Resource_Report_Collection_Abstract $totalsCollection */
- $totalsCollection = Mage::getResourceModel($this->getResourceCollectionName());
- $totalsCollection
- ->setPeriod($filterData->getData('period_type'))
- ->setDateRange($filterData->getData('from', null), $filterData->getData('to', null))
- ->addStoreFilter($this->_getStoreIds())
- ->setAggregatedColumns($this->_getAggregatedColumns())
- ->isTotals(true);
-
- $this->_addOrderStatusFilter($totalsCollection, $filterData);
- $this->_addCustomFilter($totalsCollection, $filterData);
-
- if (count($totalsCollection->getItems()) < 1 || !$filterData->getData('from')) {
- $this->setTotals(new Varien_Object());
- } else {
- foreach ($totalsCollection->getItems() as $item) {
- $this->setTotals($item);
- break;
- }
- }
- }
- return parent::getCountTotals();
- }
-
- public function getSubTotals()
- {
- $filterData = $this->getFilterData();
- /** @var Mage_Sales_Model_Resource_Report_Collection_Abstract $subTotalsCollection */
- $subTotalsCollection = Mage::getResourceModel($this->getResourceCollectionName());
- $subTotalsCollection
- ->setPeriod($filterData->getData('period_type'))
- ->setDateRange($filterData->getData('from', null), $filterData->getData('to', null))
- ->addStoreFilter($this->_getStoreIds())
- ->setAggregatedColumns($this->_getAggregatedColumns())
- ->isSubTotals(true);
-
- $this->_addOrderStatusFilter($subTotalsCollection, $filterData);
- $this->_addCustomFilter($subTotalsCollection, $filterData);
-
- $this->setSubTotals($subTotalsCollection->getItems());
- return parent::getSubTotals();
- }
-
- public function setStoreIds($storeIds)
- {
- $this->_storeIds = $storeIds;
- return $this;
- }
-
- public function getCurrentCurrencyCode()
- {
- if (is_null($this->_currentCurrencyCode)) {
- $this->_currentCurrencyCode = (count($this->_storeIds) > 0)
- ? Mage::app()->getStore(array_shift($this->_storeIds))->getBaseCurrencyCode()
- : Mage::app()->getStore()->getBaseCurrencyCode();
- }
- return $this->_currentCurrencyCode;
- }
-
- /**
- * Get currency rate (base to given currency)
- *
- * @param string|Mage_Directory_Model_Currency $toCurrency
- * @return double
- */
- public function getRate($toCurrency)
- {
- return Mage::app()->getStore()->getBaseCurrency()->getRate($toCurrency);
- }
-
/**
* Add order status filter
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Product/Downloads.php b/app/code/core/Mage/Adminhtml/Block/Report/Product/Downloads.php
index 86e45d5428b..20c83ef9083 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Product/Downloads.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Product/Downloads.php
@@ -30,18 +30,6 @@ public function __construct()
$this->_removeButton('add');
}
- protected function _prepareLayout()
- {
- $this->setChild(
- 'store_switcher',
- $this->getLayout()->createBlock('adminhtml/store_switcher')
- ->setUseConfirm(false)
- ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
- ->setTemplate('report/store/switcher.phtml'),
- );
- return parent::_prepareLayout();
- }
-
public function getStoreSwitcherHtml()
{
return Mage::app()->isSingleStoreMode() ? '' : $this->getChildHtml('store_switcher');
@@ -56,4 +44,16 @@ public function getHeaderCssClass()
{
return 'icon-head head-report';
}
+
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'store_switcher',
+ $this->getLayout()->createBlock('adminhtml/store_switcher')
+ ->setUseConfirm(false)
+ ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
+ ->setTemplate('report/store/switcher.phtml'),
+ );
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Product/Lowstock.php b/app/code/core/Mage/Adminhtml/Block/Report/Product/Lowstock.php
index 4b6b601ce0a..ca293d53aa9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Product/Lowstock.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Product/Lowstock.php
@@ -30,18 +30,6 @@ public function __construct()
$this->_removeButton('add');
}
- protected function _prepareLayout()
- {
- $this->setChild(
- 'store_switcher',
- $this->getLayout()->createBlock('adminhtml/store_switcher')
- ->setUseConfirm(false)
- ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
- ->setTemplate('report/store/switcher.phtml'),
- );
- return parent::_prepareLayout();
- }
-
public function getStoreSwitcherHtml()
{
return Mage::app()->isSingleStoreMode() ? '' : $this->getChildHtml('store_switcher');
@@ -56,4 +44,16 @@ public function getHeaderCssClass()
{
return 'icon-head head-report';
}
+
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'store_switcher',
+ $this->getLayout()->createBlock('adminhtml/store_switcher')
+ ->setUseConfirm(false)
+ ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
+ ->setTemplate('report/store/switcher.phtml'),
+ );
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Review/Customer/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Review/Customer/Grid.php
index f260b89f9a1..7827223c8a3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Review/Customer/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Review/Customer/Grid.php
@@ -30,6 +30,11 @@ public function __construct()
$this->setDefaultDir('desc');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_product_review', ['customerId' => $row->getCustomerId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('reports/review_customer_collection')
@@ -70,9 +75,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_product_review', ['customerId' => $row->getCustomerId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Review/Product/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Review/Product/Grid.php
index 94766e55cc6..019b2cd0299 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Review/Product/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Review/Product/Grid.php
@@ -30,6 +30,11 @@ public function __construct()
$this->setDefaultDir('desc');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_product_review/', ['productId' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('reports/review_product_collection')
@@ -95,9 +100,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_product_review/', ['productId' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Grid/Column/Renderer/Date.php b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Grid/Column/Renderer/Date.php
index cf4c89b573f..6018ccf1008 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Grid/Column/Renderer/Date.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Grid/Column/Renderer/Date.php
@@ -22,6 +22,40 @@
*/
class Mage_Adminhtml_Block_Report_Sales_Grid_Column_Renderer_Date extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Date
{
+ /**
+ * Renders grid column
+ *
+ * @return string
+ */
+ public function render(Varien_Object $row)
+ {
+ if ($data = $row->getData($this->getColumn()->getIndex())) {
+ switch ($this->getColumn()->getPeriodType()) {
+ case 'month':
+ $dateFormat = 'yyyy-MM';
+ break;
+ case 'year':
+ $dateFormat = 'yyyy';
+ break;
+ default:
+ $dateFormat = Varien_Date::DATE_INTERNAL_FORMAT;
+ break;
+ }
+
+ $format = $this->_getFormat();
+ try {
+ $data = ($this->getColumn()->getGmtoffset())
+ ? Mage::app()->getLocale()->date($data, $dateFormat)->toString($format)
+ : Mage::getSingleton('core/locale')->date($data, $dateFormat, null, false)->toString($format);
+ } catch (Exception $e) {
+ $data = ($this->getColumn()->getTimezone())
+ ? Mage::app()->getLocale()->date($data, $dateFormat)->toString($format)
+ : Mage::getSingleton('core/locale')->date($data, $dateFormat, null, false)->toString($format);
+ }
+ return $data;
+ }
+ return $this->getColumn()->getDefault();
+ }
/**
* Retrieve date format
*
@@ -57,39 +91,4 @@ protected function _getFormat()
}
return $format;
}
-
- /**
- * Renders grid column
- *
- * @return string
- */
- public function render(Varien_Object $row)
- {
- if ($data = $row->getData($this->getColumn()->getIndex())) {
- switch ($this->getColumn()->getPeriodType()) {
- case 'month':
- $dateFormat = 'yyyy-MM';
- break;
- case 'year':
- $dateFormat = 'yyyy';
- break;
- default:
- $dateFormat = Varien_Date::DATE_INTERNAL_FORMAT;
- break;
- }
-
- $format = $this->_getFormat();
- try {
- $data = ($this->getColumn()->getGmtoffset())
- ? Mage::app()->getLocale()->date($data, $dateFormat)->toString($format)
- : Mage::getSingleton('core/locale')->date($data, $dateFormat, null, false)->toString($format);
- } catch (Exception $e) {
- $data = ($this->getColumn()->getTimezone())
- ? Mage::app()->getLocale()->date($data, $dateFormat)->toString($format)
- : Mage::getSingleton('core/locale')->date($data, $dateFormat, null, false)->toString($format);
- }
- return $data;
- }
- return $this->getColumn()->getDefault();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Search/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Search/Grid.php
index 3c86fa4439a..8f6d4011292 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Search/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Search/Grid.php
@@ -34,6 +34,16 @@ public function __construct()
$this->setDefaultDir('desc');
}
+ /**
+ * Retrieve Row Click callback URL
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_search/edit', ['id' => $row->getId()]);
+ }
+
/**
* Prepare Search Report collection for grid
*
@@ -96,14 +106,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Retrieve Row Click callback URL
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_search/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Abandoned.php b/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Abandoned.php
index 54bdb529a9c..c77b4e3f3c0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Abandoned.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Abandoned.php
@@ -30,18 +30,6 @@ public function __construct()
$this->_removeButton('add');
}
- protected function _prepareLayout()
- {
- $this->setChild(
- 'store_switcher',
- $this->getLayout()->createBlock('adminhtml/store_switcher')
- ->setUseConfirm(false)
- ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
- ->setTemplate('report/store/switcher.phtml'),
- );
- return parent::_prepareLayout();
- }
-
public function getStoreSwitcherHtml()
{
return Mage::app()->isSingleStoreMode() ? '' : $this->getChildHtml('store_switcher');
@@ -56,4 +44,16 @@ public function getHeaderCssClass()
{
return 'icon-head head-report';
}
+
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'store_switcher',
+ $this->getLayout()->createBlock('adminhtml/store_switcher')
+ ->setUseConfirm(false)
+ ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
+ ->setTemplate('report/store/switcher.phtml'),
+ );
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Abandoned/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Abandoned/Grid.php
index a50381c6e9a..aa69681ee96 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Abandoned/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Abandoned/Grid.php
@@ -28,6 +28,11 @@ public function __construct()
$this->setId('gridAbandoned');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/customer/edit', ['id' => $row->getCustomerId(), 'active_tab' => 'cart']);
+ }
+
protected function _prepareCollection()
{
/** @var Mage_Reports_Model_Resource_Quote_Collection $collection */
@@ -152,9 +157,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/customer/edit', ['id' => $row->getCustomerId(), 'active_tab' => 'cart']);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Product/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Product/Grid.php
index 2dfe122f568..b9247685fe9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Product/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Shopcart/Product/Grid.php
@@ -28,6 +28,11 @@ public function __construct()
$this->setId('gridProducts');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_product/edit', ['id' => $row->getEntityId()]);
+ }
+
protected function _prepareCollection()
{
/** @var Mage_Reports_Model_Resource_Quote_Collection $collection */
@@ -80,9 +85,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_product/edit', ['id' => $row->getEntityId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Customer/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Customer/Grid.php
index 6883073782c..7e7dda0ff4e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Customer/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Customer/Grid.php
@@ -28,6 +28,11 @@ public function __construct()
$this->setId('grid');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/customerDetail', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('reports/tag_customer_collection');
@@ -91,9 +96,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/customerDetail', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular.php b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular.php
index 86048fdcea1..52ba26c392e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular.php
@@ -30,18 +30,6 @@ public function __construct()
$this->_removeButton('add');
}
- protected function _prepareLayout()
- {
- $this->setChild(
- 'store_switcher',
- $this->getLayout()->createBlock('adminhtml/store_switcher')
- ->setUseConfirm(false)
- ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
- ->setTemplate('report/store/switcher.phtml'),
- );
- return parent::_prepareLayout();
- }
-
public function getStoreSwitcherHtml()
{
return Mage::app()->isSingleStoreMode() ? '' : $this->getChildHtml('store_switcher');
@@ -56,4 +44,16 @@ public function getHeaderCssClass()
{
return 'icon-head head-report';
}
+
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'store_switcher',
+ $this->getLayout()->createBlock('adminhtml/store_switcher')
+ ->setUseConfirm(false)
+ ->setSwitchUrl($this->getUrl('*/*/*', ['store' => null]))
+ ->setTemplate('report/store/switcher.phtml'),
+ );
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular/Grid.php
index 7dbe47c53d7..9f11af7408b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular/Grid.php
@@ -28,6 +28,11 @@ public function __construct()
$this->setId('grid');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/tagDetail', ['id' => $row->getTagId()]);
+ }
+
protected function _prepareCollection()
{
if ($this->getRequest()->getParam('website')) {
@@ -88,9 +93,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/tagDetail', ['id' => $row->getTagId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Product/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Product/Grid.php
index 0aec93a368b..4258a7a6d57 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Product/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Product/Grid.php
@@ -28,6 +28,11 @@ public function __construct()
$this->setId('gridProducts');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/productDetail', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('reports/tag_product_collection');
@@ -94,9 +99,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/productDetail', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Review/Grid.php b/app/code/core/Mage/Adminhtml/Block/Review/Grid.php
index 36c4c6a919f..2472e36655b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Review/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Review/Grid.php
@@ -31,6 +31,33 @@ public function __construct()
$this->setDefaultSort('created_at');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_product_review/edit', [
+ 'id' => $row->getReviewId(),
+ 'productId' => $this->getProductId(),
+ 'customerId' => $this->getCustomerId(),
+ 'ret' => (Mage::registry('usePendingFilter')) ? 'pending' : null,
+ ]);
+ }
+
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ if ($this->getProductId() || $this->getCustomerId()) {
+ return $this->getUrl(
+ '*/catalog_product_review/' . (Mage::registry('usePendingFilter') ? 'pending' : ''),
+ [
+ 'productId' => $this->getProductId(),
+ 'customerId' => $this->getCustomerId(),
+ ],
+ );
+ }
+ return $this->getCurrentUrl();
+ }
+
/**
* @inheritDoc
* @throws Exception
@@ -242,31 +269,4 @@ protected function _prepareMassaction()
]);
return parent::_prepareMassaction();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_product_review/edit', [
- 'id' => $row->getReviewId(),
- 'productId' => $this->getProductId(),
- 'customerId' => $this->getCustomerId(),
- 'ret' => (Mage::registry('usePendingFilter')) ? 'pending' : null,
- ]);
- }
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- if ($this->getProductId() || $this->getCustomerId()) {
- return $this->getUrl(
- '*/catalog_product_review/' . (Mage::registry('usePendingFilter') ? 'pending' : ''),
- [
- 'productId' => $this->getProductId(),
- 'customerId' => $this->getCustomerId(),
- ],
- );
- }
- return $this->getCurrentUrl();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Review/Grid/Filter/Type.php b/app/code/core/Mage/Adminhtml/Block/Review/Grid/Filter/Type.php
index 923280b9848..42ee368bad6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Review/Grid/Filter/Type.php
+++ b/app/code/core/Mage/Adminhtml/Block/Review/Grid/Filter/Type.php
@@ -22,19 +22,6 @@
*/
class Mage_Adminhtml_Block_Review_Grid_Filter_Type extends Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Select
{
- /**
- * @return array
- */
- protected function _getOptions()
- {
- return [
- ['label' => '', 'value' => ''],
- ['label' => Mage::helper('review')->__('Administrator'), 'value' => 1],
- ['label' => Mage::helper('review')->__('Customer'), 'value' => 2],
- ['label' => Mage::helper('review')->__('Guest'), 'value' => 3],
- ];
- }
-
/**
* @return int
*/
@@ -48,4 +35,16 @@ public function getCondition()
return 3;
}
}
+ /**
+ * @return array
+ */
+ protected function _getOptions()
+ {
+ return [
+ ['label' => '', 'value' => ''],
+ ['label' => Mage::helper('review')->__('Administrator'), 'value' => 1],
+ ['label' => Mage::helper('review')->__('Customer'), 'value' => 2],
+ ['label' => Mage::helper('review')->__('Guest'), 'value' => 3],
+ ];
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Review/Product/Grid.php b/app/code/core/Mage/Adminhtml/Block/Review/Product/Grid.php
index 41153296ff8..9c6e997b9d9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Review/Product/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Review/Product/Grid.php
@@ -30,6 +30,23 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/productGrid', ['_current' => true]);
+ }
+
+ /**
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/jsonProductInfo', ['id' => $row->getId()]);
+ }
+
/**
* @return $this
*/
@@ -97,23 +114,6 @@ protected function _prepareColumns()
return $this;
}
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/productGrid', ['_current' => true]);
- }
-
- /**
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/jsonProductInfo', ['id' => $row->getId()]);
- }
-
/**
* @return $this
*/
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Creditmemo/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Creditmemo/Grid.php
index 192c4cc8e3a..b8780bc234f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Creditmemo/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Creditmemo/Grid.php
@@ -32,6 +32,32 @@ public function __construct()
$this->setDefaultDir('DESC');
}
+ /**
+ * @param Mage_Sales_Model_Order_Creditmemo $row
+ * @return false|string
+ */
+ public function getRowUrl($row)
+ {
+ if (!Mage::getSingleton('admin/session')->isAllowed('sales/order/creditmemo')) {
+ return false;
+ }
+
+ return $this->getUrl(
+ '*/sales_creditmemo/view',
+ [
+ 'creditmemo_id' => $row->getId(),
+ ],
+ );
+ }
+
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/*', ['_current' => true]);
+ }
+
/**
* Retrieve collection class
*
@@ -141,30 +167,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * @param Mage_Sales_Model_Order_Creditmemo $row
- * @return false|string
- */
- public function getRowUrl($row)
- {
- if (!Mage::getSingleton('admin/session')->isAllowed('sales/order/creditmemo')) {
- return false;
- }
-
- return $this->getUrl(
- '*/sales_creditmemo/view',
- [
- 'creditmemo_id' => $row->getId(),
- ],
- );
- }
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/*', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Invoice/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Invoice/Grid.php
index 9f5579a3afb..dd4e6beb276 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Invoice/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Invoice/Grid.php
@@ -34,6 +34,32 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * @param Mage_Sales_Model_Order_Invoice $row
+ * @return false|string
+ */
+ public function getRowUrl($row)
+ {
+ if (!Mage::getSingleton('admin/session')->isAllowed('sales/order/invoice')) {
+ return false;
+ }
+
+ return $this->getUrl(
+ '*/sales_invoice/view',
+ [
+ 'invoice_id' => $row->getId(),
+ ],
+ );
+ }
+
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
/**
* Retrieve collection class
*
@@ -143,30 +169,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * @param Mage_Sales_Model_Order_Invoice $row
- * @return false|string
- */
- public function getRowUrl($row)
- {
- if (!Mage::getSingleton('admin/session')->isAllowed('sales/order/invoice')) {
- return false;
- }
-
- return $this->getUrl(
- '*/sales_invoice/view',
- [
- 'invoice_id' => $row->getId(),
- ],
- );
- }
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Items/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Sales/Items/Abstract.php
index 7c3cc555096..16532500f43 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Items/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Items/Abstract.php
@@ -49,17 +49,6 @@ class Mage_Adminhtml_Block_Sales_Items_Abstract extends Mage_Adminhtml_Block_Tem
*/
protected $_canEditQty = null;
- /**
- * Init block
- *
- */
- protected function _construct()
- {
- $this->addColumnRender('qty', 'adminhtml/sales_items_column_qty', 'sales/items/column/qty.phtml');
- $this->addColumnRender('name', 'adminhtml/sales_items_column_name', 'sales/items/column/name.phtml');
- parent::_construct();
- }
-
/**
* Add item renderer
*
@@ -588,4 +577,15 @@ public function isShipmentRegular()
}
return true;
}
+
+ /**
+ * Init block
+ *
+ */
+ protected function _construct()
+ {
+ $this->addColumnRender('qty', 'adminhtml/sales_items_column_qty', 'sales/items/column/qty.phtml');
+ $this->addColumnRender('name', 'adminhtml/sales_items_column_name', 'sales/items/column/name.phtml');
+ parent::_construct();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Address/Form.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Address/Form.php
index ec1984a7f4f..6b899191543 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Address/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Address/Form.php
@@ -22,6 +22,25 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Address_Form extends Mage_Adminhtml_Block_Sales_Order_Create_Form_Address
{
+ /**
+ * Form header text getter
+ *
+ * @return string
+ */
+ public function getHeaderText()
+ {
+ return Mage::helper('sales')->__('Order Address Information');
+ }
+
+ /**
+ * Return Form Elements values
+ *
+ * @return array
+ */
+ public function getFormValues()
+ {
+ return $this->_getAddress()->getData();
+ }
protected function _construct()
{
parent::_construct();
@@ -52,24 +71,4 @@ protected function _prepareForm()
$this->_form->setUseContainer(true);
return $this;
}
-
- /**
- * Form header text getter
- *
- * @return string
- */
- public function getHeaderText()
- {
- return Mage::helper('sales')->__('Order Address Information');
- }
-
- /**
- * Return Form Elements values
- *
- * @return array
- */
- public function getFormValues()
- {
- return $this->_getAddress()->getData();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Comments/View.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Comments/View.php
index 29542fbb1ff..1ba8a8f2c82 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Comments/View.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Comments/View.php
@@ -22,34 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Comments_View extends Mage_Adminhtml_Block_Template
{
- /**
- * Retrieve required options from parent
- */
- protected function _beforeToHtml()
- {
- if (!$this->getParentBlock()) {
- Mage::throwException(Mage::helper('adminhtml')->__('Invalid parent block for this block.'));
- }
- $this->setEntity($this->getParentBlock()->getSource());
- return parent::_beforeToHtml();
- }
-
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $button = $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'id' => 'submit_comment_button',
- 'label' => Mage::helper('sales')->__('Submit Comment'),
- 'class' => 'save',
- ]);
- $this->setChild('submit_button', $button);
-
- return parent::_prepareLayout();
- }
-
public function getSubmitUrl()
{
return $this->getUrl('*/*/addComment', ['id' => $this->getEntity()->getId()]);
@@ -86,4 +58,31 @@ public function escapeHtml($data, $allowedTags = null)
{
return Mage::helper('adminhtml/sales')->escapeHtmlWithLinks($data, $allowedTags);
}
+ /**
+ * Retrieve required options from parent
+ */
+ protected function _beforeToHtml()
+ {
+ if (!$this->getParentBlock()) {
+ Mage::throwException(Mage::helper('adminhtml')->__('Invalid parent block for this block.'));
+ }
+ $this->setEntity($this->getParentBlock()->getSource());
+ return parent::_beforeToHtml();
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $button = $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'id' => 'submit_comment_button',
+ 'label' => Mage::helper('sales')->__('Submit Comment'),
+ 'class' => 'save',
+ ]);
+ $this->setChild('submit_button', $button);
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create.php
index f22fda88e61..b9c4e1b6b51 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create.php
@@ -66,16 +66,6 @@ public function __construct()
);
}
- /**
- * Check access for cancel action
- *
- * @return bool
- */
- protected function _isCanCancel()
- {
- return Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/cancel');
- }
-
/**
* Prepare header html
*
@@ -107,16 +97,6 @@ public function getHeaderWidth()
return 'width: 70%;';
}
- /**
- * Retrieve quote session object
- *
- * @return Mage_Adminhtml_Model_Session_Quote
- */
- protected function _getSession()
- {
- return Mage::getSingleton('adminhtml/session_quote');
- }
-
/**
* @return string
*/
@@ -142,4 +122,24 @@ public function getBackUrl()
{
return $this->getUrl('*/' . $this->_controller . '/');
}
+
+ /**
+ * Check access for cancel action
+ *
+ * @return bool
+ */
+ protected function _isCanCancel()
+ {
+ return Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/cancel');
+ }
+
+ /**
+ * Retrieve quote session object
+ *
+ * @return Mage_Adminhtml_Model_Session_Quote
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('adminhtml/session_quote');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Abstract.php
index a24e57a0360..3e2571a7bed 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Abstract.php
@@ -32,16 +32,6 @@ public function getCreateOrderModel()
return Mage::getSingleton('adminhtml/sales_order_create');
}
- /**
- * Retrieve quote session object
- *
- * @return Mage_Adminhtml_Model_Session_Quote
- */
- protected function _getSession()
- {
- return Mage::getSingleton('adminhtml/session_quote');
- }
-
/**
* Retrieve quote model object
*
@@ -107,4 +97,14 @@ public function convertPrice($value, $format = true)
{
return $this->getStore()->convertPrice($value, $format);
}
+
+ /**
+ * Retrieve quote session object
+ *
+ * @return Mage_Adminhtml_Model_Session_Quote
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('adminhtml/session_quote');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Billing/Address.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Billing/Address.php
index e47443b6f38..adafcb9b27c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Billing/Address.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Billing/Address.php
@@ -42,23 +42,6 @@ public function getHeaderCssClass()
return 'head-billing-address';
}
- /**
- * Prepare Form and add elements to form
- *
- * @return $this
- */
- protected function _prepareForm()
- {
- $this->setJsVariablePrefix('billingAddress');
- parent::_prepareForm();
-
- $this->_form->addFieldNameSuffix('order[billing_address]');
- $this->_form->setHtmlNamePrefix('order[billing_address]');
- $this->_form->setHtmlIdPrefix('order-billing_address_');
-
- return $this;
- }
-
/**
* Return Form Elements values
*
@@ -88,4 +71,21 @@ public function getAddress()
{
return $this->getCreateOrderModel()->getBillingAddress();
}
+
+ /**
+ * Prepare Form and add elements to form
+ *
+ * @return $this
+ */
+ protected function _prepareForm()
+ {
+ $this->setJsVariablePrefix('billingAddress');
+ parent::_prepareForm();
+
+ $this->_form->addFieldNameSuffix('order[billing_address]');
+ $this->_form->setHtmlNamePrefix('order[billing_address]');
+ $this->_form->setHtmlIdPrefix('order-billing_address_');
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Billing/Method/Form.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Billing/Method/Form.php
index afd43b6a14c..5f599de4831 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Billing/Method/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Billing/Method/Form.php
@@ -22,17 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Create_Billing_Method_Form extends Mage_Payment_Block_Form_Container
{
- /**
- * Check payment method model
- *
- * @param Mage_Payment_Model_Method_Abstract|null $method
- * @return bool
- */
- protected function _canUseMethod($method)
- {
- return $method && $method->canUseInternal() && parent::_canUseMethod($method);
- }
-
/**
* Check existing of payment methods
*
@@ -92,4 +81,14 @@ public function hasSsCardType()
}
return false;
}
+ /**
+ * Check payment method model
+ *
+ * @param Mage_Payment_Model_Method_Abstract|null $method
+ * @return bool
+ */
+ protected function _canUseMethod($method)
+ {
+ return $method && $method->canUseInternal() && parent::_canUseMethod($method);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Customer/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Customer/Grid.php
index af794b21cca..e74b6367a9c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Customer/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Customer/Grid.php
@@ -31,6 +31,24 @@ public function __construct()
$this->setDefaultSort('entity_id');
}
+ /**
+ * @deprecated since 1.1.7
+ */
+ public function getRowId($row)
+ {
+ return $row->getId();
+ }
+
+ public function getRowUrl($row)
+ {
+ return $row->getId();
+ }
+
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/loadBlock', ['block' => 'customer_grid']);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('customer/customer_collection')
@@ -95,22 +113,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * @deprecated since 1.1.7
- */
- public function getRowId($row)
- {
- return $row->getId();
- }
-
- public function getRowUrl($row)
- {
- return $row->getId();
- }
-
- public function getGridUrl()
- {
- return $this->getUrl('*/*/loadBlock', ['block' => 'customer_grid']);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Abstract.php
index 2fab48adc38..d7b147e3a82 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Abstract.php
@@ -29,6 +29,31 @@ abstract class Mage_Adminhtml_Block_Sales_Order_Create_Form_Abstract extends Mag
*/
protected $_form;
+ /**
+ * Return Form object
+ *
+ * @return Varien_Data_Form
+ */
+ public function getForm()
+ {
+ if (is_null($this->_form)) {
+ $this->_form = new Varien_Data_Form();
+ $this->_prepareForm();
+ }
+
+ return $this->_form;
+ }
+
+ /**
+ * Return Form Elements values
+ *
+ * @return array
+ */
+ public function getFormValues()
+ {
+ return [];
+ }
+
/**
* Prepare global layout
* Add renderers to Varien_Data_Form
@@ -57,21 +82,6 @@ protected function _prepareLayout()
return $this;
}
- /**
- * Return Form object
- *
- * @return Varien_Data_Form
- */
- public function getForm()
- {
- if (is_null($this->_form)) {
- $this->_form = new Varien_Data_Form();
- $this->_prepareForm();
- }
-
- return $this->_form;
- }
-
/**
* Prepare Form and add elements to form
*
@@ -165,14 +175,4 @@ protected function _addAttributesToForm($attributes, Varien_Data_Form_Abstract $
return $this;
}
-
- /**
- * Return Form Elements values
- *
- * @return array
- */
- public function getFormValues()
- {
- return [];
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Account.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Account.php
index 3e27b118bf7..0f8ec2095e0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Account.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Account.php
@@ -42,6 +42,38 @@ public function getHeaderText()
return Mage::helper('sales')->__('Account Information');
}
+ /**
+ * Return customer data
+ *
+ * @deprecated since 1.4.0.1
+ * @return array
+ */
+ public function getCustomerData()
+ {
+ return $this->getFormValues();
+ }
+
+ /**
+ * Return Form Elements values
+ *
+ * @return array
+ */
+ public function getFormValues()
+ {
+ $data = $this->getCustomer()->getData();
+ foreach ($this->getQuote()->getData() as $key => $value) {
+ if (str_starts_with($key, 'customer_')) {
+ $data[substr($key, 9)] = $value;
+ }
+ }
+
+ if ($this->getQuote()->getCustomerEmail()) {
+ $data['email'] = $this->getQuote()->getCustomerEmail();
+ }
+
+ return $data;
+ }
+
/**
* Prepare Form and add elements to form
*
@@ -105,36 +137,4 @@ protected function _addAdditionalFormElementData(Varien_Data_Form_Element_Abstra
}
return $this;
}
-
- /**
- * Return customer data
- *
- * @deprecated since 1.4.0.1
- * @return array
- */
- public function getCustomerData()
- {
- return $this->getFormValues();
- }
-
- /**
- * Return Form Elements values
- *
- * @return array
- */
- public function getFormValues()
- {
- $data = $this->getCustomer()->getData();
- foreach ($this->getQuote()->getData() as $key => $value) {
- if (str_starts_with($key, 'customer_')) {
- $data[substr($key, 9)] = $value;
- }
- }
-
- if ($this->getQuote()->getCustomerEmail()) {
- $data['email'] = $this->getQuote()->getCustomerEmail();
- }
-
- return $data;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Address.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Address.php
index 6aaa4302d28..801b76c04b9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Address.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Address.php
@@ -49,21 +49,6 @@ public function getAddressCollection()
return $addresses;
}
- /**
- * Return customer address form instance
- *
- * @return Mage_Customer_Model_Form
- */
- protected function _getAddressForm()
- {
- if (is_null($this->_addressForm)) {
- $this->_addressForm = Mage::getModel('customer/form')
- ->setFormCode('adminhtml_customer_address')
- ->setStore($this->getStore());
- }
- return $this->_addressForm;
- }
-
/**
* Return Customer Address Collection as JSON
*
@@ -89,6 +74,42 @@ public function getAddressCollectionJson()
return Mage::helper('core')->jsonEncode($data);
}
+ /**
+ * Return customer address id
+ *
+ * @return false
+ */
+ public function getAddressId()
+ {
+ return false;
+ }
+
+ /**
+ * Return customer address formatted as one-line string
+ *
+ * @param Mage_Customer_Model_Address $address
+ * @return string
+ */
+ public function getAddressAsString($address)
+ {
+ return $this->escapeHtml($address->format('oneline'));
+ }
+
+ /**
+ * Return customer address form instance
+ *
+ * @return Mage_Customer_Model_Form
+ */
+ protected function _getAddressForm()
+ {
+ if (is_null($this->_addressForm)) {
+ $this->_addressForm = Mage::getModel('customer/form')
+ ->setFormCode('adminhtml_customer_address')
+ ->setStore($this->getStore());
+ }
+ return $this->_addressForm;
+ }
+
/**
* Prepare Form and add elements to form
*
@@ -199,25 +220,4 @@ protected function _addAdditionalFormElementData(Varien_Data_Form_Element_Abstra
}
return $this;
}
-
- /**
- * Return customer address id
- *
- * @return false
- */
- public function getAddressId()
- {
- return false;
- }
-
- /**
- * Return customer address formatted as one-line string
- *
- * @param Mage_Customer_Model_Address $address
- * @return string
- */
- public function getAddressAsString($address)
- {
- return $this->escapeHtml($address->format('oneline'));
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Giftmessage.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Giftmessage.php
index 237a7536f11..90967182e75 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Giftmessage.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Giftmessage.php
@@ -70,16 +70,6 @@ public function getItems()
return false;
}
- /**
- * Retrieve gift message save model
- *
- * @return Mage_Adminhtml_Model_Giftmessage_Save
- */
- protected function _getGiftmessageSaveModel()
- {
- return Mage::getSingleton('adminhtml/giftmessage_save');
- }
-
public function canDisplayGiftmessage(): bool
{
if (!$this->isModuleOutputEnabled('Mage_GiftMessage')) {
@@ -89,4 +79,14 @@ public function canDisplayGiftmessage(): bool
$helper = $this->helper('giftmessage/message');
return $helper->getIsMessagesAvailable($helper::TYPE_CONFIG, $this->getQuote(), $this->getStoreId());
}
+
+ /**
+ * Retrieve gift message save model
+ *
+ * @return Mage_Adminhtml_Model_Giftmessage_Save
+ */
+ protected function _getGiftmessageSaveModel()
+ {
+ return Mage::getSingleton('adminhtml/giftmessage_save');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Giftmessage/Form.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Giftmessage/Form.php
index dedc745041c..e3ae48e2d55 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Giftmessage/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Giftmessage/Form.php
@@ -57,14 +57,6 @@ public function getEntity()
return $this->_entity;
}
- /**
- * @return Mage_Adminhtml_Model_Session_Quote
- */
- protected function _getSession()
- {
- return Mage::getSingleton('adminhtml/session_quote');
- }
-
/**
* Retrieve default value for giftmessage sender
*
@@ -166,6 +158,28 @@ public function _prepareForm()
return $this;
}
+ /**
+ * Retrieve gift message for entity
+ *
+ * @return Mage_GiftMessage_Model_Message
+ */
+ public function getMessage()
+ {
+ if (is_null($this->_giftMessage)) {
+ $this->_initMessage();
+ }
+
+ return $this->_giftMessage;
+ }
+
+ /**
+ * @return Mage_Adminhtml_Model_Session_Quote
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('adminhtml/session_quote');
+ }
+
/**
* Prepare form fieldset
* All fields are hidden
@@ -254,20 +268,6 @@ protected function _initMessage()
return $this;
}
- /**
- * Retrieve gift message for entity
- *
- * @return Mage_GiftMessage_Model_Message
- */
- public function getMessage()
- {
- if (is_null($this->_giftMessage)) {
- $this->_initMessage();
- }
-
- return $this->_giftMessage;
- }
-
/**
* Retrieve real name for field
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Search/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Search/Grid.php
index 3b7f5ac0eb8..207117d95e1 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Search/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Search/Grid.php
@@ -60,6 +60,14 @@ public function getQuote()
return Mage::getSingleton('adminhtml/session_quote')->getQuote();
}
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/loadBlock', ['block' => 'search_grid', '_current' => true, 'collapse' => null]);
+ }
+
/**
* @param Mage_Adminhtml_Block_Widget_Grid_Column $column
* @return $this
@@ -167,14 +175,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/loadBlock', ['block' => 'search_grid', '_current' => true, 'collapse' => null]);
- }
-
/**
* @return array
* @throws Exception
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Search/Grid/Renderer/Qty.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Search/Grid/Renderer/Qty.php
index 530badbfca7..1a1eef0ae1e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Search/Grid/Renderer/Qty.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Search/Grid/Renderer/Qty.php
@@ -22,17 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Create_Search_Grid_Renderer_Qty extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Input
{
- /**
- * Returns whether this qty field must be inactive
- *
- * @param Varien_Object $row
- * @return bool
- */
- protected function _isInactive($row)
- {
- return $row->getTypeId() == Mage_Catalog_Model_Product_Type_Grouped::TYPE_CODE;
- }
-
/**
* Render product qty field
*
@@ -62,4 +51,14 @@ public function render(Varien_Object $row)
}
return $html . ('class="input-text ' . $this->getColumn()->getInlineCss() . ($isInactive ? ' input-inactive' : '') . '" />');
}
+ /**
+ * Returns whether this qty field must be inactive
+ *
+ * @param Varien_Object $row
+ * @return bool
+ */
+ protected function _isInactive($row)
+ {
+ return $row->getTypeId() == Mage_Catalog_Model_Product_Type_Grouped::TYPE_CODE;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Shipping/Address.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Shipping/Address.php
index 5d2e1ec9a1d..82136ff50b5 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Shipping/Address.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Shipping/Address.php
@@ -42,23 +42,6 @@ public function getHeaderCssClass()
return 'head-shipping-address';
}
- /**
- * Prepare Form and add elements to form
- *
- * @return $this
- */
- protected function _prepareForm()
- {
- $this->setJsVariablePrefix('shippingAddress');
- parent::_prepareForm();
-
- $this->_form->addFieldNameSuffix('order[shipping_address]');
- $this->_form->setHtmlNamePrefix('order[shipping_address]');
- $this->_form->setHtmlIdPrefix('order-shipping_address_');
-
- return $this;
- }
-
/**
* Return is shipping address flag
*
@@ -134,4 +117,21 @@ public function getIsDisabled()
{
return $this->getQuote()->isVirtual();
}
+
+ /**
+ * Prepare Form and add elements to form
+ *
+ * @return $this
+ */
+ protected function _prepareForm()
+ {
+ $this->setJsVariablePrefix('shippingAddress');
+ parent::_prepareForm();
+
+ $this->_form->addFieldNameSuffix('order[shipping_address]');
+ $this->_form->setHtmlNamePrefix('order[shipping_address]');
+ $this->_form->setHtmlIdPrefix('order-shipping_address_');
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar.php
index 95c81225a31..15308ca8d26 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar.php
@@ -22,6 +22,13 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Create_Sidebar extends Mage_Adminhtml_Block_Sales_Order_Create_Abstract
{
+ public function canDisplay($child)
+ {
+ if (method_exists($child, 'canDisplay')) {
+ return $child->canDisplay();
+ }
+ return true;
+ }
protected function _prepareLayout()
{
if ($this->getCustomerId()) {
@@ -40,12 +47,4 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
-
- public function canDisplay($child)
- {
- if (method_exists($child, 'canDisplay')) {
- return $child->canDisplay();
- }
- return true;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Cart.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Cart.php
index fac2f7aa78b..6d682410eac 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Cart.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Cart.php
@@ -29,13 +29,6 @@ class Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Cart extends Mage_Adminhtm
*/
protected $_sidebarStorageAction = 'add_cart_item';
- protected function _construct()
- {
- parent::_construct();
- $this->setId('sales_order_create_sidebar_cart');
- $this->setDataId('cart');
- }
-
/**
* @return string
*/
@@ -89,6 +82,13 @@ public function getProductId($item)
return $item->getProduct()->getId();
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setId('sales_order_create_sidebar_cart');
+ $this->setDataId('cart');
+ }
+
/**
* @inheritDoc
*/
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Compared.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Compared.php
index b3e7d3a9c11..b0173caeb31 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Compared.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Compared.php
@@ -22,13 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Compared extends Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Abstract
{
- protected function _construct()
- {
- parent::_construct();
- $this->setId('sales_order_create_sidebar_compared');
- $this->setDataId('compared');
- }
-
/**
* @return string
*/
@@ -67,4 +60,10 @@ public function getItemId($item)
{
return $item->getCatalogCompareItemId();
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setId('sales_order_create_sidebar_compared');
+ $this->setDataId('compared');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Pcompared.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Pcompared.php
index 2bdb00d6b59..d199e57a478 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Pcompared.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Pcompared.php
@@ -22,13 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Pcompared extends Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Abstract
{
- protected function _construct()
- {
- parent::_construct();
- $this->setId('sales_order_create_sidebar_pcompared');
- $this->setDataId('pcompared');
- }
-
/**
* @return string
*/
@@ -111,4 +104,10 @@ public function getProductId($item)
{
return $item->getId();
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setId('sales_order_create_sidebar_pcompared');
+ $this->setDataId('pcompared');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Pviewed.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Pviewed.php
index 9e50846ff4f..34ad9ffc9b3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Pviewed.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Pviewed.php
@@ -22,13 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Pviewed extends Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Abstract
{
- protected function _construct()
- {
- parent::_construct();
- $this->setId('sales_order_create_sidebar_pviewed');
- $this->setDataId('pviewed');
- }
-
/**
* @return string
*/
@@ -98,4 +91,10 @@ public function getIdentifierId($item)
{
return $item->getId();
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setId('sales_order_create_sidebar_pviewed');
+ $this->setDataId('pviewed');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Reorder.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Reorder.php
index f47cfbe2fca..e1904ab61cd 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Reorder.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Reorder.php
@@ -29,13 +29,6 @@ class Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Reorder extends Mage_Admin
*/
protected $_sidebarStorageAction = 'add_order_item';
- protected function _construct()
- {
- parent::_construct();
- $this->setId('sales_order_create_sidebar_reorder');
- $this->setDataId('reorder');
- }
-
/**
* @return string
*/
@@ -117,4 +110,11 @@ public function getIdentifierId($item)
{
return $item->getId();
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setId('sales_order_create_sidebar_reorder');
+ $this->setDataId('reorder');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Viewed.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Viewed.php
index fd6a6580965..b53c5f28e0c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Viewed.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Viewed.php
@@ -22,13 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Viewed extends Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Abstract
{
- protected function _construct()
- {
- parent::_construct();
- $this->setId('sales_order_create_sidebar_viewed');
- $this->setDataId('viewed');
- }
-
/**
* Retrieve display block availability
*
@@ -56,4 +49,10 @@ public function getHeaderText()
{
return Mage::helper('sales')->__('Recently Viewed');
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setId('sales_order_create_sidebar_viewed');
+ $this->setDataId('viewed');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Wishlist.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Wishlist.php
index 9852f5ce55f..ddc6816abf0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Wishlist.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Sidebar/Wishlist.php
@@ -29,13 +29,6 @@ class Mage_Adminhtml_Block_Sales_Order_Create_Sidebar_Wishlist extends Mage_Admi
*/
protected $_sidebarStorageAction = 'add_wishlist_item';
- protected function _construct()
- {
- parent::_construct();
- $this->setId('sales_order_create_sidebar_wishlist');
- $this->setDataId('wishlist');
- }
-
/**
* @return string
*/
@@ -121,4 +114,11 @@ public function canDisplayItemQty()
{
return true;
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setId('sales_order_create_sidebar_wishlist');
+ $this->setDataId('wishlist');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Totals.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Totals.php
index 3514b819174..bee30de11ce 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Totals.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Totals.php
@@ -52,26 +52,6 @@ public function getHeaderCssClass()
return 'head-money';
}
- protected function _getTotalRenderer($code)
- {
- $blockName = $code . '_total_renderer';
- $block = $this->getLayout()->getBlock($blockName);
- if (!$block) {
- $block = $this->_defaultRenderer;
- $config = Mage::getConfig()->getNode("global/sales/quote/totals/{$code}/admin_renderer");
- if ($config) {
- $block = (string) $config;
- }
-
- $block = $this->getLayout()->createBlock($block, $blockName);
- }
- /**
- * Transfer totals to renderer
- */
- $block->setTotals($this->getTotals());
- return $block;
- }
-
public function renderTotal($total, $area = null, $colspan = 1)
{
return $this->_getTotalRenderer($total->getCode())
@@ -100,4 +80,24 @@ public function canSendNewOrderConfirmationEmail()
{
return Mage::helper('sales')->canSendNewOrderConfirmationEmail($this->getQuote()->getStoreId());
}
+
+ protected function _getTotalRenderer($code)
+ {
+ $blockName = $code . '_total_renderer';
+ $block = $this->getLayout()->getBlock($blockName);
+ if (!$block) {
+ $block = $this->_defaultRenderer;
+ $config = Mage::getConfig()->getNode("global/sales/quote/totals/{$code}/admin_renderer");
+ if ($config) {
+ $block = (string) $config;
+ }
+
+ $block = $this->getLayout()->createBlock($block, $blockName);
+ }
+ /**
+ * Transfer totals to renderer
+ */
+ $block->setTotals($this->getTotals());
+ return $block;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Totals/Default.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Totals/Default.php
index ac066401581..8d0e3abfda9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Totals/Default.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Totals/Default.php
@@ -24,21 +24,6 @@ class Mage_Adminhtml_Block_Sales_Order_Create_Totals_Default extends Mage_Adminh
{
protected $_template = 'sales/order/create/totals/default.phtml';
- protected function _construct()
- {
- $this->setTemplate($this->_template);
- }
-
- /**
- * Retrieve quote session object
- *
- * @return Mage_Adminhtml_Model_Session_Quote
- */
- protected function _getSession()
- {
- return Mage::getSingleton('adminhtml/session_quote');
- }
-
/**
* Retrieve store model object
*
@@ -53,4 +38,19 @@ public function formatPrice($value)
{
return $this->getStore()->formatPrice($value);
}
+
+ protected function _construct()
+ {
+ $this->setTemplate($this->_template);
+ }
+
+ /**
+ * Retrieve quote session object
+ *
+ * @return Mage_Adminhtml_Model_Session_Quote
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('adminhtml/session_quote');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Creditmemo/Create/Items.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Creditmemo/Create/Items.php
index a4e8cf21be1..d5703600d38 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Creditmemo/Create/Items.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Creditmemo/Create/Items.php
@@ -23,55 +23,6 @@
class Mage_Adminhtml_Block_Sales_Order_Creditmemo_Create_Items extends Mage_Adminhtml_Block_Sales_Items_Abstract
{
protected $_canReturnToStock;
- /**
- * Prepare child blocks
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- $onclick = "submitAndReloadArea($('creditmemo_item_container'),'" . $this->getUpdateUrl() . "')";
- $this->setChild(
- 'update_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('sales')->__('Update Qty\'s'),
- 'class' => 'update-button',
- 'onclick' => $onclick,
- ]),
- );
-
- if ($this->getCreditmemo()->canRefund()) {
- if ($this->getCreditmemo()->getInvoice() && $this->getCreditmemo()->getInvoice()->getTransactionId()) {
- $this->setChild(
- 'submit_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('sales')->__('Refund'),
- 'class' => 'save submit-button',
- 'onclick' => 'disableElements(\'submit-button\');submitCreditMemo()',
- ]),
- );
- }
- $this->setChild(
- 'submit_offline',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('sales')->__('Refund Offline'),
- 'class' => 'save submit-button',
- 'onclick' => 'disableElements(\'submit-button\');submitCreditMemoOffline()',
- ]),
- );
- } else {
- $this->setChild(
- 'submit_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('sales')->__('Refund Offline'),
- 'class' => 'save submit-button',
- 'onclick' => 'disableElements(\'submit-button\');submitCreditMemoOffline()',
- ]),
- );
- }
-
- return parent::_prepareLayout();
- }
/**
* Retrieve invoice order
@@ -189,4 +140,53 @@ public function canSendCreditmemoEmail()
{
return Mage::helper('sales')->canSendNewCreditmemoEmail($this->getOrder()->getStore()->getId());
}
+ /**
+ * Prepare child blocks
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $onclick = "submitAndReloadArea($('creditmemo_item_container'),'" . $this->getUpdateUrl() . "')";
+ $this->setChild(
+ 'update_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('sales')->__('Update Qty\'s'),
+ 'class' => 'update-button',
+ 'onclick' => $onclick,
+ ]),
+ );
+
+ if ($this->getCreditmemo()->canRefund()) {
+ if ($this->getCreditmemo()->getInvoice() && $this->getCreditmemo()->getInvoice()->getTransactionId()) {
+ $this->setChild(
+ 'submit_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('sales')->__('Refund'),
+ 'class' => 'save submit-button',
+ 'onclick' => 'disableElements(\'submit-button\');submitCreditMemo()',
+ ]),
+ );
+ }
+ $this->setChild(
+ 'submit_offline',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('sales')->__('Refund Offline'),
+ 'class' => 'save submit-button',
+ 'onclick' => 'disableElements(\'submit-button\');submitCreditMemoOffline()',
+ ]),
+ );
+ } else {
+ $this->setChild(
+ 'submit_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('sales')->__('Refund Offline'),
+ 'class' => 'save submit-button',
+ 'onclick' => 'disableElements(\'submit-button\');submitCreditMemoOffline()',
+ ]),
+ );
+ }
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php
index 0a741c51538..86ac1f7b846 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php
@@ -34,6 +34,52 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * Add link to RSS feed when enabled for filtered store-view
+ *
+ * @return $this
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ public function addRssFeedLink()
+ {
+ if ($this->isModuleOutputEnabled('Mage_Rss', 'sales')) {
+ $storeId = null;
+
+ $filterString = $this->getParam($this->getVarNameFilter(), '');
+ if ($filterString) {
+ $filter = Mage::helper('adminhtml')->prepareFilterString($filterString);
+ $storeId = $filter['store_id'] ?? null;
+ }
+
+ if (Mage::helper('rss')->isRssAdminOrderNewEnabled($storeId)) {
+ $slug = $storeId ? '/store/' . $storeId : '';
+ $this->addRssList('rss/order/new' . $slug, Mage::helper('sales')->__('New Order RSS'));
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * @param Mage_Sales_Model_Order $row
+ * @return false|string
+ */
+ public function getRowUrl($row)
+ {
+ if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
+ return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
+ }
+ return false;
+ }
+
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
/**
* Retrieve collection class
*
@@ -144,32 +190,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Add link to RSS feed when enabled for filtered store-view
- *
- * @return $this
- * @throws Mage_Core_Model_Store_Exception
- */
- public function addRssFeedLink()
- {
- if ($this->isModuleOutputEnabled('Mage_Rss', 'sales')) {
- $storeId = null;
-
- $filterString = $this->getParam($this->getVarNameFilter(), '');
- if ($filterString) {
- $filter = Mage::helper('adminhtml')->prepareFilterString($filterString);
- $storeId = $filter['store_id'] ?? null;
- }
-
- if (Mage::helper('rss')->isRssAdminOrderNewEnabled($storeId)) {
- $slug = $storeId ? '/store/' . $storeId : '';
- $this->addRssList('rss/order/new' . $slug, Mage::helper('sales')->__('New Order RSS'));
- }
- }
-
- return $this;
- }
-
/**
* @return $this
*/
@@ -227,24 +247,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * @param Mage_Sales_Model_Order $row
- * @return false|string
- */
- public function getRowUrl($row)
- {
- if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
- return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
- }
- return false;
- }
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Form.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Form.php
index 4c92c895170..09b5d7200a0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Form.php
@@ -52,29 +52,6 @@ public function getInvoice()
return Mage::registry('current_invoice');
}
- protected function _prepareLayout()
- {
- /* $infoBlock = $this->getLayout()->createBlock('adminhtml/sales_order_view_info')
- ->setOrder($this->getInvoice()->getOrder());
- $this->setChild('order_info', $infoBlock);
-*/
- /* $this->setChild(
- 'items',
- $this->getLayout()->createBlock('adminhtml/sales_order_invoice_create_items')
- );
- */
- $trackingBlock = $this->getLayout()->createBlock('adminhtml/sales_order_invoice_create_tracking');
- //$this->setChild('order_tracking', $trackingBlock);
- $this->setChild('tracking', $trackingBlock);
-
- /*
- $paymentInfoBlock = $this->getLayout()->createBlock('adminhtml/sales_order_payment')
- ->setPayment($this->getInvoice()->getOrder()->getPayment());
- $this->setChild('payment_info', $paymentInfoBlock);
- */
- return parent::_prepareLayout();
- }
-
public function getSaveUrl()
{
return $this->getUrl('*/*/save', ['order_id' => $this->getInvoice()->getOrderId()]);
@@ -118,4 +95,27 @@ public function getForcedShipmentCreate()
{
return (int) $this->getOrder()->getForcedDoShipmentWithInvoice();
}
+
+ protected function _prepareLayout()
+ {
+ /* $infoBlock = $this->getLayout()->createBlock('adminhtml/sales_order_view_info')
+ ->setOrder($this->getInvoice()->getOrder());
+ $this->setChild('order_info', $infoBlock);
+*/
+ /* $this->setChild(
+ 'items',
+ $this->getLayout()->createBlock('adminhtml/sales_order_invoice_create_items')
+ );
+ */
+ $trackingBlock = $this->getLayout()->createBlock('adminhtml/sales_order_invoice_create_tracking');
+ //$this->setChild('order_tracking', $trackingBlock);
+ $this->setChild('tracking', $trackingBlock);
+
+ /*
+ $paymentInfoBlock = $this->getLayout()->createBlock('adminhtml/sales_order_payment')
+ ->setPayment($this->getInvoice()->getOrder()->getPayment());
+ $this->setChild('payment_info', $paymentInfoBlock);
+ */
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Items.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Items.php
index 4953077efc5..1cc28b6e870 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Items.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Items.php
@@ -24,52 +24,6 @@ class Mage_Adminhtml_Block_Sales_Order_Invoice_Create_Items extends Mage_Adminht
{
protected $_disableSubmitButton = false;
- /**
- * Prepare child blocks
- *
- * @return $this
- */
- protected function _beforeToHtml()
- {
- $onclick = "submitAndReloadArea($('invoice_item_container'),'" . $this->getUpdateUrl() . "')";
- $this->setChild(
- 'update_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'class' => 'update-button',
- 'label' => Mage::helper('sales')->__('Update Qty\'s'),
- 'onclick' => $onclick,
- ]),
- );
- $this->_disableSubmitButton = true;
- $submitButtonClass = ' disabled';
- foreach ($this->getInvoice()->getAllItems() as $item) {
- /**
- * @see bug #14839
- */
- if ($item->getQty()/* || $this->getSource()->getData('base_grand_total')*/) {
- $this->_disableSubmitButton = false;
- $submitButtonClass = '';
- break;
- }
- }
- if ($this->getOrder()->getForcedDoShipmentWithInvoice()) {
- $submitLabel = Mage::helper('sales')->__('Submit Invoice and Shipment');
- } else {
- $submitLabel = Mage::helper('sales')->__('Submit Invoice');
- }
- $this->setChild(
- 'submit_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => $submitLabel,
- 'class' => 'save submit-button' . $submitButtonClass,
- 'onclick' => 'disableElements(\'submit-button\');$(\'edit_form\').submit()',
- 'disabled' => $this->_disableSubmitButton,
- ]),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* Get is submit button disabled or not
*
@@ -207,4 +161,50 @@ public function canSendInvoiceEmail()
{
return Mage::helper('sales')->canSendNewInvoiceEmail($this->getOrder()->getStore()->getId());
}
+
+ /**
+ * Prepare child blocks
+ *
+ * @return $this
+ */
+ protected function _beforeToHtml()
+ {
+ $onclick = "submitAndReloadArea($('invoice_item_container'),'" . $this->getUpdateUrl() . "')";
+ $this->setChild(
+ 'update_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'class' => 'update-button',
+ 'label' => Mage::helper('sales')->__('Update Qty\'s'),
+ 'onclick' => $onclick,
+ ]),
+ );
+ $this->_disableSubmitButton = true;
+ $submitButtonClass = ' disabled';
+ foreach ($this->getInvoice()->getAllItems() as $item) {
+ /**
+ * @see bug #14839
+ */
+ if ($item->getQty()/* || $this->getSource()->getData('base_grand_total')*/) {
+ $this->_disableSubmitButton = false;
+ $submitButtonClass = '';
+ break;
+ }
+ }
+ if ($this->getOrder()->getForcedDoShipmentWithInvoice()) {
+ $submitLabel = Mage::helper('sales')->__('Submit Invoice and Shipment');
+ } else {
+ $submitLabel = Mage::helper('sales')->__('Submit Invoice');
+ }
+ $this->setChild(
+ 'submit_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => $submitLabel,
+ 'class' => 'save submit-button' . $submitButtonClass,
+ 'onclick' => 'disableElements(\'submit-button\');$(\'edit_form\').submit()',
+ 'disabled' => $this->_disableSubmitButton,
+ ]),
+ );
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Tracking.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Tracking.php
index eaefbd32bac..946b8317251 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Tracking.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Invoice/Create/Tracking.php
@@ -27,25 +27,6 @@ public function _construct()
$this->setTemplate('sales/order/invoice/create/tracking.phtml');
}
- /**
- * Prepares layout of block
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'add_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('sales')->__('Add Tracking Number'),
- 'class' => '',
- 'onclick' => 'trackingControl.add()',
- ]),
- );
- return $this;
- }
-
/**
* Retrieve shipment model instance
*
@@ -85,4 +66,23 @@ public function getCarriers()
}
return $carriers;
}
+
+ /**
+ * Prepares layout of block
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'add_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('sales')->__('Add Tracking Number'),
+ 'class' => '',
+ 'onclick' => 'trackingControl.add()',
+ ]),
+ );
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Payment.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Payment.php
index d446bd9f880..627bbfa7465 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Payment.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Payment.php
@@ -22,6 +22,13 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Payment extends Mage_Adminhtml_Block_Template
{
+ public function setPayment($payment)
+ {
+ $paymentInfoBlock = Mage::helper('payment')->getInfoBlock($payment);
+ $this->setChild('info', $paymentInfoBlock);
+ $this->setData('payment', $payment);
+ return $this;
+ }
/**
* Retrieve required options from parent
*/
@@ -34,14 +41,6 @@ protected function _beforeToHtml()
return parent::_beforeToHtml();
}
- public function setPayment($payment)
- {
- $paymentInfoBlock = Mage::helper('payment')->getInfoBlock($payment);
- $this->setChild('info', $paymentInfoBlock);
- $this->setData('payment', $payment);
- return $this;
- }
-
protected function _toHtml()
{
return $this->getChildHtml('info');
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Form.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Form.php
index 9095380ef58..985e6ebcf2d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Form.php
@@ -52,20 +52,6 @@ public function getShipment()
return Mage::registry('current_shipment');
}
- protected function _prepareLayout()
- {
- $this->setChild(
- 'items',
- $this->getLayout()->createBlock('adminhtml/sales_order_shipment_create_items'),
- );
- $this->setChild(
- 'tracking',
- $this->getLayout()->createBlock('adminhtml/sales_order_shipment_create_tracking'),
- );
-
- return $this;
- }
-
public function getPaymentHtml()
{
return $this->getChildHtml('order_payment');
@@ -80,4 +66,18 @@ public function getSaveUrl()
{
return $this->getUrl('*/*/save', ['order_id' => $this->getShipment()->getOrderId()]);
}
+
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'items',
+ $this->getLayout()->createBlock('adminhtml/sales_order_shipment_create_items'),
+ );
+ $this->setChild(
+ 'tracking',
+ $this->getLayout()->createBlock('adminhtml/sales_order_shipment_create_tracking'),
+ );
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Items.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Items.php
index 72044b587fa..5d9ce641700 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Items.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Items.php
@@ -52,23 +52,6 @@ public function getShipment()
return Mage::registry('current_shipment');
}
- /**
- * Prepare child blocks
- */
- protected function _beforeToHtml()
- {
- $this->setChild(
- 'submit_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
- 'label' => Mage::helper('sales')->__('Submit Shipment'),
- 'class' => 'save submit-button',
- 'onclick' => 'submitShipment(this);',
- ]),
- );
-
- return parent::_beforeToHtml();
- }
-
/**
* Format given price
*
@@ -120,4 +103,21 @@ public function canCreateShippingLabel()
$shippingCarrier = $this->getOrder()->getShippingCarrier();
return $shippingCarrier && $shippingCarrier->isShippingLabelsAvailable();
}
+
+ /**
+ * Prepare child blocks
+ */
+ protected function _beforeToHtml()
+ {
+ $this->setChild(
+ 'submit_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->setData([
+ 'label' => Mage::helper('sales')->__('Submit Shipment'),
+ 'class' => 'save submit-button',
+ 'onclick' => 'submitShipment(this);',
+ ]),
+ );
+
+ return parent::_beforeToHtml();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Tracking.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Tracking.php
index 06aae1fe827..222b328281e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Tracking.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Create/Tracking.php
@@ -22,25 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Shipment_Create_Tracking extends Mage_Adminhtml_Block_Template
{
- /**
- * Prepares layout of block
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'add_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('sales')->__('Add Tracking Number'),
- 'class' => '',
- 'onclick' => 'trackingControl.add()',
- ]),
- );
- return $this;
- }
-
/**
* Retrieve shipment model instance
*
@@ -70,4 +51,22 @@ public function getCarriers()
}
return $carriers;
}
+ /**
+ * Prepares layout of block
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'add_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('sales')->__('Add Tracking Number'),
+ 'class' => '',
+ 'onclick' => 'trackingControl.add()',
+ ]),
+ );
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Packaging.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Packaging.php
index 6a97b0623ed..a71eb988426 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Packaging.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Packaging.php
@@ -121,20 +121,6 @@ public function getContainers()
return [];
}
- /**
- * Get codes of customizable container types of carrier
- *
- * @return array
- */
- protected function _getCustomizableContainers()
- {
- $carrier = $this->getShipment()->getOrder()->getShippingCarrier();
- if ($carrier) {
- return $carrier->getCustomizableContainerTypes();
- }
- return [];
- }
-
/**
* Return name of container type by its code
*
@@ -360,4 +346,18 @@ public function getQtyOrderedItem($itemId)
return;
}
}
+
+ /**
+ * Get codes of customizable container types of carrier
+ *
+ * @return array
+ */
+ protected function _getCustomizableContainers()
+ {
+ $carrier = $this->getShipment()->getOrder()->getShippingCarrier();
+ if ($carrier) {
+ return $carrier->getCustomizableContainerTypes();
+ }
+ return [];
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/View/Tracking.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/View/Tracking.php
index b009eacc6f1..ad8398dca7f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/View/Tracking.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/View/Tracking.php
@@ -22,26 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Shipment_View_Tracking extends Mage_Adminhtml_Block_Template
{
- /**
- * Prepares layout of block
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- $onclick = "submitAndReloadArea($('shipment_tracking_info').parentNode, '" . $this->getSubmitUrl() . "')";
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('sales')->__('Add'),
- 'class' => 'save',
- 'onclick' => $onclick,
- ]),
- );
- return $this;
- }
-
/**
* Retrieve shipment model instance
*
@@ -129,4 +109,23 @@ public function getCarrierTitle($code)
}
return Mage::helper('sales')->__('Custom Value');
}
+ /**
+ * Prepares layout of block
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $onclick = "submitAndReloadArea($('shipment_tracking_info').parentNode, '" . $this->getSubmitUrl() . "')";
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('sales')->__('Add'),
+ 'class' => 'save',
+ 'onclick' => $onclick,
+ ]),
+ );
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/Grid.php
index 993683d0fd5..7435a885b42 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/Grid.php
@@ -32,6 +32,41 @@ public function __construct()
$this->setDefaultDir('DESC');
}
+ /**
+ * Decorate status column values
+ *
+ * @return string
+ */
+ public function decorateState($value, $row, $column, $isExport)
+ {
+ if ($value) {
+ $cell = $value . ' [' . Mage::getSingleton('sales/order_config')->getStateLabel($value) . ']';
+ } else {
+ $cell = $value;
+ }
+ return $cell;
+ }
+
+ public function decorateAction($value, $row, $column, $isExport)
+ {
+ $cell = '';
+ $state = $row->getState();
+ if (!empty($state)) {
+ $url = $this->getUrl(
+ '*/*/unassign',
+ ['status' => $row->getStatus(), 'state' => $row->getState()],
+ );
+ $label = Mage::helper('sales')->__('Unassign');
+ $cell = '' . $label . '';
+ }
+ return $cell;
+ }
+
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/sales_order_status/edit', ['status' => $row->getStatus()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('sales/order_status_collection');
@@ -86,36 +121,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Decorate status column values
- *
- * @return string
- */
- public function decorateState($value, $row, $column, $isExport)
- {
- if ($value) {
- $cell = $value . ' [' . Mage::getSingleton('sales/order_config')->getStateLabel($value) . ']';
- } else {
- $cell = $value;
- }
- return $cell;
- }
-
- public function decorateAction($value, $row, $column, $isExport)
- {
- $cell = '';
- $state = $row->getState();
- if (!empty($state)) {
- $url = $this->getUrl(
- '*/*/unassign',
- ['status' => $row->getStatus(), 'state' => $row->getState()],
- );
- $label = Mage::helper('sales')->__('Unassign');
- $cell = '' . $label . '';
- }
- return $cell;
- }
-
/**
* No pegination for this grid
*/
@@ -123,9 +128,4 @@ protected function _preparePage()
{
return $this;
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/sales_order_status/edit', ['status' => $row->getStatus()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totalbar.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totalbar.php
index 9763b85e2cd..4da8ba77324 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totalbar.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totalbar.php
@@ -24,6 +24,16 @@ class Mage_Adminhtml_Block_Sales_Order_Totalbar extends Mage_Adminhtml_Block_Sal
{
protected $_totals = [];
+ public function addTotal($label, $value, $grand = false)
+ {
+ $this->_totals[] = [
+ 'label' => $label,
+ 'value' => $value,
+ 'grand' => $grand,
+ ];
+ return $this;
+ }
+
/**
* Retrieve required options from parent
*/
@@ -47,14 +57,4 @@ protected function getTotals()
{
return $this->_totals;
}
-
- public function addTotal($label, $value, $grand = false)
- {
- $this->_totals[] = [
- 'label' => $label,
- 'value' => $value,
- 'grand' => $grand,
- ];
- return $this;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totals/Item.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totals/Item.php
index 85333185f8d..a243b7a5ae9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totals/Item.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totals/Item.php
@@ -22,22 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_Totals_Item extends Mage_Adminhtml_Block_Sales_Order_Totals
{
- /**
- * Determine display parameters before rendering HTML
- *
- * @return $this
- */
- protected function _beforeToHtml()
- {
- parent::_beforeToHtml();
-
- $this->setCanDisplayTotalPaid($this->getParentBlock()->getCanDisplayTotalPaid());
- $this->setCanDisplayTotalRefunded($this->getParentBlock()->getCanDisplayTotalRefunded());
- $this->setCanDisplayTotalDue($this->getParentBlock()->getCanDisplayTotalDue());
-
- return $this;
- }
-
/**
* Initialize totals object
*
@@ -97,4 +81,19 @@ public function getSource()
{
return $this->getParentBlock()->getSource();
}
+ /**
+ * Determine display parameters before rendering HTML
+ *
+ * @return $this
+ */
+ protected function _beforeToHtml()
+ {
+ parent::_beforeToHtml();
+
+ $this->setCanDisplayTotalPaid($this->getParentBlock()->getCanDisplayTotalPaid());
+ $this->setCanDisplayTotalRefunded($this->getParentBlock()->getCanDisplayTotalRefunded());
+ $this->setCanDisplayTotalDue($this->getParentBlock()->getCanDisplayTotalDue());
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totals/Tax.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totals/Tax.php
index 343d8ac95c5..d4474952d64 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totals/Tax.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Totals/Tax.php
@@ -40,16 +40,6 @@ public function getFullTaxInfo()
return $taxClassAmount;
}
- /**
- * Return Mage_Tax_Helper_Data instance
- *
- * @return Mage_Tax_Helper_Data
- */
- protected function _getTaxHelper()
- {
- return Mage::helper('tax');
- }
-
/**
* Display tax amount
*
@@ -77,4 +67,14 @@ public function getStore()
{
return Mage::app()->getStore();
}
+
+ /**
+ * Return Mage_Tax_Helper_Data instance
+ *
+ * @return Mage_Tax_Helper_Data
+ */
+ protected function _getTaxHelper()
+ {
+ return Mage::helper('tax');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php
index 7218d8cc256..d686d5af8cb 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php
@@ -335,15 +335,6 @@ public function getVoidPaymentUrl()
return $this->getUrl('*/*/voidPayment');
}
- /**
- * @param string $action
- * @return bool
- */
- protected function _isAllowedAction($action)
- {
- return Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/' . $action);
- }
-
/**
* Return back url for view grid
*
@@ -376,4 +367,13 @@ public function getHeaderHtml()
{
return '';
}
+
+ /**
+ * @param string $action
+ * @return bool
+ */
+ protected function _isAllowedAction($action)
+ {
+ return Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/' . $action);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Giftmessage.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Giftmessage.php
index c966c6e4f8f..20d070b4547 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Giftmessage.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Giftmessage.php
@@ -29,16 +29,6 @@ class Mage_Adminhtml_Block_Sales_Order_View_Giftmessage extends Mage_Adminhtml_B
*/
protected $_entity;
- /**
- * Retrieve order model instance
- *
- * @return Mage_Sales_Model_Order
- */
- public function getOrder()
- {
- return Mage::registry('current_order');
- }
-
/**
* Giftmessage object
*
@@ -47,36 +37,13 @@ public function getOrder()
protected $_giftMessage;
/**
- * @inheritDoc
- */
- protected function _beforeToHtml()
- {
- if ($this->isModuleOutputEnabled('Mage_GiftMessage')) {
- if ($this->getParentBlock() && ($order = $this->getOrder())) {
- $this->setEntity($order);
- }
- return parent::_beforeToHtml();
- } else {
- return parent::_beforeToHtml();
- }
- }
-
- /**
- * @return $this
+ * Retrieve order model instance
+ *
+ * @return Mage_Sales_Model_Order
*/
- protected function _prepareLayout()
+ public function getOrder()
{
- if ($this->isModuleOutputEnabled('Mage_GiftMessage')) {
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('giftmessage')->__('Save Gift Message'),
- 'class' => 'save',
- ]),
- );
- }
- return $this;
+ return Mage::registry('current_order');
}
/**
@@ -206,29 +173,6 @@ public function getFieldIdPrefix()
return 'giftmessage_order_' . $this->getEntity()->getId() . '_';
}
- /**
- * Initialize gift message for entity
- *
- * @return $this
- * @throws Exception
- */
- protected function _initMessage()
- {
- /** @var Mage_GiftMessage_Helper_Message $helper */
- $helper = $this->helper('giftmessage/message');
- $this->_giftMessage = $helper->getGiftMessage($this->getEntity()->getGiftMessageId());
-
- // init default values for giftmessage form
- if (!$this->getMessage()->getSender()) {
- $this->getMessage()->setSender($this->getDefaultSender());
- }
- if (!$this->getMessage()->getRecipient()) {
- $this->getMessage()->setRecipient($this->getDefaultRecipient());
- }
-
- return $this;
- }
-
/**
* Retrieve gift message for entity
*
@@ -287,4 +231,60 @@ public function canDisplayGiftmessage()
$helper = $this->helper('giftmessage/message');
return $helper->getIsMessagesAvailable($helper::TYPE_ORDER, $this->getEntity(), $this->getEntity()->getStoreId());
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _beforeToHtml()
+ {
+ if ($this->isModuleOutputEnabled('Mage_GiftMessage')) {
+ if ($this->getParentBlock() && ($order = $this->getOrder())) {
+ $this->setEntity($order);
+ }
+ return parent::_beforeToHtml();
+ } else {
+ return parent::_beforeToHtml();
+ }
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ if ($this->isModuleOutputEnabled('Mage_GiftMessage')) {
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('giftmessage')->__('Save Gift Message'),
+ 'class' => 'save',
+ ]),
+ );
+ }
+ return $this;
+ }
+
+ /**
+ * Initialize gift message for entity
+ *
+ * @return $this
+ * @throws Exception
+ */
+ protected function _initMessage()
+ {
+ /** @var Mage_GiftMessage_Helper_Message $helper */
+ $helper = $this->helper('giftmessage/message');
+ $this->_giftMessage = $helper->getGiftMessage($this->getEntity()->getGiftMessageId());
+
+ // init default values for giftmessage form
+ if (!$this->getMessage()->getSender()) {
+ $this->getMessage()->setSender($this->getDefaultSender());
+ }
+ if (!$this->getMessage()->getRecipient()) {
+ $this->getMessage()->setRecipient($this->getDefaultRecipient());
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/History.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/History.php
index b8213637082..109c5937399 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/History.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/History.php
@@ -22,19 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_View_History extends Mage_Adminhtml_Block_Template
{
- protected function _prepareLayout()
- {
- $onclick = "submitAndReloadArea($('order_history_block').parentNode, '" . $this->getSubmitUrl() . "')";
- $button = $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('sales')->__('Submit Comment'),
- 'class' => 'save',
- 'onclick' => $onclick,
- ]);
- $this->setChild('submit_button', $button);
- return parent::_prepareLayout();
- }
-
public function getStatuses()
{
$state = $this->getOrder()->getState();
@@ -88,4 +75,16 @@ public function escapeHtml($data, $allowedTags = null)
{
return Mage::helper('adminhtml/sales')->escapeHtmlWithLinks($data, $allowedTags);
}
+ protected function _prepareLayout()
+ {
+ $onclick = "submitAndReloadArea($('order_history_block').parentNode, '" . $this->getSubmitUrl() . "')";
+ $button = $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('sales')->__('Submit Comment'),
+ 'class' => 'save',
+ 'onclick' => $onclick,
+ ]);
+ $this->setChild('submit_button', $button);
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Info.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Info.php
index ddc33164b6e..61818bfe681 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Info.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Info.php
@@ -22,23 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_View_Info extends Mage_Adminhtml_Block_Sales_Order_Abstract
{
- /**
- * Retrieve required options from parent
- */
- protected function _beforeToHtml()
- {
- if (!$this->getParentBlock()) {
- Mage::throwException(Mage::helper('adminhtml')->__('Invalid parent block for this block.'));
- }
- $this->setOrder($this->getParentBlock()->getOrder());
-
- foreach ($this->getParentBlock()->getOrderInfoData() as $k => $v) {
- $this->setDataUsingMethod($k, $v);
- }
-
- return parent::_beforeToHtml();
- }
-
public function getOrderStoreName()
{
if ($this->getOrder()) {
@@ -82,21 +65,6 @@ public function getViewUrl($orderId)
return $this->getUrl('*/sales_order/view', ['order_id' => $orderId]);
}
- /**
- * Find sort order for account data
- * Sort Order used as array key
- *
- * @param int $sortOrder
- * @return int
- */
- protected function _prepareAccountDataSortOrder(array $data, $sortOrder)
- {
- if (isset($data[$sortOrder])) {
- return $this->_prepareAccountDataSortOrder($data, $sortOrder + 1);
- }
- return $sortOrder;
- }
-
/**
* Return array of additional account data
* Value is option style array
@@ -161,4 +129,35 @@ public function shouldDisplayCustomerIp()
{
return !Mage::getStoreConfigFlag('sales/general/hide_customer_ip', $this->getOrder()->getStoreId());
}
+ /**
+ * Retrieve required options from parent
+ */
+ protected function _beforeToHtml()
+ {
+ if (!$this->getParentBlock()) {
+ Mage::throwException(Mage::helper('adminhtml')->__('Invalid parent block for this block.'));
+ }
+ $this->setOrder($this->getParentBlock()->getOrder());
+
+ foreach ($this->getParentBlock()->getOrderInfoData() as $k => $v) {
+ $this->setDataUsingMethod($k, $v);
+ }
+
+ return parent::_beforeToHtml();
+ }
+
+ /**
+ * Find sort order for account data
+ * Sort Order used as array key
+ *
+ * @param int $sortOrder
+ * @return int
+ */
+ protected function _prepareAccountDataSortOrder(array $data, $sortOrder)
+ {
+ if (isset($data[$sortOrder])) {
+ return $this->_prepareAccountDataSortOrder($data, $sortOrder + 1);
+ }
+ return $sortOrder;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items.php
index ba28644794d..f4d53eabf8f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items.php
@@ -22,6 +22,15 @@
*/
class Mage_Adminhtml_Block_Sales_Order_View_Items extends Mage_Adminhtml_Block_Sales_Items_Abstract
{
+ /**
+ * Retrieve order items collection
+ *
+ * @return Mage_Sales_Model_Order_Item[]|Mage_Sales_Model_Resource_Order_Item_Collection
+ */
+ public function getItemsCollection()
+ {
+ return $this->getOrder()->getItemsCollection();
+ }
/**
* Retrieve required options from parent
*/
@@ -33,14 +42,4 @@ protected function _beforeToHtml()
$this->setOrder($this->getParentBlock()->getOrder());
return parent::_beforeToHtml();
}
-
- /**
- * Retrieve order items collection
- *
- * @return Mage_Sales_Model_Order_Item[]|Mage_Sales_Model_Resource_Order_Item_Collection
- */
- public function getItemsCollection()
- {
- return $this->getOrder()->getItemsCollection();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items/Renderer/Default.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items/Renderer/Default.php
index 09b01e0b9b9..01c57cf6314 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items/Renderer/Default.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items/Renderer/Default.php
@@ -22,6 +22,13 @@
*/
class Mage_Adminhtml_Block_Sales_Order_View_Items_Renderer_Default extends Mage_Adminhtml_Block_Sales_Items_Abstract
{
+ /**
+ * Giftmessage object
+ *
+ * @deprecated after 1.4.2.0
+ * @var Mage_GiftMessage_Model_Message
+ */
+ protected $_giftMessage = [];
public function getItem()
{
return $this->_getData('item');
@@ -59,14 +66,6 @@ public function canDisplayContainer()
return $this->getRequest()->getParam('reload') != 1;
}
- /**
- * Giftmessage object
- *
- * @deprecated after 1.4.2.0
- * @var Mage_GiftMessage_Model_Message
- */
- protected $_giftMessage = [];
-
/**
* Retrieve default value for giftmessage sender
*
@@ -131,31 +130,6 @@ public function getFieldName($name)
return 'giftmessage[' . $this->getItem()->getId() . '][' . $name . ']';
}
- /**
- * Initialize gift message for entity
- *
- * @deprecated after 1.4.2.0
- * @return $this
- */
- protected function _initMessage()
- {
- /** @var Mage_GiftMessage_Helper_Message $helper */
- $helper = $this->helper('giftmessage/message');
-
- $this->_giftMessage[$this->getItem()->getGiftMessageId()] =
- $helper->getGiftMessage($this->getItem()->getGiftMessageId());
-
- // init default values for giftmessage form
- if (!$this->getMessage()->getSender()) {
- $this->getMessage()->setSender($this->getDefaultSender());
- }
- if (!$this->getMessage()->getRecipient()) {
- $this->getMessage()->setRecipient($this->getDefaultRecipient());
- }
-
- return $this;
- }
-
/**
* Retrieve gift message for entity
*
@@ -247,4 +221,29 @@ public function displayPriceInclTax(Varien_Object $item)
$helper->getPriceInclTax($item),
);
}
+
+ /**
+ * Initialize gift message for entity
+ *
+ * @deprecated after 1.4.2.0
+ * @return $this
+ */
+ protected function _initMessage()
+ {
+ /** @var Mage_GiftMessage_Helper_Message $helper */
+ $helper = $this->helper('giftmessage/message');
+
+ $this->_giftMessage[$this->getItem()->getGiftMessageId()] =
+ $helper->getGiftMessage($this->getItem()->getGiftMessageId());
+
+ // init default values for giftmessage form
+ if (!$this->getMessage()->getSender()) {
+ $this->getMessage()->setSender($this->getDefaultSender());
+ }
+ if (!$this->getMessage()->getRecipient()) {
+ $this->getMessage()->setRecipient($this->getDefaultRecipient());
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Messages.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Messages.php
index 6e786594a1f..e31c95bccfa 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Messages.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Messages.php
@@ -22,11 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_View_Messages extends Mage_Adminhtml_Block_Messages
{
- protected function _getOrder()
- {
- return Mage::registry('sales_order');
- }
-
public function _prepareLayout()
{
/**
@@ -44,4 +39,8 @@ public function _prepareLayout()
return parent::_prepareLayout();
}
+ protected function _getOrder()
+ {
+ return Mage::registry('sales_order');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Creditmemos.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Creditmemos.php
index aa5c2847643..9f3105cb509 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Creditmemos.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Creditmemos.php
@@ -29,6 +29,52 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * Retrieve order model instance
+ *
+ * @return Mage_Sales_Model_Order
+ */
+ public function getOrder()
+ {
+ return Mage::registry('current_order');
+ }
+
+ public function getRowUrl($row)
+ {
+ return $this->getUrl(
+ '*/sales_order_creditmemo/view',
+ [
+ 'creditmemo_id' => $row->getId(),
+ 'order_id' => $row->getOrderId(),
+ ],
+ );
+ }
+
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/creditmemos', ['_current' => true]);
+ }
+
+ public function getTabLabel()
+ {
+ return Mage::helper('sales')->__('Credit Memos');
+ }
+
+ public function getTabTitle()
+ {
+ return Mage::helper('sales')->__('Credit Memos');
+ }
+
+ public function canShowTab()
+ {
+ return Mage::getSingleton('admin/session')->isAllowed('sales/creditmemo');
+ }
+
+ public function isHidden()
+ {
+ return false;
+ }
+
/**
* Retrieve collection class
*
@@ -93,50 +139,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Retrieve order model instance
- *
- * @return Mage_Sales_Model_Order
- */
- public function getOrder()
- {
- return Mage::registry('current_order');
- }
-
- public function getRowUrl($row)
- {
- return $this->getUrl(
- '*/sales_order_creditmemo/view',
- [
- 'creditmemo_id' => $row->getId(),
- 'order_id' => $row->getOrderId(),
- ],
- );
- }
-
- public function getGridUrl()
- {
- return $this->getUrl('*/*/creditmemos', ['_current' => true]);
- }
-
- public function getTabLabel()
- {
- return Mage::helper('sales')->__('Credit Memos');
- }
-
- public function getTabTitle()
- {
- return Mage::helper('sales')->__('Credit Memos');
- }
-
- public function canShowTab()
- {
- return Mage::getSingleton('admin/session')->isAllowed('sales/creditmemo');
- }
-
- public function isHidden()
- {
- return false;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/History.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/History.php
index 0b04cd66254..6687cf22847 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/History.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/History.php
@@ -22,12 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Order_View_Tab_History extends Mage_Adminhtml_Block_Template implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('sales/order/view/tab/history.phtml');
- }
-
/**
* Retrieve order model instance
*
@@ -180,25 +174,6 @@ public function getItemComment(array $item)
return $strItemComment;
}
- /**
- * Map history items as array
- *
- * @param string $label
- * @param bool $notified
- * @param Zend_Date $created
- * @param string $comment
- * @return array
- */
- protected function _prepareHistoryItem($label, $notified, $created, $comment = '')
- {
- return [
- 'title' => $label,
- 'notified' => $notified,
- 'comment' => $comment,
- 'created_at' => $created,
- ];
- }
-
/**
* Get Tab Label
*
@@ -279,6 +254,30 @@ public function isCustomerNotificationNotApplicable($historyItem)
{
return $historyItem['notified'] == Mage_Sales_Model_Order_Status_History::CUSTOMER_NOTIFICATION_NOT_APPLICABLE;
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('sales/order/view/tab/history.phtml');
+ }
+
+ /**
+ * Map history items as array
+ *
+ * @param string $label
+ * @param bool $notified
+ * @param Zend_Date $created
+ * @param string $comment
+ * @return array
+ */
+ protected function _prepareHistoryItem($label, $notified, $created, $comment = '')
+ {
+ return [
+ 'title' => $label,
+ 'notified' => $notified,
+ 'comment' => $comment,
+ 'created_at' => $created,
+ ];
+ }
/**
* Comparison For Sorting History By Timestamp
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Invoices.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Invoices.php
index 4f577cafe0b..8bdfa6f8a6d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Invoices.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Invoices.php
@@ -29,6 +29,52 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * Retrieve order model instance
+ *
+ * @return Mage_Sales_Model_Order
+ */
+ public function getOrder()
+ {
+ return Mage::registry('current_order');
+ }
+
+ public function getRowUrl($row)
+ {
+ return $this->getUrl(
+ '*/sales_order_invoice/view',
+ [
+ 'invoice_id' => $row->getId(),
+ 'order_id' => $row->getOrderId(),
+ ],
+ );
+ }
+
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/invoices', ['_current' => true]);
+ }
+
+ public function getTabLabel()
+ {
+ return Mage::helper('sales')->__('Invoices');
+ }
+
+ public function getTabTitle()
+ {
+ return Mage::helper('sales')->__('Invoices');
+ }
+
+ public function canShowTab()
+ {
+ return Mage::getSingleton('admin/session')->isAllowed('sales/invoice');
+ }
+
+ public function isHidden()
+ {
+ return false;
+ }
+
/**
* Retrieve collection class
*
@@ -94,50 +140,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Retrieve order model instance
- *
- * @return Mage_Sales_Model_Order
- */
- public function getOrder()
- {
- return Mage::registry('current_order');
- }
-
- public function getRowUrl($row)
- {
- return $this->getUrl(
- '*/sales_order_invoice/view',
- [
- 'invoice_id' => $row->getId(),
- 'order_id' => $row->getOrderId(),
- ],
- );
- }
-
- public function getGridUrl()
- {
- return $this->getUrl('*/*/invoices', ['_current' => true]);
- }
-
- public function getTabLabel()
- {
- return Mage::helper('sales')->__('Invoices');
- }
-
- public function getTabTitle()
- {
- return Mage::helper('sales')->__('Invoices');
- }
-
- public function canShowTab()
- {
- return Mage::getSingleton('admin/session')->isAllowed('sales/invoice');
- }
-
- public function isHidden()
- {
- return false;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Shipments.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Shipments.php
index 798eddebea6..fb26f3b4d11 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Shipments.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tab/Shipments.php
@@ -29,6 +29,55 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * Retrieve order model instance
+ *
+ * @return Mage_Sales_Model_Order
+ */
+ public function getOrder()
+ {
+ return Mage::registry('current_order');
+ }
+
+ public function getRowUrl($row)
+ {
+ return $this->getUrl(
+ '*/sales_order_shipment/view',
+ [
+ 'shipment_id' => $row->getId(),
+ 'order_id' => $row->getOrderId(),
+ ],
+ );
+ }
+
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/shipments', ['_current' => true]);
+ }
+
+ public function getTabLabel()
+ {
+ return Mage::helper('sales')->__('Shipments');
+ }
+
+ public function getTabTitle()
+ {
+ return Mage::helper('sales')->__('Shipments');
+ }
+
+ public function canShowTab()
+ {
+ if ($this->getOrder()->getIsVirtual()) {
+ return false;
+ }
+ return Mage::getSingleton('admin/session')->isAllowed('sales/shipment');
+ }
+
+ public function isHidden()
+ {
+ return false;
+ }
+
/**
* Retrieve collection class
*
@@ -79,53 +128,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Retrieve order model instance
- *
- * @return Mage_Sales_Model_Order
- */
- public function getOrder()
- {
- return Mage::registry('current_order');
- }
-
- public function getRowUrl($row)
- {
- return $this->getUrl(
- '*/sales_order_shipment/view',
- [
- 'shipment_id' => $row->getId(),
- 'order_id' => $row->getOrderId(),
- ],
- );
- }
-
- public function getGridUrl()
- {
- return $this->getUrl('*/*/shipments', ['_current' => true]);
- }
-
- public function getTabLabel()
- {
- return Mage::helper('sales')->__('Shipments');
- }
-
- public function getTabTitle()
- {
- return Mage::helper('sales')->__('Shipments');
- }
-
- public function canShowTab()
- {
- if ($this->getOrder()->getIsVirtual()) {
- return false;
- }
- return Mage::getSingleton('admin/session')->isAllowed('sales/shipment');
- }
-
- public function isHidden()
- {
- return false;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tabs.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tabs.php
index c5e38e5f1be..d7643846d19 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tabs.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Tabs.php
@@ -22,6 +22,13 @@
*/
class Mage_Adminhtml_Block_Sales_Order_View_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
+ public function __construct()
+ {
+ parent::__construct();
+ $this->setId('sales_order_view_tabs');
+ $this->setDestElementId('sales_order_view');
+ $this->setTitle(Mage::helper('sales')->__('Order View'));
+ }
/**
* Retrieve available order
*
@@ -40,12 +47,4 @@ public function getOrder()
}
Mage::throwException(Mage::helper('sales')->__('Cannot get the order instance.'));
}
-
- public function __construct()
- {
- parent::__construct();
- $this->setId('sales_order_view_tabs');
- $this->setDestElementId('sales_order_view');
- $this->setTitle(Mage::helper('sales')->__('Order View'));
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Reorder/Renderer/Action.php b/app/code/core/Mage/Adminhtml/Block/Sales/Reorder/Renderer/Action.php
index d12659b1e48..ececf377062 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Reorder/Renderer/Action.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Reorder/Renderer/Action.php
@@ -43,6 +43,16 @@ public function render(Varien_Object $row)
return $this->_actionsToHtml();
}
+ /**
+ * Add one action array to all options data storage
+ *
+ * @param array $actionArray
+ */
+ public function addToActions($actionArray)
+ {
+ $this->_actions[] = $actionArray;
+ }
+
protected function _getEscapedValue($value)
{
return addcslashes(htmlspecialchars($value), '\\\'');
@@ -68,14 +78,4 @@ protected function _actionsToHtml(array $actions = [])
}
return implode('|', $html);
}
-
- /**
- * Add one action array to all options data storage
- *
- * @param array $actionArray
- */
- public function addToActions($actionArray)
- {
- $this->_actions[] = $actionArray;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Shipment/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Shipment/Grid.php
index adaecc24401..dd48eadfc55 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Shipment/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Shipment/Grid.php
@@ -35,6 +35,31 @@ public function __construct()
$this->setDefaultDir('DESC');
}
+ /**
+ * Get url for row
+ *
+ * @param Mage_Sales_Model_Order_Shipment $row
+ * @return string|false
+ */
+ public function getRowUrl($row)
+ {
+ if (!Mage::getSingleton('admin/session')->isAllowed('sales/order/shipment')) {
+ return false;
+ }
+
+ return $this->getUrl('*/sales_shipment/view', ['shipment_id' => $row->getId()]);
+ }
+
+ /**
+ * Get url of grid
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/*', ['_current' => true]);
+ }
+
/**
* Retrieve collection class
*
@@ -122,21 +147,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Get url for row
- *
- * @param Mage_Sales_Model_Order_Shipment $row
- * @return string|false
- */
- public function getRowUrl($row)
- {
- if (!Mage::getSingleton('admin/session')->isAllowed('sales/order/shipment')) {
- return false;
- }
-
- return $this->getUrl('*/sales_shipment/view', ['shipment_id' => $row->getId()]);
- }
-
/**
* Prepare and set options for massaction
*
@@ -160,14 +170,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * Get url of grid
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/*', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Transactions/Detail/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Transactions/Detail/Grid.php
index b1a4eb930ec..acbfb98dd9d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Transactions/Detail/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Transactions/Detail/Grid.php
@@ -22,6 +22,18 @@
*/
class Mage_Adminhtml_Block_Sales_Transactions_Detail_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
+ /**
+ * Retrieve Transaction additional info
+ *
+ * @return array
+ */
+ public function getTransactionAdditionalInfo()
+ {
+ $info = Mage::registry('current_transaction')->getAdditionalInformation(
+ Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS,
+ );
+ return (is_array($info)) ? $info : [];
+ }
/**
* Initialize default sorting and html ID
*/
@@ -74,17 +86,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Retrieve Transaction additional info
- *
- * @return array
- */
- public function getTransactionAdditionalInfo()
- {
- $info = Mage::registry('current_transaction')->getAdditionalInformation(
- Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS,
- );
- return (is_array($info)) ? $info : [];
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Transactions/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Transactions/Grid.php
index 62809e7da8f..7ae0dc5c4c5 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Transactions/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Transactions/Grid.php
@@ -37,6 +37,26 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * Retrieve grid url
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
+ /**
+ * Retrieve row url
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/view', ['txn_id' => $row->getId()]);
+ }
+
/**
* Prepare collection for grid
*
@@ -123,24 +143,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Retrieve grid url
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
-
- /**
- * Retrieve row url
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/view', ['txn_id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Sitemap/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sitemap/Grid.php
index ed6841f4875..5b274dbd6a2 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sitemap/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sitemap/Grid.php
@@ -29,6 +29,16 @@ public function __construct()
$this->setDefaultSort('sitemap_id');
}
+ /**
+ * Row click url
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['sitemap_id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
/** @var Mage_Sitemap_Model_Resource_Sitemap_Collection $collection */
@@ -81,14 +91,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Row click url
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['sitemap_id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Store/Switcher.php b/app/code/core/Mage/Adminhtml/Block/Store/Switcher.php
index 44cf9c77f62..3b5721c8ecb 100644
--- a/app/code/core/Mage/Adminhtml/Block/Store/Switcher.php
+++ b/app/code/core/Mage/Adminhtml/Block/Store/Switcher.php
@@ -206,17 +206,6 @@ public function isShow()
return !Mage::app()->isSingleStoreMode();
}
- /**
- * @return string
- */
- protected function _toHtml()
- {
- if (!Mage::app()->isSingleStoreMode()) {
- return parent::_toHtml();
- }
- return '';
- }
-
/**
* Set/Get whether the switcher should show default option
*
@@ -230,4 +219,15 @@ public function hasDefaultOption($hasDefaultOption = null)
}
return $this->_hasDefaultOption;
}
+
+ /**
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ if (!Mage::app()->isSingleStoreMode()) {
+ return parent::_toHtml();
+ }
+ return '';
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Store/Switcher/Form/Renderer/Fieldset.php b/app/code/core/Mage/Adminhtml/Block/Store/Switcher/Form/Renderer/Fieldset.php
index 945ad160dfc..cbdb602262c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Store/Switcher/Form/Renderer/Fieldset.php
+++ b/app/code/core/Mage/Adminhtml/Block/Store/Switcher/Form/Renderer/Fieldset.php
@@ -29,11 +29,6 @@ class Mage_Adminhtml_Block_Store_Switcher_Form_Renderer_Fieldset extends Mage_Ad
*/
protected $_element;
- protected function _construct()
- {
- $this->setTemplate('store/switcher/form/renderer/fieldset.phtml');
- }
-
/**
* Retrieve an element
*
@@ -54,4 +49,9 @@ public function render(Varien_Data_Form_Element_Abstract $element)
$this->_element = $element;
return $this->toHtml();
}
+
+ protected function _construct()
+ {
+ $this->setTemplate('store/switcher/form/renderer/fieldset.phtml');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Store/Switcher/Form/Renderer/Fieldset/Element.php b/app/code/core/Mage/Adminhtml/Block/Store/Switcher/Form/Renderer/Fieldset/Element.php
index d52f40f0990..a88e9814d14 100644
--- a/app/code/core/Mage/Adminhtml/Block/Store/Switcher/Form/Renderer/Fieldset/Element.php
+++ b/app/code/core/Mage/Adminhtml/Block/Store/Switcher/Form/Renderer/Fieldset/Element.php
@@ -29,11 +29,6 @@ class Mage_Adminhtml_Block_Store_Switcher_Form_Renderer_Fieldset_Element extends
*/
protected $_element;
- protected function _construct()
- {
- $this->setTemplate('store/switcher/form/renderer/fieldset/element.phtml');
- }
-
/**
* Retrieve an element
*
@@ -54,4 +49,9 @@ public function render(Varien_Data_Form_Element_Abstract $element)
$this->_element = $element;
return $this->toHtml();
}
+
+ protected function _construct()
+ {
+ $this->setTemplate('store/switcher/form/renderer/fieldset/element.phtml');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Cache/Edit.php b/app/code/core/Mage/Adminhtml/Block/System/Cache/Edit.php
index 467881d6e52..42333793df1 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Cache/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Cache/Edit.php
@@ -32,23 +32,6 @@ public function __construct()
$this->setTitle('Cache Management');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('adminhtml')->__('Save Cache Settings'),
- 'onclick' => 'configForm.submit()',
- 'class' => 'save',
- ]),
- );
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -186,4 +169,21 @@ public function getCatalogData()
],
];
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('adminhtml')->__('Save Cache Settings'),
+ 'onclick' => 'configForm.submit()',
+ 'class' => 'save',
+ ]),
+ );
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Config/Edit.php b/app/code/core/Mage/Adminhtml/Block/System/Config/Edit.php
index 95cf45677cb..ddd889f2913 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Config/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Config/Edit.php
@@ -44,23 +44,6 @@ public function __construct()
$this->setHeaderCss((string) $this->_section->header_css);
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('adminhtml')->__('Save Config'),
- 'onclick' => 'configForm.submit()',
- 'class' => 'save',
- ]),
- );
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -93,4 +76,21 @@ public function initForm()
);
return $this;
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('adminhtml')->__('Save Config'),
+ 'onclick' => 'configForm.submit()',
+ 'class' => 'save',
+ ]),
+ );
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php b/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php
index 62f8e44c0f7..13bdb0599a3 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php
@@ -82,22 +82,6 @@ public function __construct()
];
}
- /**
- * @return $this
- */
- protected function _initObjects()
- {
- $this->_configDataObject = Mage::getSingleton('adminhtml/config_data');
- $this->_configRoot = $this->_configDataObject->getConfigRoot();
- $this->_configData = $this->_configDataObject->load();
-
- $this->_configFields = Mage::getSingleton('adminhtml/config');
-
- $this->_defaultFieldsetRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_fieldset');
- $this->_defaultFieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
- return $this;
- }
-
/**
* @return $this
*/
@@ -138,81 +122,6 @@ public function initForm()
return $this;
}
- /**
- * Init config group
- *
- * @param Varien_Data_Form $form
- * @param Varien_Simplexml_Element $group
- * @param Varien_Simplexml_Element $section
- * @param Varien_Data_Form_Element_Fieldset|null $parentElement
- */
- protected function _initGroup($form, $group, $section, $parentElement = null)
- {
- /** @var Mage_Adminhtml_Block_System_Config_Form_Fieldset $fieldsetRenderer */
- $fieldsetRenderer = $group->frontend_model
- ? Mage::getBlockSingleton((string) $group->frontend_model)
- : $this->_defaultFieldsetRenderer;
- $fieldsetRenderer->setForm($this)
- ->setConfigData($this->_configData);
-
- if ($this->_configFields->hasChildren($group, $this->getWebsiteCode(), $this->getStoreCode())) {
- $helperName = $this->_configFields->getAttributeModule($section, $group);
- $fieldsetConfig = ['legend' => Mage::helper($helperName)->__((string) $group->label)];
- if (!empty($group->comment)) {
- $fieldsetConfig['comment'] = $this->_prepareGroupComment($group, $helperName);
- }
- if (!empty($group->expanded)) {
- $fieldsetConfig['expanded'] = (bool) $group->expanded;
- }
-
- $fieldset = new Varien_Data_Form_Element_Fieldset($fieldsetConfig);
- $fieldset->setId($section->getName() . '_' . $group->getName())
- ->setRenderer($fieldsetRenderer)
- ->setGroup($group);
-
- if ($parentElement) {
- $fieldset->setIsNested(true);
- $parentElement->addElement($fieldset);
- } else {
- $form->addElement($fieldset);
- }
-
- $this->_prepareFieldOriginalData($fieldset, $group);
- $this->_addElementTypes($fieldset);
-
- $this->_fieldsets[$group->getName()] = $fieldset;
-
- if ($group->clone_fields) {
- if ($group->clone_model) {
- $cloneModel = Mage::getModel((string) $group->clone_model);
- } else {
- Mage::throwException($this->__('Config form fieldset clone model required to be able to clone fields'));
- }
- foreach ($cloneModel->getPrefixes() as $prefix) {
- $this->initFields($fieldset, $group, $section, $prefix['field'], $prefix['label']);
- }
- } else {
- $this->initFields($fieldset, $group, $section);
- }
- }
- }
-
- /**
- * Return dependency block object
- *
- * @return Mage_Adminhtml_Block_Widget_Form_Element_Dependence
- */
- protected function _getDependence()
- {
- if (!$this->getChild('element_dependense')) {
- $this->setChild(
- 'element_dependense',
- $this->getLayout()->createBlock('adminhtml/widget_form_element_dependence'),
- );
- }
- return $this->getChild('element_dependense');
- }
-
/**
* Init fieldset fields
*
@@ -461,101 +370,6 @@ public function getConfigRoot()
return $this->_configRoot;
}
- /**
- * Set "original_data" array to the element, composed from nodes with scalar values
- *
- * @param Varien_Data_Form_Element_Abstract $field
- * @param Varien_Simplexml_Element $xmlElement
- */
- protected function _prepareFieldOriginalData($field, $xmlElement)
- {
- $originalData = [];
- foreach ($xmlElement as $key => $value) {
- if (!$value->hasChildren()) {
- $originalData[$key] = (string) $value;
- }
- }
- $field->setOriginalData($originalData);
- }
-
- /**
- * Support models "getCommentText" method for field note generation
- *
- * @param Mage_Core_Model_Config_Element $element
- * @param string $helper
- * @return string
- */
- protected function _prepareFieldComment($element, $helper, $currentValue)
- {
- $comment = '';
- if ($element->comment) {
- $commentInfo = $element->comment->asArray();
- if (is_array($commentInfo)) {
- if (isset($commentInfo['model'])) {
- $model = Mage::getModel($commentInfo['model']);
- if (method_exists($model, 'getCommentText')) {
- $comment = $model->getCommentText($element, $currentValue);
- }
- }
- } else {
- $comment = Mage::helper($helper)->__($commentInfo);
- }
- }
- return $comment;
- }
-
- /**
- * Support models "getCommentText" method for group note generation
- *
- * @param Mage_Core_Model_Config_Element $element
- * @param string $helper
- * @return string
- */
- protected function _prepareGroupComment($element, $helper)
- {
- return $this->_prepareFieldComment($element, $helper, null);
- }
-
- /**
- * Prepare additional comment for field like tooltip
- *
- * @param Mage_Core_Model_Config_Element $element
- * @param string $helper
- * @return string
- */
- protected function _prepareFieldTooltip($element, $helper)
- {
- if ($element->tooltip) {
- return Mage::helper($helper)->__((string) $element->tooltip);
- } elseif ($element->tooltip_block) {
- return $this->getLayout()->createBlock((string) $element->tooltip_block)->toHtml();
- }
- return '';
- }
-
- /**
- * Append dependence block at then end of form block
- *
- *
- */
- protected function _afterToHtml($html)
- {
- if ($this->_getDependence()) {
- $html .= $this->_getDependence()->toHtml();
- }
- return parent::_afterToHtml($html);
- }
-
- /**
- * @param Varien_Simplexml_Element $a
- * @param Varien_Simplexml_Element $b
- * @return int
- */
- protected function _sortForm($a, $b)
- {
- return (int) $a->sort_order < (int) $b->sort_order ? -1 : ((int) $a->sort_order > (int) $b->sort_order ? 1 : 0);
- }
-
/**
* @param Varien_Simplexml_Element $field
* @return bool
@@ -583,30 +397,6 @@ public function canUseWebsiteValue($field)
return false;
}
- /**
- * Checking field visibility
- *
- * @param Varien_Simplexml_Element $field
- * @return bool
- */
- protected function _canShowField($field)
- {
- $ifModuleEnabled = trim((string) $field->if_module_enabled);
- if ($ifModuleEnabled && !$this->isModuleEnabled($ifModuleEnabled)) {
- return false;
- }
-
- switch ($this->getScope()) {
- case self::SCOPE_DEFAULT:
- return (bool) (int) $field->show_in_default;
- case self::SCOPE_WEBSITES:
- return (bool) (int) $field->show_in_website;
- case self::SCOPE_STORES:
- return (bool) (int) $field->show_in_store;
- }
- return true;
- }
-
/**
* Retrieve current scope
*
@@ -688,21 +478,6 @@ public function getScopeId()
return $scopeId;
}
- /**
- * @return array
- */
- protected function _getAdditionalElementTypes()
- {
- return [
- 'export' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_export'),
- 'import' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_import'),
- 'allowspecific' => Mage::getConfig()
- ->getBlockClassName('adminhtml/system_config_form_field_select_allowspecific'),
- 'image' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_image'),
- 'file' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_file'),
- ];
- }
-
/**
* Temporary moved those $this->getRequest()->getParam('blabla') from the code across this block
* to getBlala() methods to be later set from controller with setters
@@ -733,4 +508,229 @@ public function getStoreCode()
{
return $this->getRequest()->getParam('store', '');
}
+
+ /**
+ * @return $this
+ */
+ protected function _initObjects()
+ {
+ $this->_configDataObject = Mage::getSingleton('adminhtml/config_data');
+ $this->_configRoot = $this->_configDataObject->getConfigRoot();
+ $this->_configData = $this->_configDataObject->load();
+
+ $this->_configFields = Mage::getSingleton('adminhtml/config');
+
+ $this->_defaultFieldsetRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_fieldset');
+ $this->_defaultFieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
+ return $this;
+ }
+
+ /**
+ * Init config group
+ *
+ * @param Varien_Data_Form $form
+ * @param Varien_Simplexml_Element $group
+ * @param Varien_Simplexml_Element $section
+ * @param Varien_Data_Form_Element_Fieldset|null $parentElement
+ */
+ protected function _initGroup($form, $group, $section, $parentElement = null)
+ {
+ /** @var Mage_Adminhtml_Block_System_Config_Form_Fieldset $fieldsetRenderer */
+ $fieldsetRenderer = $group->frontend_model
+ ? Mage::getBlockSingleton((string) $group->frontend_model)
+ : $this->_defaultFieldsetRenderer;
+ $fieldsetRenderer->setForm($this)
+ ->setConfigData($this->_configData);
+
+ if ($this->_configFields->hasChildren($group, $this->getWebsiteCode(), $this->getStoreCode())) {
+ $helperName = $this->_configFields->getAttributeModule($section, $group);
+ $fieldsetConfig = ['legend' => Mage::helper($helperName)->__((string) $group->label)];
+ if (!empty($group->comment)) {
+ $fieldsetConfig['comment'] = $this->_prepareGroupComment($group, $helperName);
+ }
+ if (!empty($group->expanded)) {
+ $fieldsetConfig['expanded'] = (bool) $group->expanded;
+ }
+
+ $fieldset = new Varien_Data_Form_Element_Fieldset($fieldsetConfig);
+ $fieldset->setId($section->getName() . '_' . $group->getName())
+ ->setRenderer($fieldsetRenderer)
+ ->setGroup($group);
+
+ if ($parentElement) {
+ $fieldset->setIsNested(true);
+ $parentElement->addElement($fieldset);
+ } else {
+ $form->addElement($fieldset);
+ }
+
+ $this->_prepareFieldOriginalData($fieldset, $group);
+ $this->_addElementTypes($fieldset);
+
+ $this->_fieldsets[$group->getName()] = $fieldset;
+
+ if ($group->clone_fields) {
+ if ($group->clone_model) {
+ $cloneModel = Mage::getModel((string) $group->clone_model);
+ } else {
+ Mage::throwException($this->__('Config form fieldset clone model required to be able to clone fields'));
+ }
+ foreach ($cloneModel->getPrefixes() as $prefix) {
+ $this->initFields($fieldset, $group, $section, $prefix['field'], $prefix['label']);
+ }
+ } else {
+ $this->initFields($fieldset, $group, $section);
+ }
+ }
+ }
+
+ /**
+ * Return dependency block object
+ *
+ * @return Mage_Adminhtml_Block_Widget_Form_Element_Dependence
+ */
+ protected function _getDependence()
+ {
+ if (!$this->getChild('element_dependense')) {
+ $this->setChild(
+ 'element_dependense',
+ $this->getLayout()->createBlock('adminhtml/widget_form_element_dependence'),
+ );
+ }
+ return $this->getChild('element_dependense');
+ }
+
+ /**
+ * Set "original_data" array to the element, composed from nodes with scalar values
+ *
+ * @param Varien_Data_Form_Element_Abstract $field
+ * @param Varien_Simplexml_Element $xmlElement
+ */
+ protected function _prepareFieldOriginalData($field, $xmlElement)
+ {
+ $originalData = [];
+ foreach ($xmlElement as $key => $value) {
+ if (!$value->hasChildren()) {
+ $originalData[$key] = (string) $value;
+ }
+ }
+ $field->setOriginalData($originalData);
+ }
+
+ /**
+ * Support models "getCommentText" method for field note generation
+ *
+ * @param Mage_Core_Model_Config_Element $element
+ * @param string $helper
+ * @return string
+ */
+ protected function _prepareFieldComment($element, $helper, $currentValue)
+ {
+ $comment = '';
+ if ($element->comment) {
+ $commentInfo = $element->comment->asArray();
+ if (is_array($commentInfo)) {
+ if (isset($commentInfo['model'])) {
+ $model = Mage::getModel($commentInfo['model']);
+ if (method_exists($model, 'getCommentText')) {
+ $comment = $model->getCommentText($element, $currentValue);
+ }
+ }
+ } else {
+ $comment = Mage::helper($helper)->__($commentInfo);
+ }
+ }
+ return $comment;
+ }
+
+ /**
+ * Support models "getCommentText" method for group note generation
+ *
+ * @param Mage_Core_Model_Config_Element $element
+ * @param string $helper
+ * @return string
+ */
+ protected function _prepareGroupComment($element, $helper)
+ {
+ return $this->_prepareFieldComment($element, $helper, null);
+ }
+
+ /**
+ * Prepare additional comment for field like tooltip
+ *
+ * @param Mage_Core_Model_Config_Element $element
+ * @param string $helper
+ * @return string
+ */
+ protected function _prepareFieldTooltip($element, $helper)
+ {
+ if ($element->tooltip) {
+ return Mage::helper($helper)->__((string) $element->tooltip);
+ } elseif ($element->tooltip_block) {
+ return $this->getLayout()->createBlock((string) $element->tooltip_block)->toHtml();
+ }
+ return '';
+ }
+
+ /**
+ * Append dependence block at then end of form block
+ *
+ *
+ */
+ protected function _afterToHtml($html)
+ {
+ if ($this->_getDependence()) {
+ $html .= $this->_getDependence()->toHtml();
+ }
+ return parent::_afterToHtml($html);
+ }
+
+ /**
+ * @param Varien_Simplexml_Element $a
+ * @param Varien_Simplexml_Element $b
+ * @return int
+ */
+ protected function _sortForm($a, $b)
+ {
+ return (int) $a->sort_order < (int) $b->sort_order ? -1 : ((int) $a->sort_order > (int) $b->sort_order ? 1 : 0);
+ }
+
+ /**
+ * Checking field visibility
+ *
+ * @param Varien_Simplexml_Element $field
+ * @return bool
+ */
+ protected function _canShowField($field)
+ {
+ $ifModuleEnabled = trim((string) $field->if_module_enabled);
+ if ($ifModuleEnabled && !$this->isModuleEnabled($ifModuleEnabled)) {
+ return false;
+ }
+
+ switch ($this->getScope()) {
+ case self::SCOPE_DEFAULT:
+ return (bool) (int) $field->show_in_default;
+ case self::SCOPE_WEBSITES:
+ return (bool) (int) $field->show_in_website;
+ case self::SCOPE_STORES:
+ return (bool) (int) $field->show_in_store;
+ }
+ return true;
+ }
+
+ /**
+ * @return array
+ */
+ protected function _getAdditionalElementTypes()
+ {
+ return [
+ 'export' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_export'),
+ 'import' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_import'),
+ 'allowspecific' => Mage::getConfig()
+ ->getBlockClassName('adminhtml/system_config_form_field_select_allowspecific'),
+ 'image' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_image'),
+ 'file' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_file'),
+ ];
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Field.php b/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Field.php
index 4cada9d2247..0df269356e5 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Field.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Field.php
@@ -22,14 +22,6 @@
*/
class Mage_Adminhtml_Block_System_Config_Form_Field extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface
{
- /**
- * @return string
- */
- protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
- {
- return $element->getElementHtml();
- }
-
/**
* @return string
*/
@@ -126,6 +118,13 @@ public function render(Varien_Data_Form_Element_Abstract $element)
return $this->_decorateRowHtml($element, $html);
}
+ /**
+ * @return string
+ */
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
+ {
+ return $element->getElementHtml();
+ }
/**
* Decorate field row html
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Field/Array/Abstract.php b/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Field/Array/Abstract.php
index 8d9776f577d..08e4957d3c8 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Field/Array/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Field/Array/Abstract.php
@@ -44,18 +44,18 @@ abstract class Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract exte
protected $_addButtonLabel;
/**
- * Rows cache
+ * Indication whether block is prepared to render or no
*
- * @var array|null
+ * @var bool
*/
- private $_arrayRowsCache;
+ protected $_isPreparedToRender = false;
/**
- * Indication whether block is prepared to render or no
+ * Rows cache
*
- * @var bool
+ * @var array|null
*/
- protected $_isPreparedToRender = false;
+ private $_arrayRowsCache;
/**
* Check if columns are defined, set template
@@ -92,27 +92,6 @@ public function addColumn($name, $params)
}
}
- /**
- * Get the grid and scripts contents
- *
- * @return string
- */
- protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
- {
- $this->setElement($element);
- $html = $this->_toHtml();
- $this->_arrayRowsCache = null; // doh, the object is used as singleton!
- return $html;
- }
-
- /**
- * Prepare existing row data object
- */
- protected function _prepareArrayRow(Varien_Object $row)
- {
- // override in descendants
- }
-
/**
* Obtain existing data from form element
*
@@ -142,6 +121,27 @@ public function getArrayRows()
return $this->_arrayRowsCache;
}
+ /**
+ * Get the grid and scripts contents
+ *
+ * @return string
+ */
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
+ {
+ $this->setElement($element);
+ $html = $this->_toHtml();
+ $this->_arrayRowsCache = null; // doh, the object is used as singleton!
+ return $html;
+ }
+
+ /**
+ * Prepare existing row data object
+ */
+ protected function _prepareArrayRow(Varien_Object $row)
+ {
+ // override in descendants
+ }
+
/**
* Render array cell for prototypeJS template
*
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Fieldset.php b/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Fieldset.php
index d627fa8a0d5..94f991a11dd 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Fieldset.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Config/Form/Fieldset.php
@@ -39,6 +39,24 @@ public function render(Varien_Data_Form_Element_Abstract $element)
return $html . $this->_getFooterHtml($element);
}
+ /**
+ * Get group xml data of the element
+ *
+ * @param null|Varien_Data_Form_Element_Abstract $element
+ * @return Mage_Core_Model_Config_Element
+ */
+ public function getGroup($element = null)
+ {
+ if (is_null($element)) {
+ $element = $this->getElement();
+ }
+ if ($element && $element->getGroup() instanceof Mage_Core_Model_Config_Element) {
+ return $element->getGroup();
+ }
+
+ return new Mage_Core_Model_Config_Element('');
+ }
+
/**
* Return header html for fieldset
*
@@ -83,24 +101,6 @@ protected function _getFrontendClass($element)
return 'section-config' . (empty($frontendClass) ? '' : (' ' . $frontendClass));
}
- /**
- * Get group xml data of the element
- *
- * @param null|Varien_Data_Form_Element_Abstract $element
- * @return Mage_Core_Model_Config_Element
- */
- public function getGroup($element = null)
- {
- if (is_null($element)) {
- $element = $this->getElement();
- }
- if ($element && $element->getGroup() instanceof Mage_Core_Model_Config_Element) {
- return $element->getGroup();
- }
-
- return new Mage_Core_Model_Config_Element('');
- }
-
/**
* Return header title part of html for fieldset
*
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Config/Switcher.php b/app/code/core/Mage/Adminhtml/Block/System/Config/Switcher.php
index 615f643c334..786f1726ce8 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Config/Switcher.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Config/Switcher.php
@@ -20,15 +20,6 @@
*/
class Mage_Adminhtml_Block_System_Config_Switcher extends Mage_Adminhtml_Block_Template
{
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setTemplate('system/config/switcher.phtml');
- return parent::_prepareLayout();
- }
-
/**
* @return array
*/
@@ -100,4 +91,12 @@ public function getStoreSelectOptions()
return $options;
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setTemplate('system/config/switcher.phtml');
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Config/System/Storage/Media/Synchronize.php b/app/code/core/Mage/Adminhtml/Block/System/Config/System/Storage/Media/Synchronize.php
index 0f80ac00eac..14756f428c5 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Config/System/Storage/Media/Synchronize.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Config/System/Storage/Media/Synchronize.php
@@ -22,15 +22,6 @@
*/
class Mage_Adminhtml_Block_System_Config_System_Storage_Media_Synchronize extends Mage_Adminhtml_Block_System_Config_Form_Field
{
- /**
- * Set template
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('system/config/system/storage/media/synchronize.phtml');
- }
-
/**
* Remove scope label
*
@@ -42,16 +33,6 @@ public function render(Varien_Data_Form_Element_Abstract $element)
return parent::render($element);
}
- /**
- * Return element html
- *
- * @return string
- */
- protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
- {
- return $this->_toHtml();
- }
-
/**
* Return ajax url for synchronize button
*
@@ -122,4 +103,22 @@ public function getSyncStorageParams()
'connection_name' => $connectionName,
];
}
+ /**
+ * Set template
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('system/config/system/storage/media/synchronize.phtml');
+ }
+
+ /**
+ * Return element html
+ *
+ * @return string
+ */
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
+ {
+ return $this->_toHtml();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Config/Tabs.php b/app/code/core/Mage/Adminhtml/Block/System/Config/Tabs.php
index ba75eeec702..dd7f44902fc 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Config/Tabs.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Config/Tabs.php
@@ -27,23 +27,6 @@ class Mage_Adminhtml_Block_System_Config_Tabs extends Mage_Adminhtml_Block_Widge
*/
protected $_tabs;
- protected function _construct()
- {
- $this->setId('system_config_tabs');
- $this->setTitle(Mage::helper('adminhtml')->__('Configuration'));
- $this->setTemplate('system/config/tabs.phtml');
- }
-
- /**
- * @param Mage_Core_Model_Config_Element $a
- * @param Mage_Core_Model_Config_Element $b
- * @return int
- */
- protected function _sort($a, $b)
- {
- return (int) $a->sort_order < (int) $b->sort_order ? -1 : ((int) $a->sort_order > (int) $b->sort_order ? 1 : 0);
- }
-
public function initTabs()
{
$current = $this->getRequest()->getParam('section');
@@ -317,4 +300,21 @@ public function checkSectionPermissions($code = null)
}
return $showTab;
}
+
+ protected function _construct()
+ {
+ $this->setId('system_config_tabs');
+ $this->setTitle(Mage::helper('adminhtml')->__('Configuration'));
+ $this->setTemplate('system/config/tabs.phtml');
+ }
+
+ /**
+ * @param Mage_Core_Model_Config_Element $a
+ * @param Mage_Core_Model_Config_Element $b
+ * @return int
+ */
+ protected function _sort($a, $b)
+ {
+ return (int) $a->sort_order < (int) $b->sort_order ? -1 : ((int) $a->sort_order > (int) $b->sort_order ? 1 : 0);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Convert/Gui/Edit/Tab/Wizard.php b/app/code/core/Mage/Adminhtml/Block/System/Convert/Gui/Edit/Tab/Wizard.php
index f52fc557834..3e23f36c370 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Convert/Gui/Edit/Tab/Wizard.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Convert/Gui/Edit/Tab/Wizard.php
@@ -42,17 +42,6 @@ public function __construct()
$this->setTemplate('system/convert/profile/wizard.phtml');
}
- /**
- * @return $this
- */
- protected function _prepareLayout()
- {
- if ($head = $this->getLayout()->getBlock('head')) {
- $head->setCanLoadCalendarJs(true);
- }
- return $this;
- }
-
/**
* @param string $entityType
* @return array|string[]
@@ -238,19 +227,6 @@ public function getCountryFilterOptions()
return $options;
}
- /**
- * Retrieve system store model
- *
- * @return Mage_Adminhtml_Model_System_Store
- */
- protected function _getStoreModel()
- {
- if (is_null($this->_storeModel)) {
- $this->_storeModel = Mage::getSingleton('adminhtml/system_store');
- }
- return $this->_storeModel;
- }
-
/**
* @return array
*/
@@ -287,4 +263,28 @@ public function getShortDateFormat()
}
return $this->_shortDateFormat;
}
+
+ /**
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ if ($head = $this->getLayout()->getBlock('head')) {
+ $head->setCanLoadCalendarJs(true);
+ }
+ return $this;
+ }
+
+ /**
+ * Retrieve system store model
+ *
+ * @return Mage_Adminhtml_Model_System_Store
+ */
+ protected function _getStoreModel()
+ {
+ if (is_null($this->_storeModel)) {
+ $this->_storeModel = Mage::getSingleton('adminhtml/system_store');
+ }
+ return $this->_storeModel;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Convert/Gui/Grid.php b/app/code/core/Mage/Adminhtml/Block/System/Convert/Gui/Grid.php
index 3184bd67b5e..515eb0f53f1 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Convert/Gui/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Convert/Gui/Grid.php
@@ -29,6 +29,11 @@ public function __construct()
$this->setDefaultSort('profile_id');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('dataflow/profile_collection')
@@ -95,9 +100,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Edit/Tab/History.php b/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Edit/Tab/History.php
index 674839d4cf2..6c6806f6235 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Edit/Tab/History.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Edit/Tab/History.php
@@ -34,6 +34,14 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/history', ['_current' => true]);
+ }
+
/**
* @inheritDoc
*/
@@ -77,12 +85,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/history', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Grid.php b/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Grid.php
index bad8381e7f1..3a156b1c391 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Grid.php
@@ -29,6 +29,11 @@ public function __construct()
$this->setDefaultSort('profile_id');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('dataflow/profile_collection')
@@ -76,9 +81,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Run.php b/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Run.php
index 5db413617e0..b51e134f508 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Run.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Convert/Profile/Run.php
@@ -32,77 +32,6 @@ class Mage_Adminhtml_Block_System_Convert_Profile_Run extends Mage_Adminhtml_Blo
* @var Mage_Dataflow_Model_Batch
*/
protected $_batchModel = null;
- /**
- * Preparing batch model (initialization)
- * @return $this
- */
- protected function _prepareBatchModel()
- {
- if ($this->_batchModelPrepared) {
- return $this;
- }
- $this->setShowFinished(true);
- $batchModel = Mage::getSingleton('dataflow/batch');
- $this->_batchModel = $batchModel;
- if ($batchModel->getId()) {
- if ($batchModel->getAdapter()) {
- $this->setBatchModelHasAdapter(true);
- $numberOfRecords = $this->getProfile()->getData('gui_data/import/number_of_records');
- if (!$numberOfRecords) {
- $batchParams = $batchModel->getParams();
- $numberOfRecords = $batchParams['number_of_records'] ?? 1;
- }
- $this->setNumberOfRecords($numberOfRecords);
- $this->setShowFinished(false);
- $batchImportModel = $batchModel->getBatchImportModel();
- $importIds = $batchImportModel->getIdCollection();
- $this->setBatchItemsCount(count($importIds));
- $this->setBatchConfig(
- [
- 'styles' => [
- 'error' => [
- 'icon' => Mage::getDesign()->getSkinUrl('images/error_msg_icon.gif'),
- 'bg' => '#FDD',
- ],
- 'message' => [
- 'icon' => Mage::getDesign()->getSkinUrl('images/fam_bullet_success.gif'),
- 'bg' => '#DDF',
- ],
- 'loader' => Mage::getDesign()->getSkinUrl('images/ajax-loader.gif'),
- ],
- 'template' => ''
- . '
'
- . '#{text}'
- . '',
- 'text' => $this->__('Processed %s%% %s/%d records', '#{percent}', '#{updated}', $this->getBatchItemsCount()),
- 'successText' => $this->__('Imported %s records', '#{updated}'),
- ],
- );
- $jsonIds = array_chunk($importIds, $numberOfRecords);
- $importData = [];
- foreach ($jsonIds as $part => $ids) {
- $importData[] = [
- 'batch_id' => $batchModel->getId(),
- 'rows[]' => $ids,
- ];
- }
- $this->setImportData($importData);
- } else {
- $this->setBatchModelHasAdapter(false);
- $batchModel->delete();
- }
- }
- $this->_batchModelPrepared = true;
- return $this;
- }
- /**
- * Return a batch model instance
- * @return Mage_Dataflow_Model_Batch
- */
- protected function _getBatchModel()
- {
- return $this->_batchModel;
- }
/**
* Return a batch model config JSON
* @return string
@@ -188,4 +117,75 @@ public function getExceptions()
parent::setExceptions($exceptions);
return $exceptions;
}
+ /**
+ * Preparing batch model (initialization)
+ * @return $this
+ */
+ protected function _prepareBatchModel()
+ {
+ if ($this->_batchModelPrepared) {
+ return $this;
+ }
+ $this->setShowFinished(true);
+ $batchModel = Mage::getSingleton('dataflow/batch');
+ $this->_batchModel = $batchModel;
+ if ($batchModel->getId()) {
+ if ($batchModel->getAdapter()) {
+ $this->setBatchModelHasAdapter(true);
+ $numberOfRecords = $this->getProfile()->getData('gui_data/import/number_of_records');
+ if (!$numberOfRecords) {
+ $batchParams = $batchModel->getParams();
+ $numberOfRecords = $batchParams['number_of_records'] ?? 1;
+ }
+ $this->setNumberOfRecords($numberOfRecords);
+ $this->setShowFinished(false);
+ $batchImportModel = $batchModel->getBatchImportModel();
+ $importIds = $batchImportModel->getIdCollection();
+ $this->setBatchItemsCount(count($importIds));
+ $this->setBatchConfig(
+ [
+ 'styles' => [
+ 'error' => [
+ 'icon' => Mage::getDesign()->getSkinUrl('images/error_msg_icon.gif'),
+ 'bg' => '#FDD',
+ ],
+ 'message' => [
+ 'icon' => Mage::getDesign()->getSkinUrl('images/fam_bullet_success.gif'),
+ 'bg' => '#DDF',
+ ],
+ 'loader' => Mage::getDesign()->getSkinUrl('images/ajax-loader.gif'),
+ ],
+ 'template' => ''
+ . '
'
+ . '#{text}'
+ . '',
+ 'text' => $this->__('Processed %s%% %s/%d records', '#{percent}', '#{updated}', $this->getBatchItemsCount()),
+ 'successText' => $this->__('Imported %s records', '#{updated}'),
+ ],
+ );
+ $jsonIds = array_chunk($importIds, $numberOfRecords);
+ $importData = [];
+ foreach ($jsonIds as $part => $ids) {
+ $importData[] = [
+ 'batch_id' => $batchModel->getId(),
+ 'rows[]' => $ids,
+ ];
+ }
+ $this->setImportData($importData);
+ } else {
+ $this->setBatchModelHasAdapter(false);
+ $batchModel->delete();
+ }
+ }
+ $this->_batchModelPrepared = true;
+ return $this;
+ }
+ /**
+ * Return a batch model instance
+ * @return Mage_Dataflow_Model_Batch
+ */
+ protected function _getBatchModel()
+ {
+ return $this->_batchModel;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Design/Edit.php b/app/code/core/Mage/Adminhtml/Block/System/Design/Edit.php
index 02719c525ba..6fa14a98fbb 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Design/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Design/Edit.php
@@ -28,43 +28,6 @@ public function __construct()
$this->setId('design_edit');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'back_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('core')->__('Back'),
- 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/')),
- 'class' => 'back',
- ]),
- );
-
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('core')->__('Save'),
- 'onclick' => 'designForm.submit()',
- 'class' => 'save',
- ]),
- );
-
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('core')->__('Delete'),
- 'onclick' => Mage::helper('core/js')->getConfirmSetLocationJs($this->getDeleteUrl()),
- 'class' => 'delete',
- ]),
- );
- return parent::_prepareLayout();
- }
-
public function getDesignChangeId()
{
return Mage::registry('design')->getId();
@@ -107,4 +70,41 @@ public function getHeader()
}
return Mage::helper('core')->__('New Design Change');
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'back_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('core')->__('Back'),
+ 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getUrl('*/*/')),
+ 'class' => 'back',
+ ]),
+ );
+
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('core')->__('Save'),
+ 'onclick' => 'designForm.submit()',
+ 'class' => 'save',
+ ]),
+ );
+
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('core')->__('Delete'),
+ 'onclick' => Mage::helper('core/js')->getConfirmSetLocationJs($this->getDeleteUrl()),
+ 'class' => 'delete',
+ ]),
+ );
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Design/Grid.php b/app/code/core/Mage/Adminhtml/Block/System/Design/Grid.php
index 8d022e6b9c9..0b12bab2384 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Design/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Design/Grid.php
@@ -33,6 +33,27 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * Prepare row click url
+ *
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
+ /**
+ * Prepare grid url
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
/**
* Prepare grid data collection
*
@@ -88,25 +109,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Prepare row click url
- *
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
-
- /**
- * Prepare grid url
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Email/Template.php b/app/code/core/Mage/Adminhtml/Block/System/Email/Template.php
index 9bb7bd4f89b..dacd7a7ecff 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Email/Template.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Email/Template.php
@@ -22,6 +22,25 @@
*/
class Mage_Adminhtml_Block_System_Email_Template extends Mage_Adminhtml_Block_Template
{
+ /**
+ * Get URL for create new email template
+ *
+ * @return string
+ */
+ public function getCreateUrl()
+ {
+ return $this->getUrl('*/*/new');
+ }
+
+ /**
+ * Get transactional emails page header text
+ *
+ * @return string
+ */
+ public function getHeaderText()
+ {
+ return Mage::helper('adminhtml')->__('Transactional Emails');
+ }
/**
* Set transactional emails grid template
*/
@@ -49,26 +68,6 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
- /**
- * Get URL for create new email template
- *
- * @return string
- */
- public function getCreateUrl()
- {
- return $this->getUrl('*/*/new');
- }
-
- /**
- * Get transactional emails page header text
- *
- * @return string
- */
- public function getHeaderText()
- {
- return Mage::helper('adminhtml')->__('Transactional Emails');
- }
-
/**
* Get Add New Template button html
*
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit.php b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit.php
index 23c8d945397..17e1dcfeacd 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit.php
@@ -28,126 +28,6 @@ public function __construct()
$this->setTemplate('system/email/template/edit.phtml');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'back_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('adminhtml')->__('Back'),
- 'onclick' => "window.location.href = '" . $this->getUrl('*/*') . "'",
- 'class' => 'back',
- ],
- ),
- );
-
- $this->setChild(
- 'reset_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('adminhtml')->__('Reset'),
- 'onclick' => 'window.location.href = window.location.href',
- ],
- ),
- );
-
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('adminhtml')->__('Delete Template'),
- 'onclick' => 'templateControl.deleteTemplate();',
- 'class' => 'delete',
- ],
- ),
- );
-
- $this->setChild(
- 'to_plain_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('adminhtml')->__('Convert to Plain Text'),
- 'onclick' => 'templateControl.stripTags();',
- 'id' => 'convert_button',
- ],
- ),
- );
-
- $this->setChild(
- 'to_html_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('adminhtml')->__('Return Html Version'),
- 'onclick' => 'templateControl.unStripTags();',
- 'id' => 'convert_button_back',
- 'style' => 'display:none',
- ],
- ),
- );
-
- $this->setChild(
- 'toggle_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('adminhtml')->__('Toggle Editor'),
- 'onclick' => 'templateControl.toggleEditor();',
- 'id' => 'toggle_button',
- ],
- ),
- );
-
- $this->setChild(
- 'preview_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('adminhtml')->__('Preview Template'),
- 'onclick' => 'templateControl.preview();',
- ],
- ),
- );
-
- $this->setChild(
- 'save_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('adminhtml')->__('Save Template'),
- 'onclick' => 'templateControl.save();',
- 'class' => 'save',
- ],
- ),
- );
-
- $this->setChild(
- 'load_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData(
- [
- 'label' => Mage::helper('adminhtml')->__('Load Template'),
- 'onclick' => 'templateControl.load();',
- 'type' => 'button',
- 'class' => 'save',
- ],
- ),
- );
-
- $this->setChild(
- 'form',
- $this->getLayout()->createBlock('adminhtml/system_email_template_edit_form'),
- );
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -358,6 +238,136 @@ public function getUsedCurrentlyForPaths($asJSON = true)
return $pathsParts;
}
+ /**
+ * Return original template code of current template
+ *
+ * @return string
+ */
+ public function getOrigTemplateCode()
+ {
+ return $this->getEmailTemplate()->getOrigTemplateCode();
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'back_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('adminhtml')->__('Back'),
+ 'onclick' => "window.location.href = '" . $this->getUrl('*/*') . "'",
+ 'class' => 'back',
+ ],
+ ),
+ );
+
+ $this->setChild(
+ 'reset_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('adminhtml')->__('Reset'),
+ 'onclick' => 'window.location.href = window.location.href',
+ ],
+ ),
+ );
+
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('adminhtml')->__('Delete Template'),
+ 'onclick' => 'templateControl.deleteTemplate();',
+ 'class' => 'delete',
+ ],
+ ),
+ );
+
+ $this->setChild(
+ 'to_plain_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('adminhtml')->__('Convert to Plain Text'),
+ 'onclick' => 'templateControl.stripTags();',
+ 'id' => 'convert_button',
+ ],
+ ),
+ );
+
+ $this->setChild(
+ 'to_html_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('adminhtml')->__('Return Html Version'),
+ 'onclick' => 'templateControl.unStripTags();',
+ 'id' => 'convert_button_back',
+ 'style' => 'display:none',
+ ],
+ ),
+ );
+
+ $this->setChild(
+ 'toggle_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('adminhtml')->__('Toggle Editor'),
+ 'onclick' => 'templateControl.toggleEditor();',
+ 'id' => 'toggle_button',
+ ],
+ ),
+ );
+
+ $this->setChild(
+ 'preview_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('adminhtml')->__('Preview Template'),
+ 'onclick' => 'templateControl.preview();',
+ ],
+ ),
+ );
+
+ $this->setChild(
+ 'save_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('adminhtml')->__('Save Template'),
+ 'onclick' => 'templateControl.save();',
+ 'class' => 'save',
+ ],
+ ),
+ );
+
+ $this->setChild(
+ 'load_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData(
+ [
+ 'label' => Mage::helper('adminhtml')->__('Load Template'),
+ 'onclick' => 'templateControl.load();',
+ 'type' => 'button',
+ 'class' => 'save',
+ ],
+ ),
+ );
+
+ $this->setChild(
+ 'form',
+ $this->getLayout()->createBlock('adminhtml/system_email_template_edit_form'),
+ );
+ return parent::_prepareLayout();
+ }
+
/**
* Convert xml config paths to decorated names
*
@@ -420,14 +430,4 @@ protected function _getSystemConfigPathsParts($paths)
}
return $result;
}
-
- /**
- * Return original template code of current template
- *
- * @return string
- */
- public function getOrigTemplateCode()
- {
- return $this->getEmailTemplate()->getOrigTemplateCode();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit/Form.php b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit/Form.php
index 62ac731cc09..d516f336a13 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit/Form.php
@@ -22,6 +22,38 @@
*/
class Mage_Adminhtml_Block_System_Email_Template_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
+ /**
+ * Return current email template model
+ *
+ * @return Mage_Core_Model_Email_Template
+ */
+ public function getEmailTemplate()
+ {
+ return Mage::registry('current_email_template');
+ }
+
+ /**
+ * Retrieve variables to insert into email
+ *
+ * @return array
+ */
+ public function getVariables()
+ {
+ $variables = [];
+ $variables[] = Mage::getModel('core/source_email_variables')
+ ->toOptionArray(true);
+ $customVariables = Mage::getModel('core/variable')
+ ->getVariablesOptionArray(true);
+ if ($customVariables) {
+ $variables[] = $customVariables;
+ }
+ /** @var Mage_Core_Model_Email_Template $template */
+ $template = Mage::registry('current_email_template');
+ if ($template->getId() && $templateVariables = $template->getVariablesOptionArray(true)) {
+ $variables[] = $templateVariables;
+ }
+ return $variables;
+ }
/**
* Prepare layout.
* Add files to use dialog windows
@@ -145,37 +177,4 @@ protected function _prepareForm()
return parent::_prepareForm();
}
-
- /**
- * Return current email template model
- *
- * @return Mage_Core_Model_Email_Template
- */
- public function getEmailTemplate()
- {
- return Mage::registry('current_email_template');
- }
-
- /**
- * Retrieve variables to insert into email
- *
- * @return array
- */
- public function getVariables()
- {
- $variables = [];
- $variables[] = Mage::getModel('core/source_email_variables')
- ->toOptionArray(true);
- $customVariables = Mage::getModel('core/variable')
- ->getVariablesOptionArray(true);
- if ($customVariables) {
- $variables[] = $customVariables;
- }
- /** @var Mage_Core_Model_Email_Template $template */
- $template = Mage::registry('current_email_template');
- if ($template->getId() && $templateVariables = $template->getVariablesOptionArray(true)) {
- $variables[] = $templateVariables;
- }
- return $variables;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Grid.php b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Grid.php
index 1b440ba29cd..742b1ddf929 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Grid.php
@@ -22,6 +22,10 @@
*/
class Mage_Adminhtml_Block_System_Email_Template_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
protected function _construct()
{
$this->setEmptyText(Mage::helper('adminhtml')->__('No Templates Found'));
@@ -113,9 +117,4 @@ protected function _prepareColumns()
);
return $this;
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Grid/Filter/Type.php b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Grid/Filter/Type.php
index fb0607fec74..af7cd6465d6 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Grid/Filter/Type.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Grid/Filter/Type.php
@@ -29,27 +29,27 @@ class Mage_Adminhtml_Block_System_Email_Template_Grid_Filter_Type extends Mage_A
];
/**
- * @return array
+ * @return array|null
*/
- protected function _getOptions()
+ public function getCondition()
{
- $result = [];
- foreach (self::$_types as $code => $label) {
- $result[] = ['value' => $code, 'label' => Mage::helper('adminhtml')->__($label)];
+ if (is_null($this->getValue())) {
+ return null;
}
- return $result;
+ return ['eq' => $this->getValue()];
}
/**
- * @return array|null
+ * @return array
*/
- public function getCondition()
+ protected function _getOptions()
{
- if (is_null($this->getValue())) {
- return null;
+ $result = [];
+ foreach (self::$_types as $code => $label) {
+ $result[] = ['value' => $code, 'label' => Mage::helper('adminhtml')->__($label)];
}
- return ['eq' => $this->getValue()];
+ return $result;
}
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Store/Store.php b/app/code/core/Mage/Adminhtml/Block/System/Store/Store.php
index bd10ca089a6..86b78a664c0 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Store/Store.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Store/Store.php
@@ -31,6 +31,30 @@ public function __construct()
parent::__construct();
}
+ /**
+ * Retrieve grid
+ *
+ * @return string
+ */
+ public function getGridHtml()
+ {
+ return $this->getLayout()->createBlock('adminhtml/system_store_tree')->toHtml();
+ }
+
+ /**
+ * Retrieve buttons
+ *
+ * @return string
+ */
+ public function getAddNewButtonHtml()
+ {
+ return implode(' ', [
+ $this->getChildHtml('add_new_website'),
+ $this->getChildHtml('add_new_group'),
+ $this->getChildHtml('add_new_store'),
+ ]);
+ }
+
/**
* @inheritDoc
*/
@@ -59,28 +83,4 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
-
- /**
- * Retrieve grid
- *
- * @return string
- */
- public function getGridHtml()
- {
- return $this->getLayout()->createBlock('adminhtml/system_store_tree')->toHtml();
- }
-
- /**
- * Retrieve buttons
- *
- * @return string
- */
- public function getAddNewButtonHtml()
- {
- return implode(' ', [
- $this->getChildHtml('add_new_website'),
- $this->getChildHtml('add_new_group'),
- $this->getChildHtml('add_new_store'),
- ]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Store/Tree.php b/app/code/core/Mage/Adminhtml/Block/System/Store/Tree.php
index c7f284e28b0..943fdac56b5 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Store/Tree.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Store/Tree.php
@@ -38,19 +38,6 @@ public function _construct()
parent::_construct();
}
- /**
- * Prepare block layout
- *
- * @return Mage_Core_Block_Abstract
- */
- protected function _prepareLayout()
- {
- $this->_cellTemplate = $this->getLayout()
- ->createBlock('adminhtml/template')
- ->setTemplate('system/store/cell.phtml');
- return parent::_prepareLayout();
- }
-
/**
* Get table data
*
@@ -99,16 +86,6 @@ public function getTableData()
return $data;
}
- /**
- * Create new cell template
- *
- * @return Mage_Adminhtml_Block_Template
- */
- protected function _createCellTemplate()
- {
- return clone($this->_cellTemplate);
- }
-
/**
* Render website
*
@@ -154,4 +131,27 @@ public function renderStore(Mage_Core_Model_Store $store)
}
return $cell->toHtml();
}
+
+ /**
+ * Prepare block layout
+ *
+ * @return Mage_Core_Block_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ $this->_cellTemplate = $this->getLayout()
+ ->createBlock('adminhtml/template')
+ ->setTemplate('system/store/cell.phtml');
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Create new cell template
+ *
+ * @return Mage_Adminhtml_Block_Template
+ */
+ protected function _createCellTemplate()
+ {
+ return clone($this->_cellTemplate);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Variable/Edit.php b/app/code/core/Mage/Adminhtml/Block/System/Variable/Edit.php
index 81a4cb8141c..5e5c7b298e3 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Variable/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Variable/Edit.php
@@ -22,13 +22,6 @@
*/
class Mage_Adminhtml_Block_System_Variable_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
- protected function _construct()
- {
- parent::_construct();
- $this->_objectId = 'variable_id';
- $this->_controller = 'system_variable';
- }
-
/**
* @return Mage_Core_Model_Variable
*/
@@ -37,22 +30,6 @@ public function getVariable()
return Mage::registry('current_variable');
}
- /**
- * @inheritDoc
- */
- protected function _preparelayout()
- {
- $this->_addButton('save_and_edit', [
- 'label' => Mage::helper('adminhtml')->__('Save and Continue Edit'),
- 'class' => 'save',
- 'onclick' => 'editForm.submit(\'' . $this->getSaveAndContinueUrl() . '\');',
- ], 100);
- if (!$this->getVariable()->getId()) {
- $this->removeButton('delete');
- }
- return parent::_prepareLayout();
- }
-
/**
* Return form HTML
*
@@ -111,4 +88,26 @@ public function getSaveAndContinueUrl()
{
return $this->getUrl('*/*/save', ['_current' => true, 'back' => 'edit']);
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_objectId = 'variable_id';
+ $this->_controller = 'system_variable';
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _preparelayout()
+ {
+ $this->_addButton('save_and_edit', [
+ 'label' => Mage::helper('adminhtml')->__('Save and Continue Edit'),
+ 'class' => 'save',
+ 'onclick' => 'editForm.submit(\'' . $this->getSaveAndContinueUrl() . '\');',
+ ], 100);
+ if (!$this->getVariable()->getId()) {
+ $this->removeButton('delete');
+ }
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Variable/Grid.php b/app/code/core/Mage/Adminhtml/Block/System/Variable/Grid.php
index c91e6ae68b2..1ee081a1457 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Variable/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Variable/Grid.php
@@ -22,6 +22,15 @@
*/
class Mage_Adminhtml_Block_System_Variable_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
+ /**
+ * Row click url
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['variable_id' => $row->getId()]);
+ }
/**
* Internal constructor
*
@@ -72,14 +81,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Row click url
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['variable_id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tag/Assigned/Grid.php b/app/code/core/Mage/Adminhtml/Block/Tag/Assigned/Grid.php
index a934e0e8a06..a6ed59b11e8 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tag/Assigned/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tag/Assigned/Grid.php
@@ -42,6 +42,28 @@ public function __construct()
}
}
+ /**
+ * Retrieve Grid Url
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/assignedGridOnly', ['_current' => true]);
+ }
+
+ /**
+ * Retrieve related products
+ *
+ * @return array
+ */
+ public function getRelatedProducts()
+ {
+ return $this->_currentTagModel
+ ->setStatusFilter(Mage_Tag_Model_Tag::STATUS_APPROVED)
+ ->getRelatedProductIds();
+ }
+
/**
* Tag ID getter
*
@@ -253,26 +275,4 @@ protected function _getSelectedProducts()
}
return $products;
}
-
- /**
- * Retrieve Grid Url
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/assignedGridOnly', ['_current' => true]);
- }
-
- /**
- * Retrieve related products
- *
- * @return array
- */
- public function getRelatedProducts()
- {
- return $this->_currentTagModel
- ->setStatusFilter(Mage_Tag_Model_Tag::STATUS_APPROVED)
- ->getRelatedProductIds();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tag/Customer/Grid.php b/app/code/core/Mage/Adminhtml/Block/Tag/Customer/Grid.php
index 2a6b586453e..de12e64f3f6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tag/Customer/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tag/Customer/Grid.php
@@ -43,6 +43,15 @@ public function getGridUrl()
return $this->getUrl('*/*/customer', ['_current' => true]);
}
+ /**
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/customer/edit', ['id' => $row->getId()]);
+ }
+
/**
* @inheritDoc
*/
@@ -115,13 +124,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/customer/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tag/Edit.php b/app/code/core/Mage/Adminhtml/Block/Tag/Edit.php
index f7b9a9dbddd..b75df1c2188 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tag/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tag/Edit.php
@@ -43,22 +43,6 @@ public function __construct()
], 1);
}
- /**
- * Add child HTML to layout
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
-
- $this->setChild('store_switcher', $this->getLayout()->createBlock('adminhtml/tag_store_switcher'))
- ->setChild('tag_assign_accordion', $this->getLayout()->createBlock('adminhtml/tag_edit_assigned'))
- ->setChild('accordion', $this->getLayout()->createBlock('adminhtml/tag_edit_accordion'));
-
- return $this;
- }
-
/**
* Retrieve Header text
*
@@ -171,4 +155,20 @@ public function getBackUrl()
{
return $this->getUrl('*/*/' . $this->getRequest()->getParam('ret', 'index'));
}
+
+ /**
+ * Add child HTML to layout
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+
+ $this->setChild('store_switcher', $this->getLayout()->createBlock('adminhtml/tag_store_switcher'))
+ ->setChild('tag_assign_accordion', $this->getLayout()->createBlock('adminhtml/tag_edit_assigned'))
+ ->setChild('accordion', $this->getLayout()->createBlock('adminhtml/tag_edit_accordion'));
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tag/Grid/All.php b/app/code/core/Mage/Adminhtml/Block/Tag/Grid/All.php
index 37682d6f89f..ee33ea4ec0d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tag/Grid/All.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tag/Grid/All.php
@@ -35,6 +35,15 @@ public function __construct()
$this->setDefaultDir('desc');
}
+ /**
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/products', ['tag_id' => $row->getId()]);
+ }
+
/**
* @inheritDoc
*/
@@ -98,13 +107,4 @@ protected function _addColumnFilterToCollection($column)
}
return $this;
}
-
- /**
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/products', ['tag_id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tag/Grid/Pending.php b/app/code/core/Mage/Adminhtml/Block/Tag/Grid/Pending.php
index 110f4160763..afd237b04f3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tag/Grid/Pending.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tag/Grid/Pending.php
@@ -36,6 +36,27 @@ public function __construct()
->setSaveParametersInSession(true);
}
+ /**
+ * Retrieves row click URL
+ *
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['tag_id' => $row->getId(), 'ret' => 'pending']);
+ }
+
+ /**
+ * Retrieves Grid Url
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/tag/ajaxPendingGrid', ['_current' => true]);
+ }
+
/**
* @inheritDoc
*/
@@ -95,17 +116,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * Retrieves row click URL
- *
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['tag_id' => $row->getId(), 'ret' => 'pending']);
- }
-
/**
* @param Mage_Adminhtml_Block_Widget_Grid_Column $column
* @return $this
@@ -156,14 +166,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * Retrieves Grid Url
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/tag/ajaxPendingGrid', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tag/Pending.php b/app/code/core/Mage/Adminhtml/Block/Tag/Pending.php
index 93ca9026d75..0305713fe2d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tag/Pending.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tag/Pending.php
@@ -28,12 +28,6 @@ public function __construct()
$this->setTemplate('tag/index.phtml');
}
- protected function _prepareLayout()
- {
- $this->setChild('tagsGrid', $this->getLayout()->createBlock('adminhtml/tag_grid_pending'));
- return parent::_prepareLayout();
- }
-
public function getCreateButtonHtml()
{
return '';
@@ -53,4 +47,10 @@ public function getHeaderCssClass()
{
return 'icon-head head-tag';
}
+
+ protected function _prepareLayout()
+ {
+ $this->setChild('tagsGrid', $this->getLayout()->createBlock('adminhtml/tag_grid_pending'));
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tag/Product/Grid.php b/app/code/core/Mage/Adminhtml/Block/Tag/Product/Grid.php
index 14dd3d4e8d9..db050b717de 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tag/Product/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tag/Product/Grid.php
@@ -46,6 +46,11 @@ public function getGridUrl()
return $this->getUrl('*/*/product', ['_current' => true]);
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
+ }
+
/**
* @inheritDoc
* @throws Exception
@@ -115,9 +120,4 @@ protected function _addColumnFilterToCollection($column)
return parent::_addColumnFilterToCollection($column);
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/catalog_product/edit', ['id' => $row->getProductId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tag/Tag/Edit.php b/app/code/core/Mage/Adminhtml/Block/Tag/Tag/Edit.php
index 92777f2499a..f9c0010dfb0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tag/Tag/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tag/Tag/Edit.php
@@ -78,18 +78,6 @@ public function __construct()
$this->_updateButton('delete', 'label', Mage::helper('tag')->__('Delete Tag'));
}
- /**
- * Add to layout accordion block
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
- $this->setChild('accordion', $this->getLayout()->createBlock('adminhtml/tag_edit_accordion'));
- return $this;
- }
-
/**
* Adds to html of form html of accordion block
*
@@ -111,4 +99,16 @@ public function getHeaderText()
}
return Mage::helper('tag')->__('New Tag');
}
+
+ /**
+ * Add to layout accordion block
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+ $this->setChild('accordion', $this->getLayout()->createBlock('adminhtml/tag_edit_accordion'));
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tag/Tag/Grid.php b/app/code/core/Mage/Adminhtml/Block/Tag/Tag/Grid.php
index 6fc9d2c739c..8d32d186b2c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tag/Tag/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tag/Tag/Grid.php
@@ -36,6 +36,27 @@ public function __construct()
->setSaveParametersInSession(true);
}
+ /**
+ * Retrieves Grid Url
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/tag/ajaxGrid', ['_current' => true]);
+ }
+
+ /**
+ * Retrieves row click URL
+ *
+ * @param Mage_Tag_Model_Tag $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['tag_id' => $row->getId()]);
+ }
+
/**
* @param Mage_Adminhtml_Block_Widget_Grid_Column $column
* @return $this
@@ -147,25 +168,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * Retrieves Grid Url
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/tag/ajaxGrid', ['_current' => true]);
- }
-
- /**
- * Retrieves row click URL
- *
- * @param Mage_Tag_Model_Tag $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['tag_id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tax/Class/Grid.php b/app/code/core/Mage/Adminhtml/Block/Tax/Class/Grid.php
index deb17dcfd3a..99434af19e9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tax/Class/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tax/Class/Grid.php
@@ -30,6 +30,11 @@ public function __construct()
$this->setDefaultDir('ASC');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getModel('tax/class')
@@ -52,9 +57,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Grid.php b/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Grid.php
index 3b6d2d31b78..3fe7fe99ed1 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Grid.php
@@ -29,6 +29,15 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * @param Mage_Tax_Model_Calculation_Rate $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['rate' => $row->getTaxCalculationRateId()]);
+ }
+
protected function _prepareCollection()
{
$rateCollection = Mage::getModel('tax/calculation_rate')->getCollection()
@@ -101,13 +110,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * @param Mage_Tax_Model_Calculation_Rate $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['rate' => $row->getTaxCalculationRateId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Title.php b/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Title.php
index 890dc48ef0c..15b6e38e1db 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Title.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Title.php
@@ -24,11 +24,6 @@ class Mage_Adminhtml_Block_Tax_Rate_Title extends Mage_Core_Block_Template
{
protected $_titles;
- protected function _construct()
- {
- $this->setTemplate('tax/rate/title.phtml');
- }
-
public function getTitles()
{
if (is_null($this->_titles)) {
@@ -58,4 +53,9 @@ public function getStores()
}
return $stores;
}
+
+ protected function _construct()
+ {
+ $this->setTemplate('tax/rate/title.phtml');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Toolbar/Save.php b/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Toolbar/Save.php
index c6e01cb61b0..dc51ed5b4c7 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Toolbar/Save.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tax/Rate/Toolbar/Save.php
@@ -33,6 +33,42 @@ public function __construct()
$this->setTemplate('tax/toolbar/rate/save.phtml');
}
+ /**
+ * @return string
+ */
+ public function getBackButtonHtml()
+ {
+ return $this->getChildHtml('backButton');
+ }
+
+ /**
+ * @return string
+ */
+ public function getResetButtonHtml()
+ {
+ return $this->getChildHtml('resetButton');
+ }
+
+ /**
+ * @return string
+ */
+ public function getSaveButtonHtml()
+ {
+ return $this->getChildHtml('saveButton');
+ }
+
+ /**
+ * @return string|void
+ * @throws Exception
+ */
+ public function getDeleteButtonHtml()
+ {
+ if ((int) $this->getRequest()->getParam('rate') == 0) {
+ return;
+ }
+ return $this->getChildHtml('deleteButton');
+ }
+
/**
* @inheritDoc
* @throws Exception
@@ -81,40 +117,4 @@ protected function _prepareLayout()
);
return parent::_prepareLayout();
}
-
- /**
- * @return string
- */
- public function getBackButtonHtml()
- {
- return $this->getChildHtml('backButton');
- }
-
- /**
- * @return string
- */
- public function getResetButtonHtml()
- {
- return $this->getChildHtml('resetButton');
- }
-
- /**
- * @return string
- */
- public function getSaveButtonHtml()
- {
- return $this->getChildHtml('saveButton');
- }
-
- /**
- * @return string|void
- * @throws Exception
- */
- public function getDeleteButtonHtml()
- {
- if ((int) $this->getRequest()->getParam('rate') == 0) {
- return;
- }
- return $this->getChildHtml('deleteButton');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Tax/Rule/Grid.php b/app/code/core/Mage/Adminhtml/Block/Tax/Rule/Grid.php
index ddd5319a6ca..ab71203c304 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tax/Rule/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tax/Rule/Grid.php
@@ -36,6 +36,17 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * Return url
+ *
+ * @param Mage_Tax_Model_Calculation_Rule $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['rule' => $row->getId()]);
+ }
+
/**
* Prepare grid collection
*
@@ -169,15 +180,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Return url
- *
- * @param Mage_Tax_Model_Calculation_Rule $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['rule' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Template.php b/app/code/core/Mage/Adminhtml/Block/Template.php
index 63314a08acc..31da6b65260 100644
--- a/app/code/core/Mage/Adminhtml/Block/Template.php
+++ b/app/code/core/Mage/Adminhtml/Block/Template.php
@@ -22,14 +22,6 @@
*/
class Mage_Adminhtml_Block_Template extends Mage_Core_Block_Template
{
- /**
- * @return string
- */
- protected function _getUrlModelClass()
- {
- return 'adminhtml/url';
- }
-
/**
* Retrieve Session Form Key
*
@@ -52,24 +44,31 @@ public function isOutputEnabled($moduleName = null)
}
/**
- * Prepare html output
+ * Deleting script tags from string
*
+ * @param string $html
* @return string
*/
- protected function _toHtml()
+ public function maliciousCodeFilter($html)
{
- Mage::dispatchEvent('adminhtml_block_html_before', ['block' => $this]);
- return parent::_toHtml();
+ return Mage::getSingleton('core/input_filter_maliciousCode')->filter($html);
+ }
+ /**
+ * @return string
+ */
+ protected function _getUrlModelClass()
+ {
+ return 'adminhtml/url';
}
/**
- * Deleting script tags from string
+ * Prepare html output
*
- * @param string $html
* @return string
*/
- public function maliciousCodeFilter($html)
+ protected function _toHtml()
{
- return Mage::getSingleton('core/input_filter_maliciousCode')->filter($html);
+ Mage::dispatchEvent('adminhtml_block_html_before', ['block' => $this]);
+ return parent::_toHtml();
}
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Category/Tree.php b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Category/Tree.php
index a86dbf97504..96fff585b52 100644
--- a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Category/Tree.php
+++ b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Category/Tree.php
@@ -95,6 +95,16 @@ public function getCategoryCollection()
return $collection;
}
+ /**
+ * Get URL for categories tree ajax loader
+ *
+ * @return string
+ */
+ public function getLoadTreeUrl()
+ {
+ return Mage::helper('adminhtml')->getUrl('*/*/categoriesJson');
+ }
+
/**
* Convert categories tree to array recursively
*
@@ -128,14 +138,4 @@ protected function _getNodesArray($node)
return $result;
}
-
- /**
- * Get URL for categories tree ajax loader
- *
- * @return string
- */
- public function getLoadTreeUrl()
- {
- return Mage::helper('adminhtml')->getUrl('*/*/categoriesJson');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit.php b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit.php
index 24a98f1e2c4..714d8017d9f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit.php
@@ -37,6 +37,101 @@ class Mage_Adminhtml_Block_Urlrewrite_Edit extends Mage_Adminhtml_Block_Widget_C
*/
protected $_buttonsHtml;
+ /**
+ * Get container buttons HTML
+ *
+ * Since buttons are set as children, we remove them as children after generating them
+ * not to duplicate them in future
+ *
+ * @return string
+ */
+ public function getButtonsHtml($area = null)
+ {
+ if ($this->_buttonsHtml === null) {
+ $this->_buttonsHtml = parent::getButtonsHtml();
+ foreach (array_keys($this->_children) as $alias) {
+ if (str_contains($alias, '_button')) {
+ $this->unsetChild($alias);
+ }
+ }
+ }
+ return $this->_buttonsHtml;
+ }
+
+ /**
+ * Get current urlrewrite instance id
+ *
+ * @return int
+ */
+ public function getUrlrewriteId()
+ {
+ return Mage::registry('current_urlrewrite')->getId();
+ }
+
+ /**
+ * Get current product instance id
+ *
+ * @return int
+ */
+ public function getProductId()
+ {
+ return Mage::registry('current_product')->getId();
+ }
+
+ /**
+ * Return current category instance id
+ *
+ * @return int
+ */
+ public function getCategoryId()
+ {
+ return Mage::registry('current_category')->getId();
+ }
+
+ /**
+ * Check whether specified selection mode is set in request
+ *
+ * @param string $mode
+ * @return bool
+ */
+ public function isMode($mode)
+ {
+ return $this->getRequest()->has($mode);
+ }
+
+ /**
+ * Update layout by specified mode code
+ *
+ * @param string $mode
+ * @return $this
+ * @see Mage_Adminhtml_Block_Urlrewrite_Selector
+ */
+ public function updateModeLayout($mode = null)
+ {
+ if (!$mode) {
+ $modes = array_keys(Mage::getBlockSingleton('adminhtml/urlrewrite_selector')->getModes());
+ $mode = array_shift($modes);
+ }
+
+ // edit form for new custom urlrewrite
+ if ($mode === 'id') {
+ $this->_setFormChild();
+ } elseif ($mode === 'product') { // products grid
+ $this->setChild('products_grid', $this->getLayout()->createBlock('adminhtml/urlrewrite_product_grid'));
+ } elseif ($mode === 'category') { // categories tree
+ $this->setChild('categories_tree', $this->getLayout()->createBlock('adminhtml/urlrewrite_category_tree'));
+ }
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getHeaderCssClass()
+ {
+ return 'icon-head head-urlrewrite';
+ }
+
/**
* @inheritDoc
*/
@@ -182,99 +277,4 @@ protected function _setFormChild()
return $this;
}
-
- /**
- * Get container buttons HTML
- *
- * Since buttons are set as children, we remove them as children after generating them
- * not to duplicate them in future
- *
- * @return string
- */
- public function getButtonsHtml($area = null)
- {
- if ($this->_buttonsHtml === null) {
- $this->_buttonsHtml = parent::getButtonsHtml();
- foreach (array_keys($this->_children) as $alias) {
- if (str_contains($alias, '_button')) {
- $this->unsetChild($alias);
- }
- }
- }
- return $this->_buttonsHtml;
- }
-
- /**
- * Get current urlrewrite instance id
- *
- * @return int
- */
- public function getUrlrewriteId()
- {
- return Mage::registry('current_urlrewrite')->getId();
- }
-
- /**
- * Get current product instance id
- *
- * @return int
- */
- public function getProductId()
- {
- return Mage::registry('current_product')->getId();
- }
-
- /**
- * Return current category instance id
- *
- * @return int
- */
- public function getCategoryId()
- {
- return Mage::registry('current_category')->getId();
- }
-
- /**
- * Check whether specified selection mode is set in request
- *
- * @param string $mode
- * @return bool
- */
- public function isMode($mode)
- {
- return $this->getRequest()->has($mode);
- }
-
- /**
- * Update layout by specified mode code
- *
- * @param string $mode
- * @return $this
- * @see Mage_Adminhtml_Block_Urlrewrite_Selector
- */
- public function updateModeLayout($mode = null)
- {
- if (!$mode) {
- $modes = array_keys(Mage::getBlockSingleton('adminhtml/urlrewrite_selector')->getModes());
- $mode = array_shift($modes);
- }
-
- // edit form for new custom urlrewrite
- if ($mode === 'id') {
- $this->_setFormChild();
- } elseif ($mode === 'product') { // products grid
- $this->setChild('products_grid', $this->getLayout()->createBlock('adminhtml/urlrewrite_product_grid'));
- } elseif ($mode === 'category') { // categories tree
- $this->setChild('categories_tree', $this->getLayout()->createBlock('adminhtml/urlrewrite_category_tree'));
- }
- return $this;
- }
-
- /**
- * @return string
- */
- public function getHeaderCssClass()
- {
- return 'icon-head head-urlrewrite';
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Grid.php b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Grid.php
index 090351d759a..568fa96d707 100644
--- a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Grid.php
@@ -29,6 +29,12 @@ public function __construct()
$this->setDefaultSort('url_rewrite_id');
}
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ //return $this->getUrl('*/*/view', array('id' => $row->getId()));
+ }
+
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('core/url_rewrite_collection');
@@ -92,10 +98,4 @@ protected function _prepareColumns()
//$this->addExportType('*/*/exportXml', $this->__('XML'));
return parent::_prepareColumns();
}
-
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- //return $this->getUrl('*/*/view', array('id' => $row->getId()));
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Product/Grid.php b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Product/Grid.php
index a79bd72f0a4..d3085b3ab1e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Product/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Product/Grid.php
@@ -22,6 +22,25 @@
*/
class Mage_Adminhtml_Block_Urlrewrite_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid
{
+ /**
+ * Get url for dispatching grid ajax requests
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/productGrid', ['_current' => true]);
+ }
+
+ /**
+ * Get row url
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['product' => $row->getId()]) . 'category';
+ }
/**
* Disable massaction
*
@@ -75,24 +94,4 @@ protected function _prepareColumns()
);
return $this;
}
-
- /**
- * Get url for dispatching grid ajax requests
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/productGrid', ['_current' => true]);
- }
-
- /**
- * Get row url
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['product' => $row->getId()]) . 'category';
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget.php b/app/code/core/Mage/Adminhtml/Block/Widget.php
index 831fbbd50dd..06e2b86a3ac 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget.php
@@ -58,13 +58,6 @@ public function getCurrentUrl($params = [])
return $this->getUrl('*/*/*', $params);
}
- protected function _addBreadcrumb($label, $title = null, $link = null)
- {
- /** @var Mage_Adminhtml_Block_Widget_Breadcrumbs $block */
- $block = $this->getLayout()->getBlock('breadcrumbs');
- $block->addLink($label, $title, $link);
- }
-
/**
* Create button and return its html
*
@@ -94,4 +87,11 @@ public function getGlobalIcon()
{
return '
';
}
+
+ protected function _addBreadcrumb($label, $title = null, $link = null)
+ {
+ /** @var Mage_Adminhtml_Block_Widget_Breadcrumbs $block */
+ $block = $this->getLayout()->getBlock('breadcrumbs');
+ $block->addLink($label, $title, $link);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Container.php b/app/code/core/Mage/Adminhtml/Block/Widget/Container.php
index a8fbc946cc1..e9a7d657336 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Container.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Container.php
@@ -48,31 +48,6 @@ class Mage_Adminhtml_Block_Widget_Container extends Mage_Adminhtml_Block_Templat
*/
protected $_headerText = 'Container Widget Header';
- /**
- * Add a button
- *
- * @param string $id
- * @param array $data
- * @param int $level
- * @param int $sortOrder
- * @param string|null $area area, that button should be displayed in ('header', 'footer', null)
- * @return $this
- */
- protected function _addButton($id, $data, $level = 0, $sortOrder = 0, $area = 'header')
- {
- if (!isset($this->_buttons[$level])) {
- $this->_buttons[$level] = [];
- }
- $this->_buttons[$level][$id] = $data;
- $this->_buttons[$level][$id]['area'] = $area;
- if ($sortOrder) {
- $this->_buttons[$level][$id]['sort_order'] = $sortOrder;
- } else {
- $this->_buttons[$level][$id]['sort_order'] = count($this->_buttons[$level]) * 10;
- }
- return $this;
- }
-
/**
* Public wrapper for protected _addButton method
*
@@ -88,22 +63,6 @@ public function addButton($id, $data, $level = 0, $sortOrder = 0, $area = 'heade
return $this->_addButton($id, $data, $level, $sortOrder, $area);
}
- /**
- * Remove existing button
- *
- * @param string $id
- * @return $this
- */
- protected function _removeButton($id)
- {
- foreach ($this->_buttons as $level => $buttons) {
- if (isset($buttons[$id])) {
- unset($this->_buttons[$level][$id]);
- }
- }
- return $this;
- }
-
/**
* Public wrapper for the _removeButton() method
*
@@ -115,37 +74,6 @@ public function removeButton($id)
return $this->_removeButton($id);
}
- /**
- * Update specified button property
- *
- * @param string $id
- * @param string $key
- * @param mixed $data
- * @return $this
- */
- protected function _updateButton($id, $key, $data)
- {
- foreach ($this->_buttons as $level => $buttons) {
- if (isset($buttons[$id])) {
- if (!empty($key)) {
- if ($child = $this->getChild($id . '_button')) {
- $child->setData($key, $data);
- }
- if ($key == 'level') {
- $this->_buttons[$data][$id] = $this->_buttons[$level][$id];
- unset($this->_buttons[$level][$id]);
- } else {
- $this->_buttons[$level][$id][$key] = $data;
- }
- } else {
- $this->_buttons[$level][$id] = $data;
- }
- break;
- }
- }
- return $this;
- }
-
/**
* Public wrapper for protected _updateButton method
*
@@ -159,44 +87,6 @@ public function updateButton($id, $key, $data)
return $this->_updateButton($id, $key, $data);
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- foreach ($this->_buttons as $level => $buttons) {
- foreach ($buttons as $id => $data) {
- $childId = $this->_prepareButtonBlockId($id);
- $this->_addButtonChildBlock($childId);
- }
- }
- return parent::_prepareLayout();
- }
-
- /**
- * Prepare block id for button's id
- *
- * @param string $id
- * @return string
- */
- protected function _prepareButtonBlockId($id)
- {
- return $id . '_button';
- }
-
- /**
- * Adding child block with specified child's id.
- *
- * @param string $childId
- * @return Mage_Adminhtml_Block_Widget_Button
- */
- protected function _addButtonChildBlock($childId)
- {
- $block = $this->getLayout()->createBlock('adminhtml/widget_button');
- $this->setChild($childId, $block);
- return $block;
- }
-
/**
* Produce buttons HTML
*
@@ -283,6 +173,116 @@ public function hasFooterButtons()
return false;
}
+ /**
+ * Add a button
+ *
+ * @param string $id
+ * @param array $data
+ * @param int $level
+ * @param int $sortOrder
+ * @param string|null $area area, that button should be displayed in ('header', 'footer', null)
+ * @return $this
+ */
+ protected function _addButton($id, $data, $level = 0, $sortOrder = 0, $area = 'header')
+ {
+ if (!isset($this->_buttons[$level])) {
+ $this->_buttons[$level] = [];
+ }
+ $this->_buttons[$level][$id] = $data;
+ $this->_buttons[$level][$id]['area'] = $area;
+ if ($sortOrder) {
+ $this->_buttons[$level][$id]['sort_order'] = $sortOrder;
+ } else {
+ $this->_buttons[$level][$id]['sort_order'] = count($this->_buttons[$level]) * 10;
+ }
+ return $this;
+ }
+
+ /**
+ * Remove existing button
+ *
+ * @param string $id
+ * @return $this
+ */
+ protected function _removeButton($id)
+ {
+ foreach ($this->_buttons as $level => $buttons) {
+ if (isset($buttons[$id])) {
+ unset($this->_buttons[$level][$id]);
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Update specified button property
+ *
+ * @param string $id
+ * @param string $key
+ * @param mixed $data
+ * @return $this
+ */
+ protected function _updateButton($id, $key, $data)
+ {
+ foreach ($this->_buttons as $level => $buttons) {
+ if (isset($buttons[$id])) {
+ if (!empty($key)) {
+ if ($child = $this->getChild($id . '_button')) {
+ $child->setData($key, $data);
+ }
+ if ($key == 'level') {
+ $this->_buttons[$data][$id] = $this->_buttons[$level][$id];
+ unset($this->_buttons[$level][$id]);
+ } else {
+ $this->_buttons[$level][$id][$key] = $data;
+ }
+ } else {
+ $this->_buttons[$level][$id] = $data;
+ }
+ break;
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ foreach ($this->_buttons as $level => $buttons) {
+ foreach ($buttons as $id => $data) {
+ $childId = $this->_prepareButtonBlockId($id);
+ $this->_addButtonChildBlock($childId);
+ }
+ }
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Prepare block id for button's id
+ *
+ * @param string $id
+ * @return string
+ */
+ protected function _prepareButtonBlockId($id)
+ {
+ return $id . '_button';
+ }
+
+ /**
+ * Adding child block with specified child's id.
+ *
+ * @param string $childId
+ * @return Mage_Adminhtml_Block_Widget_Button
+ */
+ protected function _addButtonChildBlock($childId)
+ {
+ $block = $this->getLayout()->createBlock('adminhtml/widget_button');
+ $this->setChild($childId, $block);
+ return $block;
+ }
+
/**
* Prepare html output
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Form.php b/app/code/core/Mage/Adminhtml/Block/Widget/Form.php
index a4910e18e85..bbf7abef5ba 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Form.php
@@ -29,45 +29,6 @@ class Mage_Adminhtml_Block_Widget_Form extends Mage_Adminhtml_Block_Widget
*/
protected $_form;
- /**
- * Class constructor
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('widget/form.phtml');
- $this->setDestElementId('edit_form');
- $this->setShowGlobalIcon(false);
- }
-
- /**
- * Preparing global layout
- *
- * You can redefine this method in child classes for changin layout
- *
- * @return Mage_Core_Block_Abstract
- */
- protected function _prepareLayout()
- {
- $renderer = $this->getLayout()->createBlock('adminhtml/widget_form_renderer_element');
- if ($renderer instanceof Varien_Data_Form_Element_Renderer_Interface) {
- Varien_Data_Form::setElementRenderer($renderer);
- }
-
- $renderer = $this->getLayout()->createBlock('adminhtml/widget_form_renderer_fieldset');
- if ($renderer instanceof Varien_Data_Form_Element_Renderer_Interface) {
- Varien_Data_Form::setFieldsetRenderer($renderer);
- }
-
- $renderer = $this->getLayout()->createBlock('adminhtml/widget_form_renderer_fieldset_element');
- if ($renderer instanceof Varien_Data_Form_Element_Renderer_Interface) {
- Varien_Data_Form::setFieldsetElementRenderer($renderer);
- }
-
- return parent::_prepareLayout();
- }
-
/**
* Get form object
*
@@ -116,6 +77,45 @@ public function setForm(Varien_Data_Form $form)
return $this;
}
+ /**
+ * Class constructor
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('widget/form.phtml');
+ $this->setDestElementId('edit_form');
+ $this->setShowGlobalIcon(false);
+ }
+
+ /**
+ * Preparing global layout
+ *
+ * You can redefine this method in child classes for changin layout
+ *
+ * @return Mage_Core_Block_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ $renderer = $this->getLayout()->createBlock('adminhtml/widget_form_renderer_element');
+ if ($renderer instanceof Varien_Data_Form_Element_Renderer_Interface) {
+ Varien_Data_Form::setElementRenderer($renderer);
+ }
+
+ $renderer = $this->getLayout()->createBlock('adminhtml/widget_form_renderer_fieldset');
+ if ($renderer instanceof Varien_Data_Form_Element_Renderer_Interface) {
+ Varien_Data_Form::setFieldsetRenderer($renderer);
+ }
+
+ $renderer = $this->getLayout()->createBlock('adminhtml/widget_form_renderer_fieldset_element');
+ if ($renderer instanceof Varien_Data_Form_Element_Renderer_Interface) {
+ Varien_Data_Form::setFieldsetElementRenderer($renderer);
+ }
+
+ return parent::_prepareLayout();
+ }
+
/**
* Prepare form before rendering HTML
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php
index 4c4bcc1f1e1..a0c81d88d7b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php
@@ -64,22 +64,6 @@ public function __construct()
], 1);
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- if ($this->_blockGroup && $this->_controller && $this->_mode) {
- $this->setChild('form', $this->getLayout()->createBlock($this->_blockGroup
- . '/'
- . $this->_controller
- . '_'
- . $this->_mode
- . '_form'));
- }
- return parent::_prepareLayout();
- }
-
/**
* Get URL for back (reset) button
*
@@ -193,4 +177,20 @@ public function setDataObject($object)
$this->getChild('form')->setDataObject($object);
return $this->setData('data_object', $object);
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ if ($this->_blockGroup && $this->_controller && $this->_mode) {
+ $this->setChild('form', $this->getLayout()->createBlock($this->_blockGroup
+ . '/'
+ . $this->_controller
+ . '_'
+ . $this->_mode
+ . '_form'));
+ }
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Element/Gallery.php b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Element/Gallery.php
index 67a6cff6c9c..770b18b358c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Element/Gallery.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Element/Gallery.php
@@ -51,6 +51,16 @@ public function getValues()
return $this->getElement()->getValue();
}
+ public function getAddButtonHtml()
+ {
+ return $this->getChildHtml('add_button');
+ }
+
+ public function getDeleteButtonHtml($image)
+ {
+ return str_replace('#image#', $image, $this->getChildHtml('delete_button'));
+ }
+
protected function _prepareLayout()
{
$this->setChild(
@@ -74,14 +84,4 @@ protected function _prepareLayout()
);
return parent::_prepareLayout();
}
-
- public function getAddButtonHtml()
- {
- return $this->getChildHtml('add_button');
- }
-
- public function getDeleteButtonHtml($image)
- {
- return str_replace('#image#', $image, $this->getChildHtml('delete_button'));
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Element.php b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Element.php
index 74faa985055..ceeaecc8939 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Element.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Element.php
@@ -24,11 +24,6 @@ class Mage_Adminhtml_Block_Widget_Form_Renderer_Element extends Mage_Adminhtml_B
{
protected $_element;
- protected function _construct()
- {
- $this->setTemplate('widget/form/renderer/element.phtml');
- }
-
public function getElement()
{
return $this->_element;
@@ -39,4 +34,9 @@ public function render(Varien_Data_Form_Element_Abstract $element)
$this->_element = $element;
return $this->toHtml();
}
+
+ protected function _construct()
+ {
+ $this->setTemplate('widget/form/renderer/element.phtml');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Fieldset.php b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Fieldset.php
index 64c280935ff..b90b91dd48c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Fieldset.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Fieldset.php
@@ -24,11 +24,6 @@ class Mage_Adminhtml_Block_Widget_Form_Renderer_Fieldset extends Mage_Adminhtml_
{
protected $_element;
- protected function _construct()
- {
- $this->setTemplate('widget/form/renderer/fieldset.phtml');
- }
-
public function getElement()
{
return $this->_element;
@@ -39,4 +34,9 @@ public function render(Varien_Data_Form_Element_Abstract $element)
$this->_element = $element;
return $this->toHtml();
}
+
+ protected function _construct()
+ {
+ $this->setTemplate('widget/form/renderer/fieldset.phtml');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Fieldset/Element.php b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Fieldset/Element.php
index 17538a325c0..bff33a9dc35 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Fieldset/Element.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Renderer/Fieldset/Element.php
@@ -24,11 +24,6 @@ class Mage_Adminhtml_Block_Widget_Form_Renderer_Fieldset_Element extends Mage_Ad
{
protected $_element;
- protected function _construct()
- {
- $this->setTemplate('widget/form/renderer/fieldset/element.phtml');
- }
-
public function getElement()
{
return $this->_element;
@@ -39,4 +34,9 @@ public function render(Varien_Data_Form_Element_Abstract $element)
$this->_element = $element;
return $this->toHtml();
}
+
+ protected function _construct()
+ {
+ $this->setTemplate('widget/form/renderer/fieldset/element.phtml');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php
index ccdafd1d1d1..9c2e143d525 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php
@@ -226,40 +226,6 @@ public function __construct($attributes = [])
$this->_emptyText = Mage::helper('adminhtml')->__('No records found.');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'export_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('adminhtml')->__('Export'),
- 'onclick' => $this->getJsObjectName() . '.doExport()',
- 'class' => 'task',
- ]),
- );
- $this->setChild(
- 'reset_filter_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('adminhtml')->__('Reset Filter'),
- 'onclick' => $this->getJsObjectName() . '.resetFilter()',
- ]),
- );
- $this->setChild(
- 'search_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('adminhtml')->__('Search'),
- 'onclick' => $this->getJsObjectName() . '.doFilter()',
- 'class' => 'task',
- ]),
- );
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -523,376 +489,116 @@ public function getColumns()
}
/**
- * @param array $data
- *
- * @return $this
+ * @return string
*/
- protected function _setFilterValues($data)
+ public function getVarNameLimit()
{
- foreach (array_keys($data) as $columnId) {
- $column = $this->getColumn($columnId);
- if ($column instanceof Mage_Adminhtml_Block_Widget_Grid_Column
- && (!empty($data[$columnId]) || strlen($data[$columnId]) > 0)
- && $column->getFilter()
- ) {
- $column->getFilter()->setValue($data[$columnId]);
- $this->_addColumnFilterToCollection($column);
- }
- }
-
- return $this;
+ return $this->_varNameLimit;
}
/**
- * Add filter
- *
- * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
- * @return $this
+ * @return string
*/
- protected function _addColumnFilterToCollection($column)
+ public function getVarNamePage()
{
- if ($this->getCollection()) {
- $field = $column->getFilterIndex() ?: $column->getIndex();
- if ($column->getFilterConditionCallback() && $column->getFilterConditionCallback()[0] instanceof self) {
- call_user_func($column->getFilterConditionCallback(), $this->getCollection(), $column);
- } else {
- $cond = $column->getFilter()->getCondition();
- if ($field && $cond !== null) {
- $filtered = array_map(static function ($value) {
- return is_object($value) ? $value->__toString() : $value;
- }, is_array($cond) ? array_values($cond) : [$cond]);
- if (in_array('\'%NULL%\'', $filtered, true) || in_array('NULL', $filtered, true)) {
- $this->getCollection()->addFieldToFilter($field, ['null' => true]);
- } else {
- $this->getCollection()->addFieldToFilter($field, $cond);
- }
- }
- }
- }
- return $this;
+ return $this->_varNamePage;
}
/**
- * Add link model filter from grid column to collection
- *
- * @param Mage_Catalog_Model_Resource_Product_Link_Product_Collection $collection
- * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
- *
- * @return $this
+ * @return string
*/
- protected function _addLinkModelFilterCallback($collection, $column)
+ public function getVarNameSort()
{
- $field = $column->getFilterIndex() ?: $column->getIndex();
- $condition = $column->getFilter()->getCondition();
- $collection->addLinkModelFieldToFilter($field, $condition);
-
- return $this;
+ return $this->_varNameSort;
}
/**
- * Sets sorting order by some column
- *
- * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
- * @return $this
+ * @return string
*/
- protected function _setCollectionOrder($column)
+ public function getVarNameDir()
{
- $collection = $this->getCollection();
- if ($collection) {
- $columnIndex = $column->getFilterIndex() ?: $column->getIndex();
- $collection->setOrder($columnIndex, strtoupper($column->getDir()));
- }
- return $this;
+ return $this->_varNameDir;
}
/**
- * Prepare grid collection object
- *
- * @return $this
- * @throws Exception
+ * @return string
*/
- protected function _prepareCollection()
+ public function getVarNameFilter()
{
- if ($this->getCollection()) {
- $this->_preparePage();
-
- $columnId = $this->getParam($this->getVarNameSort(), $this->_defaultSort);
- $dir = $this->getParam($this->getVarNameDir(), $this->_defaultDir);
- $filter = $this->getParam($this->getVarNameFilter(), null);
-
- if (is_null($filter)) {
- $filter = $this->_defaultFilter;
- }
-
- if (is_string($filter)) {
- /** @var Mage_Adminhtml_Helper_Data $helper */
- $helper = $this->helper('adminhtml');
- $data = $helper->prepareFilterString($filter);
- $this->_setFilterValues($data);
- } elseif ($filter && is_array($filter)) {
- $this->_setFilterValues($filter);
- } elseif (count($this->_defaultFilter)) {
- $this->_setFilterValues($this->_defaultFilter);
- }
-
- if (isset($this->_columns[$columnId]) && $this->_columns[$columnId]->getIndex()) {
- $dir = (strtolower($dir) === 'desc') ? 'desc' : 'asc';
- $this->_columns[$columnId]->setDir($dir);
- $this->_setCollectionOrder($this->_columns[$columnId]);
- }
-
- if (!$this->_isExport) {
- $this->_beforeLoadCollection();
- $this->getCollection()->load();
- $this->_afterLoadCollection();
- }
- }
-
- return $this;
+ return $this->_varNameFilter;
}
/**
- * Decode URL encoded filter value recursive callback method
- *
- * @param string $value
+ * @param string $name
+ * @return string
*/
- protected function _decodeFilter(&$value)
+ public function setVarNameLimit($name)
{
- /** @var Mage_Adminhtml_Helper_Data $helper */
- $helper = $this->helper('adminhtml');
- $value = $helper->decodeFilter($value);
+ return $this->_varNameLimit = $name;
}
- protected function _preparePage()
+ /**
+ * @param string $name
+ * @return string
+ */
+ public function setVarNamePage($name)
{
- $this->getCollection()->setPageSize((int) $this->getParam($this->getVarNameLimit(), $this->_defaultLimit));
- $this->getCollection()->setCurPage((int) $this->getParam($this->getVarNamePage(), $this->_defaultPage));
+ return $this->_varNamePage = $name;
}
/**
- * Prepare columns for grid
- *
- * @return $this
+ * @param string $name
+ * @return string
*/
- protected function _prepareColumns()
+ public function setVarNameSort($name)
{
- $this->sortColumnsByOrder();
- return $this;
+ return $this->_varNameSort = $name;
}
/**
- * Prepare grid massaction block
- *
- * @return $this
+ * @param string $name
+ * @return string
*/
- protected function _prepareMassactionBlock()
+ public function setVarNameDir($name)
{
- $this->setChild('massaction', $this->getLayout()->createBlock($this->getMassactionBlockName()));
- $this->_prepareMassaction();
- if ($this->getMassactionBlock()->isAvailable()) {
- $this->_prepareMassactionColumn();
- }
- return $this;
+ return $this->_varNameDir = $name;
}
/**
- * Prepare grid massaction actions
- *
- * @return $this
+ * @param string $name
+ * @return string
*/
- protected function _prepareMassaction()
+ public function setVarNameFilter($name)
{
- return $this;
+ return $this->_varNameFilter = $name;
}
/**
- * Prepare grid massaction column
+ * Set visibility of column headers
*
- * @return $this
+ * @param bool $visible
*/
- protected function _prepareMassactionColumn()
+ public function setHeadersVisibility($visible = true)
{
- $columnId = 'massaction';
- $massactionColumn = $this->getLayout()->createBlock('adminhtml/widget_grid_column')
- ->setData([
- 'index' => $this->getMassactionIdField(),
- 'filter_index' => $this->getMassactionIdFilter(),
- 'type' => 'massaction',
- 'name' => $this->getMassactionBlock()->getFormFieldName(),
- 'align' => 'center',
- 'is_system' => true,
- ]);
-
- if ($this->getNoFilterMassactionColumn()) {
- $massactionColumn->setData('filter', false);
- }
-
- $massactionColumn->setSelected($this->getMassactionBlock()->getSelected())
- ->setGrid($this)
- ->setId($columnId);
-
- $oldColumns = $this->_columns;
- $this->_columns = [];
- $this->_columns[$columnId] = $massactionColumn;
- $this->_columns = array_merge($this->_columns, $oldColumns);
- return $this;
+ $this->_headersVisibility = $visible;
}
/**
- * @return $this
- * @throws Exception
+ * Return visibility of column headers
+ *
+ * @return bool
*/
- protected function _prepareGrid()
+ public function getHeadersVisibility()
{
- $this->_prepareColumns();
- $this->_prepareMassactionBlock();
- $this->_prepareCollection();
- return $this;
+ return $this->_headersVisibility;
}
/**
- * @inheritDoc
- * @throws Exception
+ * Set visibility of pager
+ *
+ * @param bool $visible
*/
- protected function _beforeToHtml()
- {
- try {
- $this->_prepareGrid();
- } catch (Exception $e) {
- $this->resetSavedParametersInSession();
- throw $e;
- }
-
- return parent::_beforeToHtml();
- }
-
- /**
- * @return $this
- */
- protected function _afterLoadCollection()
- {
- return $this;
- }
-
- /**
- * @return $this
- */
- protected function _beforeLoadCollection()
- {
- return $this;
- }
-
- /**
- * @return string
- */
- public function getVarNameLimit()
- {
- return $this->_varNameLimit;
- }
-
- /**
- * @return string
- */
- public function getVarNamePage()
- {
- return $this->_varNamePage;
- }
-
- /**
- * @return string
- */
- public function getVarNameSort()
- {
- return $this->_varNameSort;
- }
-
- /**
- * @return string
- */
- public function getVarNameDir()
- {
- return $this->_varNameDir;
- }
-
- /**
- * @return string
- */
- public function getVarNameFilter()
- {
- return $this->_varNameFilter;
- }
-
- /**
- * @param string $name
- * @return string
- */
- public function setVarNameLimit($name)
- {
- return $this->_varNameLimit = $name;
- }
-
- /**
- * @param string $name
- * @return string
- */
- public function setVarNamePage($name)
- {
- return $this->_varNamePage = $name;
- }
-
- /**
- * @param string $name
- * @return string
- */
- public function setVarNameSort($name)
- {
- return $this->_varNameSort = $name;
- }
-
- /**
- * @param string $name
- * @return string
- */
- public function setVarNameDir($name)
- {
- return $this->_varNameDir = $name;
- }
-
- /**
- * @param string $name
- * @return string
- */
- public function setVarNameFilter($name)
- {
- return $this->_varNameFilter = $name;
- }
-
- /**
- * Set visibility of column headers
- *
- * @param bool $visible
- */
- public function setHeadersVisibility($visible = true)
- {
- $this->_headersVisibility = $visible;
- }
-
- /**
- * Return visibility of column headers
- *
- * @return bool
- */
- public function getHeadersVisibility()
- {
- return $this->_headersVisibility;
- }
-
- /**
- * Set visibility of pager
- *
- * @param bool $visible
- */
- public function setPagerVisibility($visible = true)
+ public function setPagerVisibility($visible = true)
{
$this->_pagerVisibility = $visible;
}
@@ -1035,24 +741,6 @@ public function getRssLists()
return empty($this->_rssLists) ? false : $this->_rssLists;
}
- /**
- * Returns url for RSS
- * Can be overloaded in descendant classes to perform custom changes to url passed to addRssList()
- *
- * @param string $url
- * @return string
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _getRssUrl($url)
- {
- $urlModel = Mage::getModel('core/url');
- if (Mage::app()->getStore()->getStoreInUrl()) {
- // Url in 'admin' store view won't be accessible, so form it in default store view frontend
- $urlModel->setStore(Mage::app()->getDefaultStoreView());
- }
- return $urlModel->getUrl($url);
- }
-
/**
* Add new rss list to grid
*
@@ -1082,52 +770,6 @@ public function getHtml()
return $this->toHtml();
}
- /**
- * Retrieve file content from file container array
- *
- * @return string
- */
- protected function _getFileContainerContent(array $fileData)
- {
- $io = new Varien_Io_File();
- $path = $io->dirname($fileData['value']);
- $io->open(['path' => $path]);
- return $io->read($fileData['value']);
- }
-
- /**
- * Retrieve Headers row array for Export
- *
- * @return array
- */
- protected function _getExportHeaders()
- {
- $row = [];
- foreach ($this->_columns as $column) {
- if (!$column->getIsSystem()) {
- $row[] = $column->getExportHeader();
- }
- }
- return $row;
- }
-
- /**
- * Retrieve Totals row array for Export
- *
- * @return array
- */
- protected function _getExportTotals()
- {
- $totals = $this->getTotals();
- $row = [];
- foreach ($this->_columns as $column) {
- if (!$column->getIsSystem()) {
- $row[] = ($column->hasTotalsLabel()) ? $column->getTotalsLabel() : $column->getRowFieldExport($totals);
- }
- }
- return $row;
- }
-
/**
* Iterate collection and call callback method per item
* For callback method first argument always is item object
@@ -1166,23 +808,6 @@ public function _exportIterateCollection($callback, array $args)
}
}
- /**
- * Write item data to csv export file
- */
- protected function _exportCsvItem(Varien_Object $item, Varien_Io_File $adapter)
- {
- $row = [];
- foreach ($this->_columns as $column) {
- if (!$column->getIsSystem()) {
- $row[] = $column->getRowFieldExport($item);
- }
- }
-
- $adapter->streamWriteCsv(
- Mage::helper('core')->getEscapedCSVData($row),
- );
- }
-
/**
* Retrieve a file container array by grid data as CSV
*
@@ -1312,27 +937,6 @@ public function getXml()
return $xml . '';
}
- /**
- * Write item data to Excel 2003 XML export file
- *
- * @param Varien_Convert_Parser_Xml_Excel $parser
- */
- protected function _exportExcelItem(Varien_Object $item, Varien_Io_File $adapter, $parser = null)
- {
- if (is_null($parser)) {
- $parser = new Varien_Convert_Parser_Xml_Excel();
- }
-
- $row = [];
- foreach ($this->_columns as $column) {
- if (!$column->getIsSystem()) {
- $row[] = $column->getRowFieldExport($item);
- }
- }
- $data = $parser->getRowXml($row);
- $adapter->streamWrite($data);
- }
-
/**
* Retrieve a file container array by grid data as MS Excel 2003 XML Document
*
@@ -1925,4 +1529,400 @@ public function getLimitOptions(): array
{
return [20, 30, 50, 100, 200, 500, 1000];
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'export_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('adminhtml')->__('Export'),
+ 'onclick' => $this->getJsObjectName() . '.doExport()',
+ 'class' => 'task',
+ ]),
+ );
+ $this->setChild(
+ 'reset_filter_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('adminhtml')->__('Reset Filter'),
+ 'onclick' => $this->getJsObjectName() . '.resetFilter()',
+ ]),
+ );
+ $this->setChild(
+ 'search_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('adminhtml')->__('Search'),
+ 'onclick' => $this->getJsObjectName() . '.doFilter()',
+ 'class' => 'task',
+ ]),
+ );
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * @param array $data
+ *
+ * @return $this
+ */
+ protected function _setFilterValues($data)
+ {
+ foreach (array_keys($data) as $columnId) {
+ $column = $this->getColumn($columnId);
+ if ($column instanceof Mage_Adminhtml_Block_Widget_Grid_Column
+ && (!empty($data[$columnId]) || strlen($data[$columnId]) > 0)
+ && $column->getFilter()
+ ) {
+ $column->getFilter()->setValue($data[$columnId]);
+ $this->_addColumnFilterToCollection($column);
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Add filter
+ *
+ * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
+ * @return $this
+ */
+ protected function _addColumnFilterToCollection($column)
+ {
+ if ($this->getCollection()) {
+ $field = $column->getFilterIndex() ?: $column->getIndex();
+ if ($column->getFilterConditionCallback() && $column->getFilterConditionCallback()[0] instanceof self) {
+ call_user_func($column->getFilterConditionCallback(), $this->getCollection(), $column);
+ } else {
+ $cond = $column->getFilter()->getCondition();
+ if ($field && $cond !== null) {
+ $filtered = array_map(static function ($value) {
+ return is_object($value) ? $value->__toString() : $value;
+ }, is_array($cond) ? array_values($cond) : [$cond]);
+ if (in_array('\'%NULL%\'', $filtered, true) || in_array('NULL', $filtered, true)) {
+ $this->getCollection()->addFieldToFilter($field, ['null' => true]);
+ } else {
+ $this->getCollection()->addFieldToFilter($field, $cond);
+ }
+ }
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Add link model filter from grid column to collection
+ *
+ * @param Mage_Catalog_Model_Resource_Product_Link_Product_Collection $collection
+ * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
+ *
+ * @return $this
+ */
+ protected function _addLinkModelFilterCallback($collection, $column)
+ {
+ $field = $column->getFilterIndex() ?: $column->getIndex();
+ $condition = $column->getFilter()->getCondition();
+ $collection->addLinkModelFieldToFilter($field, $condition);
+
+ return $this;
+ }
+
+ /**
+ * Sets sorting order by some column
+ *
+ * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
+ * @return $this
+ */
+ protected function _setCollectionOrder($column)
+ {
+ $collection = $this->getCollection();
+ if ($collection) {
+ $columnIndex = $column->getFilterIndex() ?: $column->getIndex();
+ $collection->setOrder($columnIndex, strtoupper($column->getDir()));
+ }
+ return $this;
+ }
+
+ /**
+ * Prepare grid collection object
+ *
+ * @return $this
+ * @throws Exception
+ */
+ protected function _prepareCollection()
+ {
+ if ($this->getCollection()) {
+ $this->_preparePage();
+
+ $columnId = $this->getParam($this->getVarNameSort(), $this->_defaultSort);
+ $dir = $this->getParam($this->getVarNameDir(), $this->_defaultDir);
+ $filter = $this->getParam($this->getVarNameFilter(), null);
+
+ if (is_null($filter)) {
+ $filter = $this->_defaultFilter;
+ }
+
+ if (is_string($filter)) {
+ /** @var Mage_Adminhtml_Helper_Data $helper */
+ $helper = $this->helper('adminhtml');
+ $data = $helper->prepareFilterString($filter);
+ $this->_setFilterValues($data);
+ } elseif ($filter && is_array($filter)) {
+ $this->_setFilterValues($filter);
+ } elseif (count($this->_defaultFilter)) {
+ $this->_setFilterValues($this->_defaultFilter);
+ }
+
+ if (isset($this->_columns[$columnId]) && $this->_columns[$columnId]->getIndex()) {
+ $dir = (strtolower($dir) === 'desc') ? 'desc' : 'asc';
+ $this->_columns[$columnId]->setDir($dir);
+ $this->_setCollectionOrder($this->_columns[$columnId]);
+ }
+
+ if (!$this->_isExport) {
+ $this->_beforeLoadCollection();
+ $this->getCollection()->load();
+ $this->_afterLoadCollection();
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Decode URL encoded filter value recursive callback method
+ *
+ * @param string $value
+ */
+ protected function _decodeFilter(&$value)
+ {
+ /** @var Mage_Adminhtml_Helper_Data $helper */
+ $helper = $this->helper('adminhtml');
+ $value = $helper->decodeFilter($value);
+ }
+
+ protected function _preparePage()
+ {
+ $this->getCollection()->setPageSize((int) $this->getParam($this->getVarNameLimit(), $this->_defaultLimit));
+ $this->getCollection()->setCurPage((int) $this->getParam($this->getVarNamePage(), $this->_defaultPage));
+ }
+
+ /**
+ * Prepare columns for grid
+ *
+ * @return $this
+ */
+ protected function _prepareColumns()
+ {
+ $this->sortColumnsByOrder();
+ return $this;
+ }
+
+ /**
+ * Prepare grid massaction block
+ *
+ * @return $this
+ */
+ protected function _prepareMassactionBlock()
+ {
+ $this->setChild('massaction', $this->getLayout()->createBlock($this->getMassactionBlockName()));
+ $this->_prepareMassaction();
+ if ($this->getMassactionBlock()->isAvailable()) {
+ $this->_prepareMassactionColumn();
+ }
+ return $this;
+ }
+
+ /**
+ * Prepare grid massaction actions
+ *
+ * @return $this
+ */
+ protected function _prepareMassaction()
+ {
+ return $this;
+ }
+
+ /**
+ * Prepare grid massaction column
+ *
+ * @return $this
+ */
+ protected function _prepareMassactionColumn()
+ {
+ $columnId = 'massaction';
+ $massactionColumn = $this->getLayout()->createBlock('adminhtml/widget_grid_column')
+ ->setData([
+ 'index' => $this->getMassactionIdField(),
+ 'filter_index' => $this->getMassactionIdFilter(),
+ 'type' => 'massaction',
+ 'name' => $this->getMassactionBlock()->getFormFieldName(),
+ 'align' => 'center',
+ 'is_system' => true,
+ ]);
+
+ if ($this->getNoFilterMassactionColumn()) {
+ $massactionColumn->setData('filter', false);
+ }
+
+ $massactionColumn->setSelected($this->getMassactionBlock()->getSelected())
+ ->setGrid($this)
+ ->setId($columnId);
+
+ $oldColumns = $this->_columns;
+ $this->_columns = [];
+ $this->_columns[$columnId] = $massactionColumn;
+ $this->_columns = array_merge($this->_columns, $oldColumns);
+ return $this;
+ }
+
+ /**
+ * @return $this
+ * @throws Exception
+ */
+ protected function _prepareGrid()
+ {
+ $this->_prepareColumns();
+ $this->_prepareMassactionBlock();
+ $this->_prepareCollection();
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ * @throws Exception
+ */
+ protected function _beforeToHtml()
+ {
+ try {
+ $this->_prepareGrid();
+ } catch (Exception $e) {
+ $this->resetSavedParametersInSession();
+ throw $e;
+ }
+
+ return parent::_beforeToHtml();
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _afterLoadCollection()
+ {
+ return $this;
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _beforeLoadCollection()
+ {
+ return $this;
+ }
+
+ /**
+ * Returns url for RSS
+ * Can be overloaded in descendant classes to perform custom changes to url passed to addRssList()
+ *
+ * @param string $url
+ * @return string
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _getRssUrl($url)
+ {
+ $urlModel = Mage::getModel('core/url');
+ if (Mage::app()->getStore()->getStoreInUrl()) {
+ // Url in 'admin' store view won't be accessible, so form it in default store view frontend
+ $urlModel->setStore(Mage::app()->getDefaultStoreView());
+ }
+ return $urlModel->getUrl($url);
+ }
+
+ /**
+ * Retrieve file content from file container array
+ *
+ * @return string
+ */
+ protected function _getFileContainerContent(array $fileData)
+ {
+ $io = new Varien_Io_File();
+ $path = $io->dirname($fileData['value']);
+ $io->open(['path' => $path]);
+ return $io->read($fileData['value']);
+ }
+
+ /**
+ * Retrieve Headers row array for Export
+ *
+ * @return array
+ */
+ protected function _getExportHeaders()
+ {
+ $row = [];
+ foreach ($this->_columns as $column) {
+ if (!$column->getIsSystem()) {
+ $row[] = $column->getExportHeader();
+ }
+ }
+ return $row;
+ }
+
+ /**
+ * Retrieve Totals row array for Export
+ *
+ * @return array
+ */
+ protected function _getExportTotals()
+ {
+ $totals = $this->getTotals();
+ $row = [];
+ foreach ($this->_columns as $column) {
+ if (!$column->getIsSystem()) {
+ $row[] = ($column->hasTotalsLabel()) ? $column->getTotalsLabel() : $column->getRowFieldExport($totals);
+ }
+ }
+ return $row;
+ }
+
+ /**
+ * Write item data to csv export file
+ */
+ protected function _exportCsvItem(Varien_Object $item, Varien_Io_File $adapter)
+ {
+ $row = [];
+ foreach ($this->_columns as $column) {
+ if (!$column->getIsSystem()) {
+ $row[] = $column->getRowFieldExport($item);
+ }
+ }
+
+ $adapter->streamWriteCsv(
+ Mage::helper('core')->getEscapedCSVData($row),
+ );
+ }
+
+ /**
+ * Write item data to Excel 2003 XML export file
+ *
+ * @param Varien_Convert_Parser_Xml_Excel $parser
+ */
+ protected function _exportExcelItem(Varien_Object $item, Varien_Io_File $adapter, $parser = null)
+ {
+ if (is_null($parser)) {
+ $parser = new Varien_Convert_Parser_Xml_Excel();
+ }
+
+ $row = [];
+ foreach ($this->_columns as $column) {
+ if (!$column->getIsSystem()) {
+ $row[] = $column->getRowFieldExport($item);
+ }
+ }
+ $data = $parser->getRowXml($row);
+ $adapter->streamWrite($data);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column.php
index 9e64aa1784c..96a64c0556a 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column.php
@@ -204,6 +204,97 @@ public function getRowFieldExport(Varien_Object $row)
return $renderedValue;
}
+ /**
+ * @param string $renderer
+ * @return $this
+ */
+ public function setRenderer($renderer)
+ {
+ $this->_renderer = $renderer;
+ return $this;
+ }
+
+ /**
+ * Retrieve column renderer
+ *
+ * @return Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
+ */
+ public function getRenderer()
+ {
+ if (!$this->_renderer) {
+ $rendererClass = $this->getData('renderer');
+ if (!$rendererClass) {
+ $rendererClass = $this->_getRendererByType();
+ }
+ $this->_renderer = $this->getLayout()->createBlock($rendererClass)
+ ->setColumn($this);
+ }
+ return $this->_renderer;
+ }
+
+ /**
+ * @param string $filterClass
+ * @return void
+ */
+ public function setFilter($filterClass)
+ {
+ $this->_filter = $this->getLayout()->createBlock($filterClass)
+ ->setColumn($this);
+ }
+
+ /**
+ * @return Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Abstract|false
+ */
+ public function getFilter()
+ {
+ if (!$this->_filter) {
+ $filterClass = $this->getData('filter');
+ if ($filterClass === false) {
+ return false;
+ }
+ if (!$filterClass) {
+ $filterClass = $this->_getFilterByType();
+ if ($filterClass === false) {
+ return false;
+ }
+ }
+ $this->_filter = $this->getLayout()->createBlock($filterClass)
+ ->setColumn($this);
+ }
+
+ return $this->_filter;
+ }
+
+ /**
+ * @return string
+ */
+ public function getFilterHtml()
+ {
+ if ($this->getFilter()) {
+ return $this->getFilter()->getHtml();
+ }
+
+ return ' ';
+ }
+
+ /**
+ * Retrieve Header Name for Export
+ *
+ * @return string
+ */
+ public function getExportHeader()
+ {
+ if ($this->getHeaderExport()) {
+ return $this->getHeaderExport();
+ }
+ return $this->getHeader();
+ }
+
+ public function getType(): string
+ {
+ return (string) $this->_getData('type');
+ }
+
/**
* Decorate rendered cell value
*
@@ -232,16 +323,6 @@ protected function &_applyDecorators($value, $decorators)
return $value;
}
- /**
- * @param string $renderer
- * @return $this
- */
- public function setRenderer($renderer)
- {
- $this->_renderer = $renderer;
- return $this;
- }
-
/**
* @return string
*/
@@ -316,34 +397,6 @@ protected function _getRendererByType()
return $rendererClass;
}
- /**
- * Retrieve column renderer
- *
- * @return Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
- */
- public function getRenderer()
- {
- if (!$this->_renderer) {
- $rendererClass = $this->getData('renderer');
- if (!$rendererClass) {
- $rendererClass = $this->_getRendererByType();
- }
- $this->_renderer = $this->getLayout()->createBlock($rendererClass)
- ->setColumn($this);
- }
- return $this->_renderer;
- }
-
- /**
- * @param string $filterClass
- * @return void
- */
- public function setFilter($filterClass)
- {
- $this->_filter = $this->getLayout()->createBlock($filterClass)
- ->setColumn($this);
- }
-
/**
* @return string
*/
@@ -397,57 +450,4 @@ protected function _getFilterByType()
}
return $filterClass;
}
-
- /**
- * @return Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Abstract|false
- */
- public function getFilter()
- {
- if (!$this->_filter) {
- $filterClass = $this->getData('filter');
- if ($filterClass === false) {
- return false;
- }
- if (!$filterClass) {
- $filterClass = $this->_getFilterByType();
- if ($filterClass === false) {
- return false;
- }
- }
- $this->_filter = $this->getLayout()->createBlock($filterClass)
- ->setColumn($this);
- }
-
- return $this->_filter;
- }
-
- /**
- * @return string
- */
- public function getFilterHtml()
- {
- if ($this->getFilter()) {
- return $this->getFilter()->getHtml();
- }
-
- return ' ';
- }
-
- /**
- * Retrieve Header Name for Export
- *
- * @return string
- */
- public function getExportHeader()
- {
- if ($this->getHeaderExport()) {
- return $this->getHeaderExport();
- }
- return $this->getHeader();
- }
-
- public function getType(): string
- {
- return (string) $this->_getData('type');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Abstract.php
index acfb4ec1764..182f4cfd35a 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Abstract.php
@@ -52,48 +52,58 @@ public function getColumn()
}
/**
- * Retrieve html name of filter
+ * Retrieve escaped value
*
+ * @param mixed $index
* @return string
*/
- protected function _getHtmlName()
+ public function getEscapedValue($index = null)
{
- return $this->getColumn()->getId();
+ return htmlspecialchars((string) $this->getValue($index));
}
/**
- * Retrieve html id of filter
+ * Retrieve condition
+ *
+ * @return array
+ */
+ public function getCondition()
+ {
+ $helper = Mage::getResourceHelper('core');
+ $likeExpression = $helper->addLikeEscape($this->getValue(), ['position' => 'any']);
+ return ['like' => $likeExpression];
+ }
+
+ /**
+ * Retrieve filter html
*
* @return string
*/
- protected function _getHtmlId()
+ public function getHtml()
{
- return $this->getColumn()->getGrid()->getId() . '_'
- . $this->getColumn()->getGrid()->getVarNameFilter() . '_'
- . $this->getColumn()->getId();
+ return '';
}
/**
- * Retrieve escaped value
+ * Retrieve html name of filter
*
- * @param mixed $index
* @return string
*/
- public function getEscapedValue($index = null)
+ protected function _getHtmlName()
{
- return htmlspecialchars((string) $this->getValue($index));
+ return $this->getColumn()->getId();
}
/**
- * Retrieve condition
+ * Retrieve html id of filter
*
- * @return array
+ * @return string
*/
- public function getCondition()
+ protected function _getHtmlId()
{
- $helper = Mage::getResourceHelper('core');
- $likeExpression = $helper->addLikeEscape($this->getValue(), ['position' => 'any']);
- return ['like' => $likeExpression];
+ return $this->getColumn()->getGrid()->getId() . '_'
+ . $this->getColumn()->getGrid()->getVarNameFilter() . '_'
+ . $this->getColumn()->getId();
}
/**
@@ -105,14 +115,4 @@ protected function _escapeValue($value)
{
return str_replace('_', '\_', str_replace('\\', '\\\\', $value));
}
-
- /**
- * Retrieve filter html
- *
- * @return string
- */
- public function getHtml()
- {
- return '';
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Checkbox.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Checkbox.php
index c44e6c65724..53b0348e282 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Checkbox.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Checkbox.php
@@ -30,6 +30,21 @@ public function getHtml()
return '' . parent::getHtml() . '';
}
+ /**
+ * @return array|null
+ */
+ public function getCondition()
+ {
+ if ($this->getValue()) {
+ return $this->getColumn()->getValue();
+ } else {
+ return [
+ ['neq' => $this->getColumn()->getValue()],
+ ['is' => new Zend_Db_Expr('NULL')],
+ ];
+ }
+ }
+
/**
* @return array[]
*/
@@ -50,19 +65,4 @@ protected function _getOptions()
],
];
}
-
- /**
- * @return array|null
- */
- public function getCondition()
- {
- if ($this->getValue()) {
- return $this->getColumn()->getValue();
- } else {
- return [
- ['neq' => $this->getColumn()->getValue()],
- ['is' => new Zend_Db_Expr('NULL')],
- ];
- }
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Date.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Date.php
index b72ae442923..deb46276078 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Date.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Date.php
@@ -25,17 +25,6 @@ class Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Date extends Mage_Adminhtml
{
protected $_locale;
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- if ($head = $this->getLayout()->getBlock('head')) {
- $head->setCanLoadCalendarJs(true);
- }
- return parent::_prepareLayout();
- }
-
/**
* @return string
* @throws Exception
@@ -171,6 +160,17 @@ public function getLocale()
return $this->_locale;
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ if ($head = $this->getLayout()->getBlock('head')) {
+ $head->setCanLoadCalendarJs(true);
+ }
+ return parent::_prepareLayout();
+ }
+
/**
* Convert given date to default (UTC) timezone
*
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Datetime.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Datetime.php
index 4878943f9e2..50588805226 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Datetime.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Datetime.php
@@ -51,43 +51,6 @@ public function getValue($index = null)
return $value;
}
- /**
- * Convert given date to default (UTC) timezone
- *
- * @param string $date
- * @param string $locale
- * @return Zend_Date|null
- */
- protected function _convertDate($date, $locale)
- {
- if ($this->getColumn()->getFilterTime()) {
- try {
- $dateObj = $this->getLocale()->date(null, null, $locale, false);
-
- //set default timezone for store (admin)
- $dateObj->setTimezone(
- Mage::app()->getStore()->getConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_TIMEZONE),
- );
-
- //set date with applying timezone of store
- $dateObj->set(
- $date,
- $this->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT),
- $locale,
- );
-
- //convert store date to default date in UTC timezone without DST
- $dateObj->setTimezone(Mage_Core_Model_Locale::DEFAULT_TIMEZONE);
-
- return $dateObj;
- } catch (Exception $e) {
- return null;
- }
- }
-
- return parent::_convertDate($date, $locale);
- }
-
/**
* Render filter html
*
@@ -165,4 +128,41 @@ public function getEscapedValue($index = null)
return $this->escapeHtml(parent::getEscapedValue($index));
}
+
+ /**
+ * Convert given date to default (UTC) timezone
+ *
+ * @param string $date
+ * @param string $locale
+ * @return Zend_Date|null
+ */
+ protected function _convertDate($date, $locale)
+ {
+ if ($this->getColumn()->getFilterTime()) {
+ try {
+ $dateObj = $this->getLocale()->date(null, null, $locale, false);
+
+ //set default timezone for store (admin)
+ $dateObj->setTimezone(
+ Mage::app()->getStore()->getConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_TIMEZONE),
+ );
+
+ //set date with applying timezone of store
+ $dateObj->set(
+ $date,
+ $this->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT),
+ $locale,
+ );
+
+ //convert store date to default date in UTC timezone without DST
+ $dateObj->setTimezone(Mage_Core_Model_Locale::DEFAULT_TIMEZONE);
+
+ return $dateObj;
+ } catch (Exception $e) {
+ return null;
+ }
+ }
+
+ return parent::_convertDate($date, $locale);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Price.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Price.php
index 477ffc0d669..a2177ddf8b6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Price.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Price.php
@@ -58,39 +58,6 @@ public function getCurrencyAffect()
}
}
- protected function _getCurrencyModel()
- {
- if (is_null($this->_currencyModel)) {
- $this->_currencyModel = Mage::getModel('directory/currency');
- }
-
- return $this->_currencyModel;
- }
-
- protected function _getCurrencySelectHtml()
- {
- $value = $this->getEscapedValue('currency');
- if (!$value) {
- $value = $this->getColumn()->getCurrencyCode();
- }
-
- $html = '';
- $html .= '';
- }
-
- protected function _getCurrencyList()
- {
- if (is_null($this->_currencyList)) {
- $this->_currencyList = $this->_getCurrencyModel()->getConfigAllowCurrencies();
- }
- return $this->_currencyList;
- }
-
public function getValue($index = null)
{
if ($index) {
@@ -126,11 +93,6 @@ public function getCondition()
return $value;
}
- protected function _getRate($from, $to)
- {
- return Mage::getModel('directory/currency')->load($from)->getAnyRate($to);
- }
-
public function prepareRates($displayCurrency)
{
$storeCurrency = $this->getColumn()->getCurrencyCode();
@@ -141,4 +103,42 @@ public function prepareRates($displayCurrency)
$this->getColumn()->setCurrencyCode($displayCurrency);
}
}
+
+ protected function _getCurrencyModel()
+ {
+ if (is_null($this->_currencyModel)) {
+ $this->_currencyModel = Mage::getModel('directory/currency');
+ }
+
+ return $this->_currencyModel;
+ }
+
+ protected function _getCurrencySelectHtml()
+ {
+ $value = $this->getEscapedValue('currency');
+ if (!$value) {
+ $value = $this->getColumn()->getCurrencyCode();
+ }
+
+ $html = '';
+ $html .= '';
+ }
+
+ protected function _getCurrencyList()
+ {
+ if (is_null($this->_currencyList)) {
+ $this->_currencyList = $this->_getCurrencyModel()->getConfigAllowCurrencies();
+ }
+ return $this->_currencyList;
+ }
+
+ protected function _getRate($from, $to)
+ {
+ return Mage::getModel('directory/currency')->load($from)->getAnyRate($to);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Radio.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Radio.php
index dddce0188b5..7659b318192 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Radio.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Radio.php
@@ -22,6 +22,17 @@
*/
class Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Radio extends Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Select
{
+ public function getCondition()
+ {
+ if ($this->getValue()) {
+ return $this->getColumn()->getValue();
+ } else {
+ return [
+ ['neq' => $this->getColumn()->getValue()],
+ ['is' => new Zend_Db_Expr('NULL')],
+ ];
+ }
+ }
protected function _getOptions()
{
return [
@@ -39,16 +50,4 @@ protected function _getOptions()
],
];
}
-
- public function getCondition()
- {
- if ($this->getValue()) {
- return $this->getColumn()->getValue();
- } else {
- return [
- ['neq' => $this->getColumn()->getValue()],
- ['is' => new Zend_Db_Expr('NULL')],
- ];
- }
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Select.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Select.php
index a01e05560f9..2d8ff1d15c5 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Select.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Select.php
@@ -22,6 +22,37 @@
*/
class Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Select extends Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Abstract
{
+ /**
+ * @return string
+ */
+ public function getHtml()
+ {
+ $html = '';
+ }
+
+ /**
+ * @return array|null
+ */
+ public function getCondition()
+ {
+ if (is_null($this->getValue())) {
+ return null;
+ }
+ return ['eq' => $this->getValue()];
+ }
/**
* @return array[]
*/
@@ -58,36 +89,4 @@ protected function _renderOption($option, $value)
$selected = (($option['value'] == $value && (!is_null($value))) ? ' selected="selected"' : '');
return '';
}
-
- /**
- * @return string
- */
- public function getHtml()
- {
- $html = '';
- }
-
- /**
- * @return array|null
- */
- public function getCondition()
- {
- if (is_null($this->getValue())) {
- return null;
- }
- return ['eq' => $this->getValue()];
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Theme.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Theme.php
index 710e1fe6bbc..e90d331ff6f 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Theme.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Theme.php
@@ -57,6 +57,23 @@ public function getOptions()
return $options;
}
+ /**
+ * Retrieve filter condition for collection
+ *
+ * @return mixed
+ */
+ public function getCondition()
+ {
+ if (is_null($this->getValue())) {
+ return null;
+ }
+ $value = $this->getValue();
+ if ($value == 'all') {
+ $value = '';
+ }
+ return ['eq' => $value];
+ }
+
/**
* Render SELECT options
*
@@ -88,21 +105,4 @@ protected function _drawOptions($options)
return $html;
}
-
- /**
- * Retrieve filter condition for collection
- *
- * @return mixed
- */
- public function getCondition()
- {
- if (is_null($this->getValue())) {
- return null;
- }
- $value = $this->getValue();
- if ($value == 'all') {
- $value = '';
- }
- return ['eq' => $value];
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Abstract.php
index 72baf154573..1e32aa9b1c5 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Abstract.php
@@ -70,25 +70,6 @@ public function renderExport(Varien_Object $row)
return $this->render($row);
}
- /**
- * @return string|null
- */
- protected function _getValue(Varien_Object $row)
- {
- if ($getter = $this->getColumn()->getGetter()) {
- if (is_string($getter)) {
- return $row->$getter();
- } elseif (is_callable($getter)) {
- return call_user_func($getter, $row);
- }
- return '';
- }
- if ($index = $this->getColumn()->getIndex()) {
- return $row->getData($index);
- }
- return null;
- }
-
/**
* @return string
*/
@@ -100,14 +81,6 @@ public function _getInputValueElement(Varien_Object $row)
. '" value="' . $this->_getInputValue($row) . '"/>';
}
- /**
- * @return string|null
- */
- protected function _getInputValue(Varien_Object $row)
- {
- return $this->_getValue($row);
- }
-
/**
* @return string
*/
@@ -167,4 +140,31 @@ public function getCopyableText(Varien_Object $row)
{
return $this->_getValue($row);
}
+
+ /**
+ * @return string|null
+ */
+ protected function _getValue(Varien_Object $row)
+ {
+ if ($getter = $this->getColumn()->getGetter()) {
+ if (is_string($getter)) {
+ return $row->$getter();
+ } elseif (is_callable($getter)) {
+ return call_user_func($getter, $row);
+ }
+ return '';
+ }
+ if ($index = $this->getColumn()->getIndex()) {
+ return $row->getData($index);
+ }
+ return null;
+ }
+
+ /**
+ * @return string|null
+ */
+ protected function _getInputValue(Varien_Object $row)
+ {
+ return $this->_getValue($row);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Checkbox.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Checkbox.php
index f897745506f..c6bf39adabb 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Checkbox.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Checkbox.php
@@ -70,20 +70,6 @@ public function render(Varien_Object $row)
return $this->_getCheckboxHtml($v, $checked);
}
- /**
- * @param string $value Value of the element
- * @param bool $checked Whether it is checked
- * @return string
- */
- protected function _getCheckboxHtml($value, $checked)
- {
- $html = 'getColumn()->getFieldName() . '" ';
- $html .= 'value="' . $this->escapeHtml($value) . '" ';
- $html .= 'class="' . ($this->getColumn()->getInlineCss() ? $this->getColumn()->getInlineCss() : 'checkbox') . '"';
- return $html . ($checked . $this->getDisabled() . '/>');
- }
-
/**
* Renders header of the column
*
@@ -110,4 +96,18 @@ public function renderHeader()
$html .= 'class="checkbox"' . $checked . $disabled . ' ';
return $html . ('title="' . Mage::helper('adminhtml')->__('Select All') . '"/>');
}
+
+ /**
+ * @param string $value Value of the element
+ * @param bool $checked Whether it is checked
+ * @return string
+ */
+ protected function _getCheckboxHtml($value, $checked)
+ {
+ $html = 'getColumn()->getFieldName() . '" ';
+ $html .= 'value="' . $this->escapeHtml($value) . '" ';
+ $html .= 'class="' . ($this->getColumn()->getInlineCss() ? $this->getColumn()->getInlineCss() : 'checkbox') . '"';
+ return $html . ($checked . $this->getDisabled() . '/>');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Date.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Date.php
index b4734546385..73429ce762c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Date.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Date.php
@@ -28,29 +28,6 @@ class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Date extends Mage_Adminht
*/
protected static $_format = null;
- /**
- * Retrieve date format
- *
- * @return string
- */
- protected function _getFormat()
- {
- $format = $this->getColumn()->getFormat();
- if (!$format) {
- if (is_null(self::$_format)) {
- try {
- self::$_format = Mage::app()->getLocale()->getDateFormat(
- Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM,
- );
- } catch (Exception $e) {
- Mage::logException($e);
- }
- }
- $format = self::$_format;
- }
- return $format;
- }
-
/**
* Renders grid column
*
@@ -80,4 +57,27 @@ public function render(Varien_Object $row)
}
return $this->getColumn()->getDefault();
}
+
+ /**
+ * Retrieve date format
+ *
+ * @return string
+ */
+ protected function _getFormat()
+ {
+ $format = $this->getColumn()->getFormat();
+ if (!$format) {
+ if (is_null(self::$_format)) {
+ try {
+ self::$_format = Mage::app()->getLocale()->getDateFormat(
+ Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM,
+ );
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+ }
+ $format = self::$_format;
+ }
+ return $format;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Datetime.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Datetime.php
index 950a18c3a27..8739358e5ee 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Datetime.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Datetime.php
@@ -27,29 +27,6 @@ class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Datetime extends Mage_Adm
*/
protected static $_format = null;
- /**
- * Retrieve datetime format
- *
- * @return string
- */
- protected function _getFormat()
- {
- $format = $this->getColumn()->getFormat();
- if (!$format) {
- if (is_null(self::$_format)) {
- try {
- self::$_format = Mage::app()->getLocale()->getDateTimeFormat(
- Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM,
- );
- } catch (Exception $e) {
- Mage::logException($e);
- }
- }
- $format = self::$_format;
- }
- return $format;
- }
-
/**
* Renders grid column
*
@@ -73,4 +50,27 @@ public function render(Varien_Object $row)
}
return $this->getColumn()->getDefault();
}
+
+ /**
+ * Retrieve datetime format
+ *
+ * @return string
+ */
+ protected function _getFormat()
+ {
+ $format = $this->getColumn()->getFormat();
+ if (!$format) {
+ if (is_null(self::$_format)) {
+ try {
+ self::$_format = Mage::app()->getLocale()->getDateTimeFormat(
+ Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM,
+ );
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+ }
+ $format = self::$_format;
+ }
+ return $format;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Store.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Store.php
index 2f1ddf27e07..72b34dda876 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Store.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Store.php
@@ -25,40 +25,6 @@ class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Store extends Mage_Adminh
protected $_skipAllStoresLabel = false;
protected $_skipEmptyStoresLabel = false;
- /**
- * Retrieve System Store model
- *
- * @return Mage_Adminhtml_Model_System_Store
- */
- protected function _getStoreModel()
- {
- return Mage::getSingleton('adminhtml/system_store');
- }
-
- /**
- * Retrieve 'show all stores label' flag
- *
- * @return bool
- */
- protected function _getShowAllStoresLabelFlag()
- {
- return $this->getColumn()->getData('skipAllStoresLabel')
- ? $this->getColumn()->getData('skipAllStoresLabel')
- : $this->_skipAllStoresLabel;
- }
-
- /**
- * Retrieve 'show empty stores label' flag
- *
- * @return bool
- */
- protected function _getShowEmptyStoresLabelFlag()
- {
- return $this->getColumn()->getData('skipEmptyStoresLabel')
- ? $this->getColumn()->getData('skipEmptyStoresLabel')
- : $this->_skipEmptyStoresLabel;
- }
-
/**
* Render row store views
*
@@ -148,4 +114,38 @@ public function renderExport(Varien_Object $row)
return $out;
}
+
+ /**
+ * Retrieve System Store model
+ *
+ * @return Mage_Adminhtml_Model_System_Store
+ */
+ protected function _getStoreModel()
+ {
+ return Mage::getSingleton('adminhtml/system_store');
+ }
+
+ /**
+ * Retrieve 'show all stores label' flag
+ *
+ * @return bool
+ */
+ protected function _getShowAllStoresLabelFlag()
+ {
+ return $this->getColumn()->getData('skipAllStoresLabel')
+ ? $this->getColumn()->getData('skipAllStoresLabel')
+ : $this->_skipAllStoresLabel;
+ }
+
+ /**
+ * Retrieve 'show empty stores label' flag
+ *
+ * @return bool
+ */
+ protected function _getShowEmptyStoresLabelFlag()
+ {
+ return $this->getColumn()->getData('skipEmptyStoresLabel')
+ ? $this->getColumn()->getData('skipEmptyStoresLabel')
+ : $this->_skipEmptyStoresLabel;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Container.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Container.php
index 126e373065a..443fbba6943 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Container.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Container.php
@@ -55,21 +55,6 @@ public function __construct()
]);
}
- /**
- * @inheritdoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'grid',
- $this->getLayout()->createBlock(
- $this->_blockGroup . '/' . $this->_controller . '_grid',
- $this->_controller . '.grid',
- )->setSaveParametersInSession(true),
- );
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -89,41 +74,56 @@ public function getGridHtml()
/**
* @return string
*/
- protected function getAddButtonLabel()
+ public function getHeaderCssClass()
{
- return $this->_addButtonLabel;
+ return 'icon-head ' . parent::getHeaderCssClass();
}
/**
* @return string
*/
- protected function getBackButtonLabel()
+ public function getHeaderWidth()
{
- return $this->_backButtonLabel;
+ return 'width:50%;';
}
- protected function _addBackButton()
+ /**
+ * @inheritdoc
+ */
+ protected function _prepareLayout()
{
- $this->_addButton('back', [
- 'label' => $this->getBackButtonLabel(),
- 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getBackUrl()),
- 'class' => 'back',
- ]);
+ $this->setChild(
+ 'grid',
+ $this->getLayout()->createBlock(
+ $this->_blockGroup . '/' . $this->_controller . '_grid',
+ $this->_controller . '.grid',
+ )->setSaveParametersInSession(true),
+ );
+ return parent::_prepareLayout();
}
/**
* @return string
*/
- public function getHeaderCssClass()
+ protected function getAddButtonLabel()
{
- return 'icon-head ' . parent::getHeaderCssClass();
+ return $this->_addButtonLabel;
}
/**
* @return string
*/
- public function getHeaderWidth()
+ protected function getBackButtonLabel()
{
- return 'width:50%;';
+ return $this->_backButtonLabel;
+ }
+
+ protected function _addBackButton()
+ {
+ $this->_addButton('back', [
+ 'label' => $this->getBackButtonLabel(),
+ 'onclick' => Mage::helper('core/js')->getSetLocationJs($this->getBackUrl()),
+ 'class' => 'back',
+ ]);
}
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Massaction/Item.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Massaction/Item.php
index 880241dc15d..017ecb49083 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Massaction/Item.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Massaction/Item.php
@@ -67,17 +67,6 @@ public function setAdditionalActionBlock($block)
return $this;
}
- /**
- * @return Mage_Adminhtml_Block_Widget_Grid_Massaction_Item_Additional_Default
- */
- protected function _createFromConfig(array $config)
- {
- /** @var Mage_Adminhtml_Block_Widget_Grid_Massaction_Item_Additional_Default $block */
- $block = $this->getLayout()->createBlock('adminhtml/widget_grid_massaction_item_additional_default');
- $block->createFromConfiguration(isset($config['type']) ? $config['config'] : $config);
- return $block;
- }
-
/**
* Retrieve additional action block for this item
*
@@ -97,4 +86,15 @@ public function getAdditionalActionBlockHtml()
{
return $this->getChildHtml('additional_action');
}
+
+ /**
+ * @return Mage_Adminhtml_Block_Widget_Grid_Massaction_Item_Additional_Default
+ */
+ protected function _createFromConfig(array $config)
+ {
+ /** @var Mage_Adminhtml_Block_Widget_Grid_Massaction_Item_Additional_Default $block */
+ $block = $this->getLayout()->createBlock('adminhtml/widget_grid_massaction_item_additional_default');
+ $block->createFromConfiguration(isset($config['type']) ? $config['config'] : $config);
+ return $block;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Tabs.php b/app/code/core/Mage/Adminhtml/Block/Widget/Tabs.php
index cfa4e93ec5e..13a4be00de6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Tabs.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Tabs.php
@@ -60,11 +60,6 @@ class Mage_Adminhtml_Block_Widget_Tabs extends Mage_Adminhtml_Block_Widget
*/
protected $_destElementId = 'content';
- protected function _construct()
- {
- $this->setTemplate('widget/tabs.phtml');
- }
-
/**
* retrieve destination html element id
*
@@ -180,93 +175,6 @@ public function setActiveTab($tabId)
return $this;
}
- /**
- * Set Active Tab
- *
- * @param string $tabId
- * @return $this
- */
- protected function _setActiveTab($tabId)
- {
- foreach ($this->_tabs as $id => $tab) {
- if ($this->getTabId($tab) == $tabId) {
- $this->_activeTab = $id;
- $tab->setActive(true);
- return $this;
- }
- }
- return $this;
- }
-
- /**
- * @inheritDoc
- */
- protected function _beforeToHtml()
- {
- Mage::dispatchEvent('adminhtml_block_widget_tabs_html_before', ['block' => $this]);
- if ($activeTab = $this->getRequest()->getParam('active_tab')) {
- $this->setActiveTab($activeTab);
- } elseif ($activeTabId = Mage::getSingleton('admin/session')->getActiveTabId()) {
- $this->_setActiveTab($activeTabId);
- }
-
- if ($this->_activeTab === null && !empty($this->_tabs)) {
- $this->_activeTab = (reset($this->_tabs))->getId();
- }
-
- if (!empty($this->_afterTabIds)) {
- $this->_tabs = $this->_reorderTabs();
- }
-
- $this->assign('tabs', $this->_tabs);
- return parent::_beforeToHtml();
- }
-
- /**
- * Find the root parent Tab ID recursively.
- *
- * @param string $currentAfterTabId
- * @param int $degree Degrees of separation between child and root parent.
- * @return string The parent tab ID.
- */
- protected function _getRootParentTabId($currentAfterTabId, &$degree)
- {
- if (array_key_exists($currentAfterTabId, $this->_afterTabIds)) {
- $degree++;
- return $this->_getRootParentTabId($this->_afterTabIds[$currentAfterTabId], $degree);
- } else {
- return $currentAfterTabId;
- }
- }
-
- /**
- * @return array
- */
- protected function _reorderTabs()
- {
- // Set new position based on $afterTabId.
- foreach ($this->_afterTabIds as $tabId => $afterTabId) {
- if (array_key_exists($afterTabId, $this->_tabs)) {
- $degree = 1; // Initialize to 1 degree of separation.
- $parentAfterTabId = $this->_getRootParentTabId($afterTabId, $degree);
- $this->_tabPositions[$tabId] = $this->_tabPositions[$parentAfterTabId] + $degree;
- $degree++;
- }
- }
-
- asort($this->_tabPositions);
-
- $ordered = [];
- foreach (array_keys($this->_tabPositions) as $tabId) {
- if (isset($this->_tabs[$tabId])) {
- $tab = $this->_tabs[$tabId];
- $ordered[$tabId] = $tab;
- }
- }
-
- return $ordered;
- }
-
/**
* @return string
*/
@@ -486,4 +394,96 @@ public function removeTab($tabId)
}
return $this;
}
+
+ protected function _construct()
+ {
+ $this->setTemplate('widget/tabs.phtml');
+ }
+
+ /**
+ * Set Active Tab
+ *
+ * @param string $tabId
+ * @return $this
+ */
+ protected function _setActiveTab($tabId)
+ {
+ foreach ($this->_tabs as $id => $tab) {
+ if ($this->getTabId($tab) == $tabId) {
+ $this->_activeTab = $id;
+ $tab->setActive(true);
+ return $this;
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _beforeToHtml()
+ {
+ Mage::dispatchEvent('adminhtml_block_widget_tabs_html_before', ['block' => $this]);
+ if ($activeTab = $this->getRequest()->getParam('active_tab')) {
+ $this->setActiveTab($activeTab);
+ } elseif ($activeTabId = Mage::getSingleton('admin/session')->getActiveTabId()) {
+ $this->_setActiveTab($activeTabId);
+ }
+
+ if ($this->_activeTab === null && !empty($this->_tabs)) {
+ $this->_activeTab = (reset($this->_tabs))->getId();
+ }
+
+ if (!empty($this->_afterTabIds)) {
+ $this->_tabs = $this->_reorderTabs();
+ }
+
+ $this->assign('tabs', $this->_tabs);
+ return parent::_beforeToHtml();
+ }
+
+ /**
+ * Find the root parent Tab ID recursively.
+ *
+ * @param string $currentAfterTabId
+ * @param int $degree Degrees of separation between child and root parent.
+ * @return string The parent tab ID.
+ */
+ protected function _getRootParentTabId($currentAfterTabId, &$degree)
+ {
+ if (array_key_exists($currentAfterTabId, $this->_afterTabIds)) {
+ $degree++;
+ return $this->_getRootParentTabId($this->_afterTabIds[$currentAfterTabId], $degree);
+ } else {
+ return $currentAfterTabId;
+ }
+ }
+
+ /**
+ * @return array
+ */
+ protected function _reorderTabs()
+ {
+ // Set new position based on $afterTabId.
+ foreach ($this->_afterTabIds as $tabId => $afterTabId) {
+ if (array_key_exists($afterTabId, $this->_tabs)) {
+ $degree = 1; // Initialize to 1 degree of separation.
+ $parentAfterTabId = $this->_getRootParentTabId($afterTabId, $degree);
+ $this->_tabPositions[$tabId] = $this->_tabPositions[$parentAfterTabId] + $degree;
+ $degree++;
+ }
+ }
+
+ asort($this->_tabPositions);
+
+ $ordered = [];
+ foreach (array_keys($this->_tabPositions) as $tabId) {
+ if (isset($this->_tabs[$tabId])) {
+ $tab = $this->_tabs[$tabId];
+ $ordered[$tabId] = $tab;
+ }
+ }
+
+ return $ordered;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/View/Container.php b/app/code/core/Mage/Adminhtml/Block/Widget/View/Container.php
index f9e426d59f1..d17668c1d75 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/View/Container.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/View/Container.php
@@ -43,12 +43,6 @@ public function __construct()
]);
}
- protected function _prepareLayout()
- {
- $this->setChild('plane', $this->getLayout()->createBlock('adminhtml/' . $this->_controller . '_view_plane'));
- return parent::_prepareLayout();
- }
-
public function getEditUrl()
{
return $this->getUrl('*/*/edit', [$this->_objectId => $this->getRequest()->getParam($this->_objectId)]);
@@ -58,4 +52,10 @@ public function getViewHtml()
{
return $this->getChildHtml('plane');
}
+
+ protected function _prepareLayout()
+ {
+ $this->setChild('plane', $this->getLayout()->createBlock('adminhtml/' . $this->_controller . '_view_plane'));
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Controller/Action.php b/app/code/core/Mage/Adminhtml/Controller/Action.php
index 2c84c954b55..672c3fbfa97 100644
--- a/app/code/core/Mage/Adminhtml/Controller/Action.php
+++ b/app/code/core/Mage/Adminhtml/Controller/Action.php
@@ -72,76 +72,18 @@ class Mage_Adminhtml_Controller_Action extends Mage_Core_Controller_Varien_Actio
protected $_sessionNamespace = self::SESSION_NAMESPACE;
/**
- * Check current user permission on resource and privilege
- *
- * @return bool
- */
- protected function _isAllowed()
- {
- return Mage::getSingleton('admin/session')->isAllowed(static::ADMIN_RESOURCE);
- }
-
- /**
- * Retrieve adminhtml session model object
- *
- * @return Mage_Adminhtml_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('adminhtml/session');
- }
-
- /**
- * Retrieve base admihtml helper
- *
- * @return Mage_Adminhtml_Helper_Data
- */
- protected function _getHelper()
- {
- return Mage::helper('adminhtml');
- }
-
- /**
- * Define active menu item in menu block
+ * Translate a phrase
*
- * @return $this
- */
- protected function _setActiveMenu($menuPath)
- {
- $this->getLayout()->getBlock('menu')->setActive($menuPath);
- return $this;
- }
-
- /**
- * @return $this
- */
- protected function _addBreadcrumb($label, $title, $link = null)
- {
- /** @var Mage_Adminhtml_Block_Widget_Breadcrumbs $block */
- $block = $this->getLayout()->getBlock('breadcrumbs');
- $block->addLink($label, $title, $link);
- return $this;
- }
-
- /**
- * @return $this
+ * @return string
+ * @SuppressWarnings("PHPMD.CamelCaseMethodName")
+ * @SuppressWarnings("PHPMD.ShortMethodName")
*/
- protected function _addContent(Mage_Core_Block_Abstract $block)
- {
- $this->getLayout()->getBlock('content')->append($block);
- return $this;
- }
-
- protected function _addLeft(Mage_Core_Block_Abstract $block)
- {
- $this->getLayout()->getBlock('left')->append($block);
- return $this;
- }
-
- protected function _addJs(Mage_Core_Block_Abstract $block)
+ public function __()
{
- $this->getLayout()->getBlock('js')->append($block);
- return $this;
+ $args = func_get_args();
+ $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->getUsedModuleName());
+ array_unshift($args, $expr);
+ return Mage::app()->getTranslator()->translate($args);
}
/**
@@ -225,59 +167,6 @@ public function preDispatch()
return $this;
}
- /**
- * @deprecated after 1.4.0.0 alpha, logic moved to Mage_Adminhtml_Block_Notification_Baseurl
- * @return $this
- */
- protected function _checkUrlSettings()
- {
- /**
- * Don't check for data saving actions
- */
- if ($this->getRequest()->getPost() || $this->getRequest()->getQuery('isAjax')) {
- return $this;
- }
-
- $configData = Mage::getModel('core/config_data');
-
- $defaultUnsecure = (string) Mage::getConfig()->getNode(
- 'default/' . Mage_Core_Model_Store::XML_PATH_UNSECURE_BASE_URL,
- );
- $defaultSecure = (string) Mage::getConfig()->getNode(
- 'default/' . Mage_Core_Model_Store::XML_PATH_SECURE_BASE_URL,
- );
-
- if ($defaultSecure == '{{base_url}}' || $defaultUnsecure == '{{base_url}}') {
- $this->_getSession()->addNotice(
- $this->__('{{base_url}} is not recommended to use in a production environment to declare the Base Unsecure URL / Base Secure URL. It is highly recommended to change this value in your Magento configuration.', $this->getUrl('adminhtml/system_config/edit', ['section' => 'web'])),
- );
- return $this;
- }
-
- $dataCollection = $configData->getCollection()
- ->addValueFilter('{{base_url}}');
-
- $url = false;
- foreach ($dataCollection as $data) {
- if ($data->getScope() == 'stores') {
- $code = Mage::app()->getStore($data->getScopeId())->getCode();
- $url = $this->getUrl('adminhtml/system_config/edit', ['section' => 'web', 'store' => $code]);
- }
- if ($data->getScope() == 'websites') {
- $code = Mage::app()->getWebsite($data->getScopeId())->getCode();
- $url = $this->getUrl('adminhtml/system_config/edit', ['section' => 'web', 'website' => $code]);
- }
-
- if ($url) {
- $this->_getSession()->addNotice(
- $this->__('{{base_url}} is not recommended to use in a production environment to declare the Base Unsecure URL / Base Secure URL. It is highly recommended to change this value in your Magento configuration.', $url),
- );
- return $this;
- }
- }
- return $this;
- }
-
public function deniedAction()
{
$this->getResponse()->setHeader('HTTP/1.1', '403 Forbidden');
@@ -327,18 +216,141 @@ public function setUsedModuleName($moduleName)
}
/**
- * Translate a phrase
+ * Generate url by route and parameters
*
- * @return string
- * @SuppressWarnings("PHPMD.CamelCaseMethodName")
- * @SuppressWarnings("PHPMD.ShortMethodName")
+ * @param string $route
+ * @param array $params
+ * @return string
*/
- public function __()
+ public function getUrl($route = '', $params = [])
{
- $args = func_get_args();
- $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->getUsedModuleName());
- array_unshift($args, $expr);
- return Mage::app()->getTranslator()->translate($args);
+ return Mage::helper('adminhtml')->getUrl($route, $params);
+ }
+
+ /**
+ * Check current user permission on resource and privilege
+ *
+ * @return bool
+ */
+ protected function _isAllowed()
+ {
+ return Mage::getSingleton('admin/session')->isAllowed(static::ADMIN_RESOURCE);
+ }
+
+ /**
+ * Retrieve adminhtml session model object
+ *
+ * @return Mage_Adminhtml_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('adminhtml/session');
+ }
+
+ /**
+ * Retrieve base admihtml helper
+ *
+ * @return Mage_Adminhtml_Helper_Data
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('adminhtml');
+ }
+
+ /**
+ * Define active menu item in menu block
+ *
+ * @return $this
+ */
+ protected function _setActiveMenu($menuPath)
+ {
+ $this->getLayout()->getBlock('menu')->setActive($menuPath);
+ return $this;
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _addBreadcrumb($label, $title, $link = null)
+ {
+ /** @var Mage_Adminhtml_Block_Widget_Breadcrumbs $block */
+ $block = $this->getLayout()->getBlock('breadcrumbs');
+ $block->addLink($label, $title, $link);
+ return $this;
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _addContent(Mage_Core_Block_Abstract $block)
+ {
+ $this->getLayout()->getBlock('content')->append($block);
+ return $this;
+ }
+
+ protected function _addLeft(Mage_Core_Block_Abstract $block)
+ {
+ $this->getLayout()->getBlock('left')->append($block);
+ return $this;
+ }
+
+ protected function _addJs(Mage_Core_Block_Abstract $block)
+ {
+ $this->getLayout()->getBlock('js')->append($block);
+ return $this;
+ }
+
+ /**
+ * @deprecated after 1.4.0.0 alpha, logic moved to Mage_Adminhtml_Block_Notification_Baseurl
+ * @return $this
+ */
+ protected function _checkUrlSettings()
+ {
+ /**
+ * Don't check for data saving actions
+ */
+ if ($this->getRequest()->getPost() || $this->getRequest()->getQuery('isAjax')) {
+ return $this;
+ }
+
+ $configData = Mage::getModel('core/config_data');
+
+ $defaultUnsecure = (string) Mage::getConfig()->getNode(
+ 'default/' . Mage_Core_Model_Store::XML_PATH_UNSECURE_BASE_URL,
+ );
+ $defaultSecure = (string) Mage::getConfig()->getNode(
+ 'default/' . Mage_Core_Model_Store::XML_PATH_SECURE_BASE_URL,
+ );
+
+ if ($defaultSecure == '{{base_url}}' || $defaultUnsecure == '{{base_url}}') {
+ $this->_getSession()->addNotice(
+ $this->__('{{base_url}} is not recommended to use in a production environment to declare the Base Unsecure URL / Base Secure URL. It is highly recommended to change this value in your Magento configuration.', $this->getUrl('adminhtml/system_config/edit', ['section' => 'web'])),
+ );
+ return $this;
+ }
+
+ $dataCollection = $configData->getCollection()
+ ->addValueFilter('{{base_url}}');
+
+ $url = false;
+ foreach ($dataCollection as $data) {
+ if ($data->getScope() == 'stores') {
+ $code = Mage::app()->getStore($data->getScopeId())->getCode();
+ $url = $this->getUrl('adminhtml/system_config/edit', ['section' => 'web', 'store' => $code]);
+ }
+ if ($data->getScope() == 'websites') {
+ $code = Mage::app()->getWebsite($data->getScopeId())->getCode();
+ $url = $this->getUrl('adminhtml/system_config/edit', ['section' => 'web', 'website' => $code]);
+ }
+
+ if ($url) {
+ $this->_getSession()->addNotice(
+ $this->__('{{base_url}} is not recommended to use in a production environment to declare the Base Unsecure URL / Base Secure URL. It is highly recommended to change this value in your Magento configuration.', $url),
+ );
+ return $this;
+ }
+ }
+ return $this;
}
/**
@@ -376,18 +388,6 @@ protected function _forward($action, $controller = null, $module = null, ?array
return parent::_forward($action, $controller, $module, $params);
}
- /**
- * Generate url by route and parameters
- *
- * @param string $route
- * @param array $params
- * @return string
- */
- public function getUrl($route = '', $params = [])
- {
- return Mage::helper('adminhtml')->getUrl($route, $params);
- }
-
/**
* Validate Secret Key
*
diff --git a/app/code/core/Mage/Adminhtml/Controller/Report/Abstract.php b/app/code/core/Mage/Adminhtml/Controller/Report/Abstract.php
index 754eecb0490..d98b36b1bc6 100644
--- a/app/code/core/Mage/Adminhtml/Controller/Report/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Controller/Report/Abstract.php
@@ -29,19 +29,6 @@ abstract class Mage_Adminhtml_Controller_Report_Abstract extends Mage_Adminhtml_
*/
protected $_adminSession = null;
- /**
- * Retrieve admin session model
- *
- * @return Mage_Admin_Model_Session
- */
- protected function _getSession()
- {
- if (is_null($this->_adminSession)) {
- $this->_adminSession = Mage::getSingleton('admin/session');
- }
- return $this->_adminSession;
- }
-
/**
* Add report breadcrumbs
*
@@ -87,6 +74,19 @@ public function _initReportAction($blocks)
return $this;
}
+ /**
+ * Retrieve admin session model
+ *
+ * @return Mage_Admin_Model_Session
+ */
+ protected function _getSession()
+ {
+ if (is_null($this->_adminSession)) {
+ $this->_adminSession = Mage::getSingleton('admin/session');
+ }
+ return $this->_adminSession;
+ }
+
/**
* Add refresh statistics links
*
diff --git a/app/code/core/Mage/Adminhtml/Controller/Sales/Creditmemo.php b/app/code/core/Mage/Adminhtml/Controller/Sales/Creditmemo.php
index 8a42b617961..c8ffaad392c 100644
--- a/app/code/core/Mage/Adminhtml/Controller/Sales/Creditmemo.php
+++ b/app/code/core/Mage/Adminhtml/Controller/Sales/Creditmemo.php
@@ -28,29 +28,6 @@ class Mage_Adminhtml_Controller_Sales_Creditmemo extends Mage_Adminhtml_Controll
*/
public const ADMIN_RESOURCE = 'sales/creditmemo';
- /**
- * Additional initialization
- *
- */
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Sales');
- }
-
- /**
- * Init layout, menu and breadcrumb
- *
- * @return $this
- */
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('sales/creditmemo')
- ->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
- ->_addBreadcrumb($this->__('Credit Memos'), $this->__('Credit Memos'));
- return $this;
- }
-
/**
* Creditmemos grid
*/
@@ -125,4 +102,27 @@ public function printAction()
$this->_forward('noRoute');
}
}
+
+ /**
+ * Additional initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Sales');
+ }
+
+ /**
+ * Init layout, menu and breadcrumb
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('sales/creditmemo')
+ ->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
+ ->_addBreadcrumb($this->__('Credit Memos'), $this->__('Credit Memos'));
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Controller/Sales/Invoice.php b/app/code/core/Mage/Adminhtml/Controller/Sales/Invoice.php
index c265354e4bf..2ee4c38b720 100644
--- a/app/code/core/Mage/Adminhtml/Controller/Sales/Invoice.php
+++ b/app/code/core/Mage/Adminhtml/Controller/Sales/Invoice.php
@@ -28,28 +28,6 @@ class Mage_Adminhtml_Controller_Sales_Invoice extends Mage_Adminhtml_Controller_
*/
public const ADMIN_RESOURCE = 'sales/invoice';
- /**
- * Additional initialization
- */
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Sales');
- }
-
- /**
- * Init layout, menu and breadcrumb
- *
- * @return $this
- */
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('sales/invoice')
- ->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
- ->_addBreadcrumb($this->__('Invoices'), $this->__('Invoices'));
- return $this;
- }
-
/**
* Order grid
*/
@@ -136,4 +114,26 @@ public function pdfinvoicesAction()
}
$this->_redirect('*/*/');
}
+
+ /**
+ * Additional initialization
+ */
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Sales');
+ }
+
+ /**
+ * Init layout, menu and breadcrumb
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('sales/invoice')
+ ->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
+ ->_addBreadcrumb($this->__('Invoices'), $this->__('Invoices'));
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Controller/Sales/Shipment.php b/app/code/core/Mage/Adminhtml/Controller/Sales/Shipment.php
index 2e63d910e7f..172eca5b6f1 100644
--- a/app/code/core/Mage/Adminhtml/Controller/Sales/Shipment.php
+++ b/app/code/core/Mage/Adminhtml/Controller/Sales/Shipment.php
@@ -28,28 +28,6 @@ class Mage_Adminhtml_Controller_Sales_Shipment extends Mage_Adminhtml_Controller
*/
public const ADMIN_RESOURCE = 'sales/shipment';
- /**
- * Additional initialization
- */
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Sales');
- }
-
- /**
- * Init layout, menu and breadcrumb
- *
- * @return $this
- */
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('sales/shipment')
- ->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
- ->_addBreadcrumb($this->__('Shipments'), $this->__('Shipments'));
- return $this;
- }
-
/**
* Shipments grid
*/
@@ -101,4 +79,26 @@ public function printAction()
$this->_forward('noRoute');
}
}
+
+ /**
+ * Additional initialization
+ */
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Sales');
+ }
+
+ /**
+ * Init layout, menu and breadcrumb
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('sales/shipment')
+ ->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
+ ->_addBreadcrumb($this->__('Shipments'), $this->__('Shipments'));
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Composite.php b/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Composite.php
index 26b4e83abd0..70aa750e847 100644
--- a/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Composite.php
+++ b/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Composite.php
@@ -24,20 +24,6 @@ class Mage_Adminhtml_Helper_Catalog_Product_Composite extends Mage_Core_Helper_A
{
protected $_moduleName = 'Mage_Adminhtml';
- /**
- * Init layout of product configuration update result
- *
- * @param Mage_Adminhtml_Controller_Action $controller
- * @return $this
- */
- protected function _initUpdateResultLayout($controller)
- {
- $controller->getLayout()->getUpdate()
- ->addHandle('ADMINHTML_CATALOG_PRODUCT_COMPOSITE_UPDATE_RESULT');
- $controller->loadLayoutUpdates()->generateLayoutXml()->generateLayoutBlocks();
- return $this;
- }
-
/**
* Prepares and render result of composite product configuration update for a case
* when single configuration submitted
@@ -54,30 +40,6 @@ public function renderUpdateResult($controller, Varien_Object $updateResult)
return $this;
}
- /**
- * Init composite product configuration layout
- *
- * $isOk - true or false, whether action was completed nicely or with some error
- * If $isOk is FALSE (some error during configuration), so $productType must be null
- *
- * @param Mage_Adminhtml_Controller_Action $controller
- * @param bool $isOk
- * @param string $productType
- * @return $this
- */
- protected function _initConfigureResultLayout($controller, $isOk, $productType)
- {
- $update = $controller->getLayout()->getUpdate();
- if ($isOk) {
- $update->addHandle('ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE')
- ->addHandle('PRODUCT_TYPE_' . $productType);
- } else {
- $update->addHandle('ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE_ERROR');
- }
- $controller->loadLayoutUpdates()->generateLayoutXml()->generateLayoutBlocks();
- return $this;
- }
-
/**
* Prepares and render result of composite product configuration request
*
@@ -140,4 +102,42 @@ public function renderConfigureResult($controller, Varien_Object $configureResul
$controller->renderLayout();
return $this;
}
+
+ /**
+ * Init layout of product configuration update result
+ *
+ * @param Mage_Adminhtml_Controller_Action $controller
+ * @return $this
+ */
+ protected function _initUpdateResultLayout($controller)
+ {
+ $controller->getLayout()->getUpdate()
+ ->addHandle('ADMINHTML_CATALOG_PRODUCT_COMPOSITE_UPDATE_RESULT');
+ $controller->loadLayoutUpdates()->generateLayoutXml()->generateLayoutBlocks();
+ return $this;
+ }
+
+ /**
+ * Init composite product configuration layout
+ *
+ * $isOk - true or false, whether action was completed nicely or with some error
+ * If $isOk is FALSE (some error during configuration), so $productType must be null
+ *
+ * @param Mage_Adminhtml_Controller_Action $controller
+ * @param bool $isOk
+ * @param string $productType
+ * @return $this
+ */
+ protected function _initConfigureResultLayout($controller, $isOk, $productType)
+ {
+ $update = $controller->getLayout()->getUpdate();
+ if ($isOk) {
+ $update->addHandle('ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE')
+ ->addHandle('PRODUCT_TYPE_' . $productType);
+ } else {
+ $update->addHandle('ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE_ERROR');
+ }
+ $controller->loadLayoutUpdates()->generateLayoutXml()->generateLayoutBlocks();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Helper/Dashboard/Abstract.php b/app/code/core/Mage/Adminhtml/Helper/Dashboard/Abstract.php
index fb205cd97a4..5be2cad6b82 100644
--- a/app/code/core/Mage/Adminhtml/Helper/Dashboard/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Helper/Dashboard/Abstract.php
@@ -44,8 +44,6 @@ public function getCollection()
return $this->_collection;
}
- abstract protected function _initCollection();
-
/**
* Returns collection items
*
@@ -99,4 +97,6 @@ public function getParams()
{
return $this->_params;
}
+
+ abstract protected function _initCollection();
}
diff --git a/app/code/core/Mage/Adminhtml/Model/Config.php b/app/code/core/Mage/Adminhtml/Model/Config.php
index d4dfdf68d16..2f964715330 100644
--- a/app/code/core/Mage/Adminhtml/Model/Config.php
+++ b/app/code/core/Mage/Adminhtml/Model/Config.php
@@ -44,6 +44,21 @@ class Mage_Adminhtml_Model_Config extends Varien_Simplexml_Config
*/
protected $_tabs;
+ public function __construct()
+ {
+ $this->_cacheChecksum = null;
+ $this->setCache(Mage::app()->getCache());
+ $this->setCacheTags([Mage_Core_Model_Config::CACHE_TAG]);
+ $usesCache = Mage::app()->useCache('config');
+ if (!$usesCache || !$this->loadCache()) {
+ $this->_config = Mage::getConfig()->loadModulesConfiguration('system.xml')
+ ->applyExtends();
+ if ($usesCache) {
+ $this->saveCache();
+ }
+ }
+ }
+
/**
* @param string $sectionCode
* @param string $websiteCode
@@ -73,21 +88,6 @@ public function getTabs()
return $this->_tabs;
}
- public function __construct()
- {
- $this->_cacheChecksum = null;
- $this->setCache(Mage::app()->getCache());
- $this->setCacheTags([Mage_Core_Model_Config::CACHE_TAG]);
- $usesCache = Mage::app()->useCache('config');
- if (!$usesCache || !$this->loadCache()) {
- $this->_config = Mage::getConfig()->loadModulesConfiguration('system.xml')
- ->applyExtends();
- if ($usesCache) {
- $this->saveCache();
- }
- }
- }
-
/**
* @param array|null $tags
* @return $this|Mage_Adminhtml_Model_Config
@@ -122,17 +122,6 @@ public function loadCache()
return false;
}
- /**
- * Init modules configuration
- */
- protected function _initSectionsAndTabs()
- {
- $config = $this->_config;
- Mage::dispatchEvent('adminhtml_init_system_config', ['config' => $config]);
- $this->_sections = $config->getNode('sections');
- $this->_tabs = $config->getNode('tabs');
- }
-
/**
* @param string $sectionCode
* @param string $websiteCode
@@ -283,4 +272,15 @@ public function getEncryptedNodeEntriesPaths($explodePathToEntities = false)
}
return $paths;
}
+
+ /**
+ * Init modules configuration
+ */
+ protected function _initSectionsAndTabs()
+ {
+ $config = $this->_config;
+ Mage::dispatchEvent('adminhtml_init_system_config', ['config' => $config]);
+ $this->_sections = $config->getNode('sections');
+ $this->_tabs = $config->getNode('tabs');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Model/Config/Data.php b/app/code/core/Mage/Adminhtml/Model/Config/Data.php
index 0effd78b210..19eefe9f997 100644
--- a/app/code/core/Mage/Adminhtml/Model/Config/Data.php
+++ b/app/code/core/Mage/Adminhtml/Model/Config/Data.php
@@ -248,6 +248,116 @@ public function extendConfig($path, $full = true, $oldConfig = [])
return $extended;
}
+ /**
+ * Get config data value
+ *
+ * @param string $path
+ * @param null|bool $inherit
+ * @param null|array $configData
+ * @param-out bool $inherit
+ * @return Varien_Simplexml_Element
+ */
+ public function getConfigDataValue($path, &$inherit = null, $configData = null)
+ {
+ $this->load();
+ if (is_null($configData)) {
+ $configData = $this->_configData;
+ }
+ if (array_key_exists($path, $configData)) {
+ $data = $configData[$path];
+ $inherit = false;
+ } else {
+ $data = $this->getConfigRoot()->descend($path);
+ $inherit = true;
+ }
+
+ return $data;
+ }
+
+ /**
+ * Get config root node for current scope
+ *
+ * @return Mage_Core_Model_Config_Element
+ */
+ public function getConfigRoot()
+ {
+ if (is_null($this->_configRoot)) {
+ $this->load();
+ $this->_configRoot = Mage::getConfig()->getNode(null, $this->getScope(), $this->getScopeCode());
+ }
+ return $this->_configRoot;
+ }
+
+ /**
+ * Secure set groups
+ *
+ * @param array $groups
+ * @return Mage_Adminhtml_Model_Config_Data
+ * @throws Mage_Core_Exception
+ */
+ public function setGroupsSecure($groups)
+ {
+ $this->_validate();
+ $this->_getScope();
+
+ $groupsSecure = [];
+ $section = $this->getSection();
+ $sections = Mage::getModel('adminhtml/config')->getSections();
+
+ foreach ($groups as $group => $groupData) {
+ $groupConfig = $sections->descend($section . '/groups/' . $group);
+ foreach ($groupData['fields'] as $field => $fieldData) {
+ $fieldName = $field;
+ if ($groupConfig && $groupConfig->clone_fields) {
+ if ($groupConfig->clone_model) {
+ $cloneModel = Mage::getModel((string) $groupConfig->clone_model);
+ } else {
+ Mage::throwException(
+ $this->__('Config form fieldset clone model required to be able to clone fields'),
+ );
+ }
+ foreach ($cloneModel->getPrefixes() as $prefix) {
+ if (strpos($field, $prefix['field']) === 0) {
+ $field = substr($field, strlen($prefix['field']));
+ }
+ }
+ }
+ $fieldConfig = $sections->descend($section . '/groups/' . $group . '/fields/' . $field);
+ if (!$fieldConfig) {
+ $node = $sections->xpath($section . '//' . $group . '[@type="group"]/fields/' . $field);
+ if ($node) {
+ $fieldConfig = $node[0];
+ }
+ }
+ if (($groupConfig ? !$groupConfig->dynamic_group : true) && !$this->_isValidField($fieldConfig)) {
+ $message = Mage::helper('adminhtml')->__('Wrong field specified.') . ' ' . Mage::helper('adminhtml')->__('(%s/%s/%s)', $section, $group, $field);
+ Mage::throwException($message);
+ }
+ $groupsSecure[$group]['fields'][$fieldName] = $fieldData;
+ }
+ }
+
+ $this->setGroups($groupsSecure);
+
+ return $this;
+ }
+
+ /**
+ * Select group setter is secure or not based on the configuration
+ *
+ * @param array $groups
+ * @return Mage_Adminhtml_Model_Config_Data
+ * @throws Mage_Core_Exception
+ */
+ public function setGroupsSelector($groups)
+ {
+ if (Mage::getStoreConfigFlag('admin/security/secure_system_configuration_save_disabled')) {
+ return $this->setGroups($groups);
+ }
+
+ return $this->setGroupsSecure($groups);
+ }
+
/**
* Check if specified section allowed in ACL
*
@@ -352,100 +462,6 @@ protected function _getPathConfig($path, $full = true)
return $config;
}
- /**
- * Get config data value
- *
- * @param string $path
- * @param null|bool $inherit
- * @param null|array $configData
- * @param-out bool $inherit
- * @return Varien_Simplexml_Element
- */
- public function getConfigDataValue($path, &$inherit = null, $configData = null)
- {
- $this->load();
- if (is_null($configData)) {
- $configData = $this->_configData;
- }
- if (array_key_exists($path, $configData)) {
- $data = $configData[$path];
- $inherit = false;
- } else {
- $data = $this->getConfigRoot()->descend($path);
- $inherit = true;
- }
-
- return $data;
- }
-
- /**
- * Get config root node for current scope
- *
- * @return Mage_Core_Model_Config_Element
- */
- public function getConfigRoot()
- {
- if (is_null($this->_configRoot)) {
- $this->load();
- $this->_configRoot = Mage::getConfig()->getNode(null, $this->getScope(), $this->getScopeCode());
- }
- return $this->_configRoot;
- }
-
- /**
- * Secure set groups
- *
- * @param array $groups
- * @return Mage_Adminhtml_Model_Config_Data
- * @throws Mage_Core_Exception
- */
- public function setGroupsSecure($groups)
- {
- $this->_validate();
- $this->_getScope();
-
- $groupsSecure = [];
- $section = $this->getSection();
- $sections = Mage::getModel('adminhtml/config')->getSections();
-
- foreach ($groups as $group => $groupData) {
- $groupConfig = $sections->descend($section . '/groups/' . $group);
- foreach ($groupData['fields'] as $field => $fieldData) {
- $fieldName = $field;
- if ($groupConfig && $groupConfig->clone_fields) {
- if ($groupConfig->clone_model) {
- $cloneModel = Mage::getModel((string) $groupConfig->clone_model);
- } else {
- Mage::throwException(
- $this->__('Config form fieldset clone model required to be able to clone fields'),
- );
- }
- foreach ($cloneModel->getPrefixes() as $prefix) {
- if (strpos($field, $prefix['field']) === 0) {
- $field = substr($field, strlen($prefix['field']));
- }
- }
- }
- $fieldConfig = $sections->descend($section . '/groups/' . $group . '/fields/' . $field);
- if (!$fieldConfig) {
- $node = $sections->xpath($section . '//' . $group . '[@type="group"]/fields/' . $field);
- if ($node) {
- $fieldConfig = $node[0];
- }
- }
- if (($groupConfig ? !$groupConfig->dynamic_group : true) && !$this->_isValidField($fieldConfig)) {
- $message = Mage::helper('adminhtml')->__('Wrong field specified.') . ' ' . Mage::helper('adminhtml')->__('(%s/%s/%s)', $section, $group, $field);
- Mage::throwException($message);
- }
- $groupsSecure[$group]['fields'][$fieldName] = $fieldData;
- }
- }
-
- $this->setGroups($groupsSecure);
-
- return $this;
- }
-
/**
* Check field visibility by scope
*
@@ -469,20 +485,4 @@ protected function _isValidField($field)
return true;
}
-
- /**
- * Select group setter is secure or not based on the configuration
- *
- * @param array $groups
- * @return Mage_Adminhtml_Model_Config_Data
- * @throws Mage_Core_Exception
- */
- public function setGroupsSelector($groups)
- {
- if (Mage::getStoreConfigFlag('admin/security/secure_system_configuration_save_disabled')) {
- return $this->setGroups($groups);
- }
-
- return $this->setGroupsSecure($groups);
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Model/Giftmessage/Save.php b/app/code/core/Mage/Adminhtml/Model/Giftmessage/Save.php
index 35ff88033d9..8d10eff057a 100644
--- a/app/code/core/Mage/Adminhtml/Model/Giftmessage/Save.php
+++ b/app/code/core/Mage/Adminhtml/Model/Giftmessage/Save.php
@@ -74,81 +74,6 @@ public function saveAllInOrder()
return $this;
}
- /**
- * Save a single gift message
- *
- * @param int $entityId
- * @param array $giftmessage
- * @return $this
- * @throws Throwable
- */
- protected function _saveOne($entityId, $giftmessage)
- {
- /** @var Mage_GiftMessage_Model_Message $giftmessageModel */
- $giftmessageModel = Mage::getModel('giftmessage/message');
- $entityType = $this->_getMappedType($giftmessage['type']);
-
- switch ($entityType) {
- case 'quote':
- $entityModel = $this->_getQuote();
- break;
-
- case 'quote_item':
- $entityModel = $this->_getQuote()->getItemById($entityId);
- break;
-
- default:
- $entityModel = $giftmessageModel->getEntityModelByType($entityType)
- ->load($entityId);
- break;
- }
-
- if (!$entityModel) {
- return $this;
- }
-
- if ($entityModel->getGiftMessageId()) {
- $giftmessageModel->load($entityModel->getGiftMessageId());
- }
-
- $giftmessageModel->addData($giftmessage);
-
- if ($giftmessageModel->isMessageEmpty() && $giftmessageModel->getId()) {
- // remove empty giftmessage
- $this->_deleteOne($entityModel, $giftmessageModel);
- $this->_saved = false;
- } elseif (!$giftmessageModel->isMessageEmpty()) {
- $giftmessageModel->save();
- $entityModel->setGiftMessageId($giftmessageModel->getId());
- if ($entityType != 'quote') {
- $entityModel->save();
- }
- $this->_saved = true;
- }
-
- return $this;
- }
-
- /**
- * Delete a single gift message from entity
- *
- * @param Mage_GiftMessage_Model_Message|null $giftmessageModel
- * @param Varien_Object $entityModel
- * @return $this
- * @throws Throwable
- */
- protected function _deleteOne($entityModel, $giftmessageModel = null)
- {
- if (is_null($giftmessageModel)) {
- $giftmessageModel = Mage::getModel('giftmessage/message')
- ->load($entityModel->getGiftMessageId());
- }
- $giftmessageModel->delete();
- $entityModel->setGiftMessageId(0)
- ->save();
- return $this;
- }
-
/**
* Set allowed quote items for gift messages
*
@@ -311,6 +236,81 @@ public function importAllowQuoteItemsFromItems($items)
return $this;
}
+ /**
+ * Save a single gift message
+ *
+ * @param int $entityId
+ * @param array $giftmessage
+ * @return $this
+ * @throws Throwable
+ */
+ protected function _saveOne($entityId, $giftmessage)
+ {
+ /** @var Mage_GiftMessage_Model_Message $giftmessageModel */
+ $giftmessageModel = Mage::getModel('giftmessage/message');
+ $entityType = $this->_getMappedType($giftmessage['type']);
+
+ switch ($entityType) {
+ case 'quote':
+ $entityModel = $this->_getQuote();
+ break;
+
+ case 'quote_item':
+ $entityModel = $this->_getQuote()->getItemById($entityId);
+ break;
+
+ default:
+ $entityModel = $giftmessageModel->getEntityModelByType($entityType)
+ ->load($entityId);
+ break;
+ }
+
+ if (!$entityModel) {
+ return $this;
+ }
+
+ if ($entityModel->getGiftMessageId()) {
+ $giftmessageModel->load($entityModel->getGiftMessageId());
+ }
+
+ $giftmessageModel->addData($giftmessage);
+
+ if ($giftmessageModel->isMessageEmpty() && $giftmessageModel->getId()) {
+ // remove empty giftmessage
+ $this->_deleteOne($entityModel, $giftmessageModel);
+ $this->_saved = false;
+ } elseif (!$giftmessageModel->isMessageEmpty()) {
+ $giftmessageModel->save();
+ $entityModel->setGiftMessageId($giftmessageModel->getId());
+ if ($entityType != 'quote') {
+ $entityModel->save();
+ }
+ $this->_saved = true;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Delete a single gift message from entity
+ *
+ * @param Mage_GiftMessage_Model_Message|null $giftmessageModel
+ * @param Varien_Object $entityModel
+ * @return $this
+ * @throws Throwable
+ */
+ protected function _deleteOne($entityModel, $giftmessageModel = null)
+ {
+ if (is_null($giftmessageModel)) {
+ $giftmessageModel = Mage::getModel('giftmessage/message')
+ ->load($entityModel->getGiftMessageId());
+ }
+ $giftmessageModel->delete();
+ $entityModel->setGiftMessageId(0)
+ ->save();
+ return $this;
+ }
+
/**
* Retrieve mapped type for entity
*
diff --git a/app/code/core/Mage/Adminhtml/Model/Sales/Order.php b/app/code/core/Mage/Adminhtml/Model/Sales/Order.php
index 024a571c9ac..746970e5ae2 100644
--- a/app/code/core/Mage/Adminhtml/Model/Sales/Order.php
+++ b/app/code/core/Mage/Adminhtml/Model/Sales/Order.php
@@ -22,16 +22,6 @@
*/
class Mage_Adminhtml_Model_Sales_Order
{
- /**
- * Retrieve adminhtml session singleton
- *
- * @return Mage_Adminhtml_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('adminhtml/session');
- }
-
public function checkRelation(Mage_Sales_Model_Order $order)
{
/**
@@ -76,4 +66,13 @@ public function checkRelation(Mage_Sales_Model_Order $order)
}
return $this;
}
+ /**
+ * Retrieve adminhtml session singleton
+ *
+ * @return Mage_Adminhtml_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('adminhtml/session');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php b/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php
index 6e7451d8188..646f48c2a78 100644
--- a/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php
+++ b/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php
@@ -135,22 +135,6 @@ public function getIsValidate()
return $this->_isValidate;
}
- /**
- * Retrieve quote item
- *
- * @param int|Mage_Sales_Model_Quote_Item $item
- * @return Mage_Sales_Model_Quote_Item|false
- */
- protected function _getQuoteItem($item)
- {
- if ($item instanceof Mage_Sales_Model_Quote_Item) {
- return $item;
- } elseif (is_numeric($item)) {
- return $this->getSession()->getQuote()->getItemById($item);
- }
- return false;
- }
-
/**
* Initialize data for price rules
*
@@ -379,31 +363,6 @@ public function initFromOrder(Mage_Sales_Model_Order $order)
return $this;
}
- protected function _initBillingAddressFromOrder(Mage_Sales_Model_Order $order)
- {
- $this->getQuote()->getBillingAddress()->setCustomerAddressId('');
- Mage::helper('core')->copyFieldset(
- 'sales_copy_order_billing_address',
- 'to_order',
- $order->getBillingAddress(),
- $this->getQuote()->getBillingAddress(),
- );
- }
-
- protected function _initShippingAddressFromOrder(Mage_Sales_Model_Order $order)
- {
- $orderShippingAddress = $order->getShippingAddress();
- $quoteShippingAddress = $this->getQuote()->getShippingAddress()
- ->setCustomerAddressId('')
- ->setSameAsBilling($orderShippingAddress && $orderShippingAddress->getSameAsBilling());
- Mage::helper('core')->copyFieldset(
- 'sales_copy_order_shipping_address',
- 'to_order',
- $orderShippingAddress,
- $quoteShippingAddress,
- );
- }
-
/**
* Initialize creation data from existing order Item
*
@@ -885,340 +844,118 @@ public function updateQuoteItems($data)
}
/**
- * Parse additional options and sync them with product options
+ * Retrieve oreder quote shipping address
*
- * @param string $additionalOptions
- * @return array
+ * @return Mage_Sales_Model_Quote_Address
*/
- protected function _parseOptions(Mage_Sales_Model_Quote_Item $item, $additionalOptions)
+ public function getShippingAddress()
{
- $productOptions = Mage::getSingleton('catalog/product_option_type_default')
- ->setProduct($item->getProduct())
- ->getProductOptions();
-
- $newOptions = [];
- $newAdditionalOptions = [];
-
- foreach (explode("\n", $additionalOptions) as $additionalOption) {
- if (strlen(trim($additionalOption))) {
- try {
- if (!str_contains($additionalOption, ':')) {
- Mage::throwException(
- Mage::helper('adminhtml')->__('There is an error in one of the option rows.'),
- );
- }
- list($label, $value) = explode(':', $additionalOption, 2);
- } catch (Exception $e) {
- Mage::throwException(Mage::helper('adminhtml')->__('There is an error in one of the option rows.'));
- }
- $label = trim($label);
- $value = trim($value);
- if (empty($value)) {
- continue;
- }
-
- if (array_key_exists($label, $productOptions)) {
- $optionId = $productOptions[$label]['option_id'];
- $option = $item->getProduct()->getOptionById($optionId);
-
- $group = Mage::getSingleton('catalog/product_option')->groupFactory($option->getType())
- ->setOption($option)
- ->setProduct($item->getProduct());
-
- $parsedValue = $group->parseOptionValue($value, $productOptions[$label]['values']);
-
- if ($parsedValue !== null) {
- $newOptions[$optionId] = $parsedValue;
- } else {
- $newAdditionalOptions[] = [
- 'label' => $label,
- 'value' => $value,
- ];
- }
- } else {
- $newAdditionalOptions[] = [
- 'label' => $label,
- 'value' => $value,
- ];
- }
- }
- }
-
- return [
- 'options' => $newOptions,
- 'additional_options' => $newAdditionalOptions,
- ];
+ return $this->getQuote()->getShippingAddress();
}
/**
- * Assign options to item
- *
- * @param array $options
+ * @param array|Mage_Sales_Model_Quote_Address $address
* @return $this
*/
- protected function _assignOptionsToItem(Mage_Sales_Model_Quote_Item $item, $options)
+ public function setShippingAddress($address)
{
- if ($optionIds = $item->getOptionByCode('option_ids')) {
- foreach (explode(',', $optionIds->getValue()) as $optionId) {
- $item->removeOption('option_' . $optionId);
+ if (is_array($address)) {
+ $address['save_in_address_book'] = isset($address['save_in_address_book'])
+ && !empty($address['save_in_address_book']);
+ $shippingAddress = Mage::getModel('sales/quote_address')
+ ->setData($address)
+ ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING);
+ if (!$this->getQuote()->isVirtual()) {
+ $this->_setQuoteAddress($shippingAddress, $address);
}
- $item->removeOption('option_ids');
+ $shippingAddress->implodeStreetAddress();
}
- if ($item->getOptionByCode('additional_options')) {
- $item->removeOption('additional_options');
+ if ($address instanceof Mage_Sales_Model_Quote_Address) {
+ $shippingAddress = $address;
}
- $item->save();
- if (!empty($options['options'])) {
- $item->addOption(new Varien_Object(
- [
- 'product' => $item->getProduct(),
- 'code' => 'option_ids',
- 'value' => implode(',', array_keys($options['options'])),
- ],
- ));
- foreach ($options['options'] as $optionId => $optionValue) {
- $item->addOption(new Varien_Object(
- [
- 'product' => $item->getProduct(),
- 'code' => 'option_' . $optionId,
- 'value' => $optionValue,
- ],
- ));
- }
- }
- if (!empty($options['additional_options'])) {
- $item->addOption(new Varien_Object(
- [
- 'product' => $item->getProduct(),
- 'code' => 'additional_options',
- 'value' => serialize($options['additional_options']),
- ],
- ));
- }
+ $this->setRecollect(true);
+ $this->getQuote()->setShippingAddress($shippingAddress);
+ return $this;
+ }
+ public function setShippingAsBilling($flag)
+ {
+ if ($flag) {
+ $tmpAddress = clone $this->getBillingAddress();
+ $tmpAddress->unsAddressId()
+ ->unsAddressType();
+ $data = $tmpAddress->getData();
+ $data['save_in_address_book'] = 0; // Do not duplicate address (billing address will do saving too)
+ unset($data['shipping_method']); // Do not reset shipping method to be able to recollect totals
+ $this->getShippingAddress()->addData($data);
+ }
+ $this->getShippingAddress()->setSameAsBilling($flag);
+ $this->setRecollect(true);
return $this;
}
/**
- * Prepare options array for info buy request
+ * Retrieve quote billing address
*
- * @param Mage_Sales_Model_Quote_Item $item
- * @return array
+ * @return Mage_Sales_Model_Quote_Address
*/
- protected function _prepareOptionsForRequest($item)
+ public function getBillingAddress()
{
- $newInfoOptions = [];
- if ($optionIds = $item->getOptionByCode('option_ids')) {
- foreach (explode(',', $optionIds->getValue()) as $optionId) {
- $option = $item->getProduct()->getOptionById($optionId);
- $optionValue = $item->getOptionByCode('option_' . $optionId)->getValue();
+ return $this->getQuote()->getBillingAddress();
+ }
- $group = Mage::getSingleton('catalog/product_option')->groupFactory($option->getType())
- ->setOption($option)
- ->setQuoteItem($item);
+ /**
+ * @param array|Mage_Sales_Model_Quote_Address $address
+ * @return $this
+ */
+ public function setBillingAddress($address)
+ {
+ if (is_array($address)) {
+ $address['save_in_address_book'] = isset($address['save_in_address_book']) ? 1 : 0;
+ $billingAddress = Mage::getModel('sales/quote_address')
+ ->setData($address)
+ ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING);
+ $this->_setQuoteAddress($billingAddress, $address);
+ $billingAddress->implodeStreetAddress();
+ } elseif ($address instanceof Mage_Sales_Model_Quote_Address) {
+ $billingAddress = $address;
+ }
- $newInfoOptions[$optionId] = $group->prepareOptionValueForRequest($optionValue);
- }
+ if ($this->getShippingAddress()->getSameAsBilling()) {
+ $shippingAddress = clone $billingAddress;
+ $shippingAddress->setSameAsBilling(true);
+ $shippingAddress->setSaveInAddressBook(false);
+ $address['save_in_address_book'] = 0;
+ $this->setShippingAddress($address);
}
- return $newInfoOptions;
+
+ $this->getQuote()->setBillingAddress($billingAddress);
+ return $this;
}
- protected function _parseCustomPrice($price)
+ public function setShippingMethod($method)
{
- $price = Mage::app()->getLocale()->getNumber($price);
- return $price > 0 ? $price : 0;
+ $this->getShippingAddress()->setShippingMethod($method);
+ $this->setRecollect(true);
+ return $this;
}
- /**
- * Retrieve oreder quote shipping address
- *
- * @return Mage_Sales_Model_Quote_Address
- */
- public function getShippingAddress()
+ public function resetShippingMethod()
{
- return $this->getQuote()->getShippingAddress();
+ $this->getShippingAddress()->setShippingMethod(false);
+ $this->getShippingAddress()->removeAllShippingRates();
+ return $this;
}
/**
- * Return Customer (Checkout) Form instance
- *
- * @return Mage_Customer_Model_Form
+ * Collect shipping data for quote shipping address
*/
- protected function _getCustomerForm()
+ public function collectShippingRates()
{
- if (is_null($this->_customerForm)) {
- $this->_customerForm = Mage::getModel('customer/form')
- ->setFormCode('adminhtml_checkout')
- ->ignoreInvisible(false);
- }
- return $this->_customerForm;
- }
-
- /**
- * Return Customer Address Form instance
- *
- * @return Mage_Customer_Model_Form
- */
- protected function _getCustomerAddressForm()
- {
- if (is_null($this->_customerAddressForm)) {
- $this->_customerAddressForm = Mage::getModel('customer/form')
- ->setFormCode('adminhtml_customer_address')
- ->ignoreInvisible(false);
- }
- return $this->_customerAddressForm;
- }
-
- /**
- * Set and validate Quote address
- * All errors added to _errors
- *
- * @return $this
- */
- protected function _setQuoteAddress(Mage_Sales_Model_Quote_Address $address, array $data)
- {
- $addressForm = $this->_getCustomerAddressForm()
- ->setEntity($address)
- ->setEntityType(Mage::getSingleton('eav/config')->getEntityType('customer_address'))
- ->setIsAjaxRequest(!$this->getIsValidate());
-
- // prepare request
- // save original request structure for files
- if ($address->getAddressType() == Mage_Sales_Model_Quote_Address::TYPE_SHIPPING) {
- $requestData = ['order' => ['shipping_address' => $data]];
- $requestScope = 'order/shipping_address';
- } else {
- $requestData = ['order' => ['billing_address' => $data]];
- $requestScope = 'order/billing_address';
- }
- $request = $addressForm->prepareRequest($requestData);
- $addressData = $addressForm->extractData($request, $requestScope);
- if ($this->getIsValidate()) {
- $errors = $addressForm->validateData($addressData);
- if ($errors !== true) {
- if ($address->getAddressType() == Mage_Sales_Model_Quote_Address::TYPE_SHIPPING) {
- $typeName = Mage::helper('adminhtml')->__('Shipping Address: ');
- } else {
- $typeName = Mage::helper('adminhtml')->__('Billing Address: ');
- }
- foreach ($errors as $error) {
- $this->_errors[] = $typeName . $error;
- }
- $addressForm->restoreData($addressData);
- } else {
- $addressForm->compactData($addressData);
- }
- } else {
- $addressForm->restoreData($addressData);
- }
-
- return $this;
- }
-
- /**
- * @param array|Mage_Sales_Model_Quote_Address $address
- * @return $this
- */
- public function setShippingAddress($address)
- {
- if (is_array($address)) {
- $address['save_in_address_book'] = isset($address['save_in_address_book'])
- && !empty($address['save_in_address_book']);
- $shippingAddress = Mage::getModel('sales/quote_address')
- ->setData($address)
- ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING);
- if (!$this->getQuote()->isVirtual()) {
- $this->_setQuoteAddress($shippingAddress, $address);
- }
- $shippingAddress->implodeStreetAddress();
- }
- if ($address instanceof Mage_Sales_Model_Quote_Address) {
- $shippingAddress = $address;
- }
-
- $this->setRecollect(true);
- $this->getQuote()->setShippingAddress($shippingAddress);
- return $this;
- }
-
- public function setShippingAsBilling($flag)
- {
- if ($flag) {
- $tmpAddress = clone $this->getBillingAddress();
- $tmpAddress->unsAddressId()
- ->unsAddressType();
- $data = $tmpAddress->getData();
- $data['save_in_address_book'] = 0; // Do not duplicate address (billing address will do saving too)
- unset($data['shipping_method']); // Do not reset shipping method to be able to recollect totals
- $this->getShippingAddress()->addData($data);
- }
- $this->getShippingAddress()->setSameAsBilling($flag);
- $this->setRecollect(true);
- return $this;
- }
-
- /**
- * Retrieve quote billing address
- *
- * @return Mage_Sales_Model_Quote_Address
- */
- public function getBillingAddress()
- {
- return $this->getQuote()->getBillingAddress();
- }
-
- /**
- * @param array|Mage_Sales_Model_Quote_Address $address
- * @return $this
- */
- public function setBillingAddress($address)
- {
- if (is_array($address)) {
- $address['save_in_address_book'] = isset($address['save_in_address_book']) ? 1 : 0;
- $billingAddress = Mage::getModel('sales/quote_address')
- ->setData($address)
- ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING);
- $this->_setQuoteAddress($billingAddress, $address);
- $billingAddress->implodeStreetAddress();
- } elseif ($address instanceof Mage_Sales_Model_Quote_Address) {
- $billingAddress = $address;
- }
-
- if ($this->getShippingAddress()->getSameAsBilling()) {
- $shippingAddress = clone $billingAddress;
- $shippingAddress->setSameAsBilling(true);
- $shippingAddress->setSaveInAddressBook(false);
- $address['save_in_address_book'] = 0;
- $this->setShippingAddress($address);
- }
-
- $this->getQuote()->setBillingAddress($billingAddress);
- return $this;
- }
-
- public function setShippingMethod($method)
- {
- $this->getShippingAddress()->setShippingMethod($method);
- $this->setRecollect(true);
- return $this;
- }
-
- public function resetShippingMethod()
- {
- $this->getShippingAddress()->setShippingMethod(false);
- $this->getShippingAddress()->removeAllShippingRates();
- return $this;
- }
-
- /**
- * Collect shipping data for quote shipping address
- */
- public function collectShippingRates()
- {
- $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
- $this->collectRates();
- return $this;
+ $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
+ $this->collectRates();
+ return $this;
}
public function collectRates()
@@ -1329,51 +1066,6 @@ public function importPostData($data)
return $this;
}
- /**
- * Check whether we need to create new customer (for another website) during order creation
- *
- * @param Mage_Core_Model_Store $store
- * @return bool
- */
- protected function _customerIsInStore($store)
- {
- $customer = $this->getSession()->getCustomer();
- if ($customer->getWebsiteId() == $store->getWebsiteId()) {
- return true;
- }
- return $customer->isInStore($store);
- }
-
- /**
- * Set and validate Customer data
- *
- * @return $this
- */
- protected function _setCustomerData(Mage_Customer_Model_Customer $customer)
- {
- $form = $this->_getCustomerForm();
- $form->setEntity($customer);
-
- // emulate request
- $request = $form->prepareRequest(['order' => $this->getData()]);
- $data = $form->extractData($request, 'order/account');
- if ($this->getIsValidate()) {
- $errors = $form->validateData($data);
- if ($errors !== true) {
- foreach ($errors as $error) {
- $this->_errors[] = $error;
- }
- $form->restoreData($data);
- } else {
- $form->compactData($data);
- }
- } else {
- $form->restoreData($data);
- }
-
- return $this;
- }
-
/**
* Prepare quote customer
*
@@ -1491,27 +1183,6 @@ public function _prepareCustomer()
return $this;
}
- /**
- * Prepare item options
- */
- protected function _prepareQuoteItems()
- {
- foreach ($this->getQuote()->getAllItems() as $item) {
- $options = [];
- $productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
- if ($productOptions) {
- $productOptions['info_buyRequest']['options'] = $this->_prepareOptionsForRequest($item);
- $options = $productOptions;
- }
- $addOptions = $item->getOptionByCode('additional_options');
- if ($addOptions) {
- $options['additional_options'] = unserialize($addOptions->getValue(), ['allowed_classes' => false]);
- }
- $item->setProductOrderOptions($options);
- }
- return $this;
- }
-
/**
* Create new order
*
@@ -1578,6 +1249,335 @@ public function createOrder()
return $order;
}
+ /**
+ * Retrieve quote item
+ *
+ * @param int|Mage_Sales_Model_Quote_Item $item
+ * @return Mage_Sales_Model_Quote_Item|false
+ */
+ protected function _getQuoteItem($item)
+ {
+ if ($item instanceof Mage_Sales_Model_Quote_Item) {
+ return $item;
+ } elseif (is_numeric($item)) {
+ return $this->getSession()->getQuote()->getItemById($item);
+ }
+ return false;
+ }
+
+ protected function _initBillingAddressFromOrder(Mage_Sales_Model_Order $order)
+ {
+ $this->getQuote()->getBillingAddress()->setCustomerAddressId('');
+ Mage::helper('core')->copyFieldset(
+ 'sales_copy_order_billing_address',
+ 'to_order',
+ $order->getBillingAddress(),
+ $this->getQuote()->getBillingAddress(),
+ );
+ }
+
+ protected function _initShippingAddressFromOrder(Mage_Sales_Model_Order $order)
+ {
+ $orderShippingAddress = $order->getShippingAddress();
+ $quoteShippingAddress = $this->getQuote()->getShippingAddress()
+ ->setCustomerAddressId('')
+ ->setSameAsBilling($orderShippingAddress && $orderShippingAddress->getSameAsBilling());
+ Mage::helper('core')->copyFieldset(
+ 'sales_copy_order_shipping_address',
+ 'to_order',
+ $orderShippingAddress,
+ $quoteShippingAddress,
+ );
+ }
+
+ /**
+ * Parse additional options and sync them with product options
+ *
+ * @param string $additionalOptions
+ * @return array
+ */
+ protected function _parseOptions(Mage_Sales_Model_Quote_Item $item, $additionalOptions)
+ {
+ $productOptions = Mage::getSingleton('catalog/product_option_type_default')
+ ->setProduct($item->getProduct())
+ ->getProductOptions();
+
+ $newOptions = [];
+ $newAdditionalOptions = [];
+
+ foreach (explode("\n", $additionalOptions) as $additionalOption) {
+ if (strlen(trim($additionalOption))) {
+ try {
+ if (!str_contains($additionalOption, ':')) {
+ Mage::throwException(
+ Mage::helper('adminhtml')->__('There is an error in one of the option rows.'),
+ );
+ }
+ list($label, $value) = explode(':', $additionalOption, 2);
+ } catch (Exception $e) {
+ Mage::throwException(Mage::helper('adminhtml')->__('There is an error in one of the option rows.'));
+ }
+ $label = trim($label);
+ $value = trim($value);
+ if (empty($value)) {
+ continue;
+ }
+
+ if (array_key_exists($label, $productOptions)) {
+ $optionId = $productOptions[$label]['option_id'];
+ $option = $item->getProduct()->getOptionById($optionId);
+
+ $group = Mage::getSingleton('catalog/product_option')->groupFactory($option->getType())
+ ->setOption($option)
+ ->setProduct($item->getProduct());
+
+ $parsedValue = $group->parseOptionValue($value, $productOptions[$label]['values']);
+
+ if ($parsedValue !== null) {
+ $newOptions[$optionId] = $parsedValue;
+ } else {
+ $newAdditionalOptions[] = [
+ 'label' => $label,
+ 'value' => $value,
+ ];
+ }
+ } else {
+ $newAdditionalOptions[] = [
+ 'label' => $label,
+ 'value' => $value,
+ ];
+ }
+ }
+ }
+
+ return [
+ 'options' => $newOptions,
+ 'additional_options' => $newAdditionalOptions,
+ ];
+ }
+
+ /**
+ * Assign options to item
+ *
+ * @param array $options
+ * @return $this
+ */
+ protected function _assignOptionsToItem(Mage_Sales_Model_Quote_Item $item, $options)
+ {
+ if ($optionIds = $item->getOptionByCode('option_ids')) {
+ foreach (explode(',', $optionIds->getValue()) as $optionId) {
+ $item->removeOption('option_' . $optionId);
+ }
+ $item->removeOption('option_ids');
+ }
+ if ($item->getOptionByCode('additional_options')) {
+ $item->removeOption('additional_options');
+ }
+ $item->save();
+ if (!empty($options['options'])) {
+ $item->addOption(new Varien_Object(
+ [
+ 'product' => $item->getProduct(),
+ 'code' => 'option_ids',
+ 'value' => implode(',', array_keys($options['options'])),
+ ],
+ ));
+
+ foreach ($options['options'] as $optionId => $optionValue) {
+ $item->addOption(new Varien_Object(
+ [
+ 'product' => $item->getProduct(),
+ 'code' => 'option_' . $optionId,
+ 'value' => $optionValue,
+ ],
+ ));
+ }
+ }
+ if (!empty($options['additional_options'])) {
+ $item->addOption(new Varien_Object(
+ [
+ 'product' => $item->getProduct(),
+ 'code' => 'additional_options',
+ 'value' => serialize($options['additional_options']),
+ ],
+ ));
+ }
+
+ return $this;
+ }
+
+ /**
+ * Prepare options array for info buy request
+ *
+ * @param Mage_Sales_Model_Quote_Item $item
+ * @return array
+ */
+ protected function _prepareOptionsForRequest($item)
+ {
+ $newInfoOptions = [];
+ if ($optionIds = $item->getOptionByCode('option_ids')) {
+ foreach (explode(',', $optionIds->getValue()) as $optionId) {
+ $option = $item->getProduct()->getOptionById($optionId);
+ $optionValue = $item->getOptionByCode('option_' . $optionId)->getValue();
+
+ $group = Mage::getSingleton('catalog/product_option')->groupFactory($option->getType())
+ ->setOption($option)
+ ->setQuoteItem($item);
+
+ $newInfoOptions[$optionId] = $group->prepareOptionValueForRequest($optionValue);
+ }
+ }
+ return $newInfoOptions;
+ }
+
+ protected function _parseCustomPrice($price)
+ {
+ $price = Mage::app()->getLocale()->getNumber($price);
+ return $price > 0 ? $price : 0;
+ }
+
+ /**
+ * Return Customer (Checkout) Form instance
+ *
+ * @return Mage_Customer_Model_Form
+ */
+ protected function _getCustomerForm()
+ {
+ if (is_null($this->_customerForm)) {
+ $this->_customerForm = Mage::getModel('customer/form')
+ ->setFormCode('adminhtml_checkout')
+ ->ignoreInvisible(false);
+ }
+ return $this->_customerForm;
+ }
+
+ /**
+ * Return Customer Address Form instance
+ *
+ * @return Mage_Customer_Model_Form
+ */
+ protected function _getCustomerAddressForm()
+ {
+ if (is_null($this->_customerAddressForm)) {
+ $this->_customerAddressForm = Mage::getModel('customer/form')
+ ->setFormCode('adminhtml_customer_address')
+ ->ignoreInvisible(false);
+ }
+ return $this->_customerAddressForm;
+ }
+
+ /**
+ * Set and validate Quote address
+ * All errors added to _errors
+ *
+ * @return $this
+ */
+ protected function _setQuoteAddress(Mage_Sales_Model_Quote_Address $address, array $data)
+ {
+ $addressForm = $this->_getCustomerAddressForm()
+ ->setEntity($address)
+ ->setEntityType(Mage::getSingleton('eav/config')->getEntityType('customer_address'))
+ ->setIsAjaxRequest(!$this->getIsValidate());
+
+ // prepare request
+ // save original request structure for files
+ if ($address->getAddressType() == Mage_Sales_Model_Quote_Address::TYPE_SHIPPING) {
+ $requestData = ['order' => ['shipping_address' => $data]];
+ $requestScope = 'order/shipping_address';
+ } else {
+ $requestData = ['order' => ['billing_address' => $data]];
+ $requestScope = 'order/billing_address';
+ }
+ $request = $addressForm->prepareRequest($requestData);
+ $addressData = $addressForm->extractData($request, $requestScope);
+ if ($this->getIsValidate()) {
+ $errors = $addressForm->validateData($addressData);
+ if ($errors !== true) {
+ if ($address->getAddressType() == Mage_Sales_Model_Quote_Address::TYPE_SHIPPING) {
+ $typeName = Mage::helper('adminhtml')->__('Shipping Address: ');
+ } else {
+ $typeName = Mage::helper('adminhtml')->__('Billing Address: ');
+ }
+ foreach ($errors as $error) {
+ $this->_errors[] = $typeName . $error;
+ }
+ $addressForm->restoreData($addressData);
+ } else {
+ $addressForm->compactData($addressData);
+ }
+ } else {
+ $addressForm->restoreData($addressData);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Check whether we need to create new customer (for another website) during order creation
+ *
+ * @param Mage_Core_Model_Store $store
+ * @return bool
+ */
+ protected function _customerIsInStore($store)
+ {
+ $customer = $this->getSession()->getCustomer();
+ if ($customer->getWebsiteId() == $store->getWebsiteId()) {
+ return true;
+ }
+ return $customer->isInStore($store);
+ }
+
+ /**
+ * Set and validate Customer data
+ *
+ * @return $this
+ */
+ protected function _setCustomerData(Mage_Customer_Model_Customer $customer)
+ {
+ $form = $this->_getCustomerForm();
+ $form->setEntity($customer);
+
+ // emulate request
+ $request = $form->prepareRequest(['order' => $this->getData()]);
+ $data = $form->extractData($request, 'order/account');
+ if ($this->getIsValidate()) {
+ $errors = $form->validateData($data);
+ if ($errors !== true) {
+ foreach ($errors as $error) {
+ $this->_errors[] = $error;
+ }
+ $form->restoreData($data);
+ } else {
+ $form->compactData($data);
+ }
+ } else {
+ $form->restoreData($data);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Prepare item options
+ */
+ protected function _prepareQuoteItems()
+ {
+ foreach ($this->getQuote()->getAllItems() as $item) {
+ $options = [];
+ $productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
+ if ($productOptions) {
+ $productOptions['info_buyRequest']['options'] = $this->_prepareOptionsForRequest($item);
+ $options = $productOptions;
+ }
+ $addOptions = $item->getOptionByCode('additional_options');
+ if ($addOptions) {
+ $options['additional_options'] = unserialize($addOptions->getValue(), ['allowed_classes' => false]);
+ }
+ $item->setProductOrderOptions($options);
+ }
+ return $this;
+ }
+
/**
* Validate quote data before order creation
*
diff --git a/app/code/core/Mage/Adminhtml/Model/Sales/Order/Random.php b/app/code/core/Mage/Adminhtml/Model/Sales/Order/Random.php
index 28515f15baa..c895c246036 100644
--- a/app/code/core/Mage/Adminhtml/Model/Sales/Order/Random.php
+++ b/app/code/core/Mage/Adminhtml/Model/Sales/Order/Random.php
@@ -48,6 +48,47 @@ public function __construct()
$this->_order = Mage::getModel('sales/order');
}
+ public function render()
+ {
+ $customer = $this->_getCustomer();
+ $this->_quote->setStore($this->_getStore())
+ ->setCustomer($customer);
+ $this->_quote->getBillingAddress()->importCustomerAddress($customer->getDefaultBillingAddress());
+ $this->_quote->getShippingAddress()->importCustomerAddress($customer->getDefaultShippingAddress());
+
+ $productCount = rand(3, 10);
+ for ($i = 0; $i < $productCount; $i++) {
+ $product = $this->_getRandomProduct();
+ if ($product) {
+ $product->setQuoteQty(1);
+ $this->_quote->addCatalogProduct($product);
+ }
+ }
+ $this->_quote->getPayment()->setMethod('checkmo');
+
+ $this->_quote->getShippingAddress()->setShippingMethod('freeshipping_freeshipping');//->collectTotals()->save();
+ $this->_quote->getShippingAddress()->setCollectShippingRates(true);
+ $this->_quote->collectTotals()
+ ->save();
+ $this->_quote->save();
+ return $this;
+ }
+
+ public function save()
+ {
+ $this->_order->setStoreId($this->_getStore()->getId());
+ $this->_order->createFromQuoteAddress($this->_quote->getShippingAddress());
+ $this->_order->validate();
+ $this->_order->setInitialStatus();
+ $this->_order->save();
+ $this->_order->setCreatedAt($this->_getRandomDate());
+ $this->_order->save();
+
+ $this->_quote->setIsActive(false);
+ $this->_quote->save();
+ return $this;
+ }
+
protected function _getStores()
{
if (!self::$_storeCollection) {
@@ -117,50 +158,9 @@ protected function _getStore()
return $this->_store;
}
- public function render()
- {
- $customer = $this->_getCustomer();
- $this->_quote->setStore($this->_getStore())
- ->setCustomer($customer);
- $this->_quote->getBillingAddress()->importCustomerAddress($customer->getDefaultBillingAddress());
- $this->_quote->getShippingAddress()->importCustomerAddress($customer->getDefaultShippingAddress());
-
- $productCount = rand(3, 10);
- for ($i = 0; $i < $productCount; $i++) {
- $product = $this->_getRandomProduct();
- if ($product) {
- $product->setQuoteQty(1);
- $this->_quote->addCatalogProduct($product);
- }
- }
- $this->_quote->getPayment()->setMethod('checkmo');
-
- $this->_quote->getShippingAddress()->setShippingMethod('freeshipping_freeshipping');//->collectTotals()->save();
- $this->_quote->getShippingAddress()->setCollectShippingRates(true);
- $this->_quote->collectTotals()
- ->save();
- $this->_quote->save();
- return $this;
- }
-
protected function _getRandomDate()
{
$timestamp = mktime(rand(0, 23), rand(0, 59), 0, rand(1, 11), rand(1, 28), rand(2006, 2007));
return date(Varien_Date::DATETIME_PHP_FORMAT, $timestamp);
}
-
- public function save()
- {
- $this->_order->setStoreId($this->_getStore()->getId());
- $this->_order->createFromQuoteAddress($this->_quote->getShippingAddress());
- $this->_order->validate();
- $this->_order->setInitialStatus();
- $this->_order->save();
- $this->_order->setCreatedAt($this->_getRandomDate());
- $this->_order->save();
-
- $this->_quote->setIsActive(false);
- $this->_quote->save();
- return $this;
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custom.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custom.php
index c3f4dc4b054..d3d099ba908 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custom.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custom.php
@@ -30,23 +30,6 @@ class Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom extends Mage_Core_
public const XML_PATH_UNSECURE_BASE_LINK_URL = 'web/unsecure/base_link_url';
public const XML_PATH_SECURE_BASE_LINK_URL = 'web/secure/base_link_url';
- /**
- * Validate value before save
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- $value = $this->getValue();
-
- if (!empty($value) && substr($value, -2) !== '}}') {
- $value = rtrim($value, '/') . '/';
- }
-
- $this->setValue($value);
- return $this;
- }
-
/**
* Change secure/unsecure base_url after use_custom_url was modified
*
@@ -78,4 +61,21 @@ public function _afterSave()
return $this;
}
+
+ /**
+ * Validate value before save
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ $value = $this->getValue();
+
+ if (!empty($value) && substr($value, -2) !== '}}') {
+ $value = rtrim($value, '/') . '/';
+ }
+
+ $this->setValue($value);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Encrypted.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Encrypted.php
index 4c4399122e5..3787c9ebbad 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Encrypted.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Encrypted.php
@@ -22,6 +22,15 @@
*/
class Mage_Adminhtml_Model_System_Config_Backend_Encrypted extends Mage_Core_Model_Config_Data
{
+ /**
+ * Get & decrypt old value from configuration
+ *
+ * @return string
+ */
+ public function getOldValue()
+ {
+ return Mage::helper('core')->decrypt(parent::getOldValue());
+ }
/**
* Decrypt value after loading
*/
@@ -50,14 +59,4 @@ protected function _beforeSave()
}
return $this;
}
-
- /**
- * Get & decrypt old value from configuration
- *
- * @return string
- */
- public function getOldValue()
- {
- return Mage::helper('core')->decrypt(parent::getOldValue());
- }
}
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/File.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/File.php
index d0365d8c504..fe39cb19013 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/File.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/File.php
@@ -31,6 +31,19 @@ class Mage_Adminhtml_Model_System_Config_Backend_File extends Mage_Core_Model_Co
*/
protected $_maxFileSize = 0;
+ /**
+ * Validation callback for checking max file size
+ *
+ * @param string $filePath Path to temporary uploaded file
+ * @throws Mage_Core_Exception
+ */
+ public function validateMaxSize($filePath)
+ {
+ if ($this->_maxFileSize > 0 && filesize($filePath) > ($this->_maxFileSize * 1024)) {
+ throw Mage::exception('Mage_Core', Mage::helper('adminhtml')->__('Uploaded file is larger than %.2f kilobytes allowed by server', $this->_maxFileSize));
+ }
+ }
+
/**
* Save uploaded file before saving config value
*
@@ -79,19 +92,6 @@ protected function _beforeSave()
return $this;
}
- /**
- * Validation callback for checking max file size
- *
- * @param string $filePath Path to temporary uploaded file
- * @throws Mage_Core_Exception
- */
- public function validateMaxSize($filePath)
- {
- if ($this->_maxFileSize > 0 && filesize($filePath) > ($this->_maxFileSize * 1024)) {
- throw Mage::exception('Mage_Core', Mage::helper('adminhtml')->__('Uploaded file is larger than %.2f kilobytes allowed by server', $this->_maxFileSize));
- }
- }
-
/**
* Makes a decision about whether to add info about the scope.
*
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Cron/Frequency.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Cron/Frequency.php
index 7b17b4ab579..39e1b4d8f38 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Cron/Frequency.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Cron/Frequency.php
@@ -20,11 +20,10 @@
*/
class Mage_Adminhtml_Model_System_Config_Source_Cron_Frequency
{
- protected static $_options;
-
public const CRON_DAILY = 'D';
public const CRON_WEEKLY = 'W';
public const CRON_MONTHLY = 'M';
+ protected static $_options;
public function toOptionArray()
{
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Storage/Media/Database.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Storage/Media/Database.php
index b63abf55b06..a847af6de0c 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Storage/Media/Database.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Storage/Media/Database.php
@@ -29,30 +29,6 @@ class Mage_Adminhtml_Model_System_Config_Source_Storage_Media_Database
*/
protected $_connections = [];
- /**
- * Recursively collect connection configuration
- *
- * @param string $connectionName
- * @return array
- */
- protected function _collectConnectionConfig($connectionName)
- {
- $config = [];
-
- if (isset($this->_connections[$connectionName])) {
- $connection = $this->_connections[$connectionName];
- $connection = (array) $connection->descend('connection');
-
- if (isset($connection['use'])) {
- $config = $this->_collectConnectionConfig((string) $connection['use']);
- }
-
- $config = array_merge($config, $connection);
- }
-
- return $config;
- }
-
/**
* Options getter
*
@@ -76,4 +52,28 @@ public function toOptionArray()
return $mediaStorages;
}
+
+ /**
+ * Recursively collect connection configuration
+ *
+ * @param string $connectionName
+ * @return array
+ */
+ protected function _collectConnectionConfig($connectionName)
+ {
+ $config = [];
+
+ if (isset($this->_connections[$connectionName])) {
+ $connection = $this->_connections[$connectionName];
+ $connection = (array) $connection->descend('connection');
+
+ if (isset($connection['use'])) {
+ $config = $this->_collectConnectionConfig((string) $connection['use']);
+ }
+
+ $config = array_merge($config, $connection);
+ }
+
+ return $config;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Store.php b/app/code/core/Mage/Adminhtml/Model/System/Store.php
index 18c831a35e6..750f0c0a828 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Store.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Store.php
@@ -61,44 +61,6 @@ public function __construct()
$this->reload();
}
- /**
- * Load/Reload Website collection
- *
- * @return $this
- */
- protected function _loadWebsiteCollection()
- {
- $this->_websiteCollection = Mage::app()->getWebsites();
- return $this;
- }
-
- /**
- * Load/Reload Group collection
- *
- * @return $this
- */
- protected function _loadGroupCollection()
- {
- $this->_groupCollection = [];
- foreach (Mage::app()->getWebsites() as $website) {
- foreach ($website->getGroups() as $group) {
- $this->_groupCollection[$group->getId()] = $group;
- }
- }
- return $this;
- }
-
- /**
- * Load/Reload Store collection
- *
- * @return $this
- */
- protected function _loadStoreCollection()
- {
- $this->_storeCollection = Mage::app()->getStores();
- return $this;
- }
-
/**
* Retrieve store values for form
*
@@ -486,4 +448,42 @@ public function setIsAdminScopeAllowed($value)
$this->_isAdminScopeAllowed = (bool) $value;
return $this;
}
+
+ /**
+ * Load/Reload Website collection
+ *
+ * @return $this
+ */
+ protected function _loadWebsiteCollection()
+ {
+ $this->_websiteCollection = Mage::app()->getWebsites();
+ return $this;
+ }
+
+ /**
+ * Load/Reload Group collection
+ *
+ * @return $this
+ */
+ protected function _loadGroupCollection()
+ {
+ $this->_groupCollection = [];
+ foreach (Mage::app()->getWebsites() as $website) {
+ foreach ($website->getGroups() as $group) {
+ $this->_groupCollection[$group->getId()] = $group;
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Load/Reload Store collection
+ *
+ * @return $this
+ */
+ protected function _loadStoreCollection()
+ {
+ $this->_storeCollection = Mage::app()->getStores();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Api/RoleController.php b/app/code/core/Mage/Adminhtml/controllers/Api/RoleController.php
index a46ef0926e3..3618341381a 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Api/RoleController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Api/RoleController.php
@@ -39,16 +39,6 @@ public function preDispatch()
return parent::preDispatch();
}
- protected function _initAction()
- {
- $this->loadLayout();
- $this->_setActiveMenu('system/api/roles');
- $this->_addBreadcrumb($this->__('Web services'), $this->__('Web services'));
- $this->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'));
- $this->_addBreadcrumb($this->__('Roles'), $this->__('Roles'));
- return $this;
- }
-
public function indexAction()
{
$this->_title($this->__('System'))
@@ -206,6 +196,16 @@ public function editrolegridAction()
$this->getResponse()->setBody($this->getLayout()->createBlock('adminhtml/api_role_grid_user')->toHtml());
}
+ protected function _initAction()
+ {
+ $this->loadLayout();
+ $this->_setActiveMenu('system/api/roles');
+ $this->_addBreadcrumb($this->__('Web services'), $this->__('Web services'));
+ $this->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'));
+ $this->_addBreadcrumb($this->__('Roles'), $this->__('Roles'));
+ return $this;
+ }
+
protected function _deleteUserFromRole($userId, $roleId)
{
try {
diff --git a/app/code/core/Mage/Adminhtml/controllers/Api/UserController.php b/app/code/core/Mage/Adminhtml/controllers/Api/UserController.php
index a92e73c277d..aff1b7d5f4a 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Api/UserController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Api/UserController.php
@@ -37,17 +37,6 @@ public function preDispatch()
return parent::preDispatch();
}
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('system/api/users')
- ->_addBreadcrumb($this->__('Web Services'), $this->__('Web Services'))
- ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
- ->_addBreadcrumb($this->__('Users'), $this->__('Users'))
- ;
- return $this;
- }
-
public function indexAction()
{
$this->_title($this->__('System'))
@@ -235,4 +224,15 @@ public function roleGridAction()
->createBlock('adminhtml/api_user_grid')
->toHtml());
}
+
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('system/api/users')
+ ->_addBreadcrumb($this->__('Web Services'), $this->__('Web Services'))
+ ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
+ ->_addBreadcrumb($this->__('Users'), $this->__('Users'))
+ ;
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/CacheController.php b/app/code/core/Mage/Adminhtml/controllers/CacheController.php
index 08fce26bdb7..fe028d11ec5 100644
--- a/app/code/core/Mage/Adminhtml/controllers/CacheController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/CacheController.php
@@ -26,16 +26,6 @@ class Mage_Adminhtml_CacheController extends Mage_Adminhtml_Controller_Action
*/
public const ADMIN_RESOURCE = 'system/cache';
- /**
- * Retrieve session model
- *
- * @return Mage_Adminhtml_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('adminhtml/session');
- }
-
/**
* Display cache management grid
*/
@@ -211,4 +201,14 @@ public function cleanSwatchesAction()
}
$this->_redirect('*/*');
}
+
+ /**
+ * Retrieve session model
+ *
+ * @return Mage_Adminhtml_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('adminhtml/session');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php
index a38e1bd1aa5..fa201e8b12b 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php
@@ -27,50 +27,6 @@ class Mage_Adminhtml_Catalog_CategoryController extends Mage_Adminhtml_Controlle
* @see Mage_Adminhtml_Controller_Action::_isAllowed()
*/
public const ADMIN_RESOURCE = 'catalog/categories';
-
- /**
- * Initialize requested category and put it into registry.
- * Root category can be returned, if inappropriate store/category is specified
- *
- * @param bool $getRootInstead
- * @return Mage_Catalog_Model_Category|false
- */
- protected function _initCategory($getRootInstead = false)
- {
- $this->_title($this->__('Catalog'))
- ->_title($this->__('Categories'))
- ->_title($this->__('Manage Categories'));
-
- $categoryId = (int) $this->getRequest()->getParam('id', false);
- $storeId = (int) $this->getRequest()->getParam('store');
- $category = Mage::getModel('catalog/category');
- $category->setStoreId($storeId);
-
- if ($categoryId) {
- $category->load($categoryId);
- if ($storeId) {
- $rootId = Mage::app()->getStore($storeId)->getRootCategoryId();
- if (!in_array($rootId, $category->getPathIds())) {
- // load root category instead wrong one
- if ($getRootInstead) {
- $category->load($rootId);
- } else {
- $this->_redirect('*/*/', ['_current' => true, 'id' => null]);
- return false;
- }
- }
- }
- }
-
- if ($activeTabId = (string) $this->getRequest()->getParam('active_tab_id')) {
- Mage::getSingleton('admin/session')->setActiveTabId($activeTabId);
- }
-
- Mage::register('category', $category);
- Mage::register('current_category', $category);
- Mage::getSingleton('cms/wysiwyg_config')->setStoreId($this->getRequest()->getParam('store'));
- return $category;
- }
/**
* Catalog categories index action
*/
@@ -489,4 +445,48 @@ public function preDispatch()
$this->_setForcedFormKeyActions('delete');
return parent::preDispatch();
}
+
+ /**
+ * Initialize requested category and put it into registry.
+ * Root category can be returned, if inappropriate store/category is specified
+ *
+ * @param bool $getRootInstead
+ * @return Mage_Catalog_Model_Category|false
+ */
+ protected function _initCategory($getRootInstead = false)
+ {
+ $this->_title($this->__('Catalog'))
+ ->_title($this->__('Categories'))
+ ->_title($this->__('Manage Categories'));
+
+ $categoryId = (int) $this->getRequest()->getParam('id', false);
+ $storeId = (int) $this->getRequest()->getParam('store');
+ $category = Mage::getModel('catalog/category');
+ $category->setStoreId($storeId);
+
+ if ($categoryId) {
+ $category->load($categoryId);
+ if ($storeId) {
+ $rootId = Mage::app()->getStore($storeId)->getRootCategoryId();
+ if (!in_array($rootId, $category->getPathIds())) {
+ // load root category instead wrong one
+ if ($getRootInstead) {
+ $category->load($rootId);
+ } else {
+ $this->_redirect('*/*/', ['_current' => true, 'id' => null]);
+ return false;
+ }
+ }
+ }
+ }
+
+ if ($activeTabId = (string) $this->getRequest()->getParam('active_tab_id')) {
+ Mage::getSingleton('admin/session')->setActiveTabId($activeTabId);
+ }
+
+ Mage::register('category', $category);
+ Mage::register('current_category', $category);
+ Mage::getSingleton('cms/wysiwyg_config')->setStoreId($this->getRequest()->getParam('store'));
+ return $category;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/Action/AttributeController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/Action/AttributeController.php
index 18280d329cd..b0da457bdaa 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/Action/AttributeController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/Action/AttributeController.php
@@ -28,12 +28,6 @@ class Mage_Adminhtml_Catalog_Product_Action_AttributeController extends Mage_Adm
*/
public const ADMIN_RESOURCE = 'catalog/update_attributes';
- protected function _construct()
- {
- // Define module dependent translate
- $this->setUsedModuleName('Mage_Catalog');
- }
-
public function editAction()
{
if (!$this->_validateProducts()) {
@@ -188,39 +182,6 @@ public function saveAction()
$this->_redirect('*/catalog_product/', ['store' => $this->_getHelper()->getSelectedStoreId()]);
}
- /**
- * Validate selection of products for massupdate
- *
- * @return bool
- */
- protected function _validateProducts()
- {
- $error = false;
- $productIds = $this->_getHelper()->getProductIds();
- if (!is_array($productIds)) {
- $error = $this->__('Please select products for attributes update');
- } elseif (!Mage::getModel('catalog/product')->isProductsHasSku($productIds)) {
- $error = $this->__('Some of the processed products have no SKU value defined. Please fill it prior to performing operations on these products.');
- }
-
- if ($error) {
- $this->_getSession()->addError($error);
- $this->_redirect('*/catalog_product/', ['_current' => true]);
- }
-
- return !$error;
- }
-
- /**
- * Retrieve data manipulation helper
- *
- * @return Mage_Adminhtml_Helper_Catalog_Product_Edit_Action_Attribute
- */
- protected function _getHelper()
- {
- return Mage::helper('adminhtml/catalog_product_edit_action_attribute');
- }
-
/**
* Attributes validation action
*
@@ -264,4 +225,43 @@ public function validateAction()
$this->getResponse()->setBody($response->toJson());
}
+
+ protected function _construct()
+ {
+ // Define module dependent translate
+ $this->setUsedModuleName('Mage_Catalog');
+ }
+
+ /**
+ * Validate selection of products for massupdate
+ *
+ * @return bool
+ */
+ protected function _validateProducts()
+ {
+ $error = false;
+ $productIds = $this->_getHelper()->getProductIds();
+ if (!is_array($productIds)) {
+ $error = $this->__('Please select products for attributes update');
+ } elseif (!Mage::getModel('catalog/product')->isProductsHasSku($productIds)) {
+ $error = $this->__('Some of the processed products have no SKU value defined. Please fill it prior to performing operations on these products.');
+ }
+
+ if ($error) {
+ $this->_getSession()->addError($error);
+ $this->_redirect('*/catalog_product/', ['_current' => true]);
+ }
+
+ return !$error;
+ }
+
+ /**
+ * Retrieve data manipulation helper
+ *
+ * @return Mage_Adminhtml_Helper_Catalog_Product_Edit_Action_Attribute
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('adminhtml/catalog_product_edit_action_attribute');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/AttributeController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/AttributeController.php
index 40e1487c5f4..5bb7f14ca03 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/AttributeController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/AttributeController.php
@@ -22,8 +22,6 @@
*/
class Mage_Adminhtml_Catalog_Product_AttributeController extends Mage_Adminhtml_Controller_Action
{
- protected $_entityTypeId;
-
/**
* ACL resource
* @see Mage_Adminhtml_Controller_Action::_isAllowed()
@@ -34,16 +32,7 @@ class Mage_Adminhtml_Catalog_Product_AttributeController extends Mage_Adminhtml_
* List of tags from setting
*/
public const XML_PATH_ALLOWED_TAGS = 'system/catalog/frontend/allowed_html_tags_list';
-
- /**
- * Get list of allowed text formatted as array
- *
- * @return array
- */
- protected function _getAllowedTags()
- {
- return explode(',', Mage::getStoreConfig(self::XML_PATH_ALLOWED_TAGS));
- }
+ protected $_entityTypeId;
public function preDispatch()
{
@@ -53,27 +42,6 @@ public function preDispatch()
return $this;
}
- protected function _initAction()
- {
- $this->_title($this->__('Catalog'))
- ->_title($this->__('Attributes'))
- ->_title($this->__('Manage Attributes'));
-
- if ($this->getRequest()->getParam('popup')) {
- $this->loadLayout('popup');
- } else {
- $this->loadLayout()
- ->_setActiveMenu('catalog/attributes/attributes')
- ->_addBreadcrumb(Mage::helper('catalog')->__('Catalog'), Mage::helper('catalog')->__('Catalog'))
- ->_addBreadcrumb(
- Mage::helper('catalog')->__('Manage Product Attributes'),
- Mage::helper('catalog')->__('Manage Product Attributes'),
- )
- ;
- }
- return $this;
- }
-
public function indexAction()
{
$this->_initAction()
@@ -157,39 +125,6 @@ public function validateAction()
$this->getResponse()->setBody($response->toJson());
}
- /**
- * Filter post data
- *
- * @param array $data
- * @return array
- */
- protected function _filterPostData($data)
- {
- if ($data) {
- /** @var Mage_Catalog_Helper_Data $helperCatalog */
- $helperCatalog = Mage::helper('catalog');
- //labels
- $data['frontend_label'] = (array) $data['frontend_label'];
- foreach ($data['frontend_label'] as & $value) {
- if ($value) {
- $value = $helperCatalog->stripTags($value);
- }
- }
-
- if (!empty($data['option']) && !empty($data['option']['value']) && is_array($data['option']['value'])) {
- $allowableTags = isset($data['is_html_allowed_on_front']) && $data['is_html_allowed_on_front']
- ? sprintf('<%s>', implode('><', $this->_getAllowedTags())) : null;
- foreach ($data['option']['value'] as $key => $values) {
- foreach ($values as $storeId => $storeLabel) {
- $data['option']['value'][$key][$storeId]
- = $helperCatalog->stripTags($storeLabel, $allowableTags);
- }
- }
- }
- }
- return $data;
- }
-
public function saveAction()
{
$data = $this->getRequest()->getPost();
@@ -372,4 +307,68 @@ public function deleteAction()
);
$this->_redirect('*/*/');
}
+
+ /**
+ * Get list of allowed text formatted as array
+ *
+ * @return array
+ */
+ protected function _getAllowedTags()
+ {
+ return explode(',', Mage::getStoreConfig(self::XML_PATH_ALLOWED_TAGS));
+ }
+
+ protected function _initAction()
+ {
+ $this->_title($this->__('Catalog'))
+ ->_title($this->__('Attributes'))
+ ->_title($this->__('Manage Attributes'));
+
+ if ($this->getRequest()->getParam('popup')) {
+ $this->loadLayout('popup');
+ } else {
+ $this->loadLayout()
+ ->_setActiveMenu('catalog/attributes/attributes')
+ ->_addBreadcrumb(Mage::helper('catalog')->__('Catalog'), Mage::helper('catalog')->__('Catalog'))
+ ->_addBreadcrumb(
+ Mage::helper('catalog')->__('Manage Product Attributes'),
+ Mage::helper('catalog')->__('Manage Product Attributes'),
+ )
+ ;
+ }
+ return $this;
+ }
+
+ /**
+ * Filter post data
+ *
+ * @param array $data
+ * @return array
+ */
+ protected function _filterPostData($data)
+ {
+ if ($data) {
+ /** @var Mage_Catalog_Helper_Data $helperCatalog */
+ $helperCatalog = Mage::helper('catalog');
+ //labels
+ $data['frontend_label'] = (array) $data['frontend_label'];
+ foreach ($data['frontend_label'] as & $value) {
+ if ($value) {
+ $value = $helperCatalog->stripTags($value);
+ }
+ }
+
+ if (!empty($data['option']) && !empty($data['option']['value']) && is_array($data['option']['value'])) {
+ $allowableTags = isset($data['is_html_allowed_on_front']) && $data['is_html_allowed_on_front']
+ ? sprintf('<%s>', implode('><', $this->_getAllowedTags())) : null;
+ foreach ($data['option']['value'] as $key => $values) {
+ foreach ($values as $storeId => $storeLabel) {
+ $data['option']['value'][$key][$storeId]
+ = $helperCatalog->stripTags($storeLabel, $allowableTags);
+ }
+ }
+ }
+ }
+ return $data;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
index e8a68682eae..3e996275eae 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
@@ -51,134 +51,6 @@ public function preDispatch()
return parent::preDispatch();
}
- protected function _construct()
- {
- // Define module dependent translate
- $this->setUsedModuleName('Mage_Catalog');
- }
-
- /**
- * Initialize product from request parameters
- *
- * @return Mage_Catalog_Model_Product
- * @throws Mage_Core_Exception
- */
- protected function _initProduct()
- {
- $this->_title($this->__('Catalog'))
- ->_title($this->__('Manage Products'));
-
- $productId = (int) $this->getRequest()->getParam('id');
- $product = Mage::getModel('catalog/product')
- ->setStoreId($this->getRequest()->getParam('store', 0));
-
- if (!$productId) {
- if ($setId = (int) $this->getRequest()->getParam('set')) {
- $product->setAttributeSetId($setId);
- }
-
- if ($typeId = $this->getRequest()->getParam('type')) {
- $product->setTypeId($typeId);
- }
- }
-
- $product->setData('_edit_mode', true);
- if ($productId) {
- try {
- $product->load($productId);
- } catch (Exception $e) {
- $product->setTypeId(Mage_Catalog_Model_Product_Type::DEFAULT_TYPE);
- Mage::logException($e);
- }
- }
-
- $attributes = $this->getRequest()->getParam('attributes');
- if ($attributes && $product->isConfigurable()) {
- /** @var Mage_Catalog_Model_Product_Type_Configurable $productType */
- $productType = $product->getTypeInstance();
- if (!$productId || !$productType->getUsedProductAttributeIds()) {
- $productType->setUsedProductAttributeIds(
- explode(',', base64_decode(urldecode($attributes))),
- );
- }
- }
-
- // Required attributes of simple product for configurable creation
- if ($this->getRequest()->getParam('popup')
- && $requiredAttributes = $this->getRequest()->getParam('required')
- ) {
- $requiredAttributes = explode(',', $requiredAttributes);
- foreach ($product->getAttributes() as $attribute) {
- if (in_array($attribute->getId(), $requiredAttributes)) {
- $attribute->setIsRequired(1);
- }
- }
- }
-
- if ($this->getRequest()->getParam('popup')
- && $this->getRequest()->getParam('product')
- && !is_array($this->getRequest()->getParam('product'))
- && $this->getRequest()->getParam('id', false) === false
- ) {
- $configProduct = Mage::getModel('catalog/product')
- ->setStoreId(0)
- ->load($this->getRequest()->getParam('product'))
- ->setTypeId($this->getRequest()->getParam('type'));
-
- /** @var Mage_Catalog_Model_Product $configProduct */
- $data = [];
- // phpcs:ignore Ecg.Performance.Loop.DataLoad
- foreach ($configProduct->getTypeInstance()->getEditableAttributes() as $attribute) {
- /** @var Mage_Catalog_Model_Resource_Eav_Attribute $attribute */
- if (!$attribute->getIsUnique()
- && $attribute->getFrontend()->getInputType() != 'gallery'
- && $attribute->getAttributeCode() != 'required_options'
- && $attribute->getAttributeCode() != 'has_options'
- && $attribute->getAttributeCode() != $configProduct->getIdFieldName()
- ) {
- $data[$attribute->getAttributeCode()] = $configProduct->getData($attribute->getAttributeCode());
- }
- }
-
- $product->addData($data)
- ->setWebsiteIds($configProduct->getWebsiteIds());
- }
-
- Mage::register('product', $product);
- Mage::register('current_product', $product);
- Mage::getSingleton('cms/wysiwyg_config')->setStoreId($this->getRequest()->getParam('store'));
- return $product;
- }
-
- /**
- * Create serializer block for a grid
- *
- * @param string $inputName
- * @param array $productsArray
- * @return Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Ajax_Serializer
- */
- protected function _createSerializerBlock($inputName, Mage_Adminhtml_Block_Widget_Grid $gridBlock, $productsArray)
- {
- return $this->getLayout()->createBlock('adminhtml/catalog_product_edit_tab_ajax_serializer')
- ->setGridBlock($gridBlock)
- ->setProducts($productsArray)
- ->setInputElementName($inputName)
- ;
- }
-
- /**
- * Output specified blocks as a text list
- */
- protected function _outputBlocks()
- {
- $blocks = func_get_args();
- $output = $this->getLayout()->createBlock('adminhtml/text_list');
- foreach ($blocks as $block) {
- $output->insert($block, '', true);
- }
- $this->getResponse()->setBody($output->toHtml());
- }
-
/**
* Product list page
*/
@@ -568,292 +440,115 @@ public function validateAction()
$this->getResponse()->setBody($response->toJson());
}
+ public function categoriesJsonAction()
+ {
+ $product = $this->_initProduct();
+
+ $this->getResponse()->setBody(
+ $this->getLayout()->createBlock('adminhtml/catalog_product_edit_tab_categories')
+ ->getCategoryChildrenJson($this->getRequest()->getParam('category')),
+ );
+ }
+
/**
- * Initialize product before saving
- * @throws Mage_Core_Exception|Zend_Json_Exception
+ * Save product action
*/
- protected function _initProductSave()
+ public function saveAction()
{
- $product = $this->_initProduct();
- $productData = $this->getRequest()->getPost('product');
- if ($productData) {
- $this->_filterStockData($productData['stock_data']);
- }
+ $storeId = $this->getRequest()->getParam('store');
+ $redirectBack = $this->getRequest()->getParam('back', false);
+ $productId = $this->getRequest()->getParam('id');
+ $isEdit = (int) ($this->getRequest()->getParam('id') != null);
- if (!isset($productData['website_ids'])) {
- $productData['website_ids'] = [];
- }
+ $data = $this->getRequest()->getPost();
+ if ($data) {
+ $this->_filterStockData($data['product']['stock_data']);
- $wasLockedMedia = false;
- if ($product->isLockedAttribute('media')) {
- $product->unlockAttribute('media');
- $wasLockedMedia = true;
- }
+ $product = $this->_initProductSave();
+ // check sku attribute
+ $productSku = $product->getSku();
+ if ($productSku && $productSku != Mage::helper('core')->stripTags($productSku)) {
+ $this->_getSession()->addError($this->__('HTML tags are not allowed in SKU attribute.'));
+ $this->_redirect('*/*/edit', [
+ 'id' => $productId,
+ '_current' => true,
+ ]);
+ return;
+ }
- $product->addData($productData);
+ try {
+ $product->validate();
+ $product->save();
+ $productId = $product->getId();
- if ($wasLockedMedia) {
- $product->lockAttribute('media');
+ if (isset($data['copy_to_stores'])) {
+ $this->_copyAttributesBetweenStores($data['copy_to_stores'], $product);
+ }
+
+ $this->_getSession()->addSuccess($this->__('The product has been saved.'));
+ } catch (Mage_Core_Exception $e) {
+ $this->_getSession()->addError($e->getMessage())
+ ->setProductData($data);
+ $redirectBack = true;
+ } catch (Exception $e) {
+ Mage::logException($e);
+ $this->_getSession()->addError($e->getMessage());
+ $redirectBack = true;
+ }
}
- if (Mage::app()->isSingleStoreMode()) {
- $product->setWebsiteIds([Mage::app()->getStore(true)->getWebsite()->getId()]);
+ if ($redirectBack) {
+ $this->_redirect('*/*/edit', [
+ 'id' => $productId,
+ '_current' => true,
+ ]);
+ } elseif ($this->getRequest()->getParam('popup')) {
+ $this->_redirect('*/*/created', [
+ '_current' => true,
+ 'id' => $productId,
+ 'edit' => $isEdit,
+ ]);
+ } else {
+ $this->_redirect('*/*/', ['store' => $storeId]);
}
+ }
- /**
- * Create Permanent Redirect for old URL key
- */
- if ($product->getId() && isset($productData['url_key_create_redirect'])) {
- $product->setData('save_rewrites_history', (bool) $productData['url_key_create_redirect']);
+ /**
+ * Create product duplicate
+ * @throws Mage_Core_Exception
+ */
+ public function duplicateAction()
+ {
+ $product = $this->_initProduct();
+ try {
+ $newProduct = $product->duplicate();
+ $this->_getSession()->addSuccess($this->__('The product has been duplicated.'));
+ $this->_redirect('*/*/edit', ['_current' => true, 'id' => $newProduct->getId()]);
+ } catch (Exception $e) {
+ Mage::logException($e);
+ $this->_getSession()->addError($e->getMessage());
+ $this->_redirect('*/*/edit', ['_current' => true]);
}
+ }
- /**
- * Check "Use Default Value" checkboxes values
- */
- if ($useDefaults = $this->getRequest()->getPost('use_default')) {
- foreach ($useDefaults as $attributeCode) {
- $product->setData($attributeCode, false);
+ /**
+ * Delete product action
+ */
+ public function deleteAction()
+ {
+ if ($id = $this->getRequest()->getParam('id')) {
+ $product = Mage::getModel('catalog/product')
+ ->load($id);
+ try {
+ $product->delete();
+ $this->_getSession()->addSuccess($this->__('The product has been deleted.'));
+ } catch (Exception $e) {
+ $this->_getSession()->addError($e->getMessage());
}
}
-
- /**
- * Init product links data (related, upsell, crosssel)
- */
- $links = $this->getRequest()->getPost('links');
- if (isset($links['related']) && !$product->getRelatedReadonly()) {
- $product->setRelatedLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['related']));
- }
- if (isset($links['upsell']) && !$product->getUpsellReadonly()) {
- $product->setUpSellLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['upsell']));
- }
- if (isset($links['crosssell']) && !$product->getCrosssellReadonly()) {
- $product->setCrossSellLinkData(Mage::helper('adminhtml/js')
- ->decodeGridSerializedInput($links['crosssell']));
- }
- if (isset($links['grouped']) && !$product->getGroupedReadonly()) {
- $product->setGroupedLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['grouped']));
- }
-
- /**
- * Initialize product categories
- */
- $categoryIds = $this->getRequest()->getPost('category_ids');
- if ($categoryIds !== null) {
- if (empty($categoryIds)) {
- $categoryIds = [];
- }
- $product->setCategoryIds($categoryIds);
- }
-
- /**
- * Initialize data for configurable product
- */
- if (($data = $this->getRequest()->getPost('configurable_products_data'))
- && !$product->getConfigurableReadonly()
- ) {
- $product->setConfigurableProductsData(Mage::helper('core')->jsonDecode($data));
- }
- if (($data = $this->getRequest()->getPost('configurable_attributes_data'))
- && !$product->getConfigurableReadonly()
- ) {
- $product->setConfigurableAttributesData(Mage::helper('core')->jsonDecode($data));
- }
-
- $product->setCanSaveConfigurableAttributes(
- (bool) $this->getRequest()->getPost('affect_configurable_product_attributes')
- && !$product->getConfigurableReadonly(),
- );
-
- /**
- * Initialize product options
- */
- if (isset($productData['options']) && !$product->getOptionsReadonly()) {
- $product->setProductOptions($productData['options']);
- }
-
- $product->setCanSaveCustomOptions(
- (bool) $this->getRequest()->getPost('affect_product_custom_options')
- && !$product->getOptionsReadonly(),
- );
-
- Mage::dispatchEvent(
- 'catalog_product_prepare_save',
- ['product' => $product, 'request' => $this->getRequest()],
- );
-
- return $product;
- }
-
- /**
- * Filter product stock data
- *
- * @param array $stockData
- */
- protected function _filterStockData(&$stockData)
- {
- if (is_null($stockData)) {
- return;
- }
- if (!isset($stockData['use_config_manage_stock'])) {
- $stockData['use_config_manage_stock'] = 0;
- }
- if (isset($stockData['qty']) && (float) $stockData['qty'] > self::MAX_QTY_VALUE) {
- $stockData['qty'] = self::MAX_QTY_VALUE;
- }
- if (isset($stockData['min_qty']) && (int) $stockData['min_qty'] < 0) {
- $stockData['min_qty'] = 0;
- }
- if (!isset($stockData['is_decimal_divided']) || $stockData['is_qty_decimal'] == 0) {
- $stockData['is_decimal_divided'] = 0;
- }
- }
-
- public function categoriesJsonAction()
- {
- $product = $this->_initProduct();
-
- $this->getResponse()->setBody(
- $this->getLayout()->createBlock('adminhtml/catalog_product_edit_tab_categories')
- ->getCategoryChildrenJson($this->getRequest()->getParam('category')),
- );
- }
-
- /**
- * Save product action
- */
- public function saveAction()
- {
- $storeId = $this->getRequest()->getParam('store');
- $redirectBack = $this->getRequest()->getParam('back', false);
- $productId = $this->getRequest()->getParam('id');
- $isEdit = (int) ($this->getRequest()->getParam('id') != null);
-
- $data = $this->getRequest()->getPost();
- if ($data) {
- $this->_filterStockData($data['product']['stock_data']);
-
- $product = $this->_initProductSave();
- // check sku attribute
- $productSku = $product->getSku();
- if ($productSku && $productSku != Mage::helper('core')->stripTags($productSku)) {
- $this->_getSession()->addError($this->__('HTML tags are not allowed in SKU attribute.'));
- $this->_redirect('*/*/edit', [
- 'id' => $productId,
- '_current' => true,
- ]);
- return;
- }
-
- try {
- $product->validate();
- $product->save();
- $productId = $product->getId();
-
- if (isset($data['copy_to_stores'])) {
- $this->_copyAttributesBetweenStores($data['copy_to_stores'], $product);
- }
-
- $this->_getSession()->addSuccess($this->__('The product has been saved.'));
- } catch (Mage_Core_Exception $e) {
- $this->_getSession()->addError($e->getMessage())
- ->setProductData($data);
- $redirectBack = true;
- } catch (Exception $e) {
- Mage::logException($e);
- $this->_getSession()->addError($e->getMessage());
- $redirectBack = true;
- }
- }
-
- if ($redirectBack) {
- $this->_redirect('*/*/edit', [
- 'id' => $productId,
- '_current' => true,
- ]);
- } elseif ($this->getRequest()->getParam('popup')) {
- $this->_redirect('*/*/created', [
- '_current' => true,
- 'id' => $productId,
- 'edit' => $isEdit,
- ]);
- } else {
- $this->_redirect('*/*/', ['store' => $storeId]);
- }
- }
-
- /**
- * Duplicates product attributes between stores.
- * @param array $stores list of store pairs: array(fromStore => toStore, fromStore => toStore,..)
- * @param Mage_Catalog_Model_Product $product whose attributes should be copied
- * @return $this
- * @throws Throwable
- */
- protected function _copyAttributesBetweenStores(array $stores, Mage_Catalog_Model_Product $product)
- {
- foreach ($stores as $storeTo => $storeFrom) {
- $productInStore = Mage::getModel('catalog/product')
- ->setStoreId($storeFrom)
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- ->load($product->getId());
- Mage::dispatchEvent('product_duplicate_attributes', [
- 'product' => $productInStore,
- 'storeTo' => $storeTo,
- 'storeFrom' => $storeFrom,
- ]);
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $productInStore->setStoreId($storeTo)->save();
- }
- return $this;
- }
-
- /**
- * Create product duplicate
- * @throws Mage_Core_Exception
- */
- public function duplicateAction()
- {
- $product = $this->_initProduct();
- try {
- $newProduct = $product->duplicate();
- $this->_getSession()->addSuccess($this->__('The product has been duplicated.'));
- $this->_redirect('*/*/edit', ['_current' => true, 'id' => $newProduct->getId()]);
- } catch (Exception $e) {
- Mage::logException($e);
- $this->_getSession()->addError($e->getMessage());
- $this->_redirect('*/*/edit', ['_current' => true]);
- }
- }
-
- /**
- * @deprecated since 1.4.0.0-alpha2
- */
- protected function _decodeInput($encoded)
- {
- parse_str($encoded, $data);
- foreach ($data as $key => $value) {
- parse_str(base64_decode($value), $data[$key]);
- }
- return $data;
- }
-
- /**
- * Delete product action
- */
- public function deleteAction()
- {
- if ($id = $this->getRequest()->getParam('id')) {
- $product = Mage::getModel('catalog/product')
- ->load($id);
- try {
- $product->delete();
- $this->_getSession()->addSuccess($this->__('The product has been deleted.'));
- } catch (Exception $e) {
- $this->_getSession()->addError($e->getMessage());
- }
- }
- $this->getResponse()
- ->setRedirect($this->getUrl('*/*/', ['store' => $this->getRequest()->getParam('store')]));
- }
+ $this->getResponse()
+ ->setRedirect($this->getUrl('*/*/', ['store' => $this->getRequest()->getParam('store')]));
+ }
/**
* Get tag grid
@@ -1139,4 +834,309 @@ public function showUpdateResultAction()
return false;
}
}
+
+ protected function _construct()
+ {
+ // Define module dependent translate
+ $this->setUsedModuleName('Mage_Catalog');
+ }
+
+ /**
+ * Initialize product from request parameters
+ *
+ * @return Mage_Catalog_Model_Product
+ * @throws Mage_Core_Exception
+ */
+ protected function _initProduct()
+ {
+ $this->_title($this->__('Catalog'))
+ ->_title($this->__('Manage Products'));
+
+ $productId = (int) $this->getRequest()->getParam('id');
+ $product = Mage::getModel('catalog/product')
+ ->setStoreId($this->getRequest()->getParam('store', 0));
+
+ if (!$productId) {
+ if ($setId = (int) $this->getRequest()->getParam('set')) {
+ $product->setAttributeSetId($setId);
+ }
+
+ if ($typeId = $this->getRequest()->getParam('type')) {
+ $product->setTypeId($typeId);
+ }
+ }
+
+ $product->setData('_edit_mode', true);
+ if ($productId) {
+ try {
+ $product->load($productId);
+ } catch (Exception $e) {
+ $product->setTypeId(Mage_Catalog_Model_Product_Type::DEFAULT_TYPE);
+ Mage::logException($e);
+ }
+ }
+
+ $attributes = $this->getRequest()->getParam('attributes');
+ if ($attributes && $product->isConfigurable()) {
+ /** @var Mage_Catalog_Model_Product_Type_Configurable $productType */
+ $productType = $product->getTypeInstance();
+ if (!$productId || !$productType->getUsedProductAttributeIds()) {
+ $productType->setUsedProductAttributeIds(
+ explode(',', base64_decode(urldecode($attributes))),
+ );
+ }
+ }
+
+ // Required attributes of simple product for configurable creation
+ if ($this->getRequest()->getParam('popup')
+ && $requiredAttributes = $this->getRequest()->getParam('required')
+ ) {
+ $requiredAttributes = explode(',', $requiredAttributes);
+ foreach ($product->getAttributes() as $attribute) {
+ if (in_array($attribute->getId(), $requiredAttributes)) {
+ $attribute->setIsRequired(1);
+ }
+ }
+ }
+
+ if ($this->getRequest()->getParam('popup')
+ && $this->getRequest()->getParam('product')
+ && !is_array($this->getRequest()->getParam('product'))
+ && $this->getRequest()->getParam('id', false) === false
+ ) {
+ $configProduct = Mage::getModel('catalog/product')
+ ->setStoreId(0)
+ ->load($this->getRequest()->getParam('product'))
+ ->setTypeId($this->getRequest()->getParam('type'));
+
+ /** @var Mage_Catalog_Model_Product $configProduct */
+ $data = [];
+ // phpcs:ignore Ecg.Performance.Loop.DataLoad
+ foreach ($configProduct->getTypeInstance()->getEditableAttributes() as $attribute) {
+ /** @var Mage_Catalog_Model_Resource_Eav_Attribute $attribute */
+ if (!$attribute->getIsUnique()
+ && $attribute->getFrontend()->getInputType() != 'gallery'
+ && $attribute->getAttributeCode() != 'required_options'
+ && $attribute->getAttributeCode() != 'has_options'
+ && $attribute->getAttributeCode() != $configProduct->getIdFieldName()
+ ) {
+ $data[$attribute->getAttributeCode()] = $configProduct->getData($attribute->getAttributeCode());
+ }
+ }
+
+ $product->addData($data)
+ ->setWebsiteIds($configProduct->getWebsiteIds());
+ }
+
+ Mage::register('product', $product);
+ Mage::register('current_product', $product);
+ Mage::getSingleton('cms/wysiwyg_config')->setStoreId($this->getRequest()->getParam('store'));
+ return $product;
+ }
+
+ /**
+ * Create serializer block for a grid
+ *
+ * @param string $inputName
+ * @param array $productsArray
+ * @return Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Ajax_Serializer
+ */
+ protected function _createSerializerBlock($inputName, Mage_Adminhtml_Block_Widget_Grid $gridBlock, $productsArray)
+ {
+ return $this->getLayout()->createBlock('adminhtml/catalog_product_edit_tab_ajax_serializer')
+ ->setGridBlock($gridBlock)
+ ->setProducts($productsArray)
+ ->setInputElementName($inputName)
+ ;
+ }
+
+ /**
+ * Output specified blocks as a text list
+ */
+ protected function _outputBlocks()
+ {
+ $blocks = func_get_args();
+ $output = $this->getLayout()->createBlock('adminhtml/text_list');
+ foreach ($blocks as $block) {
+ $output->insert($block, '', true);
+ }
+ $this->getResponse()->setBody($output->toHtml());
+ }
+
+ /**
+ * Initialize product before saving
+ * @throws Mage_Core_Exception|Zend_Json_Exception
+ */
+ protected function _initProductSave()
+ {
+ $product = $this->_initProduct();
+ $productData = $this->getRequest()->getPost('product');
+ if ($productData) {
+ $this->_filterStockData($productData['stock_data']);
+ }
+
+ if (!isset($productData['website_ids'])) {
+ $productData['website_ids'] = [];
+ }
+
+ $wasLockedMedia = false;
+ if ($product->isLockedAttribute('media')) {
+ $product->unlockAttribute('media');
+ $wasLockedMedia = true;
+ }
+
+ $product->addData($productData);
+
+ if ($wasLockedMedia) {
+ $product->lockAttribute('media');
+ }
+
+ if (Mage::app()->isSingleStoreMode()) {
+ $product->setWebsiteIds([Mage::app()->getStore(true)->getWebsite()->getId()]);
+ }
+
+ /**
+ * Create Permanent Redirect for old URL key
+ */
+ if ($product->getId() && isset($productData['url_key_create_redirect'])) {
+ $product->setData('save_rewrites_history', (bool) $productData['url_key_create_redirect']);
+ }
+
+ /**
+ * Check "Use Default Value" checkboxes values
+ */
+ if ($useDefaults = $this->getRequest()->getPost('use_default')) {
+ foreach ($useDefaults as $attributeCode) {
+ $product->setData($attributeCode, false);
+ }
+ }
+
+ /**
+ * Init product links data (related, upsell, crosssel)
+ */
+ $links = $this->getRequest()->getPost('links');
+ if (isset($links['related']) && !$product->getRelatedReadonly()) {
+ $product->setRelatedLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['related']));
+ }
+ if (isset($links['upsell']) && !$product->getUpsellReadonly()) {
+ $product->setUpSellLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['upsell']));
+ }
+ if (isset($links['crosssell']) && !$product->getCrosssellReadonly()) {
+ $product->setCrossSellLinkData(Mage::helper('adminhtml/js')
+ ->decodeGridSerializedInput($links['crosssell']));
+ }
+ if (isset($links['grouped']) && !$product->getGroupedReadonly()) {
+ $product->setGroupedLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['grouped']));
+ }
+
+ /**
+ * Initialize product categories
+ */
+ $categoryIds = $this->getRequest()->getPost('category_ids');
+ if ($categoryIds !== null) {
+ if (empty($categoryIds)) {
+ $categoryIds = [];
+ }
+ $product->setCategoryIds($categoryIds);
+ }
+
+ /**
+ * Initialize data for configurable product
+ */
+ if (($data = $this->getRequest()->getPost('configurable_products_data'))
+ && !$product->getConfigurableReadonly()
+ ) {
+ $product->setConfigurableProductsData(Mage::helper('core')->jsonDecode($data));
+ }
+ if (($data = $this->getRequest()->getPost('configurable_attributes_data'))
+ && !$product->getConfigurableReadonly()
+ ) {
+ $product->setConfigurableAttributesData(Mage::helper('core')->jsonDecode($data));
+ }
+
+ $product->setCanSaveConfigurableAttributes(
+ (bool) $this->getRequest()->getPost('affect_configurable_product_attributes')
+ && !$product->getConfigurableReadonly(),
+ );
+
+ /**
+ * Initialize product options
+ */
+ if (isset($productData['options']) && !$product->getOptionsReadonly()) {
+ $product->setProductOptions($productData['options']);
+ }
+
+ $product->setCanSaveCustomOptions(
+ (bool) $this->getRequest()->getPost('affect_product_custom_options')
+ && !$product->getOptionsReadonly(),
+ );
+
+ Mage::dispatchEvent(
+ 'catalog_product_prepare_save',
+ ['product' => $product, 'request' => $this->getRequest()],
+ );
+
+ return $product;
+ }
+
+ /**
+ * Filter product stock data
+ *
+ * @param array $stockData
+ */
+ protected function _filterStockData(&$stockData)
+ {
+ if (is_null($stockData)) {
+ return;
+ }
+ if (!isset($stockData['use_config_manage_stock'])) {
+ $stockData['use_config_manage_stock'] = 0;
+ }
+ if (isset($stockData['qty']) && (float) $stockData['qty'] > self::MAX_QTY_VALUE) {
+ $stockData['qty'] = self::MAX_QTY_VALUE;
+ }
+ if (isset($stockData['min_qty']) && (int) $stockData['min_qty'] < 0) {
+ $stockData['min_qty'] = 0;
+ }
+ if (!isset($stockData['is_decimal_divided']) || $stockData['is_qty_decimal'] == 0) {
+ $stockData['is_decimal_divided'] = 0;
+ }
+ }
+
+ /**
+ * Duplicates product attributes between stores.
+ * @param array $stores list of store pairs: array(fromStore => toStore, fromStore => toStore,..)
+ * @param Mage_Catalog_Model_Product $product whose attributes should be copied
+ * @return $this
+ * @throws Throwable
+ */
+ protected function _copyAttributesBetweenStores(array $stores, Mage_Catalog_Model_Product $product)
+ {
+ foreach ($stores as $storeTo => $storeFrom) {
+ $productInStore = Mage::getModel('catalog/product')
+ ->setStoreId($storeFrom)
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ ->load($product->getId());
+ Mage::dispatchEvent('product_duplicate_attributes', [
+ 'product' => $productInStore,
+ 'storeTo' => $storeTo,
+ 'storeFrom' => $storeFrom,
+ ]);
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $productInStore->setStoreId($storeTo)->save();
+ }
+ return $this;
+ }
+
+ /**
+ * @deprecated since 1.4.0.0-alpha2
+ */
+ protected function _decodeInput($encoded)
+ {
+ parse_str($encoded, $data);
+ foreach ($data as $key => $value) {
+ parse_str(base64_decode($value), $data[$key]);
+ }
+ return $data;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/SearchController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/SearchController.php
index 5f99d98d68d..eb87c3e225c 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/SearchController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/SearchController.php
@@ -26,15 +26,6 @@ class Mage_Adminhtml_Catalog_SearchController extends Mage_Adminhtml_Controller_
*/
public const ADMIN_RESOURCE = 'catalog/search';
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('catalog/search')
- ->_addBreadcrumb(Mage::helper('catalog')->__('Search'), Mage::helper('catalog')->__('Search'))
- ;
- return $this;
- }
-
public function indexAction()
{
$this->_title($this->__('Catalog'))->_title($this->__('Search Terms'));
@@ -199,4 +190,13 @@ public function preDispatch()
$this->_setForcedFormKeyActions('delete', 'massDelete');
return parent::preDispatch();
}
+
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('catalog/search')
+ ->_addBreadcrumb(Mage::helper('catalog')->__('Search'), Mage::helper('catalog')->__('Search'))
+ ;
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Cms/BlockController.php b/app/code/core/Mage/Adminhtml/controllers/Cms/BlockController.php
index 10399620dd2..4ae47bb1d17 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Cms/BlockController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Cms/BlockController.php
@@ -39,22 +39,6 @@ public function preDispatch()
return parent::preDispatch();
}
- /**
- * Init actions
- *
- * @return $this
- */
- protected function _initAction()
- {
- // load layout, set active menu and breadcrumbs
- $this->loadLayout()
- ->_setActiveMenu('cms/block')
- ->_addBreadcrumb(Mage::helper('cms')->__('CMS'), Mage::helper('cms')->__('CMS'))
- ->_addBreadcrumb(Mage::helper('cms')->__('Static Blocks'), Mage::helper('cms')->__('Static Blocks'))
- ;
- return $this;
- }
-
/**
* Index action
*/
@@ -194,4 +178,20 @@ public function deleteAction()
// go to grid
$this->_redirect('*/*/');
}
+
+ /**
+ * Init actions
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ // load layout, set active menu and breadcrumbs
+ $this->loadLayout()
+ ->_setActiveMenu('cms/block')
+ ->_addBreadcrumb(Mage::helper('cms')->__('CMS'), Mage::helper('cms')->__('CMS'))
+ ->_addBreadcrumb(Mage::helper('cms')->__('Static Blocks'), Mage::helper('cms')->__('Static Blocks'))
+ ;
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php b/app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php
index 261520af044..a1bf1926492 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php
@@ -22,22 +22,6 @@
*/
class Mage_Adminhtml_Cms_PageController extends Mage_Adminhtml_Controller_Action
{
- /**
- * Init actions
- *
- * @return $this
- */
- protected function _initAction()
- {
- // load layout, set active menu and breadcrumbs
- $this->loadLayout()
- ->_setActiveMenu('cms/page')
- ->_addBreadcrumb(Mage::helper('cms')->__('CMS'), Mage::helper('cms')->__('CMS'))
- ->_addBreadcrumb(Mage::helper('cms')->__('Manage Pages'), Mage::helper('cms')->__('Manage Pages'))
- ;
- return $this;
- }
-
/**
* Index action
*/
@@ -216,6 +200,21 @@ public function preDispatch()
$this->_setForcedFormKeyActions('delete');
return parent::preDispatch();
}
+ /**
+ * Init actions
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ // load layout, set active menu and breadcrumbs
+ $this->loadLayout()
+ ->_setActiveMenu('cms/page')
+ ->_addBreadcrumb(Mage::helper('cms')->__('CMS'), Mage::helper('cms')->__('CMS'))
+ ->_addBreadcrumb(Mage::helper('cms')->__('Manage Pages'), Mage::helper('cms')->__('Manage Pages'))
+ ;
+ return $this;
+ }
/**
* @inheritDoc
diff --git a/app/code/core/Mage/Adminhtml/controllers/Cms/Wysiwyg/ImagesController.php b/app/code/core/Mage/Adminhtml/controllers/Cms/Wysiwyg/ImagesController.php
index f488dd7a0ed..86c2784b93f 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Cms/Wysiwyg/ImagesController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Cms/Wysiwyg/ImagesController.php
@@ -28,17 +28,6 @@ class Mage_Adminhtml_Cms_Wysiwyg_ImagesController extends Mage_Adminhtml_Control
*/
public const ADMIN_RESOURCE = 'cms/media_gallery';
- /**
- * Init storage
- *
- * @return $this
- */
- protected function _initAction()
- {
- $this->getStorage();
- return $this;
- }
-
public function indexAction()
{
$storeId = (int) $this->getRequest()->getParam('store');
@@ -204,6 +193,17 @@ public function getStorage()
return Mage::registry('storage');
}
+ /**
+ * Init storage
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->getStorage();
+ return $this;
+ }
+
/**
* Save current path in session
*
diff --git a/app/code/core/Mage/Adminhtml/controllers/Customer/Cart/Product/Composite/CartController.php b/app/code/core/Mage/Adminhtml/controllers/Customer/Cart/Product/Composite/CartController.php
index 00abbb210b4..b37c9a5b75b 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Customer/Cart/Product/Composite/CartController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Customer/Cart/Product/Composite/CartController.php
@@ -49,36 +49,6 @@ class Mage_Adminhtml_Customer_Cart_Product_Composite_CartController extends Mage
*/
protected $_quoteItem = null;
- /**
- * Loads customer, quote and quote item by request params
- *
- * @return $this
- */
- protected function _initData()
- {
- $customerId = (int) $this->getRequest()->getParam('customer_id');
- if (!$customerId) {
- Mage::throwException($this->__('No customer id defined.'));
- }
-
- $this->_customer = Mage::getModel('customer/customer')
- ->load($customerId);
-
- $quoteItemId = (int) $this->getRequest()->getParam('id');
- $websiteId = (int) $this->getRequest()->getParam('website_id');
-
- $this->_quote = Mage::getModel('sales/quote')
- ->setWebsite(Mage::app()->getWebsite($websiteId))
- ->loadByCustomer($this->_customer);
-
- $this->_quoteItem = $this->_quote->getItemById($quoteItemId);
- if (!$this->_quoteItem) {
- Mage::throwException($this->__('Wrong quote item.'));
- }
-
- return $this;
- }
-
/**
* Ajax handler to response configuration fieldset of composite product in customer's cart
*
@@ -144,4 +114,34 @@ public function updateAction()
return $this;
}
+
+ /**
+ * Loads customer, quote and quote item by request params
+ *
+ * @return $this
+ */
+ protected function _initData()
+ {
+ $customerId = (int) $this->getRequest()->getParam('customer_id');
+ if (!$customerId) {
+ Mage::throwException($this->__('No customer id defined.'));
+ }
+
+ $this->_customer = Mage::getModel('customer/customer')
+ ->load($customerId);
+
+ $quoteItemId = (int) $this->getRequest()->getParam('id');
+ $websiteId = (int) $this->getRequest()->getParam('website_id');
+
+ $this->_quote = Mage::getModel('sales/quote')
+ ->setWebsite(Mage::app()->getWebsite($websiteId))
+ ->loadByCustomer($this->_customer);
+
+ $this->_quoteItem = $this->_quote->getItemById($quoteItemId);
+ if (!$this->_quoteItem) {
+ Mage::throwException($this->__('Wrong quote item.'));
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Customer/GroupController.php b/app/code/core/Mage/Adminhtml/controllers/Customer/GroupController.php
index 47d6167e0cc..752e64d1da6 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Customer/GroupController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Customer/GroupController.php
@@ -39,17 +39,6 @@ public function preDispatch()
return parent::preDispatch();
}
- protected function _initGroup()
- {
- $this->_title($this->__('Customers'))->_title($this->__('Customer Groups'));
-
- Mage::register('current_group', Mage::getModel('customer/group'));
- $groupId = $this->getRequest()->getParam('id');
- if (!is_null($groupId)) {
- Mage::registry('current_group')->load($groupId);
- }
- }
-
/**
* Customer groups list.
*/
@@ -158,4 +147,15 @@ public function deleteAction()
$this->_redirect('*/customer_group');
}
+
+ protected function _initGroup()
+ {
+ $this->_title($this->__('Customers'))->_title($this->__('Customer Groups'));
+
+ Mage::register('current_group', Mage::getModel('customer/group'));
+ $groupId = $this->getRequest()->getParam('id');
+ if (!is_null($groupId)) {
+ Mage::registry('current_group')->load($groupId);
+ }
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Customer/System/Config/ValidatevatController.php b/app/code/core/Mage/Adminhtml/controllers/Customer/System/Config/ValidatevatController.php
index fc2aa3a7533..5023871df65 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Customer/System/Config/ValidatevatController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Customer/System/Config/ValidatevatController.php
@@ -28,19 +28,6 @@ class Mage_Adminhtml_Customer_System_Config_ValidatevatController extends Mage_A
*/
public const ADMIN_RESOURCE = 'system/config';
- /**
- * Perform customer VAT ID validation
- *
- * @return Varien_Object
- */
- protected function _validate()
- {
- return Mage::helper('customer')->checkVatNumber(
- $this->getRequest()->getParam('country'),
- $this->getRequest()->getParam('vat'),
- );
- }
-
/**
* Check whether vat is valid
*/
@@ -81,4 +68,17 @@ public function validateAdvancedAction()
]);
$this->getResponse()->setBody($body);
}
+
+ /**
+ * Perform customer VAT ID validation
+ *
+ * @return Varien_Object
+ */
+ protected function _validate()
+ {
+ return Mage::helper('customer')->checkVatNumber(
+ $this->getRequest()->getParam('country'),
+ $this->getRequest()->getParam('vat'),
+ );
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Customer/Wishlist/Product/Composite/WishlistController.php b/app/code/core/Mage/Adminhtml/controllers/Customer/Wishlist/Product/Composite/WishlistController.php
index 08d3bb739f3..32b4266babc 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Customer/Wishlist/Product/Composite/WishlistController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Customer/Wishlist/Product/Composite/WishlistController.php
@@ -42,34 +42,6 @@ class Mage_Adminhtml_Customer_Wishlist_Product_Composite_WishlistController exte
*/
protected $_wishlistItem = null;
- /**
- * Loads wishlist and wishlist item
- *
- * @return $this
- */
- protected function _initData()
- {
- $wishlistItemId = (int) $this->getRequest()->getParam('id');
- if (!$wishlistItemId) {
- Mage::throwException($this->__('No wishlist item id defined.'));
- }
-
- /** @var Mage_Wishlist_Model_Item $wishlistItem */
- $wishlistItem = Mage::getModel('wishlist/item')
- ->loadWithOptions($wishlistItemId);
-
- if (!$wishlistItem->getWishlistId()) {
- Mage::throwException($this->__('Wishlist item is not loaded.'));
- }
-
- $this->_wishlist = Mage::getModel('wishlist/wishlist')
- ->load($wishlistItem->getWishlistId());
-
- $this->_wishlistItem = $wishlistItem;
-
- return $this;
- }
-
/**
* Ajax handler to response configuration fieldset of composite product in customer's wishlist
*
@@ -129,4 +101,32 @@ public function updateAction()
return false;
}
+
+ /**
+ * Loads wishlist and wishlist item
+ *
+ * @return $this
+ */
+ protected function _initData()
+ {
+ $wishlistItemId = (int) $this->getRequest()->getParam('id');
+ if (!$wishlistItemId) {
+ Mage::throwException($this->__('No wishlist item id defined.'));
+ }
+
+ /** @var Mage_Wishlist_Model_Item $wishlistItem */
+ $wishlistItem = Mage::getModel('wishlist/item')
+ ->loadWithOptions($wishlistItemId);
+
+ if (!$wishlistItem->getWishlistId()) {
+ Mage::throwException($this->__('Wishlist item is not loaded.'));
+ }
+
+ $this->_wishlist = Mage::getModel('wishlist/wishlist')
+ ->load($wishlistItem->getWishlistId());
+
+ $this->_wishlistItem = $wishlistItem;
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/CustomerController.php b/app/code/core/Mage/Adminhtml/controllers/CustomerController.php
index 7e6e7b9d216..5d087ae5baa 100644
--- a/app/code/core/Mage/Adminhtml/controllers/CustomerController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/CustomerController.php
@@ -39,26 +39,6 @@ public function preDispatch()
return parent::preDispatch();
}
- /**
- * @param string $idFieldName
- * @return $this
- * @throws Mage_Core_Exception
- */
- protected function _initCustomer($idFieldName = 'id')
- {
- $this->_title($this->__('Customers'))->_title($this->__('Manage Customers'));
-
- $customerId = (int) $this->getRequest()->getParam($idFieldName);
- $customer = Mage::getModel('customer/customer');
-
- if ($customerId) {
- $customer->load($customerId);
- }
-
- Mage::register('current_customer', $customer);
- return $this;
- }
-
/**
* Customers list action
*/
@@ -431,21 +411,6 @@ public function exportXmlAction()
$this->_prepareDownloadResponse($fileName, $content);
}
- /**
- * Prepare file download response
- *
- * @todo remove in 1.3
- * @deprecated please use $this->_prepareDownloadResponse()
- * @see Mage_Adminhtml_Controller_Action::_prepareDownloadResponse()
- * @param string $fileName
- * @param string $content
- * @param string $contentType
- */
- protected function _sendUploadResponse($fileName, $content, $contentType = 'application/octet-stream')
- {
- $this->_prepareDownloadResponse($fileName, $content, $contentType);
- }
-
/**
* Customer orders grid
*/
@@ -862,6 +827,41 @@ public function viewfileAction()
exit();
}
+ /**
+ * @param string $idFieldName
+ * @return $this
+ * @throws Mage_Core_Exception
+ */
+ protected function _initCustomer($idFieldName = 'id')
+ {
+ $this->_title($this->__('Customers'))->_title($this->__('Manage Customers'));
+
+ $customerId = (int) $this->getRequest()->getParam($idFieldName);
+ $customer = Mage::getModel('customer/customer');
+
+ if ($customerId) {
+ $customer->load($customerId);
+ }
+
+ Mage::register('current_customer', $customer);
+ return $this;
+ }
+
+ /**
+ * Prepare file download response
+ *
+ * @todo remove in 1.3
+ * @deprecated please use $this->_prepareDownloadResponse()
+ * @see Mage_Adminhtml_Controller_Action::_prepareDownloadResponse()
+ * @param string $fileName
+ * @param string $content
+ * @param string $contentType
+ */
+ protected function _sendUploadResponse($fileName, $content, $contentType = 'application/octet-stream')
+ {
+ $this->_prepareDownloadResponse($fileName, $content, $contentType);
+ }
+
/**
* Filtering posted data. Converting localized data if needed
*
diff --git a/app/code/core/Mage/Adminhtml/controllers/IndexController.php b/app/code/core/Mage/Adminhtml/controllers/IndexController.php
index 121305613f8..c1ca7879022 100644
--- a/app/code/core/Mage/Adminhtml/controllers/IndexController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/IndexController.php
@@ -22,24 +22,6 @@
*/
class Mage_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action
{
- /**
- * Render specified template
- *
- * @param string $tplName
- * @param array $data parameters required by template
- */
- protected function _outTemplate($tplName, $data = [])
- {
- $this->_initLayoutMessages('adminhtml/session');
- $block = $this->getLayout()->createBlock('adminhtml/template')->setTemplate("$tplName.phtml");
- foreach ($data as $index => $value) {
- $block->assign($index, $value);
- }
- $html = $block->toHtml();
- Mage::getSingleton('core/translate_inline')->processResponseBody($html);
- $this->getResponse()->setBody($html);
- }
-
/**
* Admin area entry point
* Always redirects to the startup page url
@@ -179,17 +161,6 @@ public function deniedJsonAction()
$this->getResponse()->setBody($this->_getDeniedJson());
}
- /**
- * Retrieve response for deniedJsonAction()
- */
- protected function _getDeniedJson()
- {
- return Mage::helper('core')->jsonEncode([
- 'ajaxExpired' => 1,
- 'ajaxRedirect' => $this->getUrl('*/index/login'),
- ]);
- }
-
/**
* Denied IFrame action
*/
@@ -198,15 +169,6 @@ public function deniedIframeAction()
$this->getResponse()->setBody($this->_getDeniedIframe());
}
- /**
- * Retrieve response for deniedIframeAction()
- */
- protected function _getDeniedIframe()
- {
- return '';
- }
-
/**
* Forgot administrator password action
*/
@@ -356,6 +318,43 @@ public function resetPasswordPostAction()
return;
}
}
+ /**
+ * Render specified template
+ *
+ * @param string $tplName
+ * @param array $data parameters required by template
+ */
+ protected function _outTemplate($tplName, $data = [])
+ {
+ $this->_initLayoutMessages('adminhtml/session');
+ $block = $this->getLayout()->createBlock('adminhtml/template')->setTemplate("$tplName.phtml");
+ foreach ($data as $index => $value) {
+ $block->assign($index, $value);
+ }
+ $html = $block->toHtml();
+ Mage::getSingleton('core/translate_inline')->processResponseBody($html);
+ $this->getResponse()->setBody($html);
+ }
+
+ /**
+ * Retrieve response for deniedJsonAction()
+ */
+ protected function _getDeniedJson()
+ {
+ return Mage::helper('core')->jsonEncode([
+ 'ajaxExpired' => 1,
+ 'ajaxRedirect' => $this->getUrl('*/index/login'),
+ ]);
+ }
+
+ /**
+ * Retrieve response for deniedIframeAction()
+ */
+ protected function _getDeniedIframe()
+ {
+ return '';
+ }
/**
* Check if password reset token is valid
diff --git a/app/code/core/Mage/Adminhtml/controllers/Newsletter/SubscriberController.php b/app/code/core/Mage/Adminhtml/controllers/Newsletter/SubscriberController.php
index 60fc647a0c6..fee3c845428 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Newsletter/SubscriberController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Newsletter/SubscriberController.php
@@ -83,21 +83,6 @@ public function exportXmlAction()
$this->_prepareDownloadResponse($fileName, $content);
}
- /**
- * Prepare file download response
- *
- * @todo remove in 1.3
- * @deprecated please use $this->_prepareDownloadResponse()
- * @see Mage_Adminhtml_Controller_Action::_prepareDownloadResponse()
- * @param string $fileName
- * @param string $content
- * @param string $contentType
- */
- protected function _sendUploadResponse($fileName, $content, $contentType = 'application/octet-stream')
- {
- $this->_prepareDownloadResponse($fileName, $content, $contentType);
- }
-
public function massUnsubscribeAction()
{
$subscribersIds = $this->getRequest()->getParam('subscriber');
@@ -141,4 +126,19 @@ public function massDeleteAction()
$this->_redirect('*/*/index');
}
+
+ /**
+ * Prepare file download response
+ *
+ * @todo remove in 1.3
+ * @deprecated please use $this->_prepareDownloadResponse()
+ * @see Mage_Adminhtml_Controller_Action::_prepareDownloadResponse()
+ * @param string $fileName
+ * @param string $content
+ * @param string $contentType
+ */
+ protected function _sendUploadResponse($fileName, $content, $contentType = 'application/octet-stream')
+ {
+ $this->_prepareDownloadResponse($fileName, $content, $contentType);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Newsletter/TemplateController.php b/app/code/core/Mage/Adminhtml/controllers/Newsletter/TemplateController.php
index 1556793705d..2caf1689286 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Newsletter/TemplateController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Newsletter/TemplateController.php
@@ -21,27 +21,6 @@
*/
class Mage_Adminhtml_Newsletter_TemplateController extends Mage_Adminhtml_Controller_Action
{
- /**
- * Check is allowed access
- *
- * @return bool
- */
- protected function _isAllowed()
- {
- return Mage::getSingleton('admin/session')
- ->isAllowed('newsletter/template');
- }
-
- /**
- * Set title of page
- *
- * @return $this
- */
- protected function _setTitle()
- {
- return $this->_title($this->__('Newsletter'))->_title($this->__('Newsletter Templates'));
- }
-
/**
* View Templates list
*
@@ -246,4 +225,24 @@ public function preDispatch()
$this->_setForcedFormKeyActions('delete');
return parent::preDispatch();
}
+ /**
+ * Check is allowed access
+ *
+ * @return bool
+ */
+ protected function _isAllowed()
+ {
+ return Mage::getSingleton('admin/session')
+ ->isAllowed('newsletter/template');
+ }
+
+ /**
+ * Set title of page
+ *
+ * @return $this
+ */
+ protected function _setTitle()
+ {
+ return $this->_title($this->__('Newsletter'))->_title($this->__('Newsletter Templates'));
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Permissions/BlockController.php b/app/code/core/Mage/Adminhtml/controllers/Permissions/BlockController.php
index 1a311d0c98d..ce89d09c966 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Permissions/BlockController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Permissions/BlockController.php
@@ -28,19 +28,6 @@ class Mage_Adminhtml_Permissions_BlockController extends Mage_Adminhtml_Controll
*/
public const ADMIN_RESOURCE = 'system/acl/blocks';
- /**
- * @return $this
- */
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('system/acl/blocks')
- ->_addBreadcrumb($this->__('System'), $this->__('System'))
- ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
- ->_addBreadcrumb($this->__('Blocks'), $this->__('Blocks'));
- return $this;
- }
-
/**
* Index action
*/
@@ -206,4 +193,17 @@ public function preDispatch()
$this->_setForcedFormKeyActions('delete');
return parent::preDispatch();
}
+
+ /**
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('system/acl/blocks')
+ ->_addBreadcrumb($this->__('System'), $this->__('System'))
+ ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
+ ->_addBreadcrumb($this->__('Blocks'), $this->__('Blocks'));
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Permissions/OrphanedResourceController.php b/app/code/core/Mage/Adminhtml/controllers/Permissions/OrphanedResourceController.php
index 7c3d53d8ef5..dc08ce032ce 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Permissions/OrphanedResourceController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Permissions/OrphanedResourceController.php
@@ -22,19 +22,6 @@ class Mage_Adminhtml_Permissions_OrphanedResourceController extends Mage_Adminht
*/
public const ADMIN_RESOURCE = 'system/acl/orphaned_resources';
- /**
- * @return $this
- */
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('system/acl/orphaned_resources')
- ->_addBreadcrumb($this->__('System'), $this->__('System'))
- ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
- ->_addBreadcrumb($this->__('Orphaned Resources'), $this->__('Orphaned Role Resources'));
- return $this;
- }
-
/**
* Index action
*/
@@ -81,4 +68,17 @@ public function preDispatch()
$this->_setForcedFormKeyActions('massDelete');
return parent::preDispatch();
}
+
+ /**
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('system/acl/orphaned_resources')
+ ->_addBreadcrumb($this->__('System'), $this->__('System'))
+ ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
+ ->_addBreadcrumb($this->__('Orphaned Resources'), $this->__('Orphaned Role Resources'));
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Permissions/RoleController.php b/app/code/core/Mage/Adminhtml/controllers/Permissions/RoleController.php
index ba5dea8076b..0608eaa50e3 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Permissions/RoleController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Permissions/RoleController.php
@@ -39,42 +39,6 @@ public function preDispatch()
return parent::preDispatch();
}
- /**
- * Preparing layout for output
- *
- * @return $this
- */
- protected function _initAction()
- {
- $this->loadLayout();
- $this->_setActiveMenu('system/acl/roles');
- $this->_addBreadcrumb($this->__('System'), $this->__('System'));
- $this->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'));
- $this->_addBreadcrumb($this->__('Roles'), $this->__('Roles'));
- return $this;
- }
-
- /**
- * Initialize role model by passed parameter in request
- *
- * @return Mage_Admin_Model_Roles
- */
- protected function _initRole($requestVariable = 'rid')
- {
- $this->_title($this->__('System'))
- ->_title($this->__('Permissions'))
- ->_title($this->__('Roles'));
-
- $role = Mage::getModel('admin/roles')->load($this->getRequest()->getParam($requestVariable));
- // preventing edit of relation role
- if ($role->getId() && $role->getRoleType() != 'G') {
- $role->unsetData($role->getIdFieldName());
- }
-
- Mage::register('current_role', $role);
- return Mage::registry('current_role');
- }
-
/**
* Show grid with roles existing in systems
*/
@@ -261,46 +225,6 @@ public function editrolegridAction()
);
}
- /**
- * Remove user from role
- *
- * @param int $userId
- * @param int $roleId
- * @return true
- */
- protected function _deleteUserFromRole($userId, $roleId)
- {
- try {
- Mage::getModel('admin/user')
- ->setRoleId($roleId)
- ->setUserId($userId)
- ->deleteFromRole();
- } catch (Exception $e) {
- throw $e;
- }
- return true;
- }
-
- /**
- * Assign user to role
- *
- * @param int $userId
- * @param int $roleId
- * @return bool
- */
- protected function _addUserToRole($userId, $roleId)
- {
- $user = Mage::getModel('admin/user')->load($userId);
- $user->setRoleId($roleId)->setUserId($userId);
-
- if ($user->roleUserExists() === true) {
- return false;
- } else {
- $user->add();
- return true;
- }
- }
-
/**
* Action to refresh role-rule relations.
* This method will make sure the rendered ACL resource tree checkboxes match the actual ACL permissions.
@@ -345,4 +269,80 @@ public function refreshRolesAction()
$this->_redirect('*/*/');
}
+
+ /**
+ * Preparing layout for output
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout();
+ $this->_setActiveMenu('system/acl/roles');
+ $this->_addBreadcrumb($this->__('System'), $this->__('System'));
+ $this->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'));
+ $this->_addBreadcrumb($this->__('Roles'), $this->__('Roles'));
+ return $this;
+ }
+
+ /**
+ * Initialize role model by passed parameter in request
+ *
+ * @return Mage_Admin_Model_Roles
+ */
+ protected function _initRole($requestVariable = 'rid')
+ {
+ $this->_title($this->__('System'))
+ ->_title($this->__('Permissions'))
+ ->_title($this->__('Roles'));
+
+ $role = Mage::getModel('admin/roles')->load($this->getRequest()->getParam($requestVariable));
+ // preventing edit of relation role
+ if ($role->getId() && $role->getRoleType() != 'G') {
+ $role->unsetData($role->getIdFieldName());
+ }
+
+ Mage::register('current_role', $role);
+ return Mage::registry('current_role');
+ }
+
+ /**
+ * Remove user from role
+ *
+ * @param int $userId
+ * @param int $roleId
+ * @return true
+ */
+ protected function _deleteUserFromRole($userId, $roleId)
+ {
+ try {
+ Mage::getModel('admin/user')
+ ->setRoleId($roleId)
+ ->setUserId($userId)
+ ->deleteFromRole();
+ } catch (Exception $e) {
+ throw $e;
+ }
+ return true;
+ }
+
+ /**
+ * Assign user to role
+ *
+ * @param int $userId
+ * @param int $roleId
+ * @return bool
+ */
+ protected function _addUserToRole($userId, $roleId)
+ {
+ $user = Mage::getModel('admin/user')->load($userId);
+ $user->setRoleId($roleId)->setUserId($userId);
+
+ if ($user->roleUserExists() === true) {
+ return false;
+ } else {
+ $user->add();
+ return true;
+ }
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php b/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php
index 85ede974f4d..70b30d393fc 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php
@@ -37,17 +37,6 @@ public function preDispatch()
return parent::preDispatch();
}
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('system/acl/users')
- ->_addBreadcrumb($this->__('System'), $this->__('System'))
- ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
- ->_addBreadcrumb($this->__('Users'), $this->__('Users'))
- ;
- return $this;
- }
-
public function indexAction()
{
$this->_title($this->__('System'))
@@ -243,4 +232,15 @@ public function roleGridAction()
->createBlock('adminhtml/permissions_user_grid')
->toHtml());
}
+
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('system/acl/users')
+ ->_addBreadcrumb($this->__('System'), $this->__('System'))
+ ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
+ ->_addBreadcrumb($this->__('Users'), $this->__('Users'))
+ ;
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Permissions/VariableController.php b/app/code/core/Mage/Adminhtml/controllers/Permissions/VariableController.php
index 140136408b5..e07f91c89df 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Permissions/VariableController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Permissions/VariableController.php
@@ -28,19 +28,6 @@ class Mage_Adminhtml_Permissions_VariableController extends Mage_Adminhtml_Contr
*/
public const ADMIN_RESOURCE = 'system/acl/variables';
- /**
- * @return $this
- */
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('system/acl/variables')
- ->_addBreadcrumb($this->__('System'), $this->__('System'))
- ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
- ->_addBreadcrumb($this->__('Variables'), $this->__('Variables'));
- return $this;
- }
-
/**
* Index action
*/
@@ -194,4 +181,17 @@ public function variableGridAction()
->createBlock('adminhtml/permissions_variable_grid')
->toHtml());
}
+
+ /**
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('system/acl/variables')
+ ->_addBreadcrumb($this->__('System'), $this->__('System'))
+ ->_addBreadcrumb($this->__('Permissions'), $this->__('Permissions'))
+ ->_addBreadcrumb($this->__('Variables'), $this->__('Variables'));
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Promo/CatalogController.php b/app/code/core/Mage/Adminhtml/controllers/Promo/CatalogController.php
index c27fe2c321d..88336d17f52 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Promo/CatalogController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Promo/CatalogController.php
@@ -46,17 +46,6 @@ public function preDispatch()
return parent::preDispatch();
}
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('promo/catalog')
- ->_addBreadcrumb(
- Mage::helper('catalogrule')->__('Promotions'),
- Mage::helper('catalogrule')->__('Promotions'),
- );
- return $this;
- }
-
public function indexAction()
{
$this->_title($this->__('Promotions'))->_title($this->__('Catalog Price Rules'));
@@ -348,4 +337,15 @@ public function getDirtyRulesNoticeMessage()
$defaultMessage = Mage::helper('catalogrule')->__('There are rules that have been changed but were not applied. Please, click Apply Rules in order to see immediate effect in the catalog.');
return $this->_dirtyRulesNoticeMessage ? $this->_dirtyRulesNoticeMessage : $defaultMessage;
}
+
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('promo/catalog')
+ ->_addBreadcrumb(
+ Mage::helper('catalogrule')->__('Promotions'),
+ Mage::helper('catalogrule')->__('Promotions'),
+ );
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Promo/QuoteController.php b/app/code/core/Mage/Adminhtml/controllers/Promo/QuoteController.php
index c13898a68a0..7eaee6aa116 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Promo/QuoteController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Promo/QuoteController.php
@@ -37,31 +37,6 @@ public function preDispatch()
return parent::preDispatch();
}
- protected function _initRule()
- {
- $this->_title($this->__('Promotions'))->_title($this->__('Shopping Cart Price Rules'));
-
- Mage::register('current_promo_quote_rule', Mage::getModel('salesrule/rule'));
- $id = (int) $this->getRequest()->getParam('id');
-
- if (!$id && $this->getRequest()->getParam('rule_id')) {
- $id = (int) $this->getRequest()->getParam('rule_id');
- }
-
- if ($id) {
- Mage::registry('current_promo_quote_rule')->load($id);
- }
- }
-
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('promo/quote')
- ->_addBreadcrumb(Mage::helper('salesrule')->__('Promotions'), Mage::helper('salesrule')->__('Promotions'))
- ;
- return $this;
- }
-
public function indexAction()
{
$this->_title($this->__('Promotions'))->_title($this->__('Shopping Cart Price Rules'));
@@ -444,4 +419,29 @@ public function chooserAction()
]);
$this->getResponse()->setBody($chooserBlock->toHtml());
}
+
+ protected function _initRule()
+ {
+ $this->_title($this->__('Promotions'))->_title($this->__('Shopping Cart Price Rules'));
+
+ Mage::register('current_promo_quote_rule', Mage::getModel('salesrule/rule'));
+ $id = (int) $this->getRequest()->getParam('id');
+
+ if (!$id && $this->getRequest()->getParam('rule_id')) {
+ $id = (int) $this->getRequest()->getParam('rule_id');
+ }
+
+ if ($id) {
+ Mage::registry('current_promo_quote_rule')->load($id);
+ }
+ }
+
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('promo/quote')
+ ->_addBreadcrumb(Mage::helper('salesrule')->__('Promotions'), Mage::helper('salesrule')->__('Promotions'))
+ ;
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Report/SalesController.php b/app/code/core/Mage/Adminhtml/controllers/Report/SalesController.php
index bf8bb87138d..1261bc48f9f 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Report/SalesController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Report/SalesController.php
@@ -98,17 +98,6 @@ public function exportBestsellersExcelAction()
$this->_prepareDownloadResponse($fileName, $grid->getExcelFile($fileName));
}
- /**
- * Retrieve array of collection names by code specified in request
- *
- * @deprecated after 1.4.0.1
- * @return array
- */
- protected function _getCollectionNames()
- {
- return [];
- }
-
/**
* Refresh statistics for last 25 hours
*
@@ -376,6 +365,17 @@ public function refreshStatisticsAction()
return $this->_forward('index', 'report_statistics');
}
+ /**
+ * Retrieve array of collection names by code specified in request
+ *
+ * @deprecated after 1.4.0.1
+ * @return array
+ */
+ protected function _getCollectionNames()
+ {
+ return [];
+ }
+
/**
* @inheritDoc
*/
diff --git a/app/code/core/Mage/Adminhtml/controllers/Report/StatisticsController.php b/app/code/core/Mage/Adminhtml/controllers/Report/StatisticsController.php
index 6115444fdb9..913e5991fda 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Report/StatisticsController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Report/StatisticsController.php
@@ -75,42 +75,6 @@ public function _initReportAction($blocks)
return $this;
}
- /**
- * Retrieve array of collection names by code specified in request
- *
- * @return array
- * @deprecated after 1.4.0.1
- */
- protected function _getCollectionNames()
- {
- $codes = $this->getRequest()->getParam('code');
- if (!$codes) {
- throw new Exception(Mage::helper('adminhtml')->__('No report code specified.'));
- }
-
- if (!is_array($codes) && !str_contains($codes, ',')) {
- $codes = [$codes];
- } elseif (!is_array($codes)) {
- $codes = explode(',', $codes);
- }
-
- $aliases = [
- 'sales' => 'sales/report_order',
- 'tax' => 'tax/report_tax',
- 'shipping' => 'sales/report_shipping',
- 'invoiced' => 'sales/report_invoiced',
- 'refunded' => 'sales/report_refunded',
- 'coupons' => 'salesrule/report_rule',
- 'bestsellers' => 'sales/report_bestsellers',
- 'viewed' => 'reports/report_product_viewed',
- ];
- $out = [];
- foreach ($codes as $code) {
- $out[] = $aliases[$code];
- }
- return $out;
- }
-
/**
* Refresh statistics for last 25 hours
*
@@ -180,6 +144,42 @@ public function indexAction()
->renderLayout();
}
+ /**
+ * Retrieve array of collection names by code specified in request
+ *
+ * @return array
+ * @deprecated after 1.4.0.1
+ */
+ protected function _getCollectionNames()
+ {
+ $codes = $this->getRequest()->getParam('code');
+ if (!$codes) {
+ throw new Exception(Mage::helper('adminhtml')->__('No report code specified.'));
+ }
+
+ if (!is_array($codes) && !str_contains($codes, ',')) {
+ $codes = [$codes];
+ } elseif (!is_array($codes)) {
+ $codes = explode(',', $codes);
+ }
+
+ $aliases = [
+ 'sales' => 'sales/report_order',
+ 'tax' => 'tax/report_tax',
+ 'shipping' => 'sales/report_shipping',
+ 'invoiced' => 'sales/report_invoiced',
+ 'refunded' => 'sales/report_refunded',
+ 'coupons' => 'salesrule/report_rule',
+ 'bestsellers' => 'sales/report_bestsellers',
+ 'viewed' => 'reports/report_product_viewed',
+ ];
+ $out = [];
+ foreach ($codes as $code) {
+ $out[] = $aliases[$code];
+ }
+ return $out;
+ }
+
/**
* Retrieve admin session model
*
diff --git a/app/code/core/Mage/Adminhtml/controllers/Rss/CatalogController.php b/app/code/core/Mage/Adminhtml/controllers/Rss/CatalogController.php
index 78575a3dfb1..da9a10f7cb0 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Rss/CatalogController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Rss/CatalogController.php
@@ -22,21 +22,6 @@
*/
class Mage_Adminhtml_Rss_CatalogController extends Mage_Adminhtml_Controller_Rss_Abstract
{
- /**
- * @inheritDoc
- */
- protected function _isAllowed()
- {
- $path = '';
- $action = strtolower($this->getRequest()->getActionName());
- if ($action == 'review') {
- $path = 'catalog/reviews_ratings';
- } elseif ($action == 'notifystock') {
- $path = 'catalog/products';
- }
- return Mage::getSingleton('admin/session')->isAllowed($path);
- }
-
public function notifystockAction()
{
if ($this->checkFeedEnable('admin_catalog/notifystock')) {
@@ -52,4 +37,18 @@ public function reviewAction()
$this->renderLayout();
}
}
+ /**
+ * @inheritDoc
+ */
+ protected function _isAllowed()
+ {
+ $path = '';
+ $action = strtolower($this->getRequest()->getActionName());
+ if ($action == 'review') {
+ $path = 'catalog/reviews_ratings';
+ } elseif ($action == 'notifystock') {
+ $path = 'catalog/products';
+ }
+ return Mage::getSingleton('admin/session')->isAllowed($path);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreateController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreateController.php
index c84fd6cad5e..a4ef5cc92ec 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreateController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreateController.php
@@ -22,6 +22,289 @@
*/
class Mage_Adminhtml_Sales_Order_CreateController extends Mage_Adminhtml_Controller_Action
{
+ /**
+ * Index page
+ */
+ public function indexAction()
+ {
+ $this->_title($this->__('Sales'))->_title($this->__('Orders'))->_title($this->__('New Order'));
+ $this->_initSession();
+ $this->loadLayout();
+
+ $this->_setActiveMenu('sales/order')
+ ->renderLayout();
+ }
+
+ public function reorderAction()
+ {
+ $this->_getSession()->clear();
+ $orderId = $this->getRequest()->getParam('order_id');
+ $order = Mage::getModel('sales/order')->load($orderId);
+ if (!Mage::helper('sales/reorder')->canReorder($order)) {
+ return $this->_forward('noRoute');
+ }
+
+ if ($order->getId()) {
+ $order->setReordered(true);
+ $this->_getSession()->setUseOldShippingMethod(true);
+ $this->_getOrderCreateModel()->initFromOrder($order);
+
+ $this->_redirect('*/*');
+ } else {
+ $this->_redirect('*/sales_order/');
+ }
+ }
+
+ /**
+ * Loading page block
+ */
+ public function loadBlockAction()
+ {
+ $request = $this->getRequest();
+ try {
+ $this->_initSession()
+ ->_processData();
+ } catch (Mage_Core_Exception $e) {
+ $this->_reloadQuote();
+ $this->_getSession()->addError($e->getMessage());
+ } catch (Exception $e) {
+ $this->_reloadQuote();
+ $this->_getSession()->addException($e, $e->getMessage());
+ }
+
+ $asJson = $request->getParam('json');
+ $block = $request->getParam('block');
+
+ $update = $this->getLayout()->getUpdate();
+ if ($asJson) {
+ $update->addHandle('adminhtml_sales_order_create_load_block_json');
+ } else {
+ $update->addHandle('adminhtml_sales_order_create_load_block_plain');
+ }
+
+ if ($block) {
+ $blocks = explode(',', $block);
+ if ($asJson && !in_array('message', $blocks)) {
+ $blocks[] = 'message';
+ }
+
+ foreach ($blocks as $block) {
+ $update->addHandle('adminhtml_sales_order_create_load_block_' . $block);
+ }
+ }
+ $this->loadLayoutUpdates()->generateLayoutXml()->generateLayoutBlocks();
+ $result = $this->getLayout()->getBlock('content')->toHtml();
+ if ($request->getParam('as_js_varname')) {
+ Mage::getSingleton('adminhtml/session')->setUpdateResult($result);
+ $this->_redirect('*/*/showUpdateResult');
+ } else {
+ $this->getResponse()->setBody($result);
+ }
+ }
+
+ /**
+ * Adds configured product to quote
+ */
+ public function addConfiguredAction()
+ {
+ $errorMessage = null;
+ try {
+ $this->_initSession()
+ ->_processData();
+ } catch (Exception $e) {
+ $this->_reloadQuote();
+ $errorMessage = $e->getMessage();
+ }
+
+ // Form result for client javascript
+ $updateResult = new Varien_Object();
+ if ($errorMessage) {
+ $updateResult->setError(true);
+ $updateResult->setMessage($errorMessage);
+ } else {
+ $updateResult->setOk(true);
+ }
+
+ $updateResult->setJsVarName($this->getRequest()->getParam('as_js_varname'));
+ Mage::getSingleton('adminhtml/session')->setCompositeProductResult($updateResult);
+ $this->_redirect('*/catalog_product/showUpdateResult');
+ }
+
+ /**
+ * Start order create action
+ */
+ public function startAction()
+ {
+ $this->_getSession()->clear();
+ $this->_redirect('*/*', ['customer_id' => $this->getRequest()->getParam('customer_id')]);
+ }
+
+ /**
+ * Cancel order create
+ */
+ public function cancelAction()
+ {
+ if ($orderId = $this->_getSession()->getReordered()) {
+ $this->_getSession()->clear();
+ $this->_redirect('*/sales_order/view', [
+ 'order_id' => $orderId,
+ ]);
+ } else {
+ $this->_getSession()->clear();
+ $this->_redirect('*/*');
+ }
+ }
+
+ /**
+ * Saving quote and create order
+ */
+ public function saveAction()
+ {
+ try {
+ $orderData = $this->getRequest()->getPost('order');
+ if (array_key_exists('reserved_order_id', $orderData['comment'])
+ && Mage::helper('adminhtml/sales')->hasTags($orderData['comment']['reserved_order_id'])
+ ) {
+ Mage::throwException($this->__('Invalid order data.'));
+ }
+
+ $this->_processActionData('save');
+ $paymentData = $this->getRequest()->getPost('payment');
+ if ($paymentData) {
+ $paymentData['checks'] = Mage_Payment_Model_Method_Abstract::CHECK_USE_INTERNAL
+ | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_COUNTRY
+ | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_CURRENCY
+ | Mage_Payment_Model_Method_Abstract::CHECK_ORDER_TOTAL_MIN_MAX
+ | Mage_Payment_Model_Method_Abstract::CHECK_ZERO_TOTAL;
+ $this->_getOrderCreateModel()->setPaymentData($paymentData);
+ $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($paymentData);
+ }
+
+ $order = $this->_getOrderCreateModel()
+ ->setIsValidate(true)
+ ->importPostData($this->getRequest()->getPost('order'))
+ ->createOrder();
+
+ $this->_getSession()->clear();
+ Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The order has been created.'));
+ if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
+ $this->_redirect('*/sales_order/view', ['order_id' => $order->getId()]);
+ } else {
+ $this->_redirect('*/sales_order/index');
+ }
+ } catch (Mage_Payment_Model_Info_Exception $e) {
+ $this->_getOrderCreateModel()->saveQuote();
+ $message = $e->getMessage();
+ if (!empty($message)) {
+ $this->_getSession()->addError($message);
+ }
+ $this->_redirect('*/*/');
+ } catch (Mage_Core_Exception $e) {
+ $message = $e->getMessage();
+ if (!empty($message)) {
+ $this->_getSession()->addError($message);
+ }
+ $this->_redirect('*/*/');
+ } catch (Exception $e) {
+ $this->_getSession()->addException($e, $this->__('Order saving error: %s', $e->getMessage()));
+ $this->_redirect('*/*/');
+ }
+ }
+
+ /**
+ * Ajax handler to response configuration fieldset of composite product in order
+ *
+ * @return $this
+ */
+ public function configureProductToAddAction()
+ {
+ // Prepare data
+ $productId = (int) $this->getRequest()->getParam('id');
+
+ $configureResult = new Varien_Object();
+ $configureResult->setOk(true);
+ $configureResult->setProductId($productId);
+ $sessionQuote = Mage::getSingleton('adminhtml/session_quote');
+ $configureResult->setCurrentStoreId($sessionQuote->getStore()->getId());
+ $configureResult->setCurrentCustomerId($sessionQuote->getCustomerId());
+
+ // Render page
+ /** @var Mage_Adminhtml_Helper_Catalog_Product_Composite $helper */
+ $helper = Mage::helper('adminhtml/catalog_product_composite');
+ $helper->renderConfigureResult($this, $configureResult);
+
+ return $this;
+ }
+
+ /**
+ * Ajax handler to response configuration fieldset of composite product in quote items
+ *
+ * @return $this
+ */
+ public function configureQuoteItemsAction()
+ {
+ // Prepare data
+ $configureResult = new Varien_Object();
+ try {
+ $quoteItemId = (int) $this->getRequest()->getParam('id');
+ if (!$quoteItemId) {
+ Mage::throwException($this->__('Quote item id is not received.'));
+ }
+
+ $quoteItem = Mage::getModel('sales/quote_item')->load($quoteItemId);
+ if (!$quoteItem->getId()) {
+ Mage::throwException($this->__('Quote item is not loaded.'));
+ }
+
+ $configureResult->setOk(true);
+ $optionCollection = Mage::getModel('sales/quote_item_option')->getCollection()
+ ->addItemFilter([$quoteItemId]);
+ $quoteItem->setOptions($optionCollection->getOptionsByItem($quoteItem));
+
+ $configureResult->setBuyRequest($quoteItem->getBuyRequest());
+ $configureResult->setCurrentStoreId($quoteItem->getStoreId());
+ $configureResult->setProductId($quoteItem->getProductId());
+ $sessionQuote = Mage::getSingleton('adminhtml/session_quote');
+ $configureResult->setCurrentCustomerId($sessionQuote->getCustomerId());
+ } catch (Exception $e) {
+ $configureResult->setError(true);
+ $configureResult->setMessage($e->getMessage());
+ }
+
+ // Render page
+ /** @var Mage_Adminhtml_Helper_Catalog_Product_Composite $helper */
+ $helper = Mage::helper('adminhtml/catalog_product_composite');
+ $helper->renderConfigureResult($this, $configureResult);
+
+ return $this;
+ }
+
+ /**
+ * Show item update result from loadBlockAction
+ * to prevent popup alert with resend data question
+ *
+ */
+ public function showUpdateResultAction()
+ {
+ $session = Mage::getSingleton('adminhtml/session');
+ if ($session->hasUpdateResult() && is_scalar($session->getUpdateResult())) {
+ $this->getResponse()->setBody($session->getUpdateResult());
+ $session->unsUpdateResult();
+ } else {
+ $session->unsUpdateResult();
+ return false;
+ }
+ }
+
+ /**
+ * Process data and display index page
+ */
+ public function processDataAction()
+ {
+ $this->_initSession();
+ $this->_processData();
+ $this->_forward('index');
+ }
/**
* Additional initialization
*
@@ -263,270 +546,81 @@ protected function _processActionData($action = null)
Mage::dispatchEvent('adminhtml_sales_order_create_process_data', $eventData);
$this->_getOrderCreateModel()
- ->saveQuote();
-
- if ($paymentData = $this->getRequest()->getPost('payment')) {
- $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($paymentData);
- }
-
- /**
- * Saving of giftmessages
- */
- $giftmessages = $this->getRequest()->getPost('giftmessage');
- if ($giftmessages) {
- $this->_getGiftmessageSaveModel()->setGiftmessages($giftmessages)
- ->saveAllInQuote();
- }
-
- /**
- * Importing gift message allow items from specific product grid
- */
- if ($data = $this->getRequest()->getPost('add_products')) {
- $this->_getGiftmessageSaveModel()
- ->importAllowQuoteItemsFromProducts(Mage::helper('core')->jsonDecode($data));
- }
-
- /**
- * Importing gift message allow items on update quote items
- */
- if ($this->getRequest()->getPost('update_items')) {
- $items = $this->getRequest()->getPost('item', []);
- $this->_getGiftmessageSaveModel()->importAllowQuoteItemsFromItems($items);
- }
-
- $data = $this->getRequest()->getPost('order');
- $couponCode = '';
- if (isset($data) && isset($data['coupon']['code'])) {
- $couponCode = trim($data['coupon']['code']);
- }
- if (!empty($couponCode)) {
- if ($this->_getQuote()->getCouponCode() !== $couponCode) {
- $this->_getSession()->addError(
- $this->__('"%s" coupon code is not valid.', $this->_getHelper()->escapeHtml($couponCode)),
- );
- } else {
- $this->_getSession()->addSuccess($this->__('The coupon code has been accepted.'));
- }
- }
-
- return $this;
- }
-
- /**
- * Process buyRequest file options of items
- *
- * @param array $items
- * @return array
- */
- protected function _processFiles($items)
- {
- /** @var Mage_Catalog_Helper_Product $productHelper */
- $productHelper = Mage::helper('catalog/product');
- foreach ($items as $id => $item) {
- $buyRequest = new Varien_Object($item);
- $params = ['files_prefix' => 'item_' . $id . '_'];
- $buyRequest = $productHelper->addParamsToBuyRequest($buyRequest, $params);
- if ($buyRequest->hasData()) {
- $items[$id] = $buyRequest->toArray();
- }
- }
- return $items;
- }
-
- /**
- * Index page
- */
- public function indexAction()
- {
- $this->_title($this->__('Sales'))->_title($this->__('Orders'))->_title($this->__('New Order'));
- $this->_initSession();
- $this->loadLayout();
-
- $this->_setActiveMenu('sales/order')
- ->renderLayout();
- }
-
- public function reorderAction()
- {
- $this->_getSession()->clear();
- $orderId = $this->getRequest()->getParam('order_id');
- $order = Mage::getModel('sales/order')->load($orderId);
- if (!Mage::helper('sales/reorder')->canReorder($order)) {
- return $this->_forward('noRoute');
- }
-
- if ($order->getId()) {
- $order->setReordered(true);
- $this->_getSession()->setUseOldShippingMethod(true);
- $this->_getOrderCreateModel()->initFromOrder($order);
-
- $this->_redirect('*/*');
- } else {
- $this->_redirect('*/sales_order/');
- }
- }
-
- protected function _reloadQuote()
- {
- $id = $this->_getQuote()->getId();
- $this->_getQuote()->load($id);
- return $this;
- }
-
- /**
- * Loading page block
- */
- public function loadBlockAction()
- {
- $request = $this->getRequest();
- try {
- $this->_initSession()
- ->_processData();
- } catch (Mage_Core_Exception $e) {
- $this->_reloadQuote();
- $this->_getSession()->addError($e->getMessage());
- } catch (Exception $e) {
- $this->_reloadQuote();
- $this->_getSession()->addException($e, $e->getMessage());
- }
-
- $asJson = $request->getParam('json');
- $block = $request->getParam('block');
-
- $update = $this->getLayout()->getUpdate();
- if ($asJson) {
- $update->addHandle('adminhtml_sales_order_create_load_block_json');
- } else {
- $update->addHandle('adminhtml_sales_order_create_load_block_plain');
- }
-
- if ($block) {
- $blocks = explode(',', $block);
- if ($asJson && !in_array('message', $blocks)) {
- $blocks[] = 'message';
- }
+ ->saveQuote();
- foreach ($blocks as $block) {
- $update->addHandle('adminhtml_sales_order_create_load_block_' . $block);
- }
+ if ($paymentData = $this->getRequest()->getPost('payment')) {
+ $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($paymentData);
}
- $this->loadLayoutUpdates()->generateLayoutXml()->generateLayoutBlocks();
- $result = $this->getLayout()->getBlock('content')->toHtml();
- if ($request->getParam('as_js_varname')) {
- Mage::getSingleton('adminhtml/session')->setUpdateResult($result);
- $this->_redirect('*/*/showUpdateResult');
- } else {
- $this->getResponse()->setBody($result);
+
+ /**
+ * Saving of giftmessages
+ */
+ $giftmessages = $this->getRequest()->getPost('giftmessage');
+ if ($giftmessages) {
+ $this->_getGiftmessageSaveModel()->setGiftmessages($giftmessages)
+ ->saveAllInQuote();
}
- }
- /**
- * Adds configured product to quote
- */
- public function addConfiguredAction()
- {
- $errorMessage = null;
- try {
- $this->_initSession()
- ->_processData();
- } catch (Exception $e) {
- $this->_reloadQuote();
- $errorMessage = $e->getMessage();
+ /**
+ * Importing gift message allow items from specific product grid
+ */
+ if ($data = $this->getRequest()->getPost('add_products')) {
+ $this->_getGiftmessageSaveModel()
+ ->importAllowQuoteItemsFromProducts(Mage::helper('core')->jsonDecode($data));
}
- // Form result for client javascript
- $updateResult = new Varien_Object();
- if ($errorMessage) {
- $updateResult->setError(true);
- $updateResult->setMessage($errorMessage);
- } else {
- $updateResult->setOk(true);
+ /**
+ * Importing gift message allow items on update quote items
+ */
+ if ($this->getRequest()->getPost('update_items')) {
+ $items = $this->getRequest()->getPost('item', []);
+ $this->_getGiftmessageSaveModel()->importAllowQuoteItemsFromItems($items);
}
- $updateResult->setJsVarName($this->getRequest()->getParam('as_js_varname'));
- Mage::getSingleton('adminhtml/session')->setCompositeProductResult($updateResult);
- $this->_redirect('*/catalog_product/showUpdateResult');
- }
+ $data = $this->getRequest()->getPost('order');
+ $couponCode = '';
+ if (isset($data) && isset($data['coupon']['code'])) {
+ $couponCode = trim($data['coupon']['code']);
+ }
+ if (!empty($couponCode)) {
+ if ($this->_getQuote()->getCouponCode() !== $couponCode) {
+ $this->_getSession()->addError(
+ $this->__('"%s" coupon code is not valid.', $this->_getHelper()->escapeHtml($couponCode)),
+ );
+ } else {
+ $this->_getSession()->addSuccess($this->__('The coupon code has been accepted.'));
+ }
+ }
- /**
- * Start order create action
- */
- public function startAction()
- {
- $this->_getSession()->clear();
- $this->_redirect('*/*', ['customer_id' => $this->getRequest()->getParam('customer_id')]);
+ return $this;
}
/**
- * Cancel order create
+ * Process buyRequest file options of items
+ *
+ * @param array $items
+ * @return array
*/
- public function cancelAction()
+ protected function _processFiles($items)
{
- if ($orderId = $this->_getSession()->getReordered()) {
- $this->_getSession()->clear();
- $this->_redirect('*/sales_order/view', [
- 'order_id' => $orderId,
- ]);
- } else {
- $this->_getSession()->clear();
- $this->_redirect('*/*');
+ /** @var Mage_Catalog_Helper_Product $productHelper */
+ $productHelper = Mage::helper('catalog/product');
+ foreach ($items as $id => $item) {
+ $buyRequest = new Varien_Object($item);
+ $params = ['files_prefix' => 'item_' . $id . '_'];
+ $buyRequest = $productHelper->addParamsToBuyRequest($buyRequest, $params);
+ if ($buyRequest->hasData()) {
+ $items[$id] = $buyRequest->toArray();
+ }
}
+ return $items;
}
- /**
- * Saving quote and create order
- */
- public function saveAction()
+ protected function _reloadQuote()
{
- try {
- $orderData = $this->getRequest()->getPost('order');
- if (array_key_exists('reserved_order_id', $orderData['comment'])
- && Mage::helper('adminhtml/sales')->hasTags($orderData['comment']['reserved_order_id'])
- ) {
- Mage::throwException($this->__('Invalid order data.'));
- }
-
- $this->_processActionData('save');
- $paymentData = $this->getRequest()->getPost('payment');
- if ($paymentData) {
- $paymentData['checks'] = Mage_Payment_Model_Method_Abstract::CHECK_USE_INTERNAL
- | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_COUNTRY
- | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_CURRENCY
- | Mage_Payment_Model_Method_Abstract::CHECK_ORDER_TOTAL_MIN_MAX
- | Mage_Payment_Model_Method_Abstract::CHECK_ZERO_TOTAL;
- $this->_getOrderCreateModel()->setPaymentData($paymentData);
- $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($paymentData);
- }
-
- $order = $this->_getOrderCreateModel()
- ->setIsValidate(true)
- ->importPostData($this->getRequest()->getPost('order'))
- ->createOrder();
-
- $this->_getSession()->clear();
- Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The order has been created.'));
- if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
- $this->_redirect('*/sales_order/view', ['order_id' => $order->getId()]);
- } else {
- $this->_redirect('*/sales_order/index');
- }
- } catch (Mage_Payment_Model_Info_Exception $e) {
- $this->_getOrderCreateModel()->saveQuote();
- $message = $e->getMessage();
- if (!empty($message)) {
- $this->_getSession()->addError($message);
- }
- $this->_redirect('*/*/');
- } catch (Mage_Core_Exception $e) {
- $message = $e->getMessage();
- if (!empty($message)) {
- $this->_getSession()->addError($message);
- }
- $this->_redirect('*/*/');
- } catch (Exception $e) {
- $this->_getSession()->addException($e, $this->__('Order saving error: %s', $e->getMessage()));
- $this->_redirect('*/*/');
- }
+ $id = $this->_getQuote()->getId();
+ $this->_getQuote()->load($id);
+ return $this;
}
/**
@@ -565,99 +659,4 @@ protected function _getAclResourse()
}
return $aclResource;
}
-
- /**
- * Ajax handler to response configuration fieldset of composite product in order
- *
- * @return $this
- */
- public function configureProductToAddAction()
- {
- // Prepare data
- $productId = (int) $this->getRequest()->getParam('id');
-
- $configureResult = new Varien_Object();
- $configureResult->setOk(true);
- $configureResult->setProductId($productId);
- $sessionQuote = Mage::getSingleton('adminhtml/session_quote');
- $configureResult->setCurrentStoreId($sessionQuote->getStore()->getId());
- $configureResult->setCurrentCustomerId($sessionQuote->getCustomerId());
-
- // Render page
- /** @var Mage_Adminhtml_Helper_Catalog_Product_Composite $helper */
- $helper = Mage::helper('adminhtml/catalog_product_composite');
- $helper->renderConfigureResult($this, $configureResult);
-
- return $this;
- }
-
- /**
- * Ajax handler to response configuration fieldset of composite product in quote items
- *
- * @return $this
- */
- public function configureQuoteItemsAction()
- {
- // Prepare data
- $configureResult = new Varien_Object();
- try {
- $quoteItemId = (int) $this->getRequest()->getParam('id');
- if (!$quoteItemId) {
- Mage::throwException($this->__('Quote item id is not received.'));
- }
-
- $quoteItem = Mage::getModel('sales/quote_item')->load($quoteItemId);
- if (!$quoteItem->getId()) {
- Mage::throwException($this->__('Quote item is not loaded.'));
- }
-
- $configureResult->setOk(true);
- $optionCollection = Mage::getModel('sales/quote_item_option')->getCollection()
- ->addItemFilter([$quoteItemId]);
- $quoteItem->setOptions($optionCollection->getOptionsByItem($quoteItem));
-
- $configureResult->setBuyRequest($quoteItem->getBuyRequest());
- $configureResult->setCurrentStoreId($quoteItem->getStoreId());
- $configureResult->setProductId($quoteItem->getProductId());
- $sessionQuote = Mage::getSingleton('adminhtml/session_quote');
- $configureResult->setCurrentCustomerId($sessionQuote->getCustomerId());
- } catch (Exception $e) {
- $configureResult->setError(true);
- $configureResult->setMessage($e->getMessage());
- }
-
- // Render page
- /** @var Mage_Adminhtml_Helper_Catalog_Product_Composite $helper */
- $helper = Mage::helper('adminhtml/catalog_product_composite');
- $helper->renderConfigureResult($this, $configureResult);
-
- return $this;
- }
-
- /**
- * Show item update result from loadBlockAction
- * to prevent popup alert with resend data question
- *
- */
- public function showUpdateResultAction()
- {
- $session = Mage::getSingleton('adminhtml/session');
- if ($session->hasUpdateResult() && is_scalar($session->getUpdateResult())) {
- $this->getResponse()->setBody($session->getUpdateResult());
- $session->unsUpdateResult();
- } else {
- $session->unsUpdateResult();
- return false;
- }
- }
-
- /**
- * Process data and display index page
- */
- public function processDataAction()
- {
- $this->_initSession();
- $this->_processData();
- $this->_forward('index');
- }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreditmemoController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreditmemoController.php
index 78a5b89b17b..4a2df014435 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreditmemoController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreditmemoController.php
@@ -22,155 +22,6 @@
*/
class Mage_Adminhtml_Sales_Order_CreditmemoController extends Mage_Adminhtml_Controller_Sales_Creditmemo
{
- /**
- * Get requested items qtys and return to stock flags
- */
- protected function _getItemData()
- {
- $data = $this->getRequest()->getParam('creditmemo');
- if (!$data) {
- $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
- }
- return $data['items'] ?? [];
- }
-
- /**
- * Check if creditmeno can be created for order
- * @param Mage_Sales_Model_Order $order
- * @return bool
- */
- protected function _canCreditmemo($order)
- {
- /**
- * Check order existing
- */
- if (!$order->getId()) {
- $this->_getSession()->addError($this->__('The order no longer exists.'));
- return false;
- }
-
- /**
- * Check creditmemo create availability
- */
- if (!$order->canCreditmemo()) {
- $this->_getSession()->addError($this->__('Cannot create credit memo for the order.'));
- return false;
- }
- return true;
- }
-
- /**
- * Initialize requested invoice instance
- * @param Mage_Sales_Model_Order $order
- * @return false|Mage_Sales_Model_Order_Invoice
- */
- protected function _initInvoice($order)
- {
- $invoiceId = $this->getRequest()->getParam('invoice_id');
- if ($invoiceId) {
- $invoice = Mage::getModel('sales/order_invoice')
- ->load($invoiceId)
- ->setOrder($order);
- if ($invoice->getId()) {
- return $invoice;
- }
- }
- return false;
- }
-
- /**
- * Initialize creditmemo model instance
- *
- * @return Mage_Sales_Model_Order_Creditmemo|false
- * @throws Mage_Core_Exception
- */
- protected function _initCreditmemo($update = false)
- {
- $this->_title($this->__('Sales'))->_title($this->__('Credit Memos'));
-
- $creditmemo = false;
- $creditmemoId = $this->getRequest()->getParam('creditmemo_id');
- $orderId = $this->getRequest()->getParam('order_id');
- if ($creditmemoId) {
- $creditmemo = Mage::getModel('sales/order_creditmemo')->load($creditmemoId);
- if (!$creditmemo->getId()) {
- $this->_getSession()->addError($this->__('The credit memo no longer exists.'));
- return false;
- }
- } elseif ($orderId) {
- $data = $this->getRequest()->getParam('creditmemo');
- $order = Mage::getModel('sales/order')->load($orderId);
- $invoice = $this->_initInvoice($order);
-
- if (!$this->_canCreditmemo($order)) {
- return false;
- }
-
- $savedData = $this->_getItemData();
-
- $qtys = [];
- $backToStock = [];
- foreach ($savedData as $orderItemId => $itemData) {
- if (isset($itemData['qty'])) {
- $qtys[$orderItemId] = $itemData['qty'];
- }
- if (isset($itemData['back_to_stock'])) {
- $backToStock[$orderItemId] = true;
- }
- }
- $data['qtys'] = $qtys;
-
- $service = Mage::getModel('sales/service_order', $order);
- if ($invoice) {
- $creditmemo = $service->prepareInvoiceCreditmemo($invoice, $data);
- } else {
- $creditmemo = $service->prepareCreditmemo($data);
- }
-
- /**
- * Process back to stock flags
- */
- foreach ($creditmemo->getAllItems() as $creditmemoItem) {
- $orderItem = $creditmemoItem->getOrderItem();
- $parentId = $orderItem->getParentItemId();
- if (isset($backToStock[$orderItem->getId()])) {
- $creditmemoItem->setBackToStock(true);
- } elseif ($orderItem->getParentItem() && isset($backToStock[$parentId]) && $backToStock[$parentId]) {
- $creditmemoItem->setBackToStock(true);
- } elseif (empty($savedData)) {
- $creditmemoItem->setBackToStock(Mage::helper('cataloginventory')->isAutoReturnEnabled());
- } else {
- $creditmemoItem->setBackToStock(false);
- }
- }
- }
-
- $args = ['creditmemo' => $creditmemo, 'request' => $this->getRequest()];
- Mage::dispatchEvent('adminhtml_sales_order_creditmemo_register_before', $args);
-
- Mage::register('current_creditmemo', $creditmemo);
- return $creditmemo;
- }
-
- /**
- * Save creditmemo and related order, invoice in one transaction
- * @param Mage_Sales_Model_Order_Creditmemo $creditmemo
- * @return $this
- * @throws Exception
- */
- protected function _saveCreditmemo($creditmemo)
- {
- $transactionSave = Mage::getModel('core/resource_transaction')
- ->addObject($creditmemo)
- ->addObject($creditmemo->getOrder());
- if ($creditmemo->getInvoice()) {
- $transactionSave->addObject($creditmemo->getInvoice());
- }
- $transactionSave->save();
-
- return $this;
- }
-
/**
* creditmemo information page
*/
@@ -403,6 +254,163 @@ public function addCommentAction()
$this->getResponse()->setBody($response);
}
+ /**
+ * Create pdf for current creditmemo
+ */
+ public function printAction()
+ {
+ $this->_initCreditmemo();
+ parent::printAction();
+ }
+ /**
+ * Get requested items qtys and return to stock flags
+ */
+ protected function _getItemData()
+ {
+ $data = $this->getRequest()->getParam('creditmemo');
+ if (!$data) {
+ $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
+ }
+ return $data['items'] ?? [];
+ }
+
+ /**
+ * Check if creditmeno can be created for order
+ * @param Mage_Sales_Model_Order $order
+ * @return bool
+ */
+ protected function _canCreditmemo($order)
+ {
+ /**
+ * Check order existing
+ */
+ if (!$order->getId()) {
+ $this->_getSession()->addError($this->__('The order no longer exists.'));
+ return false;
+ }
+
+ /**
+ * Check creditmemo create availability
+ */
+ if (!$order->canCreditmemo()) {
+ $this->_getSession()->addError($this->__('Cannot create credit memo for the order.'));
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Initialize requested invoice instance
+ * @param Mage_Sales_Model_Order $order
+ * @return false|Mage_Sales_Model_Order_Invoice
+ */
+ protected function _initInvoice($order)
+ {
+ $invoiceId = $this->getRequest()->getParam('invoice_id');
+ if ($invoiceId) {
+ $invoice = Mage::getModel('sales/order_invoice')
+ ->load($invoiceId)
+ ->setOrder($order);
+ if ($invoice->getId()) {
+ return $invoice;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Initialize creditmemo model instance
+ *
+ * @return Mage_Sales_Model_Order_Creditmemo|false
+ * @throws Mage_Core_Exception
+ */
+ protected function _initCreditmemo($update = false)
+ {
+ $this->_title($this->__('Sales'))->_title($this->__('Credit Memos'));
+
+ $creditmemo = false;
+ $creditmemoId = $this->getRequest()->getParam('creditmemo_id');
+ $orderId = $this->getRequest()->getParam('order_id');
+ if ($creditmemoId) {
+ $creditmemo = Mage::getModel('sales/order_creditmemo')->load($creditmemoId);
+ if (!$creditmemo->getId()) {
+ $this->_getSession()->addError($this->__('The credit memo no longer exists.'));
+ return false;
+ }
+ } elseif ($orderId) {
+ $data = $this->getRequest()->getParam('creditmemo');
+ $order = Mage::getModel('sales/order')->load($orderId);
+ $invoice = $this->_initInvoice($order);
+
+ if (!$this->_canCreditmemo($order)) {
+ return false;
+ }
+
+ $savedData = $this->_getItemData();
+
+ $qtys = [];
+ $backToStock = [];
+ foreach ($savedData as $orderItemId => $itemData) {
+ if (isset($itemData['qty'])) {
+ $qtys[$orderItemId] = $itemData['qty'];
+ }
+ if (isset($itemData['back_to_stock'])) {
+ $backToStock[$orderItemId] = true;
+ }
+ }
+ $data['qtys'] = $qtys;
+
+ $service = Mage::getModel('sales/service_order', $order);
+ if ($invoice) {
+ $creditmemo = $service->prepareInvoiceCreditmemo($invoice, $data);
+ } else {
+ $creditmemo = $service->prepareCreditmemo($data);
+ }
+
+ /**
+ * Process back to stock flags
+ */
+ foreach ($creditmemo->getAllItems() as $creditmemoItem) {
+ $orderItem = $creditmemoItem->getOrderItem();
+ $parentId = $orderItem->getParentItemId();
+ if (isset($backToStock[$orderItem->getId()])) {
+ $creditmemoItem->setBackToStock(true);
+ } elseif ($orderItem->getParentItem() && isset($backToStock[$parentId]) && $backToStock[$parentId]) {
+ $creditmemoItem->setBackToStock(true);
+ } elseif (empty($savedData)) {
+ $creditmemoItem->setBackToStock(Mage::helper('cataloginventory')->isAutoReturnEnabled());
+ } else {
+ $creditmemoItem->setBackToStock(false);
+ }
+ }
+ }
+
+ $args = ['creditmemo' => $creditmemo, 'request' => $this->getRequest()];
+ Mage::dispatchEvent('adminhtml_sales_order_creditmemo_register_before', $args);
+
+ Mage::register('current_creditmemo', $creditmemo);
+ return $creditmemo;
+ }
+
+ /**
+ * Save creditmemo and related order, invoice in one transaction
+ * @param Mage_Sales_Model_Order_Creditmemo $creditmemo
+ * @return $this
+ * @throws Exception
+ */
+ protected function _saveCreditmemo($creditmemo)
+ {
+ $transactionSave = Mage::getModel('core/resource_transaction')
+ ->addObject($creditmemo)
+ ->addObject($creditmemo->getOrder());
+ if ($creditmemo->getInvoice()) {
+ $transactionSave->addObject($creditmemo->getInvoice());
+ }
+ $transactionSave->save();
+
+ return $this;
+ }
+
/**
* Decides if we need to create dummy invoice item or not
* for example we don't need create dummy parent if all
@@ -439,13 +447,4 @@ protected function _needToAddDummy($item, $qtys)
return false;
}
-
- /**
- * Create pdf for current creditmemo
- */
- public function printAction()
- {
- $this->_initCreditmemo();
- parent::printAction();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/InvoiceController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/InvoiceController.php
index 8b7dc0b97c4..db7d9a3bf36 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/InvoiceController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/InvoiceController.php
@@ -22,107 +22,6 @@
*/
class Mage_Adminhtml_Sales_Order_InvoiceController extends Mage_Adminhtml_Controller_Sales_Invoice
{
- /**
- * Get requested items qty's from request
- */
- protected function _getItemQtys()
- {
- $data = $this->getRequest()->getParam('invoice');
- return $data['items'] ?? [];
- }
-
- /**
- * Initialize invoice model instance
- *
- * @return Mage_Sales_Model_Order_Invoice|false
- * @throws Mage_Core_Exception
- */
- protected function _initInvoice($update = false)
- {
- $this->_title($this->__('Sales'))->_title($this->__('Invoices'));
-
- $invoice = false;
- $itemsToInvoice = 0;
- $invoiceId = $this->getRequest()->getParam('invoice_id');
- $orderId = $this->getRequest()->getParam('order_id');
- if ($invoiceId) {
- $invoice = Mage::getModel('sales/order_invoice')->load($invoiceId);
- if (!$invoice->getId()) {
- $this->_getSession()->addError($this->__('The invoice no longer exists.'));
- return false;
- }
- } elseif ($orderId) {
- $order = Mage::getModel('sales/order')->load($orderId);
- /**
- * Check order existing
- */
- if (!$order->getId()) {
- $this->_getSession()->addError($this->__('The order no longer exists.'));
- return false;
- }
- /**
- * Check invoice create availability
- */
- if (!$order->canInvoice()) {
- $this->_getSession()->addError($this->__('The order does not allow creating an invoice.'));
- return false;
- }
- $savedQtys = $this->_getItemQtys();
- $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($savedQtys);
- if (!$invoice->getTotalQty()) {
- Mage::throwException($this->__('Cannot create an invoice without products.'));
- }
- }
-
- Mage::register('current_invoice', $invoice);
- return $invoice;
- }
-
- /**
- * Save data for invoice and related order
- *
- * @param Mage_Sales_Model_Order_Invoice $invoice
- * @return Mage_Adminhtml_Sales_Order_InvoiceController
- * @throws Exception
- */
- protected function _saveInvoice($invoice)
- {
- $invoice->getOrder()->setIsInProcess(true);
- $transactionSave = Mage::getModel('core/resource_transaction')
- ->addObject($invoice)
- ->addObject($invoice->getOrder())
- ->save();
-
- return $this;
- }
-
- /**
- * Prepare shipment
- *
- * @param Mage_Sales_Model_Order_Invoice $invoice
- * @return Mage_Sales_Model_Order_Shipment|false
- * @throws Mage_Core_Exception
- */
- protected function _prepareShipment($invoice)
- {
- $savedQtys = $this->_getItemQtys();
- $shipment = Mage::getModel('sales/service_order', $invoice->getOrder())->prepareShipment($savedQtys);
- if (!$shipment->getTotalQty()) {
- return false;
- }
-
- $shipment->register();
- $tracks = $this->getRequest()->getPost('tracking');
- if ($tracks) {
- foreach ($tracks as $data) {
- $track = Mage::getModel('sales/order_shipment_track')
- ->addData($data);
- $shipment->addTrack($track);
- }
- }
- return $shipment;
- }
-
/**
* Invoice information page
*/
@@ -398,6 +297,115 @@ public function addCommentAction()
$this->getResponse()->setBody($response);
}
+ /**
+ * Create pdf for current invoice
+ */
+ public function printAction()
+ {
+ $this->_initInvoice();
+ parent::printAction();
+ }
+ /**
+ * Get requested items qty's from request
+ */
+ protected function _getItemQtys()
+ {
+ $data = $this->getRequest()->getParam('invoice');
+ return $data['items'] ?? [];
+ }
+
+ /**
+ * Initialize invoice model instance
+ *
+ * @return Mage_Sales_Model_Order_Invoice|false
+ * @throws Mage_Core_Exception
+ */
+ protected function _initInvoice($update = false)
+ {
+ $this->_title($this->__('Sales'))->_title($this->__('Invoices'));
+
+ $invoice = false;
+ $itemsToInvoice = 0;
+ $invoiceId = $this->getRequest()->getParam('invoice_id');
+ $orderId = $this->getRequest()->getParam('order_id');
+ if ($invoiceId) {
+ $invoice = Mage::getModel('sales/order_invoice')->load($invoiceId);
+ if (!$invoice->getId()) {
+ $this->_getSession()->addError($this->__('The invoice no longer exists.'));
+ return false;
+ }
+ } elseif ($orderId) {
+ $order = Mage::getModel('sales/order')->load($orderId);
+ /**
+ * Check order existing
+ */
+ if (!$order->getId()) {
+ $this->_getSession()->addError($this->__('The order no longer exists.'));
+ return false;
+ }
+ /**
+ * Check invoice create availability
+ */
+ if (!$order->canInvoice()) {
+ $this->_getSession()->addError($this->__('The order does not allow creating an invoice.'));
+ return false;
+ }
+ $savedQtys = $this->_getItemQtys();
+ $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($savedQtys);
+ if (!$invoice->getTotalQty()) {
+ Mage::throwException($this->__('Cannot create an invoice without products.'));
+ }
+ }
+
+ Mage::register('current_invoice', $invoice);
+ return $invoice;
+ }
+
+ /**
+ * Save data for invoice and related order
+ *
+ * @param Mage_Sales_Model_Order_Invoice $invoice
+ * @return Mage_Adminhtml_Sales_Order_InvoiceController
+ * @throws Exception
+ */
+ protected function _saveInvoice($invoice)
+ {
+ $invoice->getOrder()->setIsInProcess(true);
+ $transactionSave = Mage::getModel('core/resource_transaction')
+ ->addObject($invoice)
+ ->addObject($invoice->getOrder())
+ ->save();
+
+ return $this;
+ }
+
+ /**
+ * Prepare shipment
+ *
+ * @param Mage_Sales_Model_Order_Invoice $invoice
+ * @return Mage_Sales_Model_Order_Shipment|false
+ * @throws Mage_Core_Exception
+ */
+ protected function _prepareShipment($invoice)
+ {
+ $savedQtys = $this->_getItemQtys();
+ $shipment = Mage::getModel('sales/service_order', $invoice->getOrder())->prepareShipment($savedQtys);
+ if (!$shipment->getTotalQty()) {
+ return false;
+ }
+
+ $shipment->register();
+ $tracks = $this->getRequest()->getPost('tracking');
+ if ($tracks) {
+ foreach ($tracks as $data) {
+ $track = Mage::getModel('sales/order_shipment_track')
+ ->addData($data);
+ $shipment->addTrack($track);
+ }
+ }
+ return $shipment;
+ }
+
/**
* Decides if we need to create dummy invoice item or not
* for example we don't need create dummy parent if all
@@ -468,13 +476,4 @@ protected function _needToAddDummyForShipment($item, $qtys)
return false;
}
-
- /**
- * Create pdf for current invoice
- */
- public function printAction()
- {
- $this->_initInvoice();
- parent::printAction();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
index 9bad471b905..a9bfd973bc5 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
@@ -22,96 +22,6 @@
*/
class Mage_Adminhtml_Sales_Order_ShipmentController extends Mage_Adminhtml_Controller_Sales_Shipment
{
- /**
- * Initialize shipment items QTY
- */
- protected function _getItemQtys()
- {
- $data = $this->getRequest()->getParam('shipment');
- return $data['items'] ?? [];
- }
-
- /**
- * Initialize shipment model instance
- *
- * @return Mage_Sales_Model_Order_Shipment|bool
- * @throws Mage_Core_Exception
- */
- protected function _initShipment()
- {
- $this->_title($this->__('Sales'))->_title($this->__('Shipments'));
-
- $shipment = false;
- $shipmentId = $this->getRequest()->getParam('shipment_id');
- $orderId = $this->getRequest()->getParam('order_id');
- if ($shipmentId) {
- $shipment = Mage::getModel('sales/order_shipment')->load($shipmentId);
- if (!$shipment->getId()) {
- $this->_getSession()->addError($this->__('The shipment no longer exists.'));
- return false;
- }
- } elseif ($orderId) {
- $order = Mage::getModel('sales/order')->load($orderId);
-
- /**
- * Check order existing
- */
- if (!$order->getId()) {
- $this->_getSession()->addError($this->__('The order no longer exists.'));
- return false;
- }
- /**
- * Check shipment is available to create separate from invoice
- */
- if ($order->getForcedDoShipmentWithInvoice()) {
- $this->_getSession()->addError($this->__('Cannot do shipment for the order separately from invoice.'));
- return false;
- }
- /**
- * Check shipment create availability
- */
- if (!$order->canShip()) {
- $this->_getSession()->addError($this->__('Cannot do shipment for the order.'));
- return false;
- }
- $savedQtys = $this->_getItemQtys();
- $shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($savedQtys);
-
- $tracks = $this->getRequest()->getPost('tracking');
- if ($tracks) {
- foreach ($tracks as $data) {
- if (empty($data['number'])) {
- Mage::throwException($this->__('Tracking number cannot be empty.'));
- }
- $track = Mage::getModel('sales/order_shipment_track')
- ->addData($data);
- $shipment->addTrack($track);
- }
- }
- }
-
- Mage::register('current_shipment', $shipment);
- return $shipment;
- }
-
- /**
- * Save shipment and order in one transaction
- *
- * @param Mage_Sales_Model_Order_Shipment $shipment
- * @return $this
- * @throws Exception
- */
- protected function _saveShipment($shipment)
- {
- $shipment->getOrder()->setIsInProcess(true);
- $transactionSave = Mage::getModel('core/resource_transaction')
- ->addObject($shipment)
- ->addObject($shipment->getOrder())
- ->save();
-
- return $this;
- }
-
/**
* Shipment information page
*/
@@ -448,94 +358,6 @@ public function addCommentAction()
$this->getResponse()->setBody($response);
}
- /**
- * Decides if we need to create dummy shipment item or not
- * for example we don't need create dummy parent if all
- * children are not in process
- *
- * @deprecated after 1.4, Mage_Sales_Model_Service_Order used
- * @param Mage_Sales_Model_Order_Item $item
- * @param array $qtys
- * @return bool
- */
- protected function _needToAddDummy($item, $qtys)
- {
- if ($item->getHasChildren()) {
- foreach ($item->getChildrenItems() as $child) {
- if ($child->getIsVirtual()) {
- continue;
- }
- if ((isset($qtys[$child->getId()]) && $qtys[$child->getId()] > 0)
- || (!isset($qtys[$child->getId()]) && $child->getQtyToShip())
- ) {
- return true;
- }
- }
- return false;
- }
-
- if ($item->getParentItem()) {
- if ($item->getIsVirtual()) {
- return false;
- }
- if ((isset($qtys[$item->getParentItem()->getId()]) && $qtys[$item->getParentItem()->getId()] > 0)
- || (!isset($qtys[$item->getParentItem()->getId()]) && $item->getParentItem()->getQtyToShip())
- ) {
- return true;
- }
- return false;
- }
-
- return false;
- }
-
- /**
- * Create shipping label for specific shipment with validation.
- *
- * @return bool
- */
- protected function _createShippingLabel(Mage_Sales_Model_Order_Shipment $shipment)
- {
- if (!$shipment) {
- return false;
- }
- $carrier = $shipment->getOrder()->getShippingCarrier();
- if (!$carrier->isShippingLabelsAvailable()) {
- return false;
- }
- $shipment->setPackages($this->getRequest()->getParam('packages'));
- $response = Mage::getModel('shipping/shipping')->requestToShipment($shipment);
- if ($response->hasErrors()) {
- Mage::throwException($response->getErrors());
- }
- if (!$response->hasInfo()) {
- return false;
- }
- $labelsContent = [];
- $trackingNumbers = [];
- $info = $response->getInfo();
- foreach ($info as $inf) {
- if (!empty($inf['tracking_number']) && !empty($inf['label_content'])) {
- $labelsContent[] = $inf['label_content'];
- $trackingNumbers[] = $inf['tracking_number'];
- }
- }
- $outputPdf = $this->_combineLabelsPdf($labelsContent);
- $shipment->setShippingLabel($outputPdf->render());
- $carrierCode = $carrier->getCarrierCode();
- $carrierTitle = Mage::getStoreConfig('carriers/' . $carrierCode . '/title', $shipment->getStoreId());
- if ($trackingNumbers) {
- foreach ($trackingNumbers as $trackingNumber) {
- $track = Mage::getModel('sales/order_shipment_track')
- ->setNumber($trackingNumber)
- ->setCarrierCode($carrierCode)
- ->setTitle($carrierTitle);
- $shipment->addTrack($track);
- }
- }
- return true;
- }
-
/**
* Create shipping label action for specific shipment
*
@@ -677,6 +499,199 @@ public function massPrintShippingLabelAction()
}
}
+ /**
+ * Return grid with shipping items for Ajax request
+ *
+ * @return Mage_Core_Controller_Response_Http
+ */
+ public function getShippingItemsGridAction()
+ {
+ $this->_initShipment();
+ return $this->getResponse()->setBody(
+ $this->getLayout()
+ ->createBlock('adminhtml/sales_order_shipment_packaging_grid')
+ ->setIndex($this->getRequest()->getParam('index'))
+ ->toHtml(),
+ );
+ }
+ /**
+ * Initialize shipment items QTY
+ */
+ protected function _getItemQtys()
+ {
+ $data = $this->getRequest()->getParam('shipment');
+ return $data['items'] ?? [];
+ }
+
+ /**
+ * Initialize shipment model instance
+ *
+ * @return Mage_Sales_Model_Order_Shipment|bool
+ * @throws Mage_Core_Exception
+ */
+ protected function _initShipment()
+ {
+ $this->_title($this->__('Sales'))->_title($this->__('Shipments'));
+
+ $shipment = false;
+ $shipmentId = $this->getRequest()->getParam('shipment_id');
+ $orderId = $this->getRequest()->getParam('order_id');
+ if ($shipmentId) {
+ $shipment = Mage::getModel('sales/order_shipment')->load($shipmentId);
+ if (!$shipment->getId()) {
+ $this->_getSession()->addError($this->__('The shipment no longer exists.'));
+ return false;
+ }
+ } elseif ($orderId) {
+ $order = Mage::getModel('sales/order')->load($orderId);
+
+ /**
+ * Check order existing
+ */
+ if (!$order->getId()) {
+ $this->_getSession()->addError($this->__('The order no longer exists.'));
+ return false;
+ }
+ /**
+ * Check shipment is available to create separate from invoice
+ */
+ if ($order->getForcedDoShipmentWithInvoice()) {
+ $this->_getSession()->addError($this->__('Cannot do shipment for the order separately from invoice.'));
+ return false;
+ }
+ /**
+ * Check shipment create availability
+ */
+ if (!$order->canShip()) {
+ $this->_getSession()->addError($this->__('Cannot do shipment for the order.'));
+ return false;
+ }
+ $savedQtys = $this->_getItemQtys();
+ $shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($savedQtys);
+
+ $tracks = $this->getRequest()->getPost('tracking');
+ if ($tracks) {
+ foreach ($tracks as $data) {
+ if (empty($data['number'])) {
+ Mage::throwException($this->__('Tracking number cannot be empty.'));
+ }
+ $track = Mage::getModel('sales/order_shipment_track')
+ ->addData($data);
+ $shipment->addTrack($track);
+ }
+ }
+ }
+
+ Mage::register('current_shipment', $shipment);
+ return $shipment;
+ }
+
+ /**
+ * Save shipment and order in one transaction
+ *
+ * @param Mage_Sales_Model_Order_Shipment $shipment
+ * @return $this
+ * @throws Exception
+ */
+ protected function _saveShipment($shipment)
+ {
+ $shipment->getOrder()->setIsInProcess(true);
+ $transactionSave = Mage::getModel('core/resource_transaction')
+ ->addObject($shipment)
+ ->addObject($shipment->getOrder())
+ ->save();
+
+ return $this;
+ }
+
+ /**
+ * Decides if we need to create dummy shipment item or not
+ * for example we don't need create dummy parent if all
+ * children are not in process
+ *
+ * @deprecated after 1.4, Mage_Sales_Model_Service_Order used
+ * @param Mage_Sales_Model_Order_Item $item
+ * @param array $qtys
+ * @return bool
+ */
+ protected function _needToAddDummy($item, $qtys)
+ {
+ if ($item->getHasChildren()) {
+ foreach ($item->getChildrenItems() as $child) {
+ if ($child->getIsVirtual()) {
+ continue;
+ }
+ if ((isset($qtys[$child->getId()]) && $qtys[$child->getId()] > 0)
+ || (!isset($qtys[$child->getId()]) && $child->getQtyToShip())
+ ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ if ($item->getParentItem()) {
+ if ($item->getIsVirtual()) {
+ return false;
+ }
+ if ((isset($qtys[$item->getParentItem()->getId()]) && $qtys[$item->getParentItem()->getId()] > 0)
+ || (!isset($qtys[$item->getParentItem()->getId()]) && $item->getParentItem()->getQtyToShip())
+ ) {
+ return true;
+ }
+ return false;
+ }
+
+ return false;
+ }
+
+ /**
+ * Create shipping label for specific shipment with validation.
+ *
+ * @return bool
+ */
+ protected function _createShippingLabel(Mage_Sales_Model_Order_Shipment $shipment)
+ {
+ if (!$shipment) {
+ return false;
+ }
+ $carrier = $shipment->getOrder()->getShippingCarrier();
+ if (!$carrier->isShippingLabelsAvailable()) {
+ return false;
+ }
+ $shipment->setPackages($this->getRequest()->getParam('packages'));
+ $response = Mage::getModel('shipping/shipping')->requestToShipment($shipment);
+ if ($response->hasErrors()) {
+ Mage::throwException($response->getErrors());
+ }
+ if (!$response->hasInfo()) {
+ return false;
+ }
+ $labelsContent = [];
+ $trackingNumbers = [];
+ $info = $response->getInfo();
+ foreach ($info as $inf) {
+ if (!empty($inf['tracking_number']) && !empty($inf['label_content'])) {
+ $labelsContent[] = $inf['label_content'];
+ $trackingNumbers[] = $inf['tracking_number'];
+ }
+ }
+ $outputPdf = $this->_combineLabelsPdf($labelsContent);
+ $shipment->setShippingLabel($outputPdf->render());
+ $carrierCode = $carrier->getCarrierCode();
+ $carrierTitle = Mage::getStoreConfig('carriers/' . $carrierCode . '/title', $shipment->getStoreId());
+ if ($trackingNumbers) {
+ foreach ($trackingNumbers as $trackingNumber) {
+ $track = Mage::getModel('sales/order_shipment_track')
+ ->setNumber($trackingNumber)
+ ->setCarrierCode($carrierCode)
+ ->setTitle($carrierTitle);
+ $shipment->addTrack($track);
+ }
+ }
+ return true;
+ }
+
/**
* Combine array of labels as instance PDF
*
@@ -727,20 +742,4 @@ protected function _createPdfPageFromImageString($imageString)
unlink($tmpFileName);
return $page;
}
-
- /**
- * Return grid with shipping items for Ajax request
- *
- * @return Mage_Core_Controller_Response_Http
- */
- public function getShippingItemsGridAction()
- {
- $this->_initShipment();
- return $this->getResponse()->setBody(
- $this->getLayout()
- ->createBlock('adminhtml/sales_order_shipment_packaging_grid')
- ->setIndex($this->getRequest()->getParam('index'))
- ->toHtml(),
- );
- }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/StatusController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/StatusController.php
index 5bfa1384309..c0bdb58c688 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/StatusController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/StatusController.php
@@ -28,30 +28,6 @@ class Mage_Adminhtml_Sales_Order_StatusController extends Mage_Adminhtml_Control
*/
public const ADMIN_RESOURCE = 'system/order_statuses';
- /**
- * Additional initialization
- */
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Sales');
- }
-
- /**
- * Initialize status model based on status code in request
- *
- * @return Mage_Sales_Model_Order_Status | false
- */
- protected function _initStatus()
- {
- $statusCode = $this->getRequest()->getParam('status');
- if ($statusCode) {
- $status = Mage::getModel('sales/order_status')->load($statusCode);
- } else {
- $status = false;
- }
- return $status;
- }
-
/**
* Statuses grid page
*/
@@ -229,4 +205,28 @@ public function unassignAction()
}
$this->_redirect('*/*/');
}
+
+ /**
+ * Additional initialization
+ */
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Sales');
+ }
+
+ /**
+ * Initialize status model based on status code in request
+ *
+ * @return Mage_Sales_Model_Order_Status | false
+ */
+ protected function _initStatus()
+ {
+ $statusCode = $this->getRequest()->getParam('status');
+ if ($statusCode) {
+ $status = Mage::getModel('sales/order_status')->load($statusCode);
+ } else {
+ $status = false;
+ }
+ return $status;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/View/GiftmessageController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/View/GiftmessageController.php
index 86a38e31c6f..d202e992718 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/View/GiftmessageController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/View/GiftmessageController.php
@@ -28,14 +28,6 @@ class Mage_Adminhtml_Sales_Order_View_GiftmessageController extends Mage_Adminht
*/
public const ADMIN_RESOURCE = 'sales/order';
- /**
- * Additional initialization
- */
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Sales');
- }
-
public function saveAction()
{
try {
@@ -59,6 +51,14 @@ public function saveAction()
}
}
+ /**
+ * Additional initialization
+ */
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Sales');
+ }
+
/**
* Retrieve gift message save model
*
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
index 8c725343389..18a34736144 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
@@ -29,50 +29,6 @@ class Mage_Adminhtml_Sales_OrderController extends Mage_Adminhtml_Controller_Act
*/
protected $_publicActions = ['view', 'index'];
- /**
- * Additional initialization
- *
- */
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Sales');
- }
-
- /**
- * Init layout, menu and breadcrumb
- *
- * @return $this
- */
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('sales/order')
- ->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
- ->_addBreadcrumb($this->__('Orders'), $this->__('Orders'));
- return $this;
- }
-
- /**
- * Initialize order model instance
- *
- * @return Mage_Sales_Model_Order | false
- */
- protected function _initOrder()
- {
- $id = $this->getRequest()->getParam('order_id');
- $order = Mage::getModel('sales/order')->load($id);
-
- if (!$order->getId()) {
- $this->_getSession()->addError($this->__('This order no longer exists.'));
- $this->_redirect('*/*/');
- $this->setFlag('', self::FLAG_NO_DISPATCH, true);
- return false;
- }
- Mage::register('sales_order', $order);
- Mage::register('current_order', $order);
- return $order;
- }
-
/**
* Orders grid
*/
@@ -649,44 +605,6 @@ public function voidPaymentAction()
$this->_redirect('*/*/view', ['order_id' => $order->getId()]);
}
- /**
- * @inheritDoc
- */
- protected function _isAllowed()
- {
- $action = strtolower($this->getRequest()->getActionName());
- switch ($action) {
- case 'hold':
- $aclResource = 'sales/order/actions/hold';
- break;
- case 'unhold':
- $aclResource = 'sales/order/actions/unhold';
- break;
- case 'email':
- $aclResource = 'sales/order/actions/email';
- break;
- case 'cancel':
- $aclResource = 'sales/order/actions/cancel';
- break;
- case 'view':
- $aclResource = 'sales/order/actions/view';
- break;
- case 'addcomment':
- $aclResource = 'sales/order/actions/comment';
- break;
- case 'creditmemos':
- $aclResource = 'sales/order/actions/creditmemo';
- break;
- case 'reviewpayment':
- $aclResource = 'sales/order/actions/review_payment';
- break;
- default:
- $aclResource = 'sales/order';
- break;
- }
- return Mage::getSingleton('admin/session')->isAllowed($aclResource);
- }
-
/**
* Export order grid to CSV format
*/
@@ -783,4 +701,86 @@ public function preDispatch()
$this->_setForcedFormKeyActions('cancel', 'massCancel');
return parent::preDispatch();
}
+
+ /**
+ * Additional initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Sales');
+ }
+
+ /**
+ * Init layout, menu and breadcrumb
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('sales/order')
+ ->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
+ ->_addBreadcrumb($this->__('Orders'), $this->__('Orders'));
+ return $this;
+ }
+
+ /**
+ * Initialize order model instance
+ *
+ * @return Mage_Sales_Model_Order | false
+ */
+ protected function _initOrder()
+ {
+ $id = $this->getRequest()->getParam('order_id');
+ $order = Mage::getModel('sales/order')->load($id);
+
+ if (!$order->getId()) {
+ $this->_getSession()->addError($this->__('This order no longer exists.'));
+ $this->_redirect('*/*/');
+ $this->setFlag('', self::FLAG_NO_DISPATCH, true);
+ return false;
+ }
+ Mage::register('sales_order', $order);
+ Mage::register('current_order', $order);
+ return $order;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _isAllowed()
+ {
+ $action = strtolower($this->getRequest()->getActionName());
+ switch ($action) {
+ case 'hold':
+ $aclResource = 'sales/order/actions/hold';
+ break;
+ case 'unhold':
+ $aclResource = 'sales/order/actions/unhold';
+ break;
+ case 'email':
+ $aclResource = 'sales/order/actions/email';
+ break;
+ case 'cancel':
+ $aclResource = 'sales/order/actions/cancel';
+ break;
+ case 'view':
+ $aclResource = 'sales/order/actions/view';
+ break;
+ case 'addcomment':
+ $aclResource = 'sales/order/actions/comment';
+ break;
+ case 'creditmemos':
+ $aclResource = 'sales/order/actions/creditmemo';
+ break;
+ case 'reviewpayment':
+ $aclResource = 'sales/order/actions/review_payment';
+ break;
+ default:
+ $aclResource = 'sales/order';
+ break;
+ }
+ return Mage::getSingleton('admin/session')->isAllowed($aclResource);
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/TransactionsController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/TransactionsController.php
index c80e92db326..345c87b3a5d 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/TransactionsController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/TransactionsController.php
@@ -22,34 +22,6 @@
*/
class Mage_Adminhtml_Sales_TransactionsController extends Mage_Adminhtml_Controller_Action
{
- /**
- * Initialize payment transaction model
- *
- * @return Mage_Sales_Model_Order_Payment_Transaction | bool
- */
- protected function _initTransaction()
- {
- $txn = Mage::getModel('sales/order_payment_transaction')->load(
- $this->getRequest()->getParam('txn_id'),
- );
-
- if (!$txn->getId()) {
- $this->_getSession()->addError($this->__('Wrong transaction ID specified.'));
- $this->_redirect('*/*/');
- $this->setFlag('', self::FLAG_NO_DISPATCH, true);
- return false;
- }
- $orderId = $this->getRequest()->getParam('order_id');
- if ($orderId) {
- $txn->setOrderUrl(
- $this->getUrl('*/sales_order/view', ['order_id' => $orderId]),
- );
- }
-
- Mage::register('current_transaction', $txn);
- return $txn;
- }
-
public function indexAction()
{
$this->_title($this->__('Sales'))
@@ -114,6 +86,33 @@ public function fetchAction()
}
$this->_redirect('*/sales_transactions/view', ['_current' => true]);
}
+ /**
+ * Initialize payment transaction model
+ *
+ * @return Mage_Sales_Model_Order_Payment_Transaction | bool
+ */
+ protected function _initTransaction()
+ {
+ $txn = Mage::getModel('sales/order_payment_transaction')->load(
+ $this->getRequest()->getParam('txn_id'),
+ );
+
+ if (!$txn->getId()) {
+ $this->_getSession()->addError($this->__('Wrong transaction ID specified.'));
+ $this->_redirect('*/*/');
+ $this->setFlag('', self::FLAG_NO_DISPATCH, true);
+ return false;
+ }
+ $orderId = $this->getRequest()->getParam('order_id');
+ if ($orderId) {
+ $txn->setOrderUrl(
+ $this->getUrl('*/sales_order/view', ['order_id' => $orderId]),
+ );
+ }
+
+ Mage::register('current_transaction', $txn);
+ return $txn;
+ }
/**
* @inheritDoc
diff --git a/app/code/core/Mage/Adminhtml/controllers/SalesController.php b/app/code/core/Mage/Adminhtml/controllers/SalesController.php
index b1621a58070..61a72898078 100644
--- a/app/code/core/Mage/Adminhtml/controllers/SalesController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/SalesController.php
@@ -28,15 +28,6 @@ class Mage_Adminhtml_SalesController extends Mage_Adminhtml_Controller_Action
*/
public const ADMIN_RESOURCE = 'sales';
- /**
- * Additional initialization
- *
- */
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Sales');
- }
-
public function indexAction()
{
$this->loadLayout();
@@ -49,4 +40,13 @@ public function indexAction()
$this->_addBreadcrumb($this->__('Orders'), $this->__('Orders'));
$this->renderLayout();
}
+
+ /**
+ * Additional initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Sales');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/SitemapController.php b/app/code/core/Mage/Adminhtml/controllers/SitemapController.php
index 472dd11c136..f16c58f3ac4 100644
--- a/app/code/core/Mage/Adminhtml/controllers/SitemapController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/SitemapController.php
@@ -44,28 +44,6 @@ public function preDispatch()
return parent::preDispatch();
}
- /**
- * Init actions
- *
- * @return $this
- */
- protected function _initAction()
- {
- // load layout, set active menu and breadcrumbs
- $this->loadLayout()
- ->_setActiveMenu('catalog/sitemap')
- ->_addBreadcrumb(
- Mage::helper('catalog')->__('Catalog'),
- Mage::helper('catalog')->__('Catalog'),
- )
- ->_addBreadcrumb(
- Mage::helper('sitemap')->__('Google Sitemap'),
- Mage::helper('sitemap')->__('Google Sitemap'),
- )
- ;
- return $this;
- }
-
/**
* Index action
*/
@@ -303,4 +281,26 @@ public function generateAction()
// go to grid
$this->_redirect('*/*/');
}
+
+ /**
+ * Init actions
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ // load layout, set active menu and breadcrumbs
+ $this->loadLayout()
+ ->_setActiveMenu('catalog/sitemap')
+ ->_addBreadcrumb(
+ Mage::helper('catalog')->__('Catalog'),
+ Mage::helper('catalog')->__('Catalog'),
+ )
+ ->_addBreadcrumb(
+ Mage::helper('sitemap')->__('Google Sitemap'),
+ Mage::helper('sitemap')->__('Google Sitemap'),
+ )
+ ;
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/CacheController.php b/app/code/core/Mage/Adminhtml/controllers/System/CacheController.php
index f5d2f4b8536..25e1de00687 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/CacheController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/CacheController.php
@@ -28,16 +28,6 @@ class Mage_Adminhtml_System_CacheController extends Mage_Adminhtml_Controller_Ac
*/
public const ADMIN_RESOURCE = 'system/cache';
- /**
- * Retrieve session model
- *
- * @return Mage_Adminhtml_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('adminhtml/session');
- }
-
/**
* Display cache management form
*/
@@ -305,4 +295,14 @@ public function refreshLayeredNavigationAction()
$this->_redirect('*/*');
}
+
+ /**
+ * Retrieve session model
+ *
+ * @return Mage_Adminhtml_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('adminhtml/session');
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/Config/System/StorageController.php b/app/code/core/Mage/Adminhtml/controllers/System/Config/System/StorageController.php
index ff9c1c15c40..d2259a1c105 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/Config/System/StorageController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/Config/System/StorageController.php
@@ -28,26 +28,6 @@ class Mage_Adminhtml_System_Config_System_StorageController extends Mage_Adminht
*/
public const ADMIN_RESOURCE = 'system/config';
- /**
- * Return file storage singleton
- *
- * @return Mage_Core_Model_File_Storage
- */
- protected function _getSyncSingleton()
- {
- return Mage::getSingleton('core/file_storage');
- }
-
- /**
- * Return synchronize process status flag
- *
- * @return Mage_Core_Model_File_Storage_Flag
- */
- protected function _getSyncFlag()
- {
- return $this->_getSyncSingleton()->getSyncFlag();
- }
-
/**
* Synchronize action between storages
*
@@ -175,4 +155,24 @@ public function statusAction()
$result = Mage::helper('core')->jsonEncode($result);
Mage::app()->getResponse()->setBody($result);
}
+
+ /**
+ * Return file storage singleton
+ *
+ * @return Mage_Core_Model_File_Storage
+ */
+ protected function _getSyncSingleton()
+ {
+ return Mage::getSingleton('core/file_storage');
+ }
+
+ /**
+ * Return synchronize process status flag
+ *
+ * @return Mage_Core_Model_File_Storage_Flag
+ */
+ protected function _getSyncFlag()
+ {
+ return $this->_getSyncSingleton()->getSyncFlag();
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php b/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php
index 95e3e98bb9c..42a3d08e014 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php
@@ -204,30 +204,6 @@ public function saveAction()
$this->_redirect('*/*/edit', ['_current' => ['section', 'website', 'store']]);
}
- /**
- * Custom save logic for section
- */
- protected function _saveSection()
- {
- $method = '_save' . uc_words($this->getRequest()->getParam('section'), '');
- if (method_exists($this, $method)) {
- $this->$method();
- }
- }
-
- /**
- * Advanced save procedure
- */
- protected function _saveAdvanced()
- {
- Mage::app()->cleanCache(
- [
- 'layout',
- Mage_Core_Model_Layout_Update::LAYOUT_GENERAL_CACHE_TAG,
- ],
- );
- }
-
/**
* Save fieldset state through AJAX
*
@@ -266,6 +242,30 @@ public function exportTableratesAction()
$this->_prepareDownloadResponse($fileName, $content);
}
+ /**
+ * Custom save logic for section
+ */
+ protected function _saveSection()
+ {
+ $method = '_save' . uc_words($this->getRequest()->getParam('section'), '');
+ if (method_exists($this, $method)) {
+ $this->$method();
+ }
+ }
+
+ /**
+ * Advanced save procedure
+ */
+ protected function _saveAdvanced()
+ {
+ Mage::app()->cleanCache(
+ [
+ 'layout',
+ Mage_Core_Model_Layout_Update::LAYOUT_GENERAL_CACHE_TAG,
+ ],
+ );
+ }
+
/**
* Check if specified section allowed in ACL
*
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/Convert/ProfileController.php b/app/code/core/Mage/Adminhtml/controllers/System/Convert/ProfileController.php
index 1591a874d84..7c357fc251f 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/Convert/ProfileController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/Convert/ProfileController.php
@@ -28,32 +28,6 @@ class Mage_Adminhtml_System_Convert_ProfileController extends Mage_Adminhtml_Con
*/
public const ADMIN_RESOURCE = 'admin/system/convert/profiles';
- protected function _initProfile($idFieldName = 'id')
- {
- $this->_title($this->__('System'))
- ->_title($this->__('Import and Export'))
- ->_title($this->__('Profiles'));
-
- $profileId = (int) $this->getRequest()->getParam($idFieldName);
- $profile = Mage::getModel('dataflow/profile');
-
- if ($profileId) {
- $profile->load($profileId);
- if (!$profile->getId()) {
- Mage::getSingleton('adminhtml/session')->addError(
- $this->__('The profile you are trying to save no longer exists'),
- );
- $this->_redirect('*/*');
- return false;
- }
- }
-
- $profile->setAdminUserId(Mage::getSingleton('admin/session')->getUser()->getId());
- Mage::register('current_convert_profile', $profile);
-
- return $this;
- }
-
/**
* Profiles list action
*/
@@ -312,4 +286,30 @@ public function historyAction()
$this->getLayout()->createBlock('adminhtml/system_convert_profile_edit_tab_history')->toHtml(),
);
}
+
+ protected function _initProfile($idFieldName = 'id')
+ {
+ $this->_title($this->__('System'))
+ ->_title($this->__('Import and Export'))
+ ->_title($this->__('Profiles'));
+
+ $profileId = (int) $this->getRequest()->getParam($idFieldName);
+ $profile = Mage::getModel('dataflow/profile');
+
+ if ($profileId) {
+ $profile->load($profileId);
+ if (!$profile->getId()) {
+ Mage::getSingleton('adminhtml/session')->addError(
+ $this->__('The profile you are trying to save no longer exists'),
+ );
+ $this->_redirect('*/*');
+ return false;
+ }
+ }
+
+ $profile->setAdminUserId(Mage::getSingleton('admin/session')->getUser()->getId());
+ Mage::register('current_convert_profile', $profile);
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/CurrencyController.php b/app/code/core/Mage/Adminhtml/controllers/System/CurrencyController.php
index e7db0e9aad7..5267ee40ba3 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/CurrencyController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/CurrencyController.php
@@ -28,21 +28,6 @@ class Mage_Adminhtml_System_CurrencyController extends Mage_Adminhtml_Controller
*/
public const ADMIN_RESOURCE = 'system/currency/rates';
- /**
- * Init currency by currency code from request
- *
- * @return Mage_Adminhtml_Controller_Action
- */
- protected function _initCurrency()
- {
- $code = $this->getRequest()->getParam('currency');
- $currency = Mage::getModel('directory/currency')
- ->load($code);
-
- Mage::register('currency', $currency);
- return $this;
- }
-
/**
* Currency management main page
*/
@@ -113,4 +98,19 @@ public function saveRatesAction()
$this->_redirect('*/*/');
}
+
+ /**
+ * Init currency by currency code from request
+ *
+ * @return Mage_Adminhtml_Controller_Action
+ */
+ protected function _initCurrency()
+ {
+ $code = $this->getRequest()->getParam('currency');
+ $currency = Mage::getModel('directory/currency')
+ ->load($code);
+
+ Mage::register('currency', $currency);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/StoreController.php b/app/code/core/Mage/Adminhtml/controllers/System/StoreController.php
index 29ad5f08df9..cd988e9b6b9 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/StoreController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/StoreController.php
@@ -39,22 +39,6 @@ public function preDispatch()
return parent::preDispatch();
}
- /**
- * Init actions
- *
- * @return $this
- */
- protected function _initAction()
- {
- // load layout, set active menu and breadcrumbs
- $this->loadLayout()
- ->_setActiveMenu('system/store')
- ->_addBreadcrumb(Mage::helper('adminhtml')->__('System'), Mage::helper('adminhtml')->__('System'))
- ->_addBreadcrumb(Mage::helper('adminhtml')->__('Manage Stores'), Mage::helper('adminhtml')->__('Manage Stores'))
- ;
- return $this;
- }
-
public function indexAction()
{
$this->_title($this->__('System'))
@@ -445,6 +429,22 @@ public function deleteStorePostAction()
$this->_redirect('*/*/editStore', ['store_id' => $itemId]);
}
+ /**
+ * Init actions
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ // load layout, set active menu and breadcrumbs
+ $this->loadLayout()
+ ->_setActiveMenu('system/store')
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('System'), Mage::helper('adminhtml')->__('System'))
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('Manage Stores'), Mage::helper('adminhtml')->__('Manage Stores'))
+ ;
+ return $this;
+ }
+
/**
* Backup database
*
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/VariableController.php b/app/code/core/Mage/Adminhtml/controllers/System/VariableController.php
index 921625e0b74..0437a63fd22 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/VariableController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/VariableController.php
@@ -28,41 +28,6 @@ class Mage_Adminhtml_System_VariableController extends Mage_Adminhtml_Controller
*/
public const ADMIN_RESOURCE = 'system/variable';
- /**
- * Initialize Layout and set breadcrumbs
- *
- * @return $this
- */
- protected function _initLayout()
- {
- $this->loadLayout()
- ->_setActiveMenu('system/variable')
- ->_addBreadcrumb(Mage::helper('adminhtml')->__('Custom Variables'), Mage::helper('adminhtml')->__('Custom Variables'));
- return $this;
- }
-
- /**
- * Initialize Variable object
- *
- * @return Mage_Core_Model_Variable
- * @throws Mage_Core_Exception
- */
- protected function _initVariable()
- {
- $this->_title($this->__('System'))->_title($this->__('Custom Variables'));
-
- $variableId = $this->getRequest()->getParam('variable_id', null);
- $storeId = (int) $this->getRequest()->getParam('store', 0);
- /** @var Mage_Core_Model_Variable $variable */
- $variable = Mage::getModel('core/variable');
- if ($variableId) {
- $variable->setStoreId($storeId)
- ->load($variableId);
- }
- Mage::register('current_variable', $variable);
- return $variable;
- }
-
/**
* Index Action
*/
@@ -185,4 +150,39 @@ public function wysiwygPluginAction()
$variables = [$storeContactVariabls, $customVariables];
$this->getResponse()->setBody(Zend_Json::encode($variables));
}
+
+ /**
+ * Initialize Layout and set breadcrumbs
+ *
+ * @return $this
+ */
+ protected function _initLayout()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('system/variable')
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('Custom Variables'), Mage::helper('adminhtml')->__('Custom Variables'));
+ return $this;
+ }
+
+ /**
+ * Initialize Variable object
+ *
+ * @return Mage_Core_Model_Variable
+ * @throws Mage_Core_Exception
+ */
+ protected function _initVariable()
+ {
+ $this->_title($this->__('System'))->_title($this->__('Custom Variables'));
+
+ $variableId = $this->getRequest()->getParam('variable_id', null);
+ $storeId = (int) $this->getRequest()->getParam('store', 0);
+ /** @var Mage_Core_Model_Variable $variable */
+ $variable = Mage::getModel('core/variable');
+ if ($variableId) {
+ $variable->setStoreId($storeId)
+ ->load($variableId);
+ }
+ Mage::register('current_variable', $variable);
+ return $variable;
+ }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/TagController.php b/app/code/core/Mage/Adminhtml/controllers/TagController.php
index a39b5a0fcb3..4c48cec865d 100644
--- a/app/code/core/Mage/Adminhtml/controllers/TagController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/TagController.php
@@ -22,41 +22,6 @@
*/
class Mage_Adminhtml_TagController extends Mage_Adminhtml_Controller_Action
{
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('catalog/tag')
- ->_addBreadcrumb(Mage::helper('adminhtml')->__('Catalog'), Mage::helper('adminhtml')->__('Catalog'))
- ->_addBreadcrumb(Mage::helper('adminhtml')->__('Tags'), Mage::helper('adminhtml')->__('Tags'));
-
- return $this;
- }
-
- /**
- * Prepare tag model for manipulation
- *
- * @return Mage_Tag_Model_Tag | false
- */
- protected function _initTag()
- {
- $model = Mage::getModel('tag/tag');
- $storeId = $this->getRequest()->getParam('store');
- $model->setStoreId($storeId);
-
- if (($id = $this->getRequest()->getParam('tag_id'))) {
- $model->setAddBasePopularity();
- $model->load($id);
- $model->setStoreId($storeId);
-
- if (!$model->getId()) {
- return false;
- }
- }
-
- Mage::register('current_tag', $model);
- return $model;
- }
-
/**
* Show grid action
*
@@ -324,6 +289,40 @@ public function massStatusAction()
$ret = $this->getRequest()->getParam('ret') ? $this->getRequest()->getParam('ret') : 'index';
$this->_redirect('*/*/' . $ret);
}
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('catalog/tag')
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('Catalog'), Mage::helper('adminhtml')->__('Catalog'))
+ ->_addBreadcrumb(Mage::helper('adminhtml')->__('Tags'), Mage::helper('adminhtml')->__('Tags'));
+
+ return $this;
+ }
+
+ /**
+ * Prepare tag model for manipulation
+ *
+ * @return Mage_Tag_Model_Tag | false
+ */
+ protected function _initTag()
+ {
+ $model = Mage::getModel('tag/tag');
+ $storeId = $this->getRequest()->getParam('store');
+ $model->setStoreId($storeId);
+
+ if (($id = $this->getRequest()->getParam('tag_id'))) {
+ $model->setAddBasePopularity();
+ $model->load($id);
+ $model->setStoreId($storeId);
+
+ if (!$model->getId()) {
+ return false;
+ }
+ }
+
+ Mage::register('current_tag', $model);
+ return $model;
+ }
/**
* @inheritDoc
diff --git a/app/code/core/Mage/Adminhtml/controllers/Tax/RateController.php b/app/code/core/Mage/Adminhtml/controllers/Tax/RateController.php
index b8281621f67..c014971300f 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Tax/RateController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Tax/RateController.php
@@ -213,20 +213,6 @@ public function exportXmlAction()
$this->_prepareDownloadResponse($fileName, $content);
}
- /**
- * Initialize action
- *
- * @return Mage_Adminhtml_Controller_Action
- */
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('sales/tax/rates')
- ->_addBreadcrumb(Mage::helper('tax')->__('Sales'), Mage::helper('tax')->__('Sales'))
- ->_addBreadcrumb(Mage::helper('tax')->__('Tax'), Mage::helper('tax')->__('Tax'));
- return $this;
- }
-
/**
* Import and export Page
*
@@ -268,6 +254,86 @@ public function importPostAction()
$this->_redirect('*/*/importExport');
}
+ /**
+ * export action from import/export tax
+ *
+ */
+ public function exportPostAction()
+ {
+ /** start csv content and set template */
+ $headers = new Varien_Object([
+ 'code' => Mage::helper('tax')->__('Code'),
+ 'country_name' => Mage::helper('tax')->__('Country'),
+ 'region_name' => Mage::helper('tax')->__('State'),
+ 'tax_postcode' => Mage::helper('tax')->__('Zip/Post Code'),
+ 'rate' => Mage::helper('tax')->__('Rate'),
+ 'zip_is_range' => Mage::helper('tax')->__('Zip/Post is Range'),
+ 'zip_from' => Mage::helper('tax')->__('Range From'),
+ 'zip_to' => Mage::helper('tax')->__('Range To'),
+ ]);
+ $template = '"{{code}}","{{country_name}}","{{region_name}}","{{tax_postcode}}","{{rate}}"'
+ . ',"{{zip_is_range}}","{{zip_from}}","{{zip_to}}"';
+ $content = $headers->toString($template);
+
+ $storeTaxTitleTemplate = [];
+ $taxCalculationRateTitleDict = [];
+
+ foreach (Mage::getModel('core/store')->getCollection()->setLoadDefault(false) as $store) {
+ $storeTitle = 'title_' . $store->getId();
+ $content .= ',"' . $store->getCode() . '"';
+ $template .= ',"{{' . $storeTitle . '}}"';
+ $storeTaxTitleTemplate[$storeTitle] = null;
+ }
+ unset($store);
+
+ $content .= "\n";
+
+ foreach (Mage::getModel('tax/calculation_rate_title')->getCollection() as $title) {
+ $rateId = $title->getTaxCalculationRateId();
+
+ if (!array_key_exists($rateId, $taxCalculationRateTitleDict)) {
+ $taxCalculationRateTitleDict[$rateId] = $storeTaxTitleTemplate;
+ }
+
+ $taxCalculationRateTitleDict[$rateId]['title_' . $title->getStoreId()] = $title->getValue();
+ }
+ unset($title);
+
+ $collection = Mage::getResourceModel('tax/calculation_rate_collection')
+ ->joinCountryTable()
+ ->joinRegionTable();
+
+ while ($rate = $collection->fetchItem()) {
+ if ($rate->getTaxRegionId() == 0) {
+ $rate->setRegionName('*');
+ }
+
+ if (array_key_exists($rate->getId(), $taxCalculationRateTitleDict)) {
+ $rate->addData($taxCalculationRateTitleDict[$rate->getId()]);
+ } else {
+ $rate->addData($storeTaxTitleTemplate);
+ }
+
+ $content .= $rate->toString($template) . "\n";
+ }
+
+ $this->_prepareDownloadResponse('tax_rates.csv', $content);
+ }
+
+ /**
+ * Initialize action
+ *
+ * @return Mage_Adminhtml_Controller_Action
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('sales/tax/rates')
+ ->_addBreadcrumb(Mage::helper('tax')->__('Sales'), Mage::helper('tax')->__('Sales'))
+ ->_addBreadcrumb(Mage::helper('tax')->__('Tax'), Mage::helper('tax')->__('Tax'));
+ return $this;
+ }
+
/**
* @SuppressWarnings("PHPMD.Superglobals")
*/
@@ -390,72 +456,6 @@ protected function _importRates()
}
}
- /**
- * export action from import/export tax
- *
- */
- public function exportPostAction()
- {
- /** start csv content and set template */
- $headers = new Varien_Object([
- 'code' => Mage::helper('tax')->__('Code'),
- 'country_name' => Mage::helper('tax')->__('Country'),
- 'region_name' => Mage::helper('tax')->__('State'),
- 'tax_postcode' => Mage::helper('tax')->__('Zip/Post Code'),
- 'rate' => Mage::helper('tax')->__('Rate'),
- 'zip_is_range' => Mage::helper('tax')->__('Zip/Post is Range'),
- 'zip_from' => Mage::helper('tax')->__('Range From'),
- 'zip_to' => Mage::helper('tax')->__('Range To'),
- ]);
- $template = '"{{code}}","{{country_name}}","{{region_name}}","{{tax_postcode}}","{{rate}}"'
- . ',"{{zip_is_range}}","{{zip_from}}","{{zip_to}}"';
- $content = $headers->toString($template);
-
- $storeTaxTitleTemplate = [];
- $taxCalculationRateTitleDict = [];
-
- foreach (Mage::getModel('core/store')->getCollection()->setLoadDefault(false) as $store) {
- $storeTitle = 'title_' . $store->getId();
- $content .= ',"' . $store->getCode() . '"';
- $template .= ',"{{' . $storeTitle . '}}"';
- $storeTaxTitleTemplate[$storeTitle] = null;
- }
- unset($store);
-
- $content .= "\n";
-
- foreach (Mage::getModel('tax/calculation_rate_title')->getCollection() as $title) {
- $rateId = $title->getTaxCalculationRateId();
-
- if (!array_key_exists($rateId, $taxCalculationRateTitleDict)) {
- $taxCalculationRateTitleDict[$rateId] = $storeTaxTitleTemplate;
- }
-
- $taxCalculationRateTitleDict[$rateId]['title_' . $title->getStoreId()] = $title->getValue();
- }
- unset($title);
-
- $collection = Mage::getResourceModel('tax/calculation_rate_collection')
- ->joinCountryTable()
- ->joinRegionTable();
-
- while ($rate = $collection->fetchItem()) {
- if ($rate->getTaxRegionId() == 0) {
- $rate->setRegionName('*');
- }
-
- if (array_key_exists($rate->getId(), $taxCalculationRateTitleDict)) {
- $rate->addData($taxCalculationRateTitleDict[$rate->getId()]);
- } else {
- $rate->addData($storeTaxTitleTemplate);
- }
-
- $content .= $rate->toString($template) . "\n";
- }
-
- $this->_prepareDownloadResponse('tax_rates.csv', $content);
- }
-
/**
* @inheritDoc
*/
diff --git a/app/code/core/Mage/Adminhtml/controllers/Tax/RuleController.php b/app/code/core/Mage/Adminhtml/controllers/Tax/RuleController.php
index 8a1f57250d2..db8fb306d24 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Tax/RuleController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Tax/RuleController.php
@@ -136,37 +136,6 @@ public function saveAction()
$this->_redirectReferer();
}
- /**
- * Check if this a duplicate rule creation request
- *
- * @param Mage_Tax_Model_Calculation_Rule $ruleModel
- * @return bool
- */
- protected function _isValidRuleRequest($ruleModel)
- {
- $existingRules = $ruleModel->fetchRuleCodes(
- $ruleModel->getTaxRate(),
- $ruleModel->getTaxCustomerClass(),
- $ruleModel->getTaxProductClass(),
- );
-
- /** @var Mage_Adminhtml_Model_Session $session */
- $session = $this->_getSingletonModel('adminhtml/session');
-
- //Remove the current one from the list
- $existingRules = array_diff($existingRules, [$ruleModel->getOrigData('code')]);
-
- //Verify if a Rule already exists. If not throw an error
- if (count($existingRules) > 0) {
- $ruleCodes = implode(',', $existingRules);
- $session->addError(
- $this->_getHelperModel('tax')->__('Rules (%s) already exist for the specified Tax Rate, Customer Tax Class and Product Tax Class combinations', $ruleCodes),
- );
- return false;
- }
- return true;
- }
-
/**
* Delete action
*/
@@ -199,6 +168,48 @@ public function deleteAction()
$this->_redirectReferer();
}
+ /**
+ * Controller pre-dispatch method
+ *
+ * @return Mage_Adminhtml_Controller_Action
+ */
+ public function preDispatch()
+ {
+ $this->_setForcedFormKeyActions('delete');
+ return parent::preDispatch();
+ }
+
+ /**
+ * Check if this a duplicate rule creation request
+ *
+ * @param Mage_Tax_Model_Calculation_Rule $ruleModel
+ * @return bool
+ */
+ protected function _isValidRuleRequest($ruleModel)
+ {
+ $existingRules = $ruleModel->fetchRuleCodes(
+ $ruleModel->getTaxRate(),
+ $ruleModel->getTaxCustomerClass(),
+ $ruleModel->getTaxProductClass(),
+ );
+
+ /** @var Mage_Adminhtml_Model_Session $session */
+ $session = $this->_getSingletonModel('adminhtml/session');
+
+ //Remove the current one from the list
+ $existingRules = array_diff($existingRules, [$ruleModel->getOrigData('code')]);
+
+ //Verify if a Rule already exists. If not throw an error
+ if (count($existingRules) > 0) {
+ $ruleCodes = implode(',', $existingRules);
+ $session->addError(
+ $this->_getHelperModel('tax')->__('Rules (%s) already exist for the specified Tax Rate, Customer Tax Class and Product Tax Class combinations', $ruleCodes),
+ );
+ return false;
+ }
+ return true;
+ }
+
/**
* Initialize action
*
@@ -236,15 +247,4 @@ protected function _getHelperModel($className)
{
return Mage::helper($className);
}
-
- /**
- * Controller pre-dispatch method
- *
- * @return Mage_Adminhtml_Controller_Action
- */
- public function preDispatch()
- {
- $this->_setForcedFormKeyActions('delete');
- return parent::preDispatch();
- }
}
diff --git a/app/code/core/Mage/Adminhtml/controllers/UrlrewriteController.php b/app/code/core/Mage/Adminhtml/controllers/UrlrewriteController.php
index f95e56a47fe..318159acb42 100644
--- a/app/code/core/Mage/Adminhtml/controllers/UrlrewriteController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/UrlrewriteController.php
@@ -28,34 +28,6 @@ class Mage_Adminhtml_UrlrewriteController extends Mage_Adminhtml_Controller_Acti
*/
public const ADMIN_RESOURCE = 'catalog/urlrewrite';
- /**
- * Instantiate urlrewrite, product and category
- *
- * @return $this
- */
- protected function _initRegistry()
- {
- $this->_title($this->__('Rewrite Rules'));
-
- // initialize urlrewrite, product and category models
- Mage::register(
- 'current_urlrewrite',
- Mage::getSingleton('core/factory')->getUrlRewriteInstance()
- ->load($this->getRequest()->getParam('id', 0)),
- );
- $productId = $this->getRequest()->getParam('product', 0);
- $categoryId = $this->getRequest()->getParam('category', 0);
- if (Mage::registry('current_urlrewrite')->getId()) {
- $productId = Mage::registry('current_urlrewrite')->getProductId();
- $categoryId = Mage::registry('current_urlrewrite')->getCategoryId();
- }
-
- Mage::register('current_product', Mage::getModel('catalog/product')->load($productId));
- Mage::register('current_category', Mage::getModel('catalog/category')->load($categoryId));
-
- return $this;
- }
-
/**
* Show urlrewrites index page
*
@@ -217,4 +189,32 @@ public function deleteAction()
}
$this->_redirect('*/*/');
}
+
+ /**
+ * Instantiate urlrewrite, product and category
+ *
+ * @return $this
+ */
+ protected function _initRegistry()
+ {
+ $this->_title($this->__('Rewrite Rules'));
+
+ // initialize urlrewrite, product and category models
+ Mage::register(
+ 'current_urlrewrite',
+ Mage::getSingleton('core/factory')->getUrlRewriteInstance()
+ ->load($this->getRequest()->getParam('id', 0)),
+ );
+ $productId = $this->getRequest()->getParam('product', 0);
+ $categoryId = $this->getRequest()->getParam('category', 0);
+ if (Mage::registry('current_urlrewrite')->getId()) {
+ $productId = Mage::registry('current_urlrewrite')->getProductId();
+ $categoryId = Mage::registry('current_urlrewrite')->getCategoryId();
+ }
+
+ Mage::register('current_product', Mage::getModel('catalog/product')->load($productId));
+ Mage::register('current_category', Mage::getModel('catalog/category')->load($categoryId));
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Api/Helper/Data.php b/app/code/core/Mage/Api/Helper/Data.php
index 4ff99e1d8a9..1ef301f3772 100644
--- a/app/code/core/Mage/Api/Helper/Data.php
+++ b/app/code/core/Mage/Api/Helper/Data.php
@@ -287,37 +287,6 @@ public function parseFilters($filters, $fieldsMap = null)
return $filters;
}
- /**
- * Parses complex filter, which may contain several nodes, e.g. when user want to fetch orders which were updated
- * between two dates.
- *
- * @param array $complexFilter
- * @return array
- */
- protected function _parseComplexFilter($complexFilter)
- {
- $parsedFilters = [];
-
- foreach ($complexFilter as $filter) {
- if (!isset($filter->key) || !isset($filter->value)) {
- continue;
- }
- $fieldName = $filter->key;
- $condition = $filter->value;
- $conditionName = $condition->key;
- $conditionValue = $condition->value;
- $this->formatFilterConditionValue($conditionName, $conditionValue);
-
- if (array_key_exists($fieldName, $parsedFilters)) {
- $parsedFilters[$fieldName] += [$conditionName => $conditionValue];
- } else {
- $parsedFilters[$fieldName] = [$conditionName => $conditionValue];
- }
- }
-
- return $parsedFilters;
- }
-
/**
* Convert condition value from the string into the array
* for the condition operators that require value to be an array.
@@ -379,4 +348,35 @@ public function getServiceUrl($routePath = null, $routeParams = null, $htmlSpeci
return $htmlSpecialChars === true ? htmlspecialchars($uri) : (string) $uri;
}
+
+ /**
+ * Parses complex filter, which may contain several nodes, e.g. when user want to fetch orders which were updated
+ * between two dates.
+ *
+ * @param array $complexFilter
+ * @return array
+ */
+ protected function _parseComplexFilter($complexFilter)
+ {
+ $parsedFilters = [];
+
+ foreach ($complexFilter as $filter) {
+ if (!isset($filter->key) || !isset($filter->value)) {
+ continue;
+ }
+ $fieldName = $filter->key;
+ $condition = $filter->value;
+ $conditionName = $condition->key;
+ $conditionValue = $condition->value;
+ $this->formatFilterConditionValue($conditionName, $conditionValue);
+
+ if (array_key_exists($fieldName, $parsedFilters)) {
+ $parsedFilters[$fieldName] += [$conditionName => $conditionValue];
+ } else {
+ $parsedFilters[$fieldName] = [$conditionName => $conditionValue];
+ }
+ }
+
+ return $parsedFilters;
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Acl.php b/app/code/core/Mage/Api/Model/Acl.php
index abb8a9dbe54..14759b6dd42 100644
--- a/app/code/core/Mage/Api/Model/Acl.php
+++ b/app/code/core/Mage/Api/Model/Acl.php
@@ -63,19 +63,6 @@ class Mage_Api_Model_Acl extends Zend_Acl
*/
public const RULE_PERM_ALLOW = 2;
- /**
- * Get role registry object or create one
- *
- * @return Mage_Api_Model_Acl_Role_Registry
- */
- protected function _getRoleRegistry()
- {
- if ($this->_roleRegistry === null) {
- $this->_roleRegistry = Mage::getModel('api/acl_role_registry');
- }
- return $this->_roleRegistry;
- }
-
/**
* Add parent to role object
*
@@ -88,4 +75,17 @@ public function addRoleParent($role, $parent)
$this->_getRoleRegistry()->addParent($role, $parent);
return $this;
}
+
+ /**
+ * Get role registry object or create one
+ *
+ * @return Mage_Api_Model_Acl_Role_Registry
+ */
+ protected function _getRoleRegistry()
+ {
+ if ($this->_roleRegistry === null) {
+ $this->_roleRegistry = Mage::getModel('api/acl_role_registry');
+ }
+ return $this->_roleRegistry;
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Config.php b/app/code/core/Mage/Api/Model/Config.php
index 66a3b30c5a3..8ba67751556 100644
--- a/app/code/core/Mage/Api/Model/Config.php
+++ b/app/code/core/Mage/Api/Model/Config.php
@@ -37,28 +37,6 @@ public function __construct($sourceData = null)
$this->_construct();
}
- /**
- * Init configuration for webservices api
- *
- * @return $this
- */
- protected function _construct()
- {
- if (Mage::app()->useCache('config_api')) {
- if ($this->loadCache()) {
- return $this;
- }
- }
-
- $config = Mage::getConfig()->loadModulesConfiguration('api.xml');
- $this->setXml($config->getNode('api'));
-
- if (Mage::app()->useCache('config_api')) {
- $this->saveCache();
- }
- return $this;
- }
-
/**
* Retrieve adapter aliases from config.
*
@@ -257,6 +235,28 @@ public function getCache()
return Mage::app()->getCache();
}
+ /**
+ * Init configuration for webservices api
+ *
+ * @return $this
+ */
+ protected function _construct()
+ {
+ if (Mage::app()->useCache('config_api')) {
+ if ($this->loadCache()) {
+ return $this;
+ }
+ }
+
+ $config = Mage::getConfig()->loadModulesConfiguration('api.xml');
+ $this->setXml($config->getNode('api'));
+
+ if (Mage::app()->useCache('config_api')) {
+ $this->saveCache();
+ }
+ return $this;
+ }
+
/**
* @param string $id
* @return bool|mixed
diff --git a/app/code/core/Mage/Api/Model/Resource/Abstract.php b/app/code/core/Mage/Api/Model/Resource/Abstract.php
index b49baf9ba57..dc2d8d63ca8 100644
--- a/app/code/core/Mage/Api/Model/Resource/Abstract.php
+++ b/app/code/core/Mage/Api/Model/Resource/Abstract.php
@@ -30,44 +30,44 @@ class Mage_Api_Model_Resource_Abstract
protected $_resourceConfig = null;
/**
- * Retrieve webservice session
+ * Set configuration for api resource
*
- * @return Mage_Api_Model_Session
+ * @return $this
*/
- protected function _getSession()
+ public function setResourceConfig(Varien_Simplexml_Element $xml)
{
- return Mage::getSingleton('api/session');
+ $this->_resourceConfig = $xml;
+ return $this;
}
/**
- * Retrieve webservice configuration
+ * Retrieve configuration for api resource
*
- * @return Mage_Api_Model_Config
+ * @return Varien_Simplexml_Element
*/
- protected function _getConfig()
+ public function getResourceConfig()
{
- return Mage::getSingleton('api/config');
+ return $this->_resourceConfig;
}
/**
- * Set configuration for api resource
+ * Retrieve webservice session
*
- * @return $this
+ * @return Mage_Api_Model_Session
*/
- public function setResourceConfig(Varien_Simplexml_Element $xml)
+ protected function _getSession()
{
- $this->_resourceConfig = $xml;
- return $this;
+ return Mage::getSingleton('api/session');
}
/**
- * Retrieve configuration for api resource
+ * Retrieve webservice configuration
*
- * @return Varien_Simplexml_Element
+ * @return Mage_Api_Model_Config
*/
- public function getResourceConfig()
+ protected function _getConfig()
{
- return $this->_resourceConfig;
+ return Mage::getSingleton('api/config');
}
/**
diff --git a/app/code/core/Mage/Api/Model/Resource/Acl.php b/app/code/core/Mage/Api/Model/Resource/Acl.php
index 6bc51511f79..d5e39ff0f99 100644
--- a/app/code/core/Mage/Api/Model/Resource/Acl.php
+++ b/app/code/core/Mage/Api/Model/Resource/Acl.php
@@ -22,15 +22,6 @@
*/
class Mage_Api_Model_Resource_Acl extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Initialize resource connections
- *
- */
- protected function _construct()
- {
- $this->_init('api/role', 'role_id');
- }
-
/**
* Load ACL for the user
*
@@ -122,4 +113,12 @@ public function loadRules(Mage_Api_Model_Acl $acl, array $rulesArr)
}
return $this;
}
+ /**
+ * Initialize resource connections
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('api/role', 'role_id');
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Resource/Role.php b/app/code/core/Mage/Api/Model/Resource/Role.php
index 2001879e5fc..6b45c092e23 100644
--- a/app/code/core/Mage/Api/Model/Resource/Role.php
+++ b/app/code/core/Mage/Api/Model/Resource/Role.php
@@ -22,6 +22,16 @@
*/
class Mage_Api_Model_Resource_Role extends Mage_Core_Model_Resource_Db_Abstract
{
+ /**
+ * @inheritDoc
+ */
+ public function load(Mage_Core_Model_Abstract $object, $value, $field = null)
+ {
+ if (!(int) $value && is_string($value)) {
+ $field = 'role_id';
+ }
+ return parent::load($object, $value, $field);
+ }
protected function _construct()
{
$this->_init('api/role', 'role_id');
@@ -41,15 +51,4 @@ protected function _beforeSave(Mage_Core_Model_Abstract $object)
$object->setModified($now);
return $this;
}
-
- /**
- * @inheritDoc
- */
- public function load(Mage_Core_Model_Abstract $object, $value, $field = null)
- {
- if (!(int) $value && is_string($value)) {
- $field = 'role_id';
- }
- return parent::load($object, $value, $field);
- }
}
diff --git a/app/code/core/Mage/Api/Model/Resource/Role/Collection.php b/app/code/core/Mage/Api/Model/Resource/Role/Collection.php
index 1bbce7a3f0a..cb4beb888b8 100644
--- a/app/code/core/Mage/Api/Model/Resource/Role/Collection.php
+++ b/app/code/core/Mage/Api/Model/Resource/Role/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Api_Model_Resource_Role_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Resource collection initialization
- *
- */
- protected function _construct()
- {
- $this->_init('api/role');
- }
-
/**
* Aet user filter
*
@@ -54,4 +45,12 @@ public function setRolesFilter()
$this->addFieldToFilter('role_type', Mage_Api_Model_Acl::ROLE_TYPE_GROUP);
return $this;
}
+ /**
+ * Resource collection initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('api/role');
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Resource/Roles.php b/app/code/core/Mage/Api/Model/Resource/Roles.php
index 2607833060e..12eb78d8c6e 100644
--- a/app/code/core/Mage/Api/Model/Resource/Roles.php
+++ b/app/code/core/Mage/Api/Model/Resource/Roles.php
@@ -36,6 +36,22 @@ class Mage_Api_Model_Resource_Roles extends Mage_Core_Model_Resource_Db_Abstract
*/
protected $_ruleTable;
+ /**
+ * Get role users
+ *
+ * @return array
+ */
+ public function getRoleUsers(Mage_Api_Model_Roles $role)
+ {
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from($this->getMainTable(), ['user_id'])
+ ->where('parent_id = ?', $role->getId())
+ ->where('role_type = ?', Mage_Api_Model_Acl::ROLE_TYPE_USER)
+ ->where('user_id > 0');
+ return $adapter->fetchCol($select);
+ }
+
protected function _construct()
{
$this->_init('api/role', 'role_id');
@@ -96,22 +112,6 @@ protected function _afterDelete(Mage_Core_Model_Abstract $role)
return $this;
}
- /**
- * Get role users
- *
- * @return array
- */
- public function getRoleUsers(Mage_Api_Model_Roles $role)
- {
- $adapter = $this->_getReadAdapter();
- $select = $adapter->select()
- ->from($this->getMainTable(), ['user_id'])
- ->where('parent_id = ?', $role->getId())
- ->where('role_type = ?', Mage_Api_Model_Acl::ROLE_TYPE_USER)
- ->where('user_id > 0');
- return $adapter->fetchCol($select);
- }
-
/**
* Update role users
*
diff --git a/app/code/core/Mage/Api/Model/Resource/Roles/Collection.php b/app/code/core/Mage/Api/Model/Resource/Roles/Collection.php
index c9fb0bca65b..429f95b4d39 100644
--- a/app/code/core/Mage/Api/Model/Resource/Roles/Collection.php
+++ b/app/code/core/Mage/Api/Model/Resource/Roles/Collection.php
@@ -22,6 +22,15 @@
*/
class Mage_Api_Model_Resource_Roles_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
+ /**
+ * Convert items array to array for select options
+ *
+ * @return array
+ */
+ public function toOptionArray()
+ {
+ return $this->_toOptionArray('role_id', 'role_name');
+ }
/**
* Resource collection initialization
*
@@ -42,14 +51,4 @@ protected function _initSelect()
$this->getSelect()->where('main_table.role_type = ?', Mage_Api_Model_Acl::ROLE_TYPE_GROUP);
return $this;
}
-
- /**
- * Convert items array to array for select options
- *
- * @return array
- */
- public function toOptionArray()
- {
- return $this->_toOptionArray('role_id', 'role_name');
- }
}
diff --git a/app/code/core/Mage/Api/Model/Resource/Rules.php b/app/code/core/Mage/Api/Model/Resource/Rules.php
index 2960fcb86bb..a0e8eac63ff 100644
--- a/app/code/core/Mage/Api/Model/Resource/Rules.php
+++ b/app/code/core/Mage/Api/Model/Resource/Rules.php
@@ -22,11 +22,6 @@
*/
class Mage_Api_Model_Resource_Rules extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('api/rule', 'rule_id');
- }
-
/**
* Save rule
*/
@@ -68,4 +63,8 @@ public function saveRel(Mage_Api_Model_Rules $rule)
$adapter->rollBack();
}
}
+ protected function _construct()
+ {
+ $this->_init('api/rule', 'rule_id');
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Resource/Rules/Collection.php b/app/code/core/Mage/Api/Model/Resource/Rules/Collection.php
index e21ef1cb475..80c3ed87645 100644
--- a/app/code/core/Mage/Api/Model/Resource/Rules/Collection.php
+++ b/app/code/core/Mage/Api/Model/Resource/Rules/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Api_Model_Resource_Rules_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Resource collection initialization
- *
- */
- protected function _construct()
- {
- $this->_init('api/rules');
- }
-
/**
* Retrieve rules by role
*
@@ -54,4 +45,12 @@ public function addSortByLength()
->order('length DESC');
return $this;
}
+ /**
+ * Resource collection initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('api/rules');
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Resource/User.php b/app/code/core/Mage/Api/Model/Resource/User.php
index 12c0082534f..92906539ac8 100644
--- a/app/code/core/Mage/Api/Model/Resource/User.php
+++ b/app/code/core/Mage/Api/Model/Resource/User.php
@@ -22,31 +22,6 @@
*/
class Mage_Api_Model_Resource_User extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('api/user', 'user_id');
- }
-
- /**
- * Initialize unique fields
- *
- * @return $this
- */
- protected function _initUniqueFields()
- {
- $this->_uniqueFields = [
- [
- 'field' => 'email',
- 'title' => Mage::helper('api')->__('Email'),
- ],
- [
- 'field' => 'username',
- 'title' => Mage::helper('api')->__('User Name'),
- ],
- ];
- return $this;
- }
-
/**
* Authenticate user by $username and $password
*
@@ -204,21 +179,6 @@ public function hasAssigned2Role($user)
return $result;
}
- /**
- * Action before save
- *
- * @return $this
- */
- protected function _beforeSave(Mage_Core_Model_Abstract $user)
- {
- $now = Varien_Date::now();
- if (!$user->getId()) {
- $user->setCreated($now);
- }
- $user->setModified($now);
- return $this;
- }
-
/**
* Delete the object
*
@@ -416,4 +376,43 @@ public function userExists(Mage_Core_Model_Abstract $user)
->where($usersTable . '.user_id != ?', (int) $user->getId());
return $adapter->fetchRow($select);
}
+ protected function _construct()
+ {
+ $this->_init('api/user', 'user_id');
+ }
+
+ /**
+ * Initialize unique fields
+ *
+ * @return $this
+ */
+ protected function _initUniqueFields()
+ {
+ $this->_uniqueFields = [
+ [
+ 'field' => 'email',
+ 'title' => Mage::helper('api')->__('Email'),
+ ],
+ [
+ 'field' => 'username',
+ 'title' => Mage::helper('api')->__('User Name'),
+ ],
+ ];
+ return $this;
+ }
+
+ /**
+ * Action before save
+ *
+ * @return $this
+ */
+ protected function _beforeSave(Mage_Core_Model_Abstract $user)
+ {
+ $now = Varien_Date::now();
+ if (!$user->getId()) {
+ $user->setCreated($now);
+ }
+ $user->setModified($now);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Roles.php b/app/code/core/Mage/Api/Model/Roles.php
index 68255a190f3..7ce37bd10eb 100644
--- a/app/code/core/Mage/Api/Model/Roles.php
+++ b/app/code/core/Mage/Api/Model/Roles.php
@@ -45,11 +45,6 @@ class Mage_Api_Model_Roles extends Mage_Core_Model_Abstract
*/
protected $_filters;
- protected function _construct()
- {
- $this->_init('api/roles');
- }
-
/**
* @return $this
*/
@@ -99,6 +94,29 @@ public function getRoleUsers()
return $this->getResource()->getRoleUsers($this);
}
+ /**
+ * Filter set data
+ *
+ * @return $this
+ */
+ public function filter()
+ {
+ $data = $this->getData();
+ if (!$this->_filters || !$data) {
+ return $this;
+ }
+ /** @var Mage_Core_Model_Input_Filter $filter */
+ $filter = Mage::getModel('core/input_filter');
+ $filter->setFilters($this->_filters);
+ $this->setData($filter->filter($data));
+ return $this;
+ }
+
+ protected function _construct()
+ {
+ $this->_init('api/roles');
+ }
+
/**
* @param string|null $parentName
* @param int $level
@@ -177,22 +195,4 @@ protected function _beforeSave()
parent::_beforeSave();
return $this;
}
-
- /**
- * Filter set data
- *
- * @return $this
- */
- public function filter()
- {
- $data = $this->getData();
- if (!$this->_filters || !$data) {
- return $this;
- }
- /** @var Mage_Core_Model_Input_Filter $filter */
- $filter = Mage::getModel('core/input_filter');
- $filter->setFilters($this->_filters);
- $this->setData($filter->filter($data));
- return $this;
- }
}
diff --git a/app/code/core/Mage/Api/Model/Rules.php b/app/code/core/Mage/Api/Model/Rules.php
index cf2d107bd98..088e7a9b50e 100644
--- a/app/code/core/Mage/Api/Model/Rules.php
+++ b/app/code/core/Mage/Api/Model/Rules.php
@@ -35,11 +35,6 @@
*/
class Mage_Api_Model_Rules extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('api/rules');
- }
-
/**
* @return $this
*/
@@ -66,4 +61,8 @@ public function saveRel()
$this->getResource()->saveRel($this);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('api/rules');
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Server/Adapter/Soap.php b/app/code/core/Mage/Api/Model/Server/Adapter/Soap.php
index 4ca5e114463..5ebf60f5e76 100644
--- a/app/code/core/Mage/Api/Model/Server/Adapter/Soap.php
+++ b/app/code/core/Mage/Api/Model/Server/Adapter/Soap.php
@@ -36,33 +36,6 @@ class Mage_Api_Model_Server_Adapter_Soap extends Varien_Object implements Mage_A
*/
protected $_soap = null;
- /**
- * Internal constructor
- */
- protected function _construct()
- {
- $this->wsdlConfig = $this->_getWsdlConfig();
- }
-
- /**
- * Get wsdl config
- *
- * @return Varien_Object
- */
- protected function _getWsdlConfig()
- {
- $wsdlConfig = new Varien_Object();
- $queryParams = $this->getController()->getRequest()->getQuery();
- if (isset($queryParams['wsdl'])) {
- unset($queryParams['wsdl']);
- }
-
- $wsdlConfig->setUrl(Mage::helper('api')->getServiceUrl('*/*/*', ['_query' => $queryParams], true));
- $wsdlConfig->setName('Magento');
- $wsdlConfig->setHandler($this->getHandler());
- return $wsdlConfig;
- }
-
/**
* Set handler class name for webservice
*
@@ -193,6 +166,33 @@ public function fault($code, $message)
}
}
+ /**
+ * Internal constructor
+ */
+ protected function _construct()
+ {
+ $this->wsdlConfig = $this->_getWsdlConfig();
+ }
+
+ /**
+ * Get wsdl config
+ *
+ * @return Varien_Object
+ */
+ protected function _getWsdlConfig()
+ {
+ $wsdlConfig = new Varien_Object();
+ $queryParams = $this->getController()->getRequest()->getQuery();
+ if (isset($queryParams['wsdl'])) {
+ unset($queryParams['wsdl']);
+ }
+
+ $wsdlConfig->setUrl(Mage::helper('api')->getServiceUrl('*/*/*', ['_query' => $queryParams], true));
+ $wsdlConfig->setName('Magento');
+ $wsdlConfig->setHandler($this->getHandler());
+ return $wsdlConfig;
+ }
+
/**
* Check whether Soap extension is loaded
*
diff --git a/app/code/core/Mage/Api/Model/Server/Handler/Abstract.php b/app/code/core/Mage/Api/Model/Server/Handler/Abstract.php
index 2e5198c5a0c..c4a1eb8efed 100644
--- a/app/code/core/Mage/Api/Model/Server/Handler/Abstract.php
+++ b/app/code/core/Mage/Api/Model/Server/Handler/Abstract.php
@@ -45,125 +45,6 @@ public function handlePhpError($errorCode, $errorMessage, $errorFile, $errLine)
return true;
}
- /**
- * Retrieve webservice session
- *
- * @return Mage_Api_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('api/session');
- }
-
- /**
- * Retrieve webservice configuration
- *
- * @return Mage_Api_Model_Config
- */
- protected function _getConfig()
- {
- return Mage::getSingleton('api/config');
- }
-
- /**
- * Retrieve webservice server
- *
- * @return Mage_Api_Model_Server
- */
- protected function _getServer()
- {
- return Mage::getSingleton('api/server');
- }
-
- /**
- * Start webservice session
- *
- * @param string $sessionId
- * @return Mage_Api_Model_Server_Handler_Abstract
- */
- protected function _startSession($sessionId = null)
- {
- $this->_getSession()->setSessionId($sessionId);
- $this->_getSession()->init('api', 'api');
- return $this;
- }
-
- /**
- * Allow insta-login via HTTP Basic Auth
- *
- * @param stdClass|string|null $sessionId
- * @return $this
- * @SuppressWarnings("PHPMD.Superglobals")
- */
- protected function _instaLogin(&$sessionId)
- {
- if ($sessionId === null && !empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
- $this->_getSession()->setIsInstaLogin();
- $sessionId = $this->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
- }
- return $this;
- }
-
- /**
- * Check current user permission on resource and privilege
- *
- *
- * @param string $resource
- * @param string $privilege
- * @return bool
- */
- protected function _isAllowed($resource, $privilege = null)
- {
- return $this->_getSession()->isAllowed($resource, $privilege);
- }
-
- /**
- * Dispatch webservice fault
- *
- * @param string $faultName
- * @param string $resourceName
- * @param string $customMessage
- */
- protected function _fault($faultName, $resourceName = null, $customMessage = null)
- {
- $faults = $this->_getConfig()->getFaults($resourceName);
- if (!isset($faults[$faultName]) && !is_null($resourceName)) {
- $this->_fault($faultName);
- return;
- } elseif (!isset($faults[$faultName])) {
- $this->_fault('unknown');
- return;
- }
- $this->_getServer()->getAdapter()->fault(
- $faults[$faultName]['code'],
- (is_null($customMessage) ? $faults[$faultName]['message'] : $customMessage),
- );
- }
-
- /**
- * Retrieve webservice fault as array
- *
- * @param string $faultName
- * @param string $resourceName
- * @param string $customMessage
- * @return array
- */
- protected function _faultAsArray($faultName, $resourceName = null, $customMessage = null)
- {
- $faults = $this->_getConfig()->getFaults($resourceName);
- if (!isset($faults[$faultName]) && !is_null($resourceName)) {
- return $this->_faultAsArray($faultName);
- } elseif (!isset($faults[$faultName])) {
- return $this->_faultAsArray('unknown');
- }
-
- return [
- 'isFault' => true,
- 'faultCode' => $faults[$faultName]['code'],
- 'faultMessage' => (is_null($customMessage) ? $faults[$faultName]['message'] : $customMessage),
- ];
- }
-
/**
* Start web service session
*
@@ -188,18 +69,6 @@ public function endSession($sessionId)
return true;
}
- /**
- * @param string $resource
- * @return string
- */
- protected function _prepareResourceModelName($resource)
- {
- if ($this->_resourceSuffix !== null) {
- return $resource . $this->_resourceSuffix;
- }
- return $resource;
- }
-
/**
* Login user and Retrieve session id
*
@@ -614,4 +483,135 @@ function ($matches) {
$row,
);
}
+
+ /**
+ * Retrieve webservice session
+ *
+ * @return Mage_Api_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('api/session');
+ }
+
+ /**
+ * Retrieve webservice configuration
+ *
+ * @return Mage_Api_Model_Config
+ */
+ protected function _getConfig()
+ {
+ return Mage::getSingleton('api/config');
+ }
+
+ /**
+ * Retrieve webservice server
+ *
+ * @return Mage_Api_Model_Server
+ */
+ protected function _getServer()
+ {
+ return Mage::getSingleton('api/server');
+ }
+
+ /**
+ * Start webservice session
+ *
+ * @param string $sessionId
+ * @return Mage_Api_Model_Server_Handler_Abstract
+ */
+ protected function _startSession($sessionId = null)
+ {
+ $this->_getSession()->setSessionId($sessionId);
+ $this->_getSession()->init('api', 'api');
+ return $this;
+ }
+
+ /**
+ * Allow insta-login via HTTP Basic Auth
+ *
+ * @param stdClass|string|null $sessionId
+ * @return $this
+ * @SuppressWarnings("PHPMD.Superglobals")
+ */
+ protected function _instaLogin(&$sessionId)
+ {
+ if ($sessionId === null && !empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
+ $this->_getSession()->setIsInstaLogin();
+ $sessionId = $this->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
+ }
+ return $this;
+ }
+
+ /**
+ * Check current user permission on resource and privilege
+ *
+ *
+ * @param string $resource
+ * @param string $privilege
+ * @return bool
+ */
+ protected function _isAllowed($resource, $privilege = null)
+ {
+ return $this->_getSession()->isAllowed($resource, $privilege);
+ }
+
+ /**
+ * Dispatch webservice fault
+ *
+ * @param string $faultName
+ * @param string $resourceName
+ * @param string $customMessage
+ */
+ protected function _fault($faultName, $resourceName = null, $customMessage = null)
+ {
+ $faults = $this->_getConfig()->getFaults($resourceName);
+ if (!isset($faults[$faultName]) && !is_null($resourceName)) {
+ $this->_fault($faultName);
+ return;
+ } elseif (!isset($faults[$faultName])) {
+ $this->_fault('unknown');
+ return;
+ }
+ $this->_getServer()->getAdapter()->fault(
+ $faults[$faultName]['code'],
+ (is_null($customMessage) ? $faults[$faultName]['message'] : $customMessage),
+ );
+ }
+
+ /**
+ * Retrieve webservice fault as array
+ *
+ * @param string $faultName
+ * @param string $resourceName
+ * @param string $customMessage
+ * @return array
+ */
+ protected function _faultAsArray($faultName, $resourceName = null, $customMessage = null)
+ {
+ $faults = $this->_getConfig()->getFaults($resourceName);
+ if (!isset($faults[$faultName]) && !is_null($resourceName)) {
+ return $this->_faultAsArray($faultName);
+ } elseif (!isset($faults[$faultName])) {
+ return $this->_faultAsArray('unknown');
+ }
+
+ return [
+ 'isFault' => true,
+ 'faultCode' => $faults[$faultName]['code'],
+ 'faultMessage' => (is_null($customMessage) ? $faults[$faultName]['message'] : $customMessage),
+ ];
+ }
+
+ /**
+ * @param string $resource
+ * @return string
+ */
+ protected function _prepareResourceModelName($resource)
+ {
+ if ($this->_resourceSuffix !== null) {
+ return $resource . $this->_resourceSuffix;
+ }
+ return $resource;
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Server/V2/Adapter/Soap.php b/app/code/core/Mage/Api/Model/Server/V2/Adapter/Soap.php
index f7e29b61dd2..fad7b1d1df0 100644
--- a/app/code/core/Mage/Api/Model/Server/V2/Adapter/Soap.php
+++ b/app/code/core/Mage/Api/Model/Server/V2/Adapter/Soap.php
@@ -22,16 +22,6 @@
*/
class Mage_Api_Model_Server_V2_Adapter_Soap extends Mage_Api_Model_Server_Adapter_Soap
{
- /**
- * Get wsdl config
- *
- * @return Mage_Api_Model_Wsdl_Config
- */
- protected function _getWsdlConfig()
- {
- return Mage::getModel('api/wsdl_config');
- }
-
/**
* Run webservice
*
@@ -83,4 +73,13 @@ public function run()
return $this;
}
+ /**
+ * Get wsdl config
+ *
+ * @return Mage_Api_Model_Wsdl_Config
+ */
+ protected function _getWsdlConfig()
+ {
+ return Mage::getModel('api/wsdl_config');
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Server/Wsi/Adapter/Soap.php b/app/code/core/Mage/Api/Model/Server/Wsi/Adapter/Soap.php
index 54f73e8ccfa..56e6bc6340d 100644
--- a/app/code/core/Mage/Api/Model/Server/Wsi/Adapter/Soap.php
+++ b/app/code/core/Mage/Api/Model/Server/Wsi/Adapter/Soap.php
@@ -22,19 +22,6 @@
*/
class Mage_Api_Model_Server_Wsi_Adapter_Soap extends Mage_Api_Model_Server_Adapter_Soap
{
- /**
- * Get wsdl config
- *
- * @return Mage_Api_Model_Wsdl_Config
- */
- protected function _getWsdlConfig()
- {
- $wsdlConfig = Mage::getModel('api/wsdl_config');
- $wsdlConfig->setHandler($this->getHandler())
- ->init();
- return $wsdlConfig;
- }
-
/**
* Run webservice
*
@@ -104,4 +91,16 @@ public function run()
return $this;
}
+ /**
+ * Get wsdl config
+ *
+ * @return Mage_Api_Model_Wsdl_Config
+ */
+ protected function _getWsdlConfig()
+ {
+ $wsdlConfig = Mage::getModel('api/wsdl_config');
+ $wsdlConfig->setHandler($this->getHandler())
+ ->init();
+ return $wsdlConfig;
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Server/Wsi/Handler.php b/app/code/core/Mage/Api/Model/Server/Wsi/Handler.php
index e396035ab46..772948042c2 100644
--- a/app/code/core/Mage/Api/Model/Server/Wsi/Handler.php
+++ b/app/code/core/Mage/Api/Model/Server/Wsi/Handler.php
@@ -95,35 +95,6 @@ public function login($username, $apiKey = null)
return $stdObject;
}
- /**
- * Return called class and method names
- *
- * @param String $apiPath
- * @return array|void
- */
- protected function _getResourceName($apiPath)
- {
- list($resourceName, $methodName) = explode('.', $apiPath);
-
- if (empty($resourceName) || empty($methodName)) {
- $this->_fault('resource_path_invalid');
- return;
- }
-
- $resourcesAlias = $this->_getConfig()->getResourcesAlias();
- $resources = $this->_getConfig()->getResources();
- if (isset($resourcesAlias->$resourceName)) {
- $resourceName = (string) $resourcesAlias->$resourceName;
- }
-
- $methodInfo = $resources->$resourceName->methods->$methodName;
- $modelName = $this->_prepareResourceModelName((string) $resources->$resourceName->model);
- $modelClass = Mage::getConfig()->getModelClassName($modelName);
- $method = (isset($methodInfo->method) ? (string) $methodInfo->method : $methodName);
-
- return [$modelClass, $method];
- }
-
/**
* Return an array of parameters for the callable method.
*
@@ -178,4 +149,33 @@ public function endSession($sessionId)
$stdObject->result = parent::endSession($sessionId->sessionId);
return $stdObject;
}
+
+ /**
+ * Return called class and method names
+ *
+ * @param String $apiPath
+ * @return array|void
+ */
+ protected function _getResourceName($apiPath)
+ {
+ list($resourceName, $methodName) = explode('.', $apiPath);
+
+ if (empty($resourceName) || empty($methodName)) {
+ $this->_fault('resource_path_invalid');
+ return;
+ }
+
+ $resourcesAlias = $this->_getConfig()->getResourcesAlias();
+ $resources = $this->_getConfig()->getResources();
+ if (isset($resourcesAlias->$resourceName)) {
+ $resourceName = (string) $resourcesAlias->$resourceName;
+ }
+
+ $methodInfo = $resources->$resourceName->methods->$methodName;
+ $modelName = $this->_prepareResourceModelName((string) $resources->$resourceName->model);
+ $modelClass = Mage::getConfig()->getModelClassName($modelName);
+ $method = (isset($methodInfo->method) ? (string) $methodInfo->method : $methodName);
+
+ return [$modelClass, $method];
+ }
}
diff --git a/app/code/core/Mage/Api/Model/User.php b/app/code/core/Mage/Api/Model/User.php
index f9d76f1487f..e287fd84499 100644
--- a/app/code/core/Mage/Api/Model/User.php
+++ b/app/code/core/Mage/Api/Model/User.php
@@ -65,11 +65,6 @@ class Mage_Api_Model_User extends Mage_Core_Model_Abstract
*/
protected $_eventPrefix = 'api_user';
- protected function _construct()
- {
- $this->_init('api/user');
- }
-
/**
* @return $this
*/
@@ -339,28 +334,6 @@ public function hasAssigned2Role($user)
return $this->getResource()->hasAssigned2Role($user);
}
- /**
- * Retrieve encoded api key
- *
- * @param string $apiKey
- * @return string
- */
- protected function _getEncodedApiKey($apiKey)
- {
- return Mage::helper('core')->getHash($apiKey, Mage_Admin_Model_User::HASH_SALT_LENGTH);
- }
-
- /**
- * Get helper instance
- *
- * @param string $helperName
- * @return Mage_Core_Helper_Abstract
- */
- protected function _getHelper($helperName)
- {
- return Mage::helper($helperName);
- }
-
/**
* Validate user attribute values.
*
@@ -422,6 +395,33 @@ public function validate()
return (array) $errors;
}
+ protected function _construct()
+ {
+ $this->_init('api/user');
+ }
+
+ /**
+ * Retrieve encoded api key
+ *
+ * @param string $apiKey
+ * @return string
+ */
+ protected function _getEncodedApiKey($apiKey)
+ {
+ return Mage::helper('core')->getHash($apiKey, Mage_Admin_Model_User::HASH_SALT_LENGTH);
+ }
+
+ /**
+ * Get helper instance
+ *
+ * @param string $helperName
+ * @return Mage_Core_Helper_Abstract
+ */
+ protected function _getHelper($helperName)
+ {
+ return Mage::helper($helperName);
+ }
+
/**
* Get min customer password length
*
diff --git a/app/code/core/Mage/Api/Model/Wsdl/Config.php b/app/code/core/Mage/Api/Model/Wsdl/Config.php
index 72a5d5579be..92051a5c351 100644
--- a/app/code/core/Mage/Api/Model/Wsdl/Config.php
+++ b/app/code/core/Mage/Api/Model/Wsdl/Config.php
@@ -68,36 +68,6 @@ public function getCache()
return Mage::app()->getCache();
}
- /**
- * @param string $id
- * @return bool|mixed
- */
- protected function _loadCache($id)
- {
- return Mage::app()->loadCache($id);
- }
-
- /**
- * @param string $data
- * @param string $id
- * @param array $tags
- * @param int|false|null $lifetime
- * @return bool|Mage_Core_Model_App
- */
- protected function _saveCache($data, $id, $tags = [], $lifetime = false)
- {
- return Mage::app()->saveCache($data, $id, $tags, $lifetime);
- }
-
- /**
- * @param string $id
- * @return Mage_Core_Model_App
- */
- protected function _removeCache($id)
- {
- return Mage::app()->removeCache($id);
- }
-
/**
* @return $this
*/
@@ -154,4 +124,34 @@ public function getXmlString()
{
return $this->getNode()->asXML();
}
+
+ /**
+ * @param string $id
+ * @return bool|mixed
+ */
+ protected function _loadCache($id)
+ {
+ return Mage::app()->loadCache($id);
+ }
+
+ /**
+ * @param string $data
+ * @param string $id
+ * @param array $tags
+ * @param int|false|null $lifetime
+ * @return bool|Mage_Core_Model_App
+ */
+ protected function _saveCache($data, $id, $tags = [], $lifetime = false)
+ {
+ return Mage::app()->saveCache($data, $id, $tags, $lifetime);
+ }
+
+ /**
+ * @param string $id
+ * @return Mage_Core_Model_App
+ */
+ protected function _removeCache($id)
+ {
+ return Mage::app()->removeCache($id);
+ }
}
diff --git a/app/code/core/Mage/Api/Model/Wsdl/Config/Element.php b/app/code/core/Mage/Api/Model/Wsdl/Config/Element.php
index ace6e7e7ec3..b763d91faa1 100644
--- a/app/code/core/Mage/Api/Model/Wsdl/Config/Element.php
+++ b/app/code/core/Mage/Api/Model/Wsdl/Config/Element.php
@@ -170,29 +170,6 @@ public function getChildren($source = null)
return self::_getChildren($source);
}
- /**
- * Return children of all namespaces
- *
- * @param Varien_Simplexml_Element $source
- * @return array
- */
- protected static function _getChildren($source)
- {
- $children = [];
- $namespaces = $source->getNamespaces(true);
-
- $isWsi = Mage::helper('api/data')->isComplianceWSI();
-
- foreach ($namespaces as $key => $value) {
- if ($key == '' || (!$isWsi && $key == 'wsdl')) {
- continue;
- }
- $children[$value] = $source->children($value);
- }
- $children[''] = $source->children('');
- return $children;
- }
-
/**
* Return if has children
*
@@ -262,4 +239,27 @@ public function getAttribute($name, $namespace = '')
$attrs = $this->attributes($namespace);
return isset($attrs[$name]) ? (string) $attrs[$name] : null;
}
+
+ /**
+ * Return children of all namespaces
+ *
+ * @param Varien_Simplexml_Element $source
+ * @return array
+ */
+ protected static function _getChildren($source)
+ {
+ $children = [];
+ $namespaces = $source->getNamespaces(true);
+
+ $isWsi = Mage::helper('api/data')->isComplianceWSI();
+
+ foreach ($namespaces as $key => $value) {
+ if ($key == '' || (!$isWsi && $key == 'wsdl')) {
+ continue;
+ }
+ $children[$value] = $source->children($value);
+ }
+ $children[''] = $source->children('');
+ return $children;
+ }
}
diff --git a/app/code/core/Mage/Api2/Block/Adminhtml/Attribute/Buttons.php b/app/code/core/Mage/Api2/Block/Adminhtml/Attribute/Buttons.php
index 9b316a2da32..b56960ec750 100644
--- a/app/code/core/Mage/Api2/Block/Adminhtml/Attribute/Buttons.php
+++ b/app/code/core/Mage/Api2/Block/Adminhtml/Attribute/Buttons.php
@@ -28,34 +28,6 @@ public function __construct()
$this->setTemplate('api2/attribute/buttons.phtml');
}
- /**
- * Prepare global layout
- *
- * @return Mage_Core_Block_Abstract
- */
- protected function _prepareLayout()
- {
- $buttons = [
- 'backButton' => [
- 'label' => $this->__('Back'),
- 'onclick' => sprintf("window.location.href='%s';", $this->getUrl('*/*/')),
- 'class' => 'back',
- ],
- 'saveButton' => [
- 'label' => $this->__('Save'),
- 'onclick' => 'form.submit(); return false;',
- 'class' => 'save',
- ],
- ];
-
- foreach ($buttons as $name => $data) {
- $button = $this->getLayout()->createBlock('adminhtml/widget_button')->setData($data);
- $this->setChild($name, $button);
- }
-
- return parent::_prepareLayout();
- }
-
/**
* Get back button HTML
*
@@ -95,4 +67,32 @@ public function getCaption()
{
return $this->__('Edit');
}
+
+ /**
+ * Prepare global layout
+ *
+ * @return Mage_Core_Block_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ $buttons = [
+ 'backButton' => [
+ 'label' => $this->__('Back'),
+ 'onclick' => sprintf("window.location.href='%s';", $this->getUrl('*/*/')),
+ 'class' => 'back',
+ ],
+ 'saveButton' => [
+ 'label' => $this->__('Save'),
+ 'onclick' => 'form.submit(); return false;',
+ 'class' => 'save',
+ ],
+ ];
+
+ foreach ($buttons as $name => $data) {
+ $button = $this->getLayout()->createBlock('adminhtml/widget_button')->setData($data);
+ $this->setChild($name, $button);
+ }
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Api2/Block/Adminhtml/Attribute/Grid.php b/app/code/core/Mage/Api2/Block/Adminhtml/Attribute/Grid.php
index e2a7d3ebeaa..7a427b309c1 100644
--- a/app/code/core/Mage/Api2/Block/Adminhtml/Attribute/Grid.php
+++ b/app/code/core/Mage/Api2/Block/Adminhtml/Attribute/Grid.php
@@ -33,6 +33,36 @@ public function __construct($attributes = [])
$this->setId('api2_attributes');
}
+ /**
+ * Disable unnecessary functionality
+ *
+ * @return $this
+ */
+ public function _prepareLayout()
+ {
+ $this->setFilterVisibility(false);
+ $this->setPagerVisibility(false);
+
+ return $this;
+ }
+
+ /**
+ * Get row URL
+ *
+ * @param Varien_Object $row
+ * @return string|null
+ */
+ public function getRowUrl($row)
+ {
+ /** @var Mage_Admin_Model_Session $session */
+ $session = Mage::getSingleton('admin/session');
+ if ($session->isAllowed('system/api/attributes/edit')) {
+ return $this->getUrl('*/*/edit', ['type' => $row->getUserTypeCode()]);
+ }
+
+ return null;
+ }
+
/**
* Collection object set up
* @return $this
@@ -66,34 +96,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Disable unnecessary functionality
- *
- * @return $this
- */
- public function _prepareLayout()
- {
- $this->setFilterVisibility(false);
- $this->setPagerVisibility(false);
-
- return $this;
- }
-
- /**
- * Get row URL
- *
- * @param Varien_Object $row
- * @return string|null
- */
- public function getRowUrl($row)
- {
- /** @var Mage_Admin_Model_Session $session */
- $session = Mage::getSingleton('admin/session');
- if ($session->isAllowed('system/api/attributes/edit')) {
- return $this->getUrl('*/*/edit', ['type' => $row->getUserTypeCode()]);
- }
-
- return null;
- }
}
diff --git a/app/code/core/Mage/Api2/Block/Adminhtml/Permissions/User/Edit/Tab/Roles.php b/app/code/core/Mage/Api2/Block/Adminhtml/Permissions/User/Edit/Tab/Roles.php
index 20eacfa0580..f1fe16fa255 100644
--- a/app/code/core/Mage/Api2/Block/Adminhtml/Permissions/User/Edit/Tab/Roles.php
+++ b/app/code/core/Mage/Api2/Block/Adminhtml/Permissions/User/Edit/Tab/Roles.php
@@ -40,6 +40,59 @@ public function __construct()
->setUseAjax(true);
}
+ /**
+ * Prepare label for tab
+ *
+ * @return string
+ */
+ public function getTabLabel()
+ {
+ return $this->__('REST Role');
+ }
+
+ /**
+ * Prepare title for tab
+ *
+ * @return string
+ */
+ public function getTabTitle()
+ {
+ return $this->__('REST Role');
+ }
+
+ /**
+ * Returns status flag about this tab can be shown or not
+ *
+ * @return true
+ */
+ public function canShowTab()
+ {
+ return true;
+ }
+
+ /**
+ * Returns status flag about this tab hidden or not
+ *
+ * @return false
+ */
+ public function isHidden()
+ {
+ return false;
+ }
+
+ /**
+ * Get controller action url for grid ajax actions
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl(
+ '*/api2_role/rolesGrid',
+ ['user_id' => Mage::registry('permissions_user')->getUserId()],
+ );
+ }
+
/**
* Prepare grid collection object
*
@@ -130,57 +183,4 @@ protected function _getSelectedRoles()
return $this->_selectedRoles;
}
-
- /**
- * Prepare label for tab
- *
- * @return string
- */
- public function getTabLabel()
- {
- return $this->__('REST Role');
- }
-
- /**
- * Prepare title for tab
- *
- * @return string
- */
- public function getTabTitle()
- {
- return $this->__('REST Role');
- }
-
- /**
- * Returns status flag about this tab can be shown or not
- *
- * @return true
- */
- public function canShowTab()
- {
- return true;
- }
-
- /**
- * Returns status flag about this tab hidden or not
- *
- * @return false
- */
- public function isHidden()
- {
- return false;
- }
-
- /**
- * Get controller action url for grid ajax actions
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl(
- '*/api2_role/rolesGrid',
- ['user_id' => Mage::registry('permissions_user')->getUserId()],
- );
- }
}
diff --git a/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Buttons.php b/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Buttons.php
index 5e2dbcc3f15..823cb3e8f7e 100644
--- a/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Buttons.php
+++ b/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Buttons.php
@@ -31,43 +31,6 @@ public function __construct()
$this->setTemplate('api2/role/buttons.phtml');
}
- /**
- * Preparing global layout
- *
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $buttons = [
- 'backButton' => [
- 'label' => Mage::helper('adminhtml')->__('Back'),
- 'onclick' => sprintf("window.location.href='%s';", $this->getUrl('*/*/')),
- 'class' => 'back',
- ],
- 'resetButton' => [
- 'label' => Mage::helper('adminhtml')->__('Reset'),
- 'onclick' => 'window.location.reload()',
- ],
- 'saveButton' => [
- 'label' => Mage::helper('adminhtml')->__('Save Role'),
- 'onclick' => 'roleForm.submit(); return false;',
- 'class' => 'save',
- ],
- 'deleteButton' => [
- 'label' => Mage::helper('adminhtml')->__('Delete Role'),
- 'onclick' => '', //roleId is not set at this moment, so we set script later
- 'class' => 'delete',
- ],
- ];
-
- foreach ($buttons as $name => $data) {
- $button = $this->getLayout()->createBlock('adminhtml/widget_button')->setData($data);
- $this->setChild($name, $button);
- }
-
- return parent::_prepareLayout();
- }
-
/**
* Get back button HTML
*
@@ -131,4 +94,41 @@ public function getCaption()
? ($this->__('Edit Role') . " '{$this->escapeHtml($this->getRole()->getRoleName())}'")
: $this->__('Add New Role');
}
+
+ /**
+ * Preparing global layout
+ *
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $buttons = [
+ 'backButton' => [
+ 'label' => Mage::helper('adminhtml')->__('Back'),
+ 'onclick' => sprintf("window.location.href='%s';", $this->getUrl('*/*/')),
+ 'class' => 'back',
+ ],
+ 'resetButton' => [
+ 'label' => Mage::helper('adminhtml')->__('Reset'),
+ 'onclick' => 'window.location.reload()',
+ ],
+ 'saveButton' => [
+ 'label' => Mage::helper('adminhtml')->__('Save Role'),
+ 'onclick' => 'roleForm.submit(); return false;',
+ 'class' => 'save',
+ ],
+ 'deleteButton' => [
+ 'label' => Mage::helper('adminhtml')->__('Delete Role'),
+ 'onclick' => '', //roleId is not set at this moment, so we set script later
+ 'class' => 'delete',
+ ],
+ ];
+
+ foreach ($buttons as $name => $data) {
+ $button = $this->getLayout()->createBlock('adminhtml/widget_button')->setData($data);
+ $this->setChild($name, $button);
+ }
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Grid.php b/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Grid.php
index 066dbe592e3..51e0739b106 100644
--- a/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Grid.php
+++ b/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Grid.php
@@ -32,53 +32,6 @@ public function __construct()
->setDefaultDir(Varien_Db_Select::SQL_DESC);
}
- /**
- * Prepare collection
- *
- * @return $this
- */
- protected function _prepareCollection()
- {
- /** @var Mage_Api2_Model_Resource_Acl_Global_Role_Collection $collection */
- $collection = Mage::getModel('api2/acl_global_role')->getCollection();
- $this->setCollection($collection);
- parent::_prepareCollection();
- return $this;
- }
-
- /**
- * Prepare columns
- *
- * @return $this
- */
- protected function _prepareColumns()
- {
- $this->addColumn('entity_id', [
- 'header' => Mage::helper('oauth')->__('ID'),
- 'index' => 'entity_id',
- ]);
-
- $this->addColumn('role_name', [
- 'header' => Mage::helper('oauth')->__('Role Name'),
- 'index' => 'role_name',
- 'escape' => true,
- ]);
-
- $this->addColumn('tole_user_type', [
- 'header' => Mage::helper('oauth')->__('User Type'),
- 'sortable' => false,
- 'frame_callback' => [$this, 'decorateUserType'],
- ]);
-
- $this->addColumn('created_at', [
- 'header' => Mage::helper('oauth')->__('Created At'),
- 'index' => 'created_at',
- ]);
-
- parent::_prepareColumns();
- return $this;
- }
-
/**
* Get grid URL
*
@@ -130,4 +83,51 @@ public function decorateUserType($renderedValue, $row, $column, $isExport)
}
return $userType;
}
+
+ /**
+ * Prepare collection
+ *
+ * @return $this
+ */
+ protected function _prepareCollection()
+ {
+ /** @var Mage_Api2_Model_Resource_Acl_Global_Role_Collection $collection */
+ $collection = Mage::getModel('api2/acl_global_role')->getCollection();
+ $this->setCollection($collection);
+ parent::_prepareCollection();
+ return $this;
+ }
+
+ /**
+ * Prepare columns
+ *
+ * @return $this
+ */
+ protected function _prepareColumns()
+ {
+ $this->addColumn('entity_id', [
+ 'header' => Mage::helper('oauth')->__('ID'),
+ 'index' => 'entity_id',
+ ]);
+
+ $this->addColumn('role_name', [
+ 'header' => Mage::helper('oauth')->__('Role Name'),
+ 'index' => 'role_name',
+ 'escape' => true,
+ ]);
+
+ $this->addColumn('tole_user_type', [
+ 'header' => Mage::helper('oauth')->__('User Type'),
+ 'sortable' => false,
+ 'frame_callback' => [$this, 'decorateUserType'],
+ ]);
+
+ $this->addColumn('created_at', [
+ 'header' => Mage::helper('oauth')->__('Created At'),
+ 'index' => 'created_at',
+ ]);
+
+ parent::_prepareColumns();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Tab/Info.php b/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Tab/Info.php
index 42dbe261288..9c4e2c60b6e 100644
--- a/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Tab/Info.php
+++ b/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Tab/Info.php
@@ -25,6 +25,55 @@
*/
class Mage_Api2_Block_Adminhtml_Roles_Tab_Info extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
+ /**
+ * Get tab label
+ *
+ * @return string
+ */
+ public function getTabLabel()
+ {
+ return Mage::helper('api2')->__('Role Info');
+ }
+
+ /**
+ * Get tab title
+ *
+ * @return string
+ */
+ public function getTabTitle()
+ {
+ return $this->getTabLabel();
+ }
+
+ /**
+ * Whether tab is available
+ *
+ * @return bool
+ */
+ public function canShowTab()
+ {
+ return true;
+ }
+
+ /**
+ * Whether tab is hidden
+ *
+ * @return bool
+ */
+ public function isHidden()
+ {
+ return false;
+ }
+
+ /**
+ * Whether role is system
+ *
+ * @return bool
+ */
+ public function isRoleSystem()
+ {
+ return $this->getRole() && Mage_Api2_Model_Acl_Global_Role::isSystemRole($this->getRole());
+ }
/**
* Prepare form object
*/
@@ -89,54 +138,4 @@ protected function _prepareForm()
$this->setForm($form);
return $this;
}
-
- /**
- * Get tab label
- *
- * @return string
- */
- public function getTabLabel()
- {
- return Mage::helper('api2')->__('Role Info');
- }
-
- /**
- * Get tab title
- *
- * @return string
- */
- public function getTabTitle()
- {
- return $this->getTabLabel();
- }
-
- /**
- * Whether tab is available
- *
- * @return bool
- */
- public function canShowTab()
- {
- return true;
- }
-
- /**
- * Whether tab is hidden
- *
- * @return bool
- */
- public function isHidden()
- {
- return false;
- }
-
- /**
- * Whether role is system
- *
- * @return bool
- */
- public function isRoleSystem()
- {
- return $this->getRole() && Mage_Api2_Model_Acl_Global_Role::isSystemRole($this->getRole());
- }
}
diff --git a/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Tab/Users.php b/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Tab/Users.php
index 1a844dbe565..734457c5a19 100644
--- a/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Tab/Users.php
+++ b/app/code/core/Mage/Api2/Block/Adminhtml/Roles/Tab/Users.php
@@ -38,64 +38,6 @@ public function __construct()
$this->setDefaultFilter(['filter_in_role_users' => 1]);
}
- /**
- * Prepare collection
- *
- * @return $this
- */
- protected function _prepareCollection()
- {
- /** @var Mage_Admin_Model_Resource_User_Collection $collection */
- $collection = Mage::getModel('admin/user')->getCollection();
- $collection->getSelect()->joinLeft(
- ['acl' => $collection->getTable('api2/acl_user')],
- 'acl.admin_id = main_table.user_id',
- 'role_id',
- );
- if ($this->getRole() && $this->getRole()->getId()) {
- $collection->addFilter('acl.role_id', $this->getRole()->getId());
- }
-
- $this->setCollection($collection);
- parent::_prepareCollection();
- return $this;
- }
-
- /**
- * Prepare columns
- *
- * @inheritDoc
- */
- protected function _prepareColumns()
- {
- $this->addColumn('filter_in_role_users', [
- 'header_css_class' => 'a-center',
- 'type' => 'checkbox',
- 'name' => 'filter_in_role_users',
- 'values' => $this->getUsers(),
- 'align' => 'center',
- 'index' => 'user_id',
- ]);
-
- $this->addColumn('user_id', [
- 'header' => Mage::helper('api2')->__('ID'), 'index' => 'user_id', 'align' => 'right', 'width' => '50px',
- ]);
-
- $this->addColumn('username', [
- 'header' => Mage::helper('adminhtml')->__('User Name'), 'align' => 'left', 'index' => 'username',
- ]);
-
- $this->addColumn('firstname', [
- 'header' => Mage::helper('adminhtml')->__('First Name'), 'align' => 'left', 'index' => 'firstname',
- ]);
-
- $this->addColumn('lastname', [
- 'header' => Mage::helper('adminhtml')->__('Last Name'), 'align' => 'left', 'index' => 'lastname',
- ]);
-
- return parent::_prepareColumns();
- }
-
/**
* Get grid URL
*
@@ -170,31 +112,6 @@ public function _toHtml()
return '';
}
- /**
- * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
- * @return $this
- */
- protected function _addColumnFilterToCollection($column)
- {
- if ($column->getId() == 'filter_in_role_users') {
- $inRoleIds = $this->getUsers();
- if (empty($inRoleIds)) {
- $inRoleIds = 0;
- }
-
- if ($column->getFilter()->getValue()) {
- $this->getCollection()->addFieldToFilter('user_id', ['in' => $inRoleIds]);
- } else {
- if ($inRoleIds) {
- $this->getCollection()->addFieldToFilter('user_id', ['nin' => $inRoleIds]);
- }
- }
- } else {
- parent::_addColumnFilterToCollection($column);
- }
- return $this;
- }
-
/**
* Get users
*
@@ -222,4 +139,87 @@ public function getUsers($json = false)
return $result;
}
+
+ /**
+ * Prepare collection
+ *
+ * @return $this
+ */
+ protected function _prepareCollection()
+ {
+ /** @var Mage_Admin_Model_Resource_User_Collection $collection */
+ $collection = Mage::getModel('admin/user')->getCollection();
+ $collection->getSelect()->joinLeft(
+ ['acl' => $collection->getTable('api2/acl_user')],
+ 'acl.admin_id = main_table.user_id',
+ 'role_id',
+ );
+ if ($this->getRole() && $this->getRole()->getId()) {
+ $collection->addFilter('acl.role_id', $this->getRole()->getId());
+ }
+
+ $this->setCollection($collection);
+ parent::_prepareCollection();
+ return $this;
+ }
+
+ /**
+ * Prepare columns
+ *
+ * @inheritDoc
+ */
+ protected function _prepareColumns()
+ {
+ $this->addColumn('filter_in_role_users', [
+ 'header_css_class' => 'a-center',
+ 'type' => 'checkbox',
+ 'name' => 'filter_in_role_users',
+ 'values' => $this->getUsers(),
+ 'align' => 'center',
+ 'index' => 'user_id',
+ ]);
+
+ $this->addColumn('user_id', [
+ 'header' => Mage::helper('api2')->__('ID'), 'index' => 'user_id', 'align' => 'right', 'width' => '50px',
+ ]);
+
+ $this->addColumn('username', [
+ 'header' => Mage::helper('adminhtml')->__('User Name'), 'align' => 'left', 'index' => 'username',
+ ]);
+
+ $this->addColumn('firstname', [
+ 'header' => Mage::helper('adminhtml')->__('First Name'), 'align' => 'left', 'index' => 'firstname',
+ ]);
+
+ $this->addColumn('lastname', [
+ 'header' => Mage::helper('adminhtml')->__('Last Name'), 'align' => 'left', 'index' => 'lastname',
+ ]);
+
+ return parent::_prepareColumns();
+ }
+
+ /**
+ * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
+ * @return $this
+ */
+ protected function _addColumnFilterToCollection($column)
+ {
+ if ($column->getId() == 'filter_in_role_users') {
+ $inRoleIds = $this->getUsers();
+ if (empty($inRoleIds)) {
+ $inRoleIds = 0;
+ }
+
+ if ($column->getFilter()->getValue()) {
+ $this->getCollection()->addFieldToFilter('user_id', ['in' => $inRoleIds]);
+ } else {
+ if ($inRoleIds) {
+ $this->getCollection()->addFieldToFilter('user_id', ['nin' => $inRoleIds]);
+ }
+ }
+ } else {
+ parent::_addColumnFilterToCollection($column);
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Api2/Helper/Data.php b/app/code/core/Mage/Api2/Helper/Data.php
index 369ca5c61fb..1daaca79ad4 100644
--- a/app/code/core/Mage/Api2/Helper/Data.php
+++ b/app/code/core/Mage/Api2/Helper/Data.php
@@ -40,21 +40,6 @@ class Mage_Api2_Helper_Data extends Mage_Core_Helper_Abstract
protected $_moduleName = 'Mage_Api2';
- /**
- * Compare order to be used in adapters list sort
- *
- * @param array $a
- * @param array $b
- * @return int
- */
- protected static function _compareOrder($a, $b)
- {
- if ($a['order'] == $b['order']) {
- return 0;
- }
- return ($a['order'] < $b['order']) ? -1 : 1;
- }
-
/**
* Retrieve Auth adapters info from configuration file as array
*
@@ -185,4 +170,19 @@ public function getTypeOfOperation($operation)
throw new Exception('Can not determine operation type');
}
}
+
+ /**
+ * Compare order to be used in adapters list sort
+ *
+ * @param array $a
+ * @param array $b
+ * @return int
+ */
+ protected static function _compareOrder($a, $b)
+ {
+ if ($a['order'] == $b['order']) {
+ return 0;
+ }
+ return ($a['order'] < $b['order']) ? -1 : 1;
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Acl.php b/app/code/core/Mage/Api2/Model/Acl.php
index b235e5f7b90..4406dedd431 100644
--- a/app/code/core/Mage/Api2/Model/Acl.php
+++ b/app/code/core/Mage/Api2/Model/Acl.php
@@ -69,6 +69,22 @@ public function __construct($options)
$this->_setRules();
}
+ /**
+ * Adds a Role having an identifier unique to the registry
+ * OVERRIDE to allow numeric roles identifiers
+ *
+ * @param int $roleId Role identifier
+ * @param Zend_Acl_Role_Interface|string|array $parents
+ * @return Zend_Acl Provides a fluent interface
+ */
+ public function addRole($roleId, $parents = null)
+ {
+ if (!is_numeric($roleId)) {
+ throw new Exception('Invalid role identifier');
+ }
+ return parent::addRole((string) $roleId);
+ }
+
/**
* Retrieve REST ACL roles collection
*
@@ -155,20 +171,4 @@ protected function _setRules()
}
return $this;
}
-
- /**
- * Adds a Role having an identifier unique to the registry
- * OVERRIDE to allow numeric roles identifiers
- *
- * @param int $roleId Role identifier
- * @param Zend_Acl_Role_Interface|string|array $parents
- * @return Zend_Acl Provides a fluent interface
- */
- public function addRole($roleId, $parents = null)
- {
- if (!is_numeric($roleId)) {
- throw new Exception('Invalid role identifier');
- }
- return parent::addRole((string) $roleId);
- }
}
diff --git a/app/code/core/Mage/Api2/Model/Acl/Filter.php b/app/code/core/Mage/Api2/Model/Acl/Filter.php
index 2141be89c69..2286f4f52d2 100644
--- a/app/code/core/Mage/Api2/Model/Acl/Filter.php
+++ b/app/code/core/Mage/Api2/Model/Acl/Filter.php
@@ -51,23 +51,6 @@ public function __construct(Mage_Api2_Model_Resource $resource)
$this->_resource = $resource;
}
- /**
- * Return only the data which keys are allowed
- *
- * @param array $allowedAttributes List of attributes available to use
- * @param array $data Associative array attribute to value
- * @return array
- */
- protected function _filter(array $allowedAttributes, array $data)
- {
- foreach (array_keys($data) as $attribute) {
- if (!in_array($attribute, $allowedAttributes)) {
- unset($data[$attribute]);
- }
- }
- return $data;
- }
-
/**
* Strip attributes in of collection items
*
@@ -179,4 +162,21 @@ public function out(array $retrievedData)
{
return $this->_filter($this->getAttributesToInclude(), $retrievedData);
}
+
+ /**
+ * Return only the data which keys are allowed
+ *
+ * @param array $allowedAttributes List of attributes available to use
+ * @param array $data Associative array attribute to value
+ * @return array
+ */
+ protected function _filter(array $allowedAttributes, array $data)
+ {
+ foreach (array_keys($data) as $attribute) {
+ if (!in_array($attribute, $allowedAttributes)) {
+ unset($data[$attribute]);
+ }
+ }
+ return $data;
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Acl/Filter/Attribute.php b/app/code/core/Mage/Api2/Model/Acl/Filter/Attribute.php
index 62d7cfea373..0d0dc96cdd4 100644
--- a/app/code/core/Mage/Api2/Model/Acl/Filter/Attribute.php
+++ b/app/code/core/Mage/Api2/Model/Acl/Filter/Attribute.php
@@ -42,11 +42,6 @@ class Mage_Api2_Model_Acl_Filter_Attribute extends Mage_Core_Model_Abstract
*/
protected $_permissionModel;
- protected function _construct()
- {
- $this->_init('api2/acl_filter_attribute');
- }
-
/**
* Get pairs resources-permissions for current attribute
*
@@ -59,4 +54,9 @@ public function getPermissionModel()
}
return $this->_permissionModel;
}
+
+ protected function _construct()
+ {
+ $this->_init('api2/acl_filter_attribute');
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Acl/Global/Role.php b/app/code/core/Mage/Api2/Model/Acl/Global/Role.php
index a9dcbcf4f2c..6b6a4fdfc5d 100644
--- a/app/code/core/Mage/Api2/Model/Acl/Global/Role.php
+++ b/app/code/core/Mage/Api2/Model/Acl/Global/Role.php
@@ -53,59 +53,6 @@ class Mage_Api2_Model_Acl_Global_Role extends Mage_Core_Model_Abstract
*/
protected $_permissionModel;
- protected function _construct()
- {
- $this->_init('api2/acl_global_role');
- }
-
- /**
- * Before save actions
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- if ($this->isObjectNew() && $this->getCreatedAt() === null) {
- $this->setCreatedAt(Varien_Date::now());
- } else {
- $this->setUpdatedAt(Varien_Date::now());
- }
-
- //check and protect guest role
-
- if (self::isSystemRole($this) && $this->getRoleName() != $this->getOrigData('role_name')) {
- /** @var Mage_Core_Helper_Data $helper */
- $helper = Mage::helper('core');
-
- Mage::throwException(
- Mage::helper('api2')->__('%s role is a special one and can\'t be changed.', $helper->escapeHtml($this->getRoleName())),
- );
- }
-
- parent::_beforeSave();
- return $this;
- }
-
- /**
- * Perform checks before role delete
- *
- * @return $this
- */
- protected function _beforeDelete()
- {
- if (self::isSystemRole($this)) {
- /** @var Mage_Core_Helper_Data $helper */
- $helper = Mage::helper('core');
-
- Mage::throwException(
- Mage::helper('api2')->__('%s role is a special one and can\'t be deleted.', $helper->escapeHtml($this->getRoleName())),
- );
- }
-
- parent::_beforeDelete();
- return $this;
- }
-
/**
* Get pairs resources-permissions for current role
*
@@ -162,4 +109,57 @@ public function getConfigNodeName()
}
return $roleNodeName;
}
+
+ protected function _construct()
+ {
+ $this->_init('api2/acl_global_role');
+ }
+
+ /**
+ * Before save actions
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ if ($this->isObjectNew() && $this->getCreatedAt() === null) {
+ $this->setCreatedAt(Varien_Date::now());
+ } else {
+ $this->setUpdatedAt(Varien_Date::now());
+ }
+
+ //check and protect guest role
+
+ if (self::isSystemRole($this) && $this->getRoleName() != $this->getOrigData('role_name')) {
+ /** @var Mage_Core_Helper_Data $helper */
+ $helper = Mage::helper('core');
+
+ Mage::throwException(
+ Mage::helper('api2')->__('%s role is a special one and can\'t be changed.', $helper->escapeHtml($this->getRoleName())),
+ );
+ }
+
+ parent::_beforeSave();
+ return $this;
+ }
+
+ /**
+ * Perform checks before role delete
+ *
+ * @return $this
+ */
+ protected function _beforeDelete()
+ {
+ if (self::isSystemRole($this)) {
+ /** @var Mage_Core_Helper_Data $helper */
+ $helper = Mage::helper('core');
+
+ Mage::throwException(
+ Mage::helper('api2')->__('%s role is a special one and can\'t be deleted.', $helper->escapeHtml($this->getRoleName())),
+ );
+ }
+
+ parent::_beforeDelete();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Acl/Global/Rule/Tree.php b/app/code/core/Mage/Api2/Model/Acl/Global/Rule/Tree.php
index dd1213ff628..0747fa21fac 100644
--- a/app/code/core/Mage/Api2/Model/Acl/Global/Rule/Tree.php
+++ b/app/code/core/Mage/Api2/Model/Acl/Global/Rule/Tree.php
@@ -131,33 +131,6 @@ public function __construct($options)
}
}
- /**
- * Initialize block
- *
- * @return $this
- * @throws Exception
- */
- protected function _init()
- {
- if ($this->_initialized) {
- return $this;
- }
-
- /** @var Mage_Api2_Model_Config $config */
- $config = Mage::getModel('api2/config');
- $this->_resourcesConfig = $config->getResourceGroups();
-
- if ($this->_type == self::TYPE_ATTRIBUTE && !$this->_existOperations) {
- throw new Exception('Operations is not set');
- }
-
- if ($this->_type == self::TYPE_PRIVILEGE && !$this->_existPrivileges) {
- throw new Exception('Privileges is not set.');
- }
-
- return $this;
- }
-
/**
* Convert to array serialized post data from tree grid
*
@@ -252,6 +225,99 @@ public function getTreeResources()
return $root[self::NAME_CHILDREN] ?? [];
}
+ /**
+ * Set role
+ *
+ * @param Mage_Api2_Model_Acl_Global_Role $role
+ * @return $this
+ */
+ public function setRole($role)
+ {
+ $this->_role = $role;
+ return $this;
+ }
+
+ /**
+ * Get role
+ *
+ * @return Mage_Api2_Model_Acl_Global_Role
+ */
+ public function getRole()
+ {
+ return $this->_role;
+ }
+
+ /**
+ * Set resources permissions
+ *
+ * @param array $resourcesPermissions
+ * @return $this
+ */
+ public function setResourcesPermissions($resourcesPermissions)
+ {
+ $this->_resourcesPermissions = $resourcesPermissions;
+ return $this;
+ }
+
+ /**
+ * Get resources permissions
+ *
+ * @return array
+ */
+ public function getResourcesPermissions()
+ {
+ return $this->_resourcesPermissions;
+ }
+
+ /**
+ * Set has entity only attributes flag
+ *
+ * @param bool $hasEntityOnlyAttributes
+ * @return $this
+ */
+ public function setHasEntityOnlyAttributes($hasEntityOnlyAttributes)
+ {
+ $this->_hasEntityOnlyAttributes = $hasEntityOnlyAttributes;
+ return $this;
+ }
+
+ /**
+ * Get has entity only attributes flag
+ *
+ * @return bool
+ */
+ public function getHasEntityOnlyAttributes()
+ {
+ return $this->_hasEntityOnlyAttributes;
+ }
+
+ /**
+ * Initialize block
+ *
+ * @return $this
+ * @throws Exception
+ */
+ protected function _init()
+ {
+ if ($this->_initialized) {
+ return $this;
+ }
+
+ /** @var Mage_Api2_Model_Config $config */
+ $config = Mage::getModel('api2/config');
+ $this->_resourcesConfig = $config->getResourceGroups();
+
+ if ($this->_type == self::TYPE_ATTRIBUTE && !$this->_existOperations) {
+ throw new Exception('Operations is not set');
+ }
+
+ if ($this->_type == self::TYPE_PRIVILEGE && !$this->_existPrivileges) {
+ throw new Exception('Privileges is not set.');
+ }
+
+ return $this;
+ }
+
/**
* Get tree node
*
@@ -463,70 +529,4 @@ protected function _sortTree($a, $b)
{
return $a['sort_order'] < $b['sort_order'] ? -1 : ($a['sort_order'] > $b['sort_order'] ? 1 : 0);
}
-
- /**
- * Set role
- *
- * @param Mage_Api2_Model_Acl_Global_Role $role
- * @return $this
- */
- public function setRole($role)
- {
- $this->_role = $role;
- return $this;
- }
-
- /**
- * Get role
- *
- * @return Mage_Api2_Model_Acl_Global_Role
- */
- public function getRole()
- {
- return $this->_role;
- }
-
- /**
- * Set resources permissions
- *
- * @param array $resourcesPermissions
- * @return $this
- */
- public function setResourcesPermissions($resourcesPermissions)
- {
- $this->_resourcesPermissions = $resourcesPermissions;
- return $this;
- }
-
- /**
- * Get resources permissions
- *
- * @return array
- */
- public function getResourcesPermissions()
- {
- return $this->_resourcesPermissions;
- }
-
- /**
- * Set has entity only attributes flag
- *
- * @param bool $hasEntityOnlyAttributes
- * @return $this
- */
- public function setHasEntityOnlyAttributes($hasEntityOnlyAttributes)
- {
- $this->_hasEntityOnlyAttributes = $hasEntityOnlyAttributes;
- return $this;
- }
-
- /**
- * Get has entity only attributes flag
- *
- * @return bool
- */
- public function getHasEntityOnlyAttributes()
- {
- return $this->_hasEntityOnlyAttributes;
- }
}
diff --git a/app/code/core/Mage/Api2/Model/Auth/Adapter.php b/app/code/core/Mage/Api2/Model/Auth/Adapter.php
index 19b94705dd8..23dd3cda2e9 100644
--- a/app/code/core/Mage/Api2/Model/Auth/Adapter.php
+++ b/app/code/core/Mage/Api2/Model/Auth/Adapter.php
@@ -29,31 +29,6 @@ class Mage_Api2_Model_Auth_Adapter
*/
protected $_adapters = [];
- /**
- * Load adapters configuration and create adapters models
- *
- * @return $this
- * @throws Exception
- */
- protected function _initAdapters()
- {
- /** @var Mage_Api2_Helper_Data $helper */
- $helper = Mage::helper('api2');
-
- foreach ($helper->getAuthAdapters(true) as $adapterKey => $adapterParams) {
- $adapterModel = Mage::getModel($adapterParams['model']);
-
- if (!$adapterModel instanceof Mage_Api2_Model_Auth_Adapter_Abstract) {
- throw new Exception('Authentication adapter must to extend Mage_Api2_Model_Auth_Adapter_Abstract');
- }
- $this->_adapters[$adapterKey] = $adapterModel;
- }
- if (!$this->_adapters) {
- throw new Exception('No active authentication adapters found');
- }
- return $this;
- }
-
/**
* Process request and figure out an API user type and its identifier
*
@@ -78,4 +53,29 @@ public function getUserParams(Mage_Api2_Model_Request $request)
}
return (object) ['type' => Mage_Api2_Model_Auth::DEFAULT_USER_TYPE, 'id' => null];
}
+
+ /**
+ * Load adapters configuration and create adapters models
+ *
+ * @return $this
+ * @throws Exception
+ */
+ protected function _initAdapters()
+ {
+ /** @var Mage_Api2_Helper_Data $helper */
+ $helper = Mage::helper('api2');
+
+ foreach ($helper->getAuthAdapters(true) as $adapterKey => $adapterParams) {
+ $adapterModel = Mage::getModel($adapterParams['model']);
+
+ if (!$adapterModel instanceof Mage_Api2_Model_Auth_Adapter_Abstract) {
+ throw new Exception('Authentication adapter must to extend Mage_Api2_Model_Auth_Adapter_Abstract');
+ }
+ $this->_adapters[$adapterKey] = $adapterModel;
+ }
+ if (!$this->_adapters) {
+ throw new Exception('No active authentication adapters found');
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Renderer/Xml.php b/app/code/core/Mage/Api2/Model/Renderer/Xml.php
index 17905230dfb..f1688459731 100644
--- a/app/code/core/Mage/Api2/Model/Renderer/Xml.php
+++ b/app/code/core/Mage/Api2/Model/Renderer/Xml.php
@@ -76,6 +76,16 @@ public function render($data)
return $writer->render();
}
+ /**
+ * Get MIME type generated by renderer
+ *
+ * @return string
+ */
+ public function getMimeType()
+ {
+ return self::MIME_TYPE;
+ }
+
/**
* Prepare convert data
*
@@ -138,14 +148,4 @@ protected function _prepareKey($key)
}
return $key;
}
-
- /**
- * Get MIME type generated by renderer
- *
- * @return string
- */
- public function getMimeType()
- {
- return self::MIME_TYPE;
- }
}
diff --git a/app/code/core/Mage/Api2/Model/Request.php b/app/code/core/Mage/Api2/Model/Request.php
index d9bf78321d4..05fe06336db 100644
--- a/app/code/core/Mage/Api2/Model/Request.php
+++ b/app/code/core/Mage/Api2/Model/Request.php
@@ -65,19 +65,6 @@ public function __construct($uri = null)
parent::__construct($uri ? $uri : null);
}
- /**
- * Get request interpreter
- *
- * @return Mage_Api2_Model_Request_Interpreter_Interface
- */
- protected function _getInterpreter()
- {
- if ($this->_interpreter === null) {
- $this->_interpreter = Mage_Api2_Model_Request_Interpreter::factory($this->getContentType());
- }
- return $this->_interpreter;
- }
-
/**
* Retrieve accept types understandable by requester in a form of array sorted by quality descending
*
@@ -311,4 +298,17 @@ public function isAssocArrayInRequestBody()
}
return false;
}
+
+ /**
+ * Get request interpreter
+ *
+ * @return Mage_Api2_Model_Request_Interpreter_Interface
+ */
+ protected function _getInterpreter()
+ {
+ if ($this->_interpreter === null) {
+ $this->_interpreter = Mage_Api2_Model_Request_Interpreter::factory($this->getContentType());
+ }
+ return $this->_interpreter;
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Resource.php b/app/code/core/Mage/Api2/Model/Resource.php
index 9d76db69a0b..146acaa8217 100644
--- a/app/code/core/Mage/Api2/Model/Resource.php
+++ b/app/code/core/Mage/Api2/Model/Resource.php
@@ -273,29 +273,6 @@ public function dispatch()
}
}
- /**
- * Trigger error for not-implemented operations
- *
- * @param string $methodName
- */
- protected function _errorIfMethodNotExist($methodName)
- {
- if (!$this->_checkMethodExist($methodName)) {
- $this->_critical(self::RESOURCE_METHOD_NOT_IMPLEMENTED);
- }
- }
-
- /**
- * Check method exist
- *
- * @param string $methodName
- * @return bool
- */
- protected function _checkMethodExist($methodName)
- {
- return method_exists($this, $methodName);
- }
-
/**
* Get request
*
@@ -592,6 +569,182 @@ public function getWorkingModel()
return Mage::getModel($this->getConfig()->getResourceWorkingModel($this->getResourceType()));
}
+ /**
+ * Set 'returnData' flag
+ *
+ * @param bool $flag
+ * @return $this
+ */
+ public function setReturnData($flag)
+ {
+ $this->_returnData = $flag;
+ return $this;
+ }
+
+ /**
+ * Get available attributes of API resource
+ *
+ * @param string $userType
+ * @param string $operation
+ * @return array
+ */
+ public function getAvailableAttributes($userType, $operation)
+ {
+ $available = $this->getAvailableAttributesFromConfig();
+ $excludedAttrs = $this->getExcludedAttributes($userType, $operation);
+ $includedAttrs = $this->getIncludedAttributes($userType, $operation);
+ $entityOnlyAttrs = $this->getEntityOnlyAttributes($userType, $operation);
+ $resourceAttrs = $this->_getResourceAttributes();
+
+ // if resource returns not-associative array - attributes' codes only
+ if (key($resourceAttrs) === 0) {
+ $resourceAttrs = array_combine($resourceAttrs, $resourceAttrs);
+ }
+ foreach ($resourceAttrs as $attrCode => $attrLabel) {
+ if (!isset($available[$attrCode])) {
+ $available[$attrCode] = empty($attrLabel) ? $attrCode : $attrLabel;
+ }
+ }
+ foreach (array_keys($available) as $code) {
+ if (in_array($code, $excludedAttrs) || ($includedAttrs && !in_array($code, $includedAttrs))) {
+ unset($available[$code]);
+ }
+ if (in_array($code, $entityOnlyAttrs)) {
+ $available[$code] .= ' *';
+ }
+ }
+ return $available;
+ }
+
+ /**
+ * Get excluded attributes for user type
+ *
+ * @param string $userType
+ * @param string $operation
+ * @return array
+ */
+ public function getExcludedAttributes($userType, $operation)
+ {
+ return $this->getConfig()->getResourceExcludedAttributes($this->getResourceType(), $userType, $operation);
+ }
+
+ /**
+ * Get forced attributes
+ *
+ * @return array
+ */
+ public function getForcedAttributes()
+ {
+ return $this->getConfig()->getResourceForcedAttributes($this->getResourceType(), $this->getUserType());
+ }
+
+ /**
+ * Retrieve list of included attributes
+ *
+ * @param string $userType API user type
+ * @param string $operationType Type of operation: one of Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_... constant
+ * @return array
+ */
+ public function getIncludedAttributes($userType, $operationType)
+ {
+ return $this->getConfig()->getResourceIncludedAttributes($this->getResourceType(), $userType, $operationType);
+ }
+
+ /**
+ * Retrieve list of entity only attributes
+ *
+ * @param string $userType API user type
+ * @param string $operationType Type of operation: one of Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_... constant
+ * @return array
+ */
+ public function getEntityOnlyAttributes($userType, $operationType)
+ {
+ return $this->getConfig()->getResourceEntityOnlyAttributes($this->getResourceType(), $userType, $operationType);
+ }
+
+ /**
+ * Get available attributes of API resource from configuration file
+ *
+ * @return array
+ */
+ public function getAvailableAttributesFromConfig()
+ {
+ return $this->getConfig()->getResourceAttributes($this->getResourceType());
+ }
+
+ /**
+ * Get available attributes of API resource from data base
+ *
+ * @return array
+ */
+ public function getDbAttributes()
+ {
+ $available = [];
+ $workModel = $this->getConfig()->getResourceWorkingModel($this->getResourceType());
+
+ if ($workModel) {
+ /** @var Mage_Core_Model_Resource_Db_Abstract $resource */
+ $resource = Mage::getResourceModel($workModel);
+
+ if (method_exists($resource, 'getMainTable')) {
+ $available = array_keys($resource->getReadConnection()->describeTable($resource->getMainTable()));
+ }
+ }
+ return $available;
+ }
+
+ /**
+ * Get EAV attributes of working model
+ *
+ * @param bool $onlyVisible OPTIONAL Show only the attributes which are visible on frontend
+ * @param bool $excludeSystem OPTIONAL Exclude attributes marked as system
+ * @return array
+ */
+ public function getEavAttributes($onlyVisible = false, $excludeSystem = false)
+ {
+ $attributes = [];
+ $model = $this->getConfig()->getResourceWorkingModel($this->getResourceType());
+
+ /** @var Mage_Eav_Model_Entity_Type $entityType */
+ $entityType = Mage::getSingleton('eav/config')->getEntityType($model, 'entity_model');
+
+ /** @var Mage_Eav_Model_Entity_Attribute $attribute */
+ foreach ($entityType->getAttributeCollection() as $attribute) {
+ if ($onlyVisible && !$attribute->getIsVisible()) {
+ continue;
+ }
+ if ($excludeSystem && $attribute->getIsSystem()) {
+ continue;
+ }
+ $attributes[$attribute->getAttributeCode()] = $attribute->getFrontendLabel();
+ }
+
+ return $attributes;
+ }
+
+ /**
+ * Trigger error for not-implemented operations
+ *
+ * @param string $methodName
+ */
+ protected function _errorIfMethodNotExist($methodName)
+ {
+ if (!$this->_checkMethodExist($methodName)) {
+ $this->_critical(self::RESOURCE_METHOD_NOT_IMPLEMENTED);
+ }
+ }
+
+ /**
+ * Check method exist
+ *
+ * @param string $methodName
+ * @return bool
+ */
+ protected function _checkMethodExist($methodName)
+ {
+ return method_exists($this, $methodName);
+ }
+
/**
* Render data using registered Renderer
*
@@ -836,18 +989,6 @@ protected function _isSubCallAllowed($resourceId)
}
}
- /**
- * Set 'returnData' flag
- *
- * @param bool $flag
- * @return $this
- */
- public function setReturnData($flag)
- {
- $this->_returnData = $flag;
- return $this;
- }
-
/**
* Get resource location
*
@@ -881,147 +1022,6 @@ protected function _getResourceAttributes()
return [];
}
- /**
- * Get available attributes of API resource
- *
- * @param string $userType
- * @param string $operation
- * @return array
- */
- public function getAvailableAttributes($userType, $operation)
- {
- $available = $this->getAvailableAttributesFromConfig();
- $excludedAttrs = $this->getExcludedAttributes($userType, $operation);
- $includedAttrs = $this->getIncludedAttributes($userType, $operation);
- $entityOnlyAttrs = $this->getEntityOnlyAttributes($userType, $operation);
- $resourceAttrs = $this->_getResourceAttributes();
-
- // if resource returns not-associative array - attributes' codes only
- if (key($resourceAttrs) === 0) {
- $resourceAttrs = array_combine($resourceAttrs, $resourceAttrs);
- }
- foreach ($resourceAttrs as $attrCode => $attrLabel) {
- if (!isset($available[$attrCode])) {
- $available[$attrCode] = empty($attrLabel) ? $attrCode : $attrLabel;
- }
- }
- foreach (array_keys($available) as $code) {
- if (in_array($code, $excludedAttrs) || ($includedAttrs && !in_array($code, $includedAttrs))) {
- unset($available[$code]);
- }
- if (in_array($code, $entityOnlyAttrs)) {
- $available[$code] .= ' *';
- }
- }
- return $available;
- }
-
- /**
- * Get excluded attributes for user type
- *
- * @param string $userType
- * @param string $operation
- * @return array
- */
- public function getExcludedAttributes($userType, $operation)
- {
- return $this->getConfig()->getResourceExcludedAttributes($this->getResourceType(), $userType, $operation);
- }
-
- /**
- * Get forced attributes
- *
- * @return array
- */
- public function getForcedAttributes()
- {
- return $this->getConfig()->getResourceForcedAttributes($this->getResourceType(), $this->getUserType());
- }
-
- /**
- * Retrieve list of included attributes
- *
- * @param string $userType API user type
- * @param string $operationType Type of operation: one of Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_... constant
- * @return array
- */
- public function getIncludedAttributes($userType, $operationType)
- {
- return $this->getConfig()->getResourceIncludedAttributes($this->getResourceType(), $userType, $operationType);
- }
-
- /**
- * Retrieve list of entity only attributes
- *
- * @param string $userType API user type
- * @param string $operationType Type of operation: one of Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_... constant
- * @return array
- */
- public function getEntityOnlyAttributes($userType, $operationType)
- {
- return $this->getConfig()->getResourceEntityOnlyAttributes($this->getResourceType(), $userType, $operationType);
- }
-
- /**
- * Get available attributes of API resource from configuration file
- *
- * @return array
- */
- public function getAvailableAttributesFromConfig()
- {
- return $this->getConfig()->getResourceAttributes($this->getResourceType());
- }
-
- /**
- * Get available attributes of API resource from data base
- *
- * @return array
- */
- public function getDbAttributes()
- {
- $available = [];
- $workModel = $this->getConfig()->getResourceWorkingModel($this->getResourceType());
-
- if ($workModel) {
- /** @var Mage_Core_Model_Resource_Db_Abstract $resource */
- $resource = Mage::getResourceModel($workModel);
-
- if (method_exists($resource, 'getMainTable')) {
- $available = array_keys($resource->getReadConnection()->describeTable($resource->getMainTable()));
- }
- }
- return $available;
- }
-
- /**
- * Get EAV attributes of working model
- *
- * @param bool $onlyVisible OPTIONAL Show only the attributes which are visible on frontend
- * @param bool $excludeSystem OPTIONAL Exclude attributes marked as system
- * @return array
- */
- public function getEavAttributes($onlyVisible = false, $excludeSystem = false)
- {
- $attributes = [];
- $model = $this->getConfig()->getResourceWorkingModel($this->getResourceType());
-
- /** @var Mage_Eav_Model_Entity_Type $entityType */
- $entityType = Mage::getSingleton('eav/config')->getEntityType($model, 'entity_model');
-
- /** @var Mage_Eav_Model_Entity_Attribute $attribute */
- foreach ($entityType->getAttributeCollection() as $attribute) {
- if ($onlyVisible && !$attribute->getIsVisible()) {
- continue;
- }
- if ($excludeSystem && $attribute->getIsSystem()) {
- continue;
- }
- $attributes[$attribute->getAttributeCode()] = $attribute->getFrontendLabel();
- }
-
- return $attributes;
- }
-
/**
* Retrieve current store according to request and API user type
*
diff --git a/app/code/core/Mage/Api2/Model/Resource/Acl/Filter/Attribute.php b/app/code/core/Mage/Api2/Model/Resource/Acl/Filter/Attribute.php
index cdb1fd42b6b..cd088525208 100644
--- a/app/code/core/Mage/Api2/Model/Resource/Acl/Filter/Attribute.php
+++ b/app/code/core/Mage/Api2/Model/Resource/Acl/Filter/Attribute.php
@@ -27,11 +27,6 @@ class Mage_Api2_Model_Resource_Acl_Filter_Attribute extends Mage_Core_Model_Reso
*/
public const FILTER_RESOURCE_ALL = 'all';
- protected function _construct()
- {
- $this->_init('api2/acl_attribute', 'entity_id');
- }
-
/**
* @param string $userType
* @param string $resourceId
@@ -66,4 +61,9 @@ public function isAllAttributesAllowed($userType)
return ($this->getReadConnection()->fetchOne($select) == 1);
}
+
+ protected function _construct()
+ {
+ $this->_init('api2/acl_attribute', 'entity_id');
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Resource/Acl/Filter/Attribute/Collection.php b/app/code/core/Mage/Api2/Model/Resource/Acl/Filter/Attribute/Collection.php
index 6bf97531abe..edd44423ffe 100644
--- a/app/code/core/Mage/Api2/Model/Resource/Acl/Filter/Attribute/Collection.php
+++ b/app/code/core/Mage/Api2/Model/Resource/Acl/Filter/Attribute/Collection.php
@@ -22,14 +22,6 @@
*/
class Mage_Api2_Model_Resource_Acl_Filter_Attribute_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Initialize collection model
- */
- protected function _construct()
- {
- $this->_init('api2/acl_filter_attribute');
- }
-
/**
* Add filtering by user type
*
@@ -41,4 +33,11 @@ public function addFilterByUserType($userType)
$this->addFilter('user_type', $userType, 'public');
return $this;
}
+ /**
+ * Initialize collection model
+ */
+ protected function _construct()
+ {
+ $this->_init('api2/acl_filter_attribute');
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Role.php b/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Role.php
index bea25a47f05..d4b5306d156 100644
--- a/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Role.php
+++ b/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Role.php
@@ -25,11 +25,6 @@
*/
class Mage_Api2_Model_Resource_Acl_Global_Role extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('api2/acl_role', 'entity_id');
- }
-
/**
* Create/update relation row of admin user to API2 role
*
@@ -100,4 +95,8 @@ public function getRoleUsers(Mage_Api2_Model_Acl_Global_Role $role)
return $adapter->fetchCol($select);
}
+ protected function _construct()
+ {
+ $this->_init('api2/acl_role', 'entity_id');
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Role/Collection.php b/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Role/Collection.php
index b40f65df61a..46608c0411e 100644
--- a/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Role/Collection.php
+++ b/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Role/Collection.php
@@ -22,14 +22,6 @@
*/
class Mage_Api2_Model_Resource_Acl_Global_Role_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Initialize collection model
- */
- protected function _construct()
- {
- $this->_init('api2/acl_global_role');
- }
-
/**
* Add filter by admin user id and join table with appropriate information
*
@@ -48,4 +40,11 @@ public function addFilterByAdminId($id)
return $this;
}
+ /**
+ * Initialize collection model
+ */
+ protected function _construct()
+ {
+ $this->_init('api2/acl_global_role');
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Rule/Collection.php b/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Rule/Collection.php
index f6a4304bc7f..cf1ff4e5fc7 100644
--- a/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Rule/Collection.php
+++ b/app/code/core/Mage/Api2/Model/Resource/Acl/Global/Rule/Collection.php
@@ -22,14 +22,6 @@
*/
class Mage_Api2_Model_Resource_Acl_Global_Rule_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Initialize collection model
- */
- protected function _construct()
- {
- $this->_init('api2/acl_global_rule');
- }
-
/**
* Add filtering by role ID
*
@@ -41,4 +33,11 @@ public function addFilterByRoleId($roleId)
$this->addFilter('role_id', $roleId, 'public');
return $this;
}
+ /**
+ * Initialize collection model
+ */
+ protected function _construct()
+ {
+ $this->_init('api2/acl_global_rule');
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Resource/Validator.php b/app/code/core/Mage/Api2/Model/Resource/Validator.php
index 597a98cb749..5f42f41f103 100644
--- a/app/code/core/Mage/Api2/Model/Resource/Validator.php
+++ b/app/code/core/Mage/Api2/Model/Resource/Validator.php
@@ -36,6 +36,21 @@ abstract class Mage_Api2_Model_Resource_Validator
*/
protected $_errors = [];
+ /**
+ * Returns an array of errors that explain why the most recent isValidData()
+ * call returned false. The array keys are validation failure error identifiers,
+ * and the array values are the corresponding human-readable error strings.
+ *
+ * If isValidData() was never called or if the most recent isValidData() call
+ * returned true, then this method returns an empty array.
+ *
+ * @return array
+ */
+ public function getErrors()
+ {
+ return $this->_errors;
+ }
+
/**
* Set an array of errors
*
@@ -72,19 +87,4 @@ protected function _addError($error)
$this->_errors[] = $error;
return $this;
}
-
- /**
- * Returns an array of errors that explain why the most recent isValidData()
- * call returned false. The array keys are validation failure error identifiers,
- * and the array values are the corresponding human-readable error strings.
- *
- * If isValidData() was never called or if the most recent isValidData() call
- * returned true, then this method returns an empty array.
- *
- * @return array
- */
- public function getErrors()
- {
- return $this->_errors;
- }
}
diff --git a/app/code/core/Mage/Api2/Model/Resource/Validator/Eav.php b/app/code/core/Mage/Api2/Model/Resource/Validator/Eav.php
index 49b9d0210d5..898fb533da8 100644
--- a/app/code/core/Mage/Api2/Model/Resource/Validator/Eav.php
+++ b/app/code/core/Mage/Api2/Model/Resource/Validator/Eav.php
@@ -109,46 +109,6 @@ public function __construct($options)
->ignoreInvisible(false);
}
- /**
- * Validate attribute value for attributes with source models
- *
- * @param mixed $attrValue
- * @return array|bool
- */
- protected function _validateAttributeWithSource(Mage_Eav_Model_Entity_Attribute_Abstract $attribute, $attrValue)
- {
- $errors = [];
-
- // validate attributes with source models
- if ($attrValue !== null && $attribute->getSourceModel()) {
- if ($attribute->getFrontendInput() !== 'multiselect' && is_array($attrValue)) {
- return ['Invalid value type for ' . $attribute->getAttributeCode()];
- }
- $possibleValues = $attribute->getSource()->getAllOptions(false);
-
- foreach ((array) $attrValue as $value) {
- if (is_scalar($value)) {
- $value = (string) $value;
- $isValid = false;
- foreach ($possibleValues as $optionData) {
- // comparison without types check is performed only when both values are numeric
- $useStrictMode = !(is_numeric($value) && is_numeric($optionData['value']));
- $isValid = $useStrictMode ? $value === $optionData['value'] : $value == $optionData['value'];
- if ($isValid) {
- break;
- }
- }
- if (!$isValid) {
- $errors[] = 'Invalid value "' . $value . '" for ' . $attribute->getAttributeCode();
- }
- } else {
- $errors[] = 'Invalid value type for ' . $attribute->getAttributeCode();
- }
- }
- }
- return $errors ? $errors : true;
- }
-
/**
* Filter request data.
*
@@ -239,4 +199,44 @@ public function getErrors()
}
return $errors;
}
+
+ /**
+ * Validate attribute value for attributes with source models
+ *
+ * @param mixed $attrValue
+ * @return array|bool
+ */
+ protected function _validateAttributeWithSource(Mage_Eav_Model_Entity_Attribute_Abstract $attribute, $attrValue)
+ {
+ $errors = [];
+
+ // validate attributes with source models
+ if ($attrValue !== null && $attribute->getSourceModel()) {
+ if ($attribute->getFrontendInput() !== 'multiselect' && is_array($attrValue)) {
+ return ['Invalid value type for ' . $attribute->getAttributeCode()];
+ }
+ $possibleValues = $attribute->getSource()->getAllOptions(false);
+
+ foreach ((array) $attrValue as $value) {
+ if (is_scalar($value)) {
+ $value = (string) $value;
+ $isValid = false;
+ foreach ($possibleValues as $optionData) {
+ // comparison without types check is performed only when both values are numeric
+ $useStrictMode = !(is_numeric($value) && is_numeric($optionData['value']));
+ $isValid = $useStrictMode ? $value === $optionData['value'] : $value == $optionData['value'];
+ if ($isValid) {
+ break;
+ }
+ }
+ if (!$isValid) {
+ $errors[] = 'Invalid value "' . $value . '" for ' . $attribute->getAttributeCode();
+ }
+ } else {
+ $errors[] = 'Invalid value type for ' . $attribute->getAttributeCode();
+ }
+ }
+ }
+ return $errors ? $errors : true;
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Resource/Validator/Fields.php b/app/code/core/Mage/Api2/Model/Resource/Validator/Fields.php
index 12792095fed..2d75a3c7eee 100644
--- a/app/code/core/Mage/Api2/Model/Resource/Validator/Fields.php
+++ b/app/code/core/Mage/Api2/Model/Resource/Validator/Fields.php
@@ -75,6 +75,49 @@ public function __construct($options)
$this->_buildValidatorsChain($validationConfig);
}
+ /**
+ * Validate data.
+ * If fails validation, then this method returns false, and
+ * getErrors() will return an array of errors that explain why the
+ * validation failed.
+ *
+ * @param bool $isPartial
+ * @return bool
+ */
+ public function isValidData(array $data, $isPartial = false)
+ {
+ $isValid = true;
+
+ // required fields
+ if (!$isPartial && count($this->_requiredFields) > 0) {
+ $notEmptyValidator = new Zend_Validate_NotEmpty();
+ foreach ($this->_requiredFields as $requiredField) {
+ if (!$notEmptyValidator->isValid($data[$requiredField] ?? null)) {
+ $isValid = false;
+ foreach ($notEmptyValidator->getMessages() as $message) {
+ $this->_addError(sprintf('%s: %s', $requiredField, $message));
+ }
+ }
+ }
+ }
+
+ // fields rules
+ foreach ($data as $field => $value) {
+ if (isset($this->_validators[$field])) {
+ /** @var Zend_Validate_Interface $validator */
+ $validator = $this->_validators[$field];
+ if (!$validator->isValid($value)) {
+ $isValid = false;
+ foreach ($validator->getMessages() as $message) {
+ $this->_addError(sprintf('%s: %s', $field, $message));
+ }
+ }
+ }
+ }
+
+ return $isValid;
+ }
+
/**
* Build validator chain with config data
*
@@ -129,47 +172,4 @@ protected function _getValidatorInstance($type, $options)
}
return new $validatorClass($options);
}
-
- /**
- * Validate data.
- * If fails validation, then this method returns false, and
- * getErrors() will return an array of errors that explain why the
- * validation failed.
- *
- * @param bool $isPartial
- * @return bool
- */
- public function isValidData(array $data, $isPartial = false)
- {
- $isValid = true;
-
- // required fields
- if (!$isPartial && count($this->_requiredFields) > 0) {
- $notEmptyValidator = new Zend_Validate_NotEmpty();
- foreach ($this->_requiredFields as $requiredField) {
- if (!$notEmptyValidator->isValid($data[$requiredField] ?? null)) {
- $isValid = false;
- foreach ($notEmptyValidator->getMessages() as $message) {
- $this->_addError(sprintf('%s: %s', $requiredField, $message));
- }
- }
- }
- }
-
- // fields rules
- foreach ($data as $field => $value) {
- if (isset($this->_validators[$field])) {
- /** @var Zend_Validate_Interface $validator */
- $validator = $this->_validators[$field];
- if (!$validator->isValid($value)) {
- $isValid = false;
- foreach ($validator->getMessages() as $message) {
- $this->_addError(sprintf('%s: %s', $field, $message));
- }
- }
- }
- }
-
- return $isValid;
- }
}
diff --git a/app/code/core/Mage/Api2/Model/Route/Abstract.php b/app/code/core/Mage/Api2/Model/Route/Abstract.php
index 6755ed8e74b..a552ca1324a 100644
--- a/app/code/core/Mage/Api2/Model/Route/Abstract.php
+++ b/app/code/core/Mage/Api2/Model/Route/Abstract.php
@@ -58,17 +58,6 @@ public function __construct(array $arguments)
);
}
- /**
- * Retrieve argument value
- *
- * @param string $name argument name
- * @return mixed
- */
- protected function _getArgumentValue($name, array $arguments)
- {
- return $arguments[$name] ?? $this->_paramsDefaultValues[$name];
- }
-
/**
* Matches a Request with parts defined by a map. Assigns and
* returns an array of variables on a successful match.
@@ -81,4 +70,15 @@ public function match($request, $partial = false)
{
return parent::match(ltrim($request->getPathInfo(), $this->_urlDelimiter), $partial);
}
+
+ /**
+ * Retrieve argument value
+ *
+ * @param string $name argument name
+ * @return mixed
+ */
+ protected function _getArgumentValue($name, array $arguments)
+ {
+ return $arguments[$name] ?? $this->_paramsDefaultValues[$name];
+ }
}
diff --git a/app/code/core/Mage/Api2/Model/Server.php b/app/code/core/Mage/Api2/Model/Server.php
index 1897a52cb2f..dd442a7c2d8 100644
--- a/app/code/core/Mage/Api2/Model/Server.php
+++ b/app/code/core/Mage/Api2/Model/Server.php
@@ -122,6 +122,16 @@ public function internalCall(Mage_Api2_Model_Request $request, Mage_Api2_Model_R
->_dispatch($request, $response, $apiUser);
}
+ /**
+ * Retrieve api types
+ *
+ * @return array
+ */
+ public static function getApiTypes()
+ {
+ return self::$_apiTypes;
+ }
+
/**
* Authenticate user
*
@@ -279,14 +289,4 @@ protected function _renderException(
return $this;
}
-
- /**
- * Retrieve api types
- *
- * @return array
- */
- public static function getApiTypes()
- {
- return self::$_apiTypes;
- }
}
diff --git a/app/code/core/Mage/Api2/controllers/Adminhtml/Api2/RoleController.php b/app/code/core/Mage/Api2/controllers/Adminhtml/Api2/RoleController.php
index be43c8afcb9..7e15ffd1229 100644
--- a/app/code/core/Mage/Api2/controllers/Adminhtml/Api2/RoleController.php
+++ b/app/code/core/Mage/Api2/controllers/Adminhtml/Api2/RoleController.php
@@ -285,16 +285,6 @@ public function deleteAction()
$this->_redirect('*/*/');
}
- /**
- * @inheritDoc
- */
- protected function _isAllowed()
- {
- /** @var Mage_Admin_Model_Session $session */
- $session = Mage::getSingleton('admin/session');
- return $session->isAllowed('system/api/rest_roles');
- }
-
/**
* Get API2 roles ajax grid action
*/
@@ -309,6 +299,16 @@ public function rolesGridAction()
->setBody($this->getLayout()->createBlock('api2/adminhtml_permissions_user_edit_tab_roles')->toHtml());
}
+ /**
+ * @inheritDoc
+ */
+ protected function _isAllowed()
+ {
+ /** @var Mage_Admin_Model_Session $session */
+ $session = Mage::getSingleton('admin/session');
+ return $session->isAllowed('system/api/rest_roles');
+ }
+
/**
* Get users possessing the role
*
diff --git a/app/code/core/Mage/Authorizenet/Block/Directpost/Form.php b/app/code/core/Mage/Authorizenet/Block/Directpost/Form.php
index 9f0c3eabdd2..eca59f1c8a8 100644
--- a/app/code/core/Mage/Authorizenet/Block/Directpost/Form.php
+++ b/app/code/core/Mage/Authorizenet/Block/Directpost/Form.php
@@ -22,32 +22,6 @@
*/
class Mage_Authorizenet_Block_Directpost_Form extends Mage_Payment_Block_Form_Cc
{
- /**
- * Internal constructor
- * Set info template for payment step
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('authorizenet/directpost/info.phtml');
- }
-
- /**
- * Render block HTML
- * If method is not directpost - nothing to return
- *
- * @return string|null
- */
- protected function _toHtml()
- {
- if ($this->getMethod()->getCode() != Mage::getSingleton('authorizenet/directpost')->getCode()) {
- return null;
- }
-
- return parent::_toHtml();
- }
-
/**
* Set method info
*
@@ -74,4 +48,29 @@ public function isAjaxRequest()
->getRequest()
->getParam('isAjax');
}
+ /**
+ * Internal constructor
+ * Set info template for payment step
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('authorizenet/directpost/info.phtml');
+ }
+
+ /**
+ * Render block HTML
+ * If method is not directpost - nothing to return
+ *
+ * @return string|null
+ */
+ protected function _toHtml()
+ {
+ if ($this->getMethod()->getCode() != Mage::getSingleton('authorizenet/directpost')->getCode()) {
+ return null;
+ }
+
+ return parent::_toHtml();
+ }
}
diff --git a/app/code/core/Mage/Authorizenet/Block/Directpost/Iframe.php b/app/code/core/Mage/Authorizenet/Block/Directpost/Iframe.php
index e24e7e0929a..514edec824d 100644
--- a/app/code/core/Mage/Authorizenet/Block/Directpost/Iframe.php
+++ b/app/code/core/Mage/Authorizenet/Block/Directpost/Iframe.php
@@ -28,15 +28,6 @@ class Mage_Authorizenet_Block_Directpost_Iframe extends Mage_Core_Block_Template
*/
protected $_params = [];
- /**
- * Set template for iframe
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('authorizenet/directpost/iframe.phtml');
- }
-
/**
* Set output params
*
@@ -58,4 +49,13 @@ public function getParams()
{
return $this->_params;
}
+
+ /**
+ * Set template for iframe
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('authorizenet/directpost/iframe.phtml');
+ }
}
diff --git a/app/code/core/Mage/Authorizenet/Helper/Data.php b/app/code/core/Mage/Authorizenet/Helper/Data.php
index 7f2ad4d45a1..ac62eefda94 100644
--- a/app/code/core/Mage/Authorizenet/Helper/Data.php
+++ b/app/code/core/Mage/Authorizenet/Helper/Data.php
@@ -36,24 +36,6 @@ public function getAdminUrl($route, $params)
return Mage::getModel('adminhtml/url')->getUrl($route, $params);
}
- /**
- * Set secure url checkout is secure for current store.
- *
- * @param string $route
- * @param array $params
- * @return string
- */
- protected function _getUrl($route, $params = [])
- {
- $params['_type'] = Mage_Core_Model_Store::URL_TYPE_LINK;
- if (isset($params['is_secure'])) {
- $params['_secure'] = (bool) $params['is_secure'];
- } elseif (Mage::app()->getStore()->isCurrentlySecure()) {
- $params['_secure'] = true;
- }
- return parent::_getUrl($route, $params);
- }
-
/**
* Retrieve save order url params
*
@@ -143,4 +125,22 @@ public function updateOrderEditIncrements(Mage_Sales_Model_Order $order)
}
}
}
+
+ /**
+ * Set secure url checkout is secure for current store.
+ *
+ * @param string $route
+ * @param array $params
+ * @return string
+ */
+ protected function _getUrl($route, $params = [])
+ {
+ $params['_type'] = Mage_Core_Model_Store::URL_TYPE_LINK;
+ if (isset($params['is_secure'])) {
+ $params['_secure'] = (bool) $params['is_secure'];
+ } elseif (Mage::app()->getStore()->isCurrentlySecure()) {
+ $params['_secure'] = true;
+ }
+ return parent::_getUrl($route, $params);
+ }
}
diff --git a/app/code/core/Mage/Authorizenet/Model/Directpost.php b/app/code/core/Mage/Authorizenet/Model/Directpost.php
index f6206256437..89b74710106 100644
--- a/app/code/core/Mage/Authorizenet/Model/Directpost.php
+++ b/app/code/core/Mage/Authorizenet/Model/Directpost.php
@@ -219,55 +219,6 @@ public function refund(Varien_Object $payment, $amount)
return $this;
}
- /**
- * refund the amount with transaction id
- *
- * @param Mage_Sales_Model_Order_Payment $payment
- * @param string $amount
- * @return $this
- * @throws Mage_Core_Exception
- */
- protected function _refund(Varien_Object $payment, $amount)
- {
- if ($amount <= 0) {
- Mage::throwException(Mage::helper('paygate')->__('Invalid amount for refund.'));
- }
-
- if (!$payment->getParentTransactionId()) {
- Mage::throwException(Mage::helper('paygate')->__('Invalid transaction ID.'));
- }
-
- $payment->setAnetTransType(self::REQUEST_TYPE_CREDIT);
- $payment->setAmount($amount);
- $payment->setXTransId($this->_getRealParentTransactionId($payment));
-
- $request = $this->_buildRequest($payment);
- $result = $this->_postRequest($request);
-
- switch ($result->getResponseCode()) {
- case self::RESPONSE_CODE_APPROVED:
- if ($result->getResponseReasonCode() == self::RESPONSE_REASON_CODE_APPROVED) {
- if ($result->getTransactionId() != $payment->getParentTransactionId()) {
- $payment->setTransactionId($result->getTransactionId());
- }
- $shouldCloseCaptureTransaction = $payment->getOrder()->canCreditmemo() ? 0 : 1;
- $payment
- ->setIsTransactionClosed(1)
- ->setShouldCloseParentTransaction($shouldCloseCaptureTransaction)
- ->setTransactionAdditionalInfo($this->_realTransactionIdKey, $result->getTransactionId());
- return $this;
- }
- Mage::throwException($this->_wrapGatewayError($result->getResponseReasonText()));
- // no break
- case self::RESPONSE_CODE_DECLINED:
- case self::RESPONSE_CODE_ERROR:
- Mage::throwException($this->_wrapGatewayError($result->getResponseReasonText()));
- // no break
- default:
- Mage::throwException(Mage::helper('paygate')->__('Payment refunding error.'));
- }
- }
-
/**
* Get CGI url
*
@@ -295,16 +246,6 @@ public function getRelayUrl($storeId = null)
'authorizenet/directpost_payment/response';
}
- /**
- * Return request model for form data building
- *
- * @return Mage_Authorizenet_Model_Directpost_Request
- */
- protected function _getRequestModel()
- {
- return Mage::getModel('authorizenet/directpost_request');
- }
-
/**
* Return response.
*
@@ -451,23 +392,6 @@ public function process(array $responseData)
}
}
- /**
- * Fill payment with credit card data from response from Authorize.net.
- */
- protected function _fillPaymentByResponse(Varien_Object $payment)
- {
- $response = $this->getResponse();
- $payment->setTransactionId($response->getXTransId())
- ->setParentTransactionId(null)
- ->setIsTransactionClosed(0)
- ->setTransactionAdditionalInfo($this->_realTransactionIdKey, $response->getXTransId());
-
- if ($response->getXMethod() == self::REQUEST_METHOD_CC) {
- $payment->setCcAvsStatus($response->getXAvsCode())
- ->setCcLast4($payment->encrypt(substr($response->getXAccountNumber(), -4)));
- }
- }
-
/**
* Check response code came from authorize.net.
*
@@ -504,6 +428,82 @@ public function checkTransId()
return true;
}
+ /**
+ * refund the amount with transaction id
+ *
+ * @param Mage_Sales_Model_Order_Payment $payment
+ * @param string $amount
+ * @return $this
+ * @throws Mage_Core_Exception
+ */
+ protected function _refund(Varien_Object $payment, $amount)
+ {
+ if ($amount <= 0) {
+ Mage::throwException(Mage::helper('paygate')->__('Invalid amount for refund.'));
+ }
+
+ if (!$payment->getParentTransactionId()) {
+ Mage::throwException(Mage::helper('paygate')->__('Invalid transaction ID.'));
+ }
+
+ $payment->setAnetTransType(self::REQUEST_TYPE_CREDIT);
+ $payment->setAmount($amount);
+ $payment->setXTransId($this->_getRealParentTransactionId($payment));
+
+ $request = $this->_buildRequest($payment);
+ $result = $this->_postRequest($request);
+
+ switch ($result->getResponseCode()) {
+ case self::RESPONSE_CODE_APPROVED:
+ if ($result->getResponseReasonCode() == self::RESPONSE_REASON_CODE_APPROVED) {
+ if ($result->getTransactionId() != $payment->getParentTransactionId()) {
+ $payment->setTransactionId($result->getTransactionId());
+ }
+ $shouldCloseCaptureTransaction = $payment->getOrder()->canCreditmemo() ? 0 : 1;
+ $payment
+ ->setIsTransactionClosed(1)
+ ->setShouldCloseParentTransaction($shouldCloseCaptureTransaction)
+ ->setTransactionAdditionalInfo($this->_realTransactionIdKey, $result->getTransactionId());
+ return $this;
+ }
+ Mage::throwException($this->_wrapGatewayError($result->getResponseReasonText()));
+ // no break
+ case self::RESPONSE_CODE_DECLINED:
+ case self::RESPONSE_CODE_ERROR:
+ Mage::throwException($this->_wrapGatewayError($result->getResponseReasonText()));
+ // no break
+ default:
+ Mage::throwException(Mage::helper('paygate')->__('Payment refunding error.'));
+ }
+ }
+
+ /**
+ * Return request model for form data building
+ *
+ * @return Mage_Authorizenet_Model_Directpost_Request
+ */
+ protected function _getRequestModel()
+ {
+ return Mage::getModel('authorizenet/directpost_request');
+ }
+
+ /**
+ * Fill payment with credit card data from response from Authorize.net.
+ */
+ protected function _fillPaymentByResponse(Varien_Object $payment)
+ {
+ $response = $this->getResponse();
+ $payment->setTransactionId($response->getXTransId())
+ ->setParentTransactionId(null)
+ ->setIsTransactionClosed(0)
+ ->setTransactionAdditionalInfo($this->_realTransactionIdKey, $response->getXTransId());
+
+ if ($response->getXMethod() == self::REQUEST_METHOD_CC) {
+ $payment->setCcAvsStatus($response->getXAvsCode())
+ ->setCcLast4($payment->encrypt(substr($response->getXAccountNumber(), -4)));
+ }
+ }
+
/**
* Compare amount with amount from the response from Authorize.net.
*
diff --git a/app/code/core/Mage/Authorizenet/Model/Directpost/Request.php b/app/code/core/Mage/Authorizenet/Model/Directpost/Request.php
index 246aec6a3cc..249a6c8dcdc 100644
--- a/app/code/core/Mage/Authorizenet/Model/Directpost/Request.php
+++ b/app/code/core/Mage/Authorizenet/Model/Directpost/Request.php
@@ -31,30 +31,6 @@ class Mage_Authorizenet_Model_Directpost_Request extends Varien_Object
*/
protected $_signatureKey = '';
- /**
- * Return merchant transaction key.
- * Needed to generate MD5 sign.
- *
- * @return string
- */
- protected function _getTransactionKey()
- {
- return $this->_transKey;
- }
-
- /**
- * Set merchant transaction key.
- * Needed to generate MD5 sign.
- *
- * @param string $transKey
- * @return $this
- */
- protected function _setTransactionKey($transKey)
- {
- $this->_transKey = $transKey;
- return $this;
- }
-
/**
* Generates the MD5 fingerprint for request.
*
@@ -189,6 +165,30 @@ public function signRequestData()
return $this;
}
+ /**
+ * Return merchant transaction key.
+ * Needed to generate MD5 sign.
+ *
+ * @return string
+ */
+ protected function _getTransactionKey()
+ {
+ return $this->_transKey;
+ }
+
+ /**
+ * Set merchant transaction key.
+ * Needed to generate MD5 sign.
+ *
+ * @param string $transKey
+ * @return $this
+ */
+ protected function _setTransactionKey($transKey)
+ {
+ $this->_transKey = $transKey;
+ return $this;
+ }
+
/**
* Generates the SHA2 fingerprint for request.
*
diff --git a/app/code/core/Mage/Authorizenet/controllers/Adminhtml/Authorizenet/Directpost/PaymentController.php b/app/code/core/Mage/Authorizenet/controllers/Adminhtml/Authorizenet/Directpost/PaymentController.php
index 3d6176a48e7..0feeb3a2b76 100644
--- a/app/code/core/Mage/Authorizenet/controllers/Adminhtml/Authorizenet/Directpost/PaymentController.php
+++ b/app/code/core/Mage/Authorizenet/controllers/Adminhtml/Authorizenet/Directpost/PaymentController.php
@@ -23,36 +23,6 @@
*/
class Mage_Authorizenet_Adminhtml_Authorizenet_Directpost_PaymentController extends Mage_Adminhtml_Sales_Order_CreateController
{
- /**
- * Get session model
- *
- * @return Mage_Authorizenet_Model_Directpost_Session
- */
- protected function _getDirectPostSession()
- {
- return Mage::getSingleton('authorizenet/directpost_session');
- }
-
- /**
- * Retrieve session object
- *
- * @return Mage_Adminhtml_Model_Session_Quote
- */
- protected function _getOrderSession()
- {
- return Mage::getSingleton('adminhtml/session_quote');
- }
-
- /**
- * Retrieve order create model
- *
- * @return Mage_Adminhtml_Model_Sales_Order_Create
- */
- protected function _getOrderCreateModel()
- {
- return Mage::getSingleton('adminhtml/sales_order_create');
- }
-
/**
* Send request to authorize.net
*
@@ -195,6 +165,35 @@ public function returnQuoteAction()
$this->_returnQuote();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode(['success' => 1]));
}
+ /**
+ * Get session model
+ *
+ * @return Mage_Authorizenet_Model_Directpost_Session
+ */
+ protected function _getDirectPostSession()
+ {
+ return Mage::getSingleton('authorizenet/directpost_session');
+ }
+
+ /**
+ * Retrieve session object
+ *
+ * @return Mage_Adminhtml_Model_Session_Quote
+ */
+ protected function _getOrderSession()
+ {
+ return Mage::getSingleton('adminhtml/session_quote');
+ }
+
+ /**
+ * Retrieve order create model
+ *
+ * @return Mage_Adminhtml_Model_Sales_Order_Create
+ */
+ protected function _getOrderCreateModel()
+ {
+ return Mage::getSingleton('adminhtml/sales_order_create');
+ }
/**
* Return quote
diff --git a/app/code/core/Mage/Authorizenet/controllers/Directpost/PaymentController.php b/app/code/core/Mage/Authorizenet/controllers/Directpost/PaymentController.php
index 9b90b63b69d..4ed05cf58ca 100644
--- a/app/code/core/Mage/Authorizenet/controllers/Directpost/PaymentController.php
+++ b/app/code/core/Mage/Authorizenet/controllers/Directpost/PaymentController.php
@@ -22,34 +22,6 @@
*/
class Mage_Authorizenet_Directpost_PaymentController extends Mage_Core_Controller_Front_Action
{
- /**
- * @return Mage_Checkout_Model_Session
- */
- protected function _getCheckout()
- {
- return Mage::getSingleton('checkout/session');
- }
-
- /**
- * Get session model
-
- * @return Mage_Authorizenet_Model_Directpost_Session
- */
- protected function _getDirectPostSession()
- {
- return Mage::getSingleton('authorizenet/directpost_session');
- }
-
- /**
- * Get iframe block instance
- *
- * @return Mage_Authorizenet_Block_Directpost_Iframe
- */
- protected function _getIframeBlock()
- {
- return $this->getLayout()->createBlock('directpost/iframe');
- }
-
/**
* Response action.
* Action for Authorize.net SIM Relay Request.
@@ -155,6 +127,33 @@ public function returnQuoteAction()
$this->_returnCustomerQuote();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode(['success' => 1]));
}
+ /**
+ * @return Mage_Checkout_Model_Session
+ */
+ protected function _getCheckout()
+ {
+ return Mage::getSingleton('checkout/session');
+ }
+
+ /**
+ * Get session model
+
+ * @return Mage_Authorizenet_Model_Directpost_Session
+ */
+ protected function _getDirectPostSession()
+ {
+ return Mage::getSingleton('authorizenet/directpost_session');
+ }
+
+ /**
+ * Get iframe block instance
+ *
+ * @return Mage_Authorizenet_Block_Directpost_Iframe
+ */
+ protected function _getIframeBlock()
+ {
+ return $this->getLayout()->createBlock('directpost/iframe');
+ }
/**
* Return customer quote
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Checkbox.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Checkbox.php
index c134a908db4..53012bd92b4 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Checkbox.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Checkbox.php
@@ -22,14 +22,6 @@
*/
class Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Options_Type_Checkbox extends Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option_Checkbox
{
- /**
- * Set template
- */
- protected function _construct()
- {
- $this->setTemplate('bundle/product/composite/fieldset/options/type/checkbox.phtml');
- }
-
/**
* @param string $elementId
* @param string $containerId
@@ -41,4 +33,11 @@ public function setValidationContainer($elementId, $containerId)
$(\'' . $elementId . '\').advaiceContainer = \'' . $containerId . '\';
';
}
+ /**
+ * Set template
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('bundle/product/composite/fieldset/options/type/checkbox.phtml');
+ }
}
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Multi.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Multi.php
index c10094333e0..015f8e43afd 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Multi.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Multi.php
@@ -22,14 +22,6 @@
*/
class Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Options_Type_Multi extends Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option_Multi
{
- /**
- * Set template
- */
- protected function _construct()
- {
- $this->setTemplate('bundle/product/composite/fieldset/options/type/multi.phtml');
- }
-
/**
* @param string $elementId
* @param string $containerId
@@ -41,4 +33,11 @@ public function setValidationContainer($elementId, $containerId)
$(\'' . $elementId . '\').advaiceContainer = \'' . $containerId . '\';
';
}
+ /**
+ * Set template
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('bundle/product/composite/fieldset/options/type/multi.phtml');
+ }
}
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Radio.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Radio.php
index d581e031170..fa9450cb658 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Radio.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Radio.php
@@ -22,14 +22,6 @@
*/
class Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Options_Type_Radio extends Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option_Radio
{
- /**
- * Set template
- */
- protected function _construct()
- {
- $this->setTemplate('bundle/product/composite/fieldset/options/type/radio.phtml');
- }
-
/**
* @param string $elementId
* @param string $containerId
@@ -41,4 +33,11 @@ public function setValidationContainer($elementId, $containerId)
$(\'' . $elementId . '\').advaiceContainer = \'' . $containerId . '\';
';
}
+ /**
+ * Set template
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('bundle/product/composite/fieldset/options/type/radio.phtml');
+ }
}
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Select.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Select.php
index 233a4c2cf25..8c37a3775f2 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Select.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Composite/Fieldset/Options/Type/Select.php
@@ -22,14 +22,6 @@
*/
class Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Options_Type_Select extends Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option_Select
{
- /**
- * Set template
- */
- protected function _construct()
- {
- $this->setTemplate('bundle/product/composite/fieldset/options/type/select.phtml');
- }
-
/**
* @param string $elementId
* @param string $containerId
@@ -41,4 +33,11 @@ public function setValidationContainer($elementId, $containerId)
$(\'' . $elementId . '\').advaiceContainer = \'' . $containerId . '\';
';
}
+ /**
+ * Set template
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('bundle/product/composite/fieldset/options/type/select.phtml');
+ }
}
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Attributes.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Attributes.php
index a292f10fbdd..265cd752441 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Attributes.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Attributes.php
@@ -24,6 +24,18 @@
*/
class Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Attributes extends Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Attributes
{
+ /**
+ * Get current product from registry
+ *
+ * @return Mage_Catalog_Model_Product
+ */
+ public function getProduct()
+ {
+ if (!$this->getData('product')) {
+ $this->setData('product', Mage::registry('product'));
+ }
+ return $this->getData('product');
+ }
/**
* Prepare attributes form of bundle product
*
@@ -152,17 +164,4 @@ function changePriceTypeMap() {
return $this;
}
-
- /**
- * Get current product from registry
- *
- * @return Mage_Catalog_Model_Product
- */
- public function getProduct()
- {
- if (!$this->getData('product')) {
- $this->setData('product', Mage::registry('product'));
- }
- return $this->getData('product');
- }
}
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle.php
index e792fb5b0fe..152e9562d76 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle.php
@@ -46,35 +46,6 @@ public function getTabClass()
return 'ajax';
}
- /**
- * Prepare layout
- *
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'add_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('bundle')->__('Add New Option'),
- 'class' => 'add',
- 'id' => 'add_new_option',
- 'on_click' => 'bOption.add()',
- ]),
- );
-
- $this->setChild(
- 'options_box',
- $this->getLayout()->createBlock(
- 'bundle/adminhtml_catalog_product_edit_tab_bundle_option',
- 'adminhtml.catalog.product.edit.tab.bundle.option',
- ),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* Check block readonly
*
@@ -148,4 +119,33 @@ public function isHidden()
{
return false;
}
+
+ /**
+ * Prepare layout
+ *
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'add_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('bundle')->__('Add New Option'),
+ 'class' => 'add',
+ 'id' => 'add_new_option',
+ 'on_click' => 'bOption.add()',
+ ]),
+ );
+
+ $this->setChild(
+ 'options_box',
+ $this->getLayout()->createBlock(
+ 'bundle/adminhtml_catalog_product_edit_tab_bundle_option',
+ 'adminhtml.catalog.product.edit.tab.bundle.option',
+ ),
+ );
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option.php
index 4e67dbb6f2d..5a5c7ecaba9 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option.php
@@ -132,51 +132,6 @@ public function isMultiWebsites()
return !Mage::app()->isSingleStoreMode();
}
- /**
- * @return Mage_Adminhtml_Block_Widget
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'add_selection_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'id' => $this->getFieldId() . '_{{index}}_add_button',
- 'label' => Mage::helper('bundle')->__('Add Selection'),
- 'on_click' => 'bSelection.showSearch(event)',
- 'class' => 'add',
- ]),
- );
-
- $this->setChild(
- 'close_search_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'id' => $this->getFieldId() . '_{{index}}_close_button',
- 'label' => Mage::helper('bundle')->__('Close'),
- 'on_click' => 'bSelection.closeSearch(event)',
- 'class' => 'back no-display',
- ]),
- );
-
- $this->setChild(
- 'option_delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Delete Option'),
- 'class' => 'delete delete-product-option',
- 'on_click' => 'bOption.remove(event)',
- ]),
- );
-
- $this->setChild(
- 'selection_template',
- $this->getLayout()->createBlock('bundle/adminhtml_catalog_product_edit_tab_bundle_option_selection'),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -308,4 +263,49 @@ public function isDefaultStore()
{
return ($this->getProduct()->getStoreId() == '0');
}
+
+ /**
+ * @return Mage_Adminhtml_Block_Widget
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'add_selection_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'id' => $this->getFieldId() . '_{{index}}_add_button',
+ 'label' => Mage::helper('bundle')->__('Add Selection'),
+ 'on_click' => 'bSelection.showSearch(event)',
+ 'class' => 'add',
+ ]),
+ );
+
+ $this->setChild(
+ 'close_search_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'id' => $this->getFieldId() . '_{{index}}_close_button',
+ 'label' => Mage::helper('bundle')->__('Close'),
+ 'on_click' => 'bSelection.closeSearch(event)',
+ 'class' => 'back no-display',
+ ]),
+ );
+
+ $this->setChild(
+ 'option_delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Delete Option'),
+ 'class' => 'delete delete-product-option',
+ 'on_click' => 'bOption.remove(event)',
+ ]),
+ );
+
+ $this->setChild(
+ 'selection_template',
+ $this->getLayout()->createBlock('bundle/adminhtml_catalog_product_edit_tab_bundle_option_selection'),
+ );
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search.php
index 2721fc493e1..c5eb97381e5 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search.php
@@ -27,18 +27,39 @@
*/
class Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option_Search extends Mage_Adminhtml_Block_Widget
{
- protected function _construct()
+ /**
+ * @return string
+ */
+ public function getHeaderText()
{
- $this->setId('bundle_option_selection_search');
- $this->setTemplate('bundle/product/edit/bundle/option/search.phtml');
+ return Mage::helper('bundle')->__('Please Select Products to Add');
}
/**
* @return string
*/
- public function getHeaderText()
+ public function getButtonsHtml()
{
- return Mage::helper('bundle')->__('Please Select Products to Add');
+ $addButtonData = [
+ 'id' => 'add_button_' . $this->getIndex(),
+ 'label' => Mage::helper('sales')->__('Add Selected Product(s) to Option'),
+ 'onclick' => 'bSelection.productGridAddSelected(event)',
+ 'class' => 'add',
+ ];
+ return $this->getLayout()->createBlock('adminhtml/widget_button')->setData($addButtonData)->toHtml();
+ }
+
+ /**
+ * @return string
+ */
+ public function getHeaderCssClass()
+ {
+ return 'head-catalog-product';
+ }
+ protected function _construct()
+ {
+ $this->setId('bundle_option_selection_search');
+ $this->setTemplate('bundle/product/edit/bundle/option/search.phtml');
}
/**
@@ -66,26 +87,4 @@ protected function _beforeToHtml()
return parent::_beforeToHtml();
}
-
- /**
- * @return string
- */
- public function getButtonsHtml()
- {
- $addButtonData = [
- 'id' => 'add_button_' . $this->getIndex(),
- 'label' => Mage::helper('sales')->__('Add Selected Product(s) to Option'),
- 'onclick' => 'bSelection.productGridAddSelected(event)',
- 'class' => 'add',
- ];
- return $this->getLayout()->createBlock('adminhtml/widget_button')->setData($addButtonData)->toHtml();
- }
-
- /**
- * @return string
- */
- public function getHeaderCssClass()
- {
- return 'head-catalog-product';
- }
}
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php
index 4c133c0beab..9c9a4a3871d 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php
@@ -37,6 +37,34 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * @return string
+ * @throws Exception
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/bundle_selection/grid', ['index' => $this->getIndex(), 'productss' => implode(',', $this->_getProducts())]);
+ }
+
+ /**
+ * @return Mage_Core_Model_Store
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ public function getStore()
+ {
+ return Mage::app()->getStore();
+ }
+
+ /**
+ * Retrieve array of allowed product types for bundle selection product
+ *
+ * @return array
+ */
+ public function getAllowedSelectionTypes()
+ {
+ return Mage::helper('bundle')->getAllowedSelectionTypes();
+ }
+
/**
* @inheritDoc
*/
@@ -153,15 +181,6 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
- /**
- * @return string
- * @throws Exception
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/bundle_selection/grid', ['index' => $this->getIndex(), 'productss' => implode(',', $this->_getProducts())]);
- }
-
/**
* @return array
* @throws Exception
@@ -185,23 +204,4 @@ protected function _getProducts()
return [];
}
}
-
- /**
- * @return Mage_Core_Model_Store
- * @throws Mage_Core_Model_Store_Exception
- */
- public function getStore()
- {
- return Mage::app()->getStore();
- }
-
- /**
- * Retrieve array of allowed product types for bundle selection product
- *
- * @return array
- */
- public function getAllowedSelectionTypes()
- {
- return Mage::helper('bundle')->getAllowedSelectionTypes();
- }
}
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Selection.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Selection.php
index 9bdd9b0becb..ed5ac89eb2b 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Selection.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Selection.php
@@ -57,25 +57,6 @@ public function getFieldName()
return 'bundle_selections';
}
- /**
- * Prepare block layout
- *
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'selection_delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('catalog')->__('Delete'),
- 'class' => 'delete icon-btn',
- 'on_click' => 'bSelection.remove(event)',
- ]),
- );
- return parent::_prepareLayout();
- }
-
/**
* Retrieve delete button html
*
@@ -164,4 +145,23 @@ public function getCheckboxScopeHtml()
}
return $checkboxHtml;
}
+
+ /**
+ * Prepare block layout
+ *
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'selection_delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('catalog')->__('Delete'),
+ 'class' => 'delete icon-btn',
+ 'on_click' => 'bSelection.remove(event)',
+ ]),
+ );
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Bundle/Block/Catalog/Product/List/Partof.php b/app/code/core/Mage/Bundle/Block/Catalog/Product/List/Partof.php
index 6c3d075bae5..5137e8b32f6 100644
--- a/app/code/core/Mage/Bundle/Block/Catalog/Product/List/Partof.php
+++ b/app/code/core/Mage/Bundle/Block/Catalog/Product/List/Partof.php
@@ -27,46 +27,6 @@ class Mage_Bundle_Block_Catalog_Product_List_Partof extends Mage_Catalog_Block_P
protected $_itemCollection;
protected $_product = null;
- /**
- * @return $this
- */
- protected function _prepareData()
- {
- $collection = Mage::getModel('catalog/product')->getResourceCollection()
- ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
- ->addAttributeToSort('position', 'asc')
- ->addStoreFilter()
- ->addAttributeToFilter('status', [
- 'in' => Mage::getSingleton('catalog/product_status')->getSaleableStatusIds(),
- ])
- ->addMinimalPrice()
- ->joinTable('bundle/option', 'parent_id=entity_id', ['option_id' => 'option_id'])
- ->joinTable('bundle/selection', 'option_id=option_id', ['product_id' => 'product_id'], '{{table}}.product_id=' . $this->getProduct()->getId());
-
- $ids = Mage::getSingleton('checkout/cart')->getProductIds();
-
- if (count($ids)) {
- $collection->addIdFilter(Mage::getSingleton('checkout/cart')->getProductIds(), true);
- }
-
- Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
- $collection->getSelect()->group('entity_id');
-
- $collection->load();
- $this->_itemCollection = $collection;
-
- return $this;
- }
-
- /**
- * @return Mage_Catalog_Block_Product_Abstract
- */
- protected function _beforeToHtml()
- {
- $this->_prepareData();
- return parent::_beforeToHtml();
- }
-
/**
* @return mixed
*/
@@ -142,4 +102,44 @@ public function getProduct()
}
return $this->_product;
}
+
+ /**
+ * @return $this
+ */
+ protected function _prepareData()
+ {
+ $collection = Mage::getModel('catalog/product')->getResourceCollection()
+ ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
+ ->addAttributeToSort('position', 'asc')
+ ->addStoreFilter()
+ ->addAttributeToFilter('status', [
+ 'in' => Mage::getSingleton('catalog/product_status')->getSaleableStatusIds(),
+ ])
+ ->addMinimalPrice()
+ ->joinTable('bundle/option', 'parent_id=entity_id', ['option_id' => 'option_id'])
+ ->joinTable('bundle/selection', 'option_id=option_id', ['product_id' => 'product_id'], '{{table}}.product_id=' . $this->getProduct()->getId());
+
+ $ids = Mage::getSingleton('checkout/cart')->getProductIds();
+
+ if (count($ids)) {
+ $collection->addIdFilter(Mage::getSingleton('checkout/cart')->getProductIds(), true);
+ }
+
+ Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
+ $collection->getSelect()->group('entity_id');
+
+ $collection->load();
+ $this->_itemCollection = $collection;
+
+ return $this;
+ }
+
+ /**
+ * @return Mage_Catalog_Block_Product_Abstract
+ */
+ protected function _beforeToHtml()
+ {
+ $this->_prepareData();
+ return parent::_beforeToHtml();
+ }
}
diff --git a/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle/Option.php b/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle/Option.php
index e8ac67d2005..63c2361d52b 100644
--- a/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle/Option.php
+++ b/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle/Option.php
@@ -40,126 +40,6 @@ class Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option extends Mage_Bun
*/
protected $_showSingle = null;
- /**
- * Check if option has a single selection
- *
- * @return bool
- */
- protected function _showSingle()
- {
- if (is_null($this->_showSingle)) {
- $option = $this->getOption();
- $selections = $option->getSelections();
-
- $this->_showSingle = (count($selections) === 1 && $option->getRequired());
- }
-
- return $this->_showSingle;
- }
-
- /**
- * Retrieve default values for template
- *
- * @return array
- */
- protected function _getDefaultValues()
- {
- $option = $this->getOption();
- $default = $option->getDefaultSelection();
- $selections = $option->getSelections();
- $selectedOptions = $this->_getSelectedOptions();
- $inPreConfigured = $this->getProduct()->hasPreconfiguredValues()
- && $this->getProduct()->getPreconfiguredValues()
- ->getData('bundle_option_qty/' . $option->getId());
-
- if (empty($selectedOptions) && $default) {
- $_defaultQty = $default->getSelectionQty() * 1;
- $_canChangeQty = $default->getSelectionCanChangeQty();
- } elseif (!$inPreConfigured && $selectedOptions && is_numeric($selectedOptions)) {
- $selectedSelection = $option->getSelectionById($selectedOptions);
- if ($selectedSelection) {
- $_defaultQty = $selectedSelection->getSelectionQty() * 1;
- $_canChangeQty = $selectedSelection->getSelectionCanChangeQty();
- } else {
- $_defaultQty = $selections[0]->getSelectionQty() * 1;
- $_canChangeQty = $selections[0]->getSelectionCanChangeQty();
- }
- } elseif (!$this->_showSingle() || $inPreConfigured) {
- $_defaultQty = $this->_getSelectedQty();
- $_canChangeQty = (bool) $_defaultQty;
- } else {
- $_defaultQty = $selections[0]->getSelectionQty() * 1;
- $_canChangeQty = $selections[0]->getSelectionCanChangeQty();
- }
-
- return [$_defaultQty, $_canChangeQty];
- }
-
- /**
- * Collect selected options
- *
- * @return int|array|string
- */
- protected function _getSelectedOptions()
- {
- if (is_null($this->_selectedOptions)) {
- $this->_selectedOptions = [];
- $option = $this->getOption();
-
- if ($this->getProduct()->hasPreconfiguredValues()) {
- $configValue = $this->getProduct()->getPreconfiguredValues()
- ->getData('bundle_option/' . $option->getId());
- if ($configValue) {
- $this->_selectedOptions = $configValue;
- } elseif (!$option->getRequired()) {
- $this->_selectedOptions = 'None';
- }
- }
- }
-
- return $this->_selectedOptions;
- }
-
- /**
- * Define if selection is selected
- *
- * @param Mage_Catalog_Model_Product $selection
- * @return bool
- */
- protected function _isSelected($selection)
- {
- $selectedOptions = $this->_getSelectedOptions();
- if (is_numeric($selectedOptions)) {
- return ($selection->getSelectionId() == $this->_getSelectedOptions());
- } elseif (is_array($selectedOptions) && !empty($selectedOptions)) {
- return in_array($selection->getSelectionId(), $this->_getSelectedOptions());
- } elseif ($selectedOptions === 'None') {
- return false;
- } else {
- return ($selection->getIsDefault() && $selection->isSaleable());
- }
- }
-
- /**
- * Retrieve selected option qty
- *
- * @return int
- */
- protected function _getSelectedQty()
- {
- if ($this->getProduct()->hasPreconfiguredValues()) {
- $selectedQty = (float) $this->getProduct()->getPreconfiguredValues()
- ->getData('bundle_option_qty/' . $this->getOption()->getId());
- if ($selectedQty < 0) {
- $selectedQty = 0;
- }
- } else {
- $selectedQty = 0;
- }
-
- return $selectedQty;
- }
-
/**
* Get product model
*
@@ -281,4 +161,124 @@ public function formatPriceString($price, $includeContainer = true)
return $formated;
}
+
+ /**
+ * Check if option has a single selection
+ *
+ * @return bool
+ */
+ protected function _showSingle()
+ {
+ if (is_null($this->_showSingle)) {
+ $option = $this->getOption();
+ $selections = $option->getSelections();
+
+ $this->_showSingle = (count($selections) === 1 && $option->getRequired());
+ }
+
+ return $this->_showSingle;
+ }
+
+ /**
+ * Retrieve default values for template
+ *
+ * @return array
+ */
+ protected function _getDefaultValues()
+ {
+ $option = $this->getOption();
+ $default = $option->getDefaultSelection();
+ $selections = $option->getSelections();
+ $selectedOptions = $this->_getSelectedOptions();
+ $inPreConfigured = $this->getProduct()->hasPreconfiguredValues()
+ && $this->getProduct()->getPreconfiguredValues()
+ ->getData('bundle_option_qty/' . $option->getId());
+
+ if (empty($selectedOptions) && $default) {
+ $_defaultQty = $default->getSelectionQty() * 1;
+ $_canChangeQty = $default->getSelectionCanChangeQty();
+ } elseif (!$inPreConfigured && $selectedOptions && is_numeric($selectedOptions)) {
+ $selectedSelection = $option->getSelectionById($selectedOptions);
+ if ($selectedSelection) {
+ $_defaultQty = $selectedSelection->getSelectionQty() * 1;
+ $_canChangeQty = $selectedSelection->getSelectionCanChangeQty();
+ } else {
+ $_defaultQty = $selections[0]->getSelectionQty() * 1;
+ $_canChangeQty = $selections[0]->getSelectionCanChangeQty();
+ }
+ } elseif (!$this->_showSingle() || $inPreConfigured) {
+ $_defaultQty = $this->_getSelectedQty();
+ $_canChangeQty = (bool) $_defaultQty;
+ } else {
+ $_defaultQty = $selections[0]->getSelectionQty() * 1;
+ $_canChangeQty = $selections[0]->getSelectionCanChangeQty();
+ }
+
+ return [$_defaultQty, $_canChangeQty];
+ }
+
+ /**
+ * Collect selected options
+ *
+ * @return int|array|string
+ */
+ protected function _getSelectedOptions()
+ {
+ if (is_null($this->_selectedOptions)) {
+ $this->_selectedOptions = [];
+ $option = $this->getOption();
+
+ if ($this->getProduct()->hasPreconfiguredValues()) {
+ $configValue = $this->getProduct()->getPreconfiguredValues()
+ ->getData('bundle_option/' . $option->getId());
+ if ($configValue) {
+ $this->_selectedOptions = $configValue;
+ } elseif (!$option->getRequired()) {
+ $this->_selectedOptions = 'None';
+ }
+ }
+ }
+
+ return $this->_selectedOptions;
+ }
+
+ /**
+ * Define if selection is selected
+ *
+ * @param Mage_Catalog_Model_Product $selection
+ * @return bool
+ */
+ protected function _isSelected($selection)
+ {
+ $selectedOptions = $this->_getSelectedOptions();
+ if (is_numeric($selectedOptions)) {
+ return ($selection->getSelectionId() == $this->_getSelectedOptions());
+ } elseif (is_array($selectedOptions) && !empty($selectedOptions)) {
+ return in_array($selection->getSelectionId(), $this->_getSelectedOptions());
+ } elseif ($selectedOptions === 'None') {
+ return false;
+ } else {
+ return ($selection->getIsDefault() && $selection->isSaleable());
+ }
+ }
+
+ /**
+ * Retrieve selected option qty
+ *
+ * @return int
+ */
+ protected function _getSelectedQty()
+ {
+ if ($this->getProduct()->hasPreconfiguredValues()) {
+ $selectedQty = (float) $this->getProduct()->getPreconfiguredValues()
+ ->getData('bundle_option_qty/' . $this->getOption()->getId());
+ if ($selectedQty < 0) {
+ $selectedQty = 0;
+ }
+ } else {
+ $selectedQty = 0;
+ }
+
+ return $selectedQty;
+ }
}
diff --git a/app/code/core/Mage/Bundle/Block/Checkout/Cart/Item/Renderer.php b/app/code/core/Mage/Bundle/Block/Checkout/Cart/Item/Renderer.php
index 2893c1121ba..da797a0b680 100644
--- a/app/code/core/Mage/Bundle/Block/Checkout/Cart/Item/Renderer.php
+++ b/app/code/core/Mage/Bundle/Block/Checkout/Cart/Item/Renderer.php
@@ -22,6 +22,40 @@
*/
class Mage_Bundle_Block_Checkout_Cart_Item_Renderer extends Mage_Checkout_Block_Cart_Item_Renderer
{
+ /**
+ * Overloaded method for getting list of bundle options
+ * Caches result in quote item, because it can be used in cart 'recent view' and on same page in cart checkout
+ *
+ * @return array
+ */
+ public function getOptionList()
+ {
+ return Mage::helper('bundle/catalog_product_configuration')->getOptions($this->getItem());
+ }
+
+ /**
+ * Return cart item error messages
+ *
+ * @return array
+ */
+ public function getMessages()
+ {
+ $messages = [];
+ $quoteItem = $this->getItem();
+
+ // Add basic messages occurring during this page load
+ $baseMessages = $quoteItem->getMessage(false);
+ if ($baseMessages) {
+ foreach ($baseMessages as $message) {
+ $messages[] = [
+ 'text' => $message,
+ 'type' => $quoteItem->getHasError() ? 'error' : 'notice',
+ ];
+ }
+ }
+
+ return $messages;
+ }
/**
* Get bundled selections (slections-products collection)
*
@@ -58,39 +92,4 @@ protected function _getSelectionQty($selectionId)
{
return Mage::helper('bundle/catalog_product_configuration')->getSelectionQty($this->getProduct(), $selectionId);
}
-
- /**
- * Overloaded method for getting list of bundle options
- * Caches result in quote item, because it can be used in cart 'recent view' and on same page in cart checkout
- *
- * @return array
- */
- public function getOptionList()
- {
- return Mage::helper('bundle/catalog_product_configuration')->getOptions($this->getItem());
- }
-
- /**
- * Return cart item error messages
- *
- * @return array
- */
- public function getMessages()
- {
- $messages = [];
- $quoteItem = $this->getItem();
-
- // Add basic messages occurring during this page load
- $baseMessages = $quoteItem->getMessage(false);
- if ($baseMessages) {
- foreach ($baseMessages as $message) {
- $messages[] = [
- 'text' => $message,
- 'type' => $quoteItem->getHasError() ? 'error' : 'notice',
- ];
- }
- }
-
- return $messages;
- }
}
diff --git a/app/code/core/Mage/Bundle/Model/Option.php b/app/code/core/Mage/Bundle/Model/Option.php
index 037f26d1a7d..d4e56b59812 100644
--- a/app/code/core/Mage/Bundle/Model/Option.php
+++ b/app/code/core/Mage/Bundle/Model/Option.php
@@ -50,12 +50,6 @@ class Mage_Bundle_Model_Option extends Mage_Core_Model_Abstract
*/
protected $_defaultSelection = null;
- protected function _construct()
- {
- $this->_init('bundle/option');
- parent::_construct();
- }
-
/**
* Add selection to option
*
@@ -172,4 +166,10 @@ public function getSelectionById($selectionId)
return $i == -1 ? false : $selections[$i];
}
+
+ protected function _construct()
+ {
+ $this->_init('bundle/option');
+ parent::_construct();
+ }
}
diff --git a/app/code/core/Mage/Bundle/Model/Price/Index.php b/app/code/core/Mage/Bundle/Model/Price/Index.php
index 801826455e7..239c2a41a05 100644
--- a/app/code/core/Mage/Bundle/Model/Price/Index.php
+++ b/app/code/core/Mage/Bundle/Model/Price/Index.php
@@ -34,24 +34,6 @@
*/
class Mage_Bundle_Model_Price_Index extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('bundle/price_index');
- }
-
- /**
- * Reindex Product price
- *
- * @param int $productId
- * @param int $priceType
- * @return $this
- */
- protected function _reindexProduct($productId, $priceType)
- {
- $this->_getResource()->reindexProduct($productId, $priceType);
- return $this;
- }
-
/**
* Reindex Bundle product Price Index
*
@@ -125,4 +107,21 @@ public function addPriceIndexToProduct($product)
}
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('bundle/price_index');
+ }
+
+ /**
+ * Reindex Product price
+ *
+ * @param int $productId
+ * @param int $priceType
+ * @return $this
+ */
+ protected function _reindexProduct($productId, $priceType)
+ {
+ $this->_getResource()->reindexProduct($productId, $priceType);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Bundle/Model/Product/Price.php b/app/code/core/Mage/Bundle/Model/Product/Price.php
index c4039dd46bd..5076104ca0e 100644
--- a/app/code/core/Mage/Bundle/Model/Product/Price.php
+++ b/app/code/core/Mage/Bundle/Model/Product/Price.php
@@ -273,166 +273,6 @@ public function getTotalPrices($product, $which = null, $includeTax = null, $tak
return [$minimalPrice, $maximalPrice];
}
- /**
- * Get minimal possible price for bundle option
- *
- * @param Mage_Catalog_Model_Product $product
- * @param bool|null $includeTax
- * @param bool $takeTierPrice
- * @return int|mixed
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _getMinimalBundleOptionsPrice($product, $includeTax, $takeTierPrice)
- {
- $options = $this->getOptions($product);
- $minimalPrice = 0;
- $minimalPriceWithTax = 0;
- $hasRequiredOptions = $this->_hasRequiredOptions($product);
- $selectionMinimalPrices = [];
- $selectionMinimalPricesWithTax = [];
-
- if (!$options) {
- return $minimalPrice;
- }
-
- foreach ($options as $option) {
- /** @var Mage_Bundle_Model_Option $option */
- $selectionPrices = $this->_getSelectionPrices($product, $option, $takeTierPrice, $includeTax);
- $selectionPricesWithTax = $this->_getSelectionPrices($product, $option, $takeTierPrice, true);
-
- if (count($selectionPrices)) {
- $selectionMinPrice = is_array($selectionPrices) ? min($selectionPrices) : $selectionPrices;
- $selectMinPriceWithTax = is_array($selectionPricesWithTax) ?
- min($selectionPricesWithTax) : $selectionPricesWithTax;
- if ($option->getRequired()) {
- $minimalPrice += $selectionMinPrice;
- $minimalPriceWithTax += $selectMinPriceWithTax;
- } elseif (!$hasRequiredOptions) {
- $selectionMinimalPrices[] = $selectionMinPrice;
- $selectionMinimalPricesWithTax[] = $selectMinPriceWithTax;
- }
- }
- }
- // condition is TRUE when all product options are NOT required
- if (!$hasRequiredOptions) {
- $minimalPrice = empty($selectionMinimalPrices) ? 0 : min($selectionMinimalPrices);
- $minimalPriceWithTax = empty($selectionMinimalPricesWithTax) ? max(0, $minimalPrice) : min($selectionMinimalPricesWithTax);
- }
-
- /** @var Mage_Tax_Helper_Data $taxHelper */
- $taxHelper = $this->_getHelperData('tax');
- $taxConfig = $taxHelper->getConfig();
-
- //In the case of total base calculation we round the tax first and
- //deduct the tax from the price including tax
- if ($taxConfig->priceIncludesTax($product->getStore())
- && Mage_Tax_Model_Calculation::CALC_TOTAL_BASE == $taxConfig->getAlgorithm($product->getStore())
- && ($minimalPriceWithTax > $minimalPrice)
- ) {
- //We convert the value to string to maintain the precision
- $tax = (string) ($minimalPriceWithTax - $minimalPrice);
- $roundedTax = $this->_getApp()->getStore()->roundPrice($tax);
- $minimalPrice = $minimalPriceWithTax - $roundedTax;
- }
- return $minimalPrice;
- }
-
- /**
- * Get maximal possible price for bundle option
- *
- * @param Mage_Catalog_Model_Product $product
- * @param bool|null $includeTax
- * @param bool $takeTierPrice
- * @return float
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _getMaximalBundleOptionsPrice($product, $includeTax, $takeTierPrice)
- {
- $maximalPrice = 0;
- $options = $this->getOptions($product);
-
- if (!$options) {
- return $maximalPrice;
- }
-
- foreach ($options as $option) {
- $selectionPrices = $this->_getSelectionPrices($product, $option, $takeTierPrice, $includeTax);
- if (count($selectionPrices)) {
- $maximalPrice += ($option->isMultiSelection())
- ? array_sum($selectionPrices)
- : max($selectionPrices);
- }
- }
- return $maximalPrice;
- }
-
- /**
- * Get all prices for bundle option selection
- *
- * @param Mage_Catalog_Model_Product $product
- * @param Mage_Bundle_Model_Option $option
- * @param bool $takeTierPrice
- * @param bool|null $includeTax
- * @return array
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _getSelectionPrices($product, $option, $takeTierPrice, $includeTax)
- {
- $selectionPrices = [];
- /** @var Mage_Tax_Helper_Data $taxHelper */
- $taxHelper = $this->_getHelperData('tax');
- $taxCalcMethod = $taxHelper->getConfig()->getAlgorithm($product->getStore());
- $isPriceFixedType = ($product->getPriceType() == self::PRICE_TYPE_FIXED);
-
- $selections = $option->getSelections();
- if (!$selections) {
- return $selectionPrices;
- }
-
- foreach ($selections as $selection) {
- /** @var Mage_Bundle_Model_Selection $selection */
- if (!$selection->isSalable()) {
- /**
- * @todo CatalogInventory Show out of stock Products
- */
- continue;
- }
-
- $item = $isPriceFixedType ? $product : $selection;
-
- $selectionUnitPrice = $this->getSelectionFinalTotalPrice(
- $product,
- $selection,
- 1,
- null,
- false,
- $takeTierPrice,
- );
- $selectionQty = $selection->getSelectionQty();
- if ($isPriceFixedType || $taxCalcMethod == Mage_Tax_Model_Calculation::CALC_TOTAL_BASE) {
- $selectionPrice = $selectionQty * $taxHelper->getPrice(
- $item,
- $selectionUnitPrice,
- $includeTax,
- null,
- null,
- null,
- null,
- null,
- false,
- );
- $selectionPrices[] = $selectionPrice;
- } elseif ($taxCalcMethod == Mage_Tax_Model_Calculation::CALC_ROW_BASE) {
- $selectionPrice = $taxHelper->getPrice($item, $selectionUnitPrice * $selectionQty, $includeTax);
- $selectionPrices[] = $selectionPrice;
- } else { //dynamic price and Mage_Tax_Model_Calculation::CALC_UNIT_BASE
- $selectionPrice = $taxHelper->getPrice($item, $selectionUnitPrice, $includeTax) * $selectionQty;
- $selectionPrices[] = $selectionPrice;
- }
- }
- return $selectionPrices;
- }
-
/**
* Calculate Minimal price of bundle (counting all required options)
*
@@ -609,28 +449,6 @@ public function getLowestPrice($bundleProduct, $price, $bundleQty = 1)
);
}
- /**
- * Apply group price for bundle product
- *
- * @param Mage_Catalog_Model_Product $product
- * @param float $finalPrice
- * @return float
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _applyGroupPrice($product, $finalPrice)
- {
- $result = $finalPrice;
- $groupPrice = $product->getGroupPrice();
-
- if (is_numeric($groupPrice)) {
- $groupPrice = $finalPrice - ($finalPrice * ($groupPrice / 100));
- $groupPrice = $this->_getApp()->getStore()->roundPrice($groupPrice);
- $result = min($finalPrice, $groupPrice);
- }
-
- return $result;
- }
-
/**
* Get product group price
*
@@ -668,32 +486,6 @@ public function getGroupPrice($product)
return $matchedPrice;
}
- /**
- * Apply tier price for bundle
- *
- * @param Mage_Catalog_Model_Product $product
- * @param float $qty
- * @param float $finalPrice
- * @return float
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _applyTierPrice($product, $qty, $finalPrice)
- {
- if (is_null($qty)) {
- return $finalPrice;
- }
-
- $tierPrice = $product->getTierPrice($qty);
-
- if (is_numeric($tierPrice)) {
- $tierPrice = $finalPrice - ($finalPrice * ($tierPrice / 100));
- $tierPrice = $this->_getApp()->getStore()->roundPrice($tierPrice);
- $finalPrice = min($finalPrice, $tierPrice);
- }
-
- return $finalPrice;
- }
-
/**
* Get product tier price by qty
*
@@ -979,6 +771,214 @@ public function isGroupPriceFixed()
return false;
}
+ /**
+ * Get minimal possible price for bundle option
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param bool|null $includeTax
+ * @param bool $takeTierPrice
+ * @return int|mixed
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _getMinimalBundleOptionsPrice($product, $includeTax, $takeTierPrice)
+ {
+ $options = $this->getOptions($product);
+ $minimalPrice = 0;
+ $minimalPriceWithTax = 0;
+ $hasRequiredOptions = $this->_hasRequiredOptions($product);
+ $selectionMinimalPrices = [];
+ $selectionMinimalPricesWithTax = [];
+
+ if (!$options) {
+ return $minimalPrice;
+ }
+
+ foreach ($options as $option) {
+ /** @var Mage_Bundle_Model_Option $option */
+ $selectionPrices = $this->_getSelectionPrices($product, $option, $takeTierPrice, $includeTax);
+ $selectionPricesWithTax = $this->_getSelectionPrices($product, $option, $takeTierPrice, true);
+
+ if (count($selectionPrices)) {
+ $selectionMinPrice = is_array($selectionPrices) ? min($selectionPrices) : $selectionPrices;
+ $selectMinPriceWithTax = is_array($selectionPricesWithTax) ?
+ min($selectionPricesWithTax) : $selectionPricesWithTax;
+ if ($option->getRequired()) {
+ $minimalPrice += $selectionMinPrice;
+ $minimalPriceWithTax += $selectMinPriceWithTax;
+ } elseif (!$hasRequiredOptions) {
+ $selectionMinimalPrices[] = $selectionMinPrice;
+ $selectionMinimalPricesWithTax[] = $selectMinPriceWithTax;
+ }
+ }
+ }
+ // condition is TRUE when all product options are NOT required
+ if (!$hasRequiredOptions) {
+ $minimalPrice = empty($selectionMinimalPrices) ? 0 : min($selectionMinimalPrices);
+ $minimalPriceWithTax = empty($selectionMinimalPricesWithTax) ? max(0, $minimalPrice) : min($selectionMinimalPricesWithTax);
+ }
+
+ /** @var Mage_Tax_Helper_Data $taxHelper */
+ $taxHelper = $this->_getHelperData('tax');
+ $taxConfig = $taxHelper->getConfig();
+
+ //In the case of total base calculation we round the tax first and
+ //deduct the tax from the price including tax
+ if ($taxConfig->priceIncludesTax($product->getStore())
+ && Mage_Tax_Model_Calculation::CALC_TOTAL_BASE == $taxConfig->getAlgorithm($product->getStore())
+ && ($minimalPriceWithTax > $minimalPrice)
+ ) {
+ //We convert the value to string to maintain the precision
+ $tax = (string) ($minimalPriceWithTax - $minimalPrice);
+ $roundedTax = $this->_getApp()->getStore()->roundPrice($tax);
+ $minimalPrice = $minimalPriceWithTax - $roundedTax;
+ }
+ return $minimalPrice;
+ }
+
+ /**
+ * Get maximal possible price for bundle option
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param bool|null $includeTax
+ * @param bool $takeTierPrice
+ * @return float
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _getMaximalBundleOptionsPrice($product, $includeTax, $takeTierPrice)
+ {
+ $maximalPrice = 0;
+ $options = $this->getOptions($product);
+
+ if (!$options) {
+ return $maximalPrice;
+ }
+
+ foreach ($options as $option) {
+ $selectionPrices = $this->_getSelectionPrices($product, $option, $takeTierPrice, $includeTax);
+ if (count($selectionPrices)) {
+ $maximalPrice += ($option->isMultiSelection())
+ ? array_sum($selectionPrices)
+ : max($selectionPrices);
+ }
+ }
+ return $maximalPrice;
+ }
+
+ /**
+ * Get all prices for bundle option selection
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param Mage_Bundle_Model_Option $option
+ * @param bool $takeTierPrice
+ * @param bool|null $includeTax
+ * @return array
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _getSelectionPrices($product, $option, $takeTierPrice, $includeTax)
+ {
+ $selectionPrices = [];
+ /** @var Mage_Tax_Helper_Data $taxHelper */
+ $taxHelper = $this->_getHelperData('tax');
+ $taxCalcMethod = $taxHelper->getConfig()->getAlgorithm($product->getStore());
+ $isPriceFixedType = ($product->getPriceType() == self::PRICE_TYPE_FIXED);
+
+ $selections = $option->getSelections();
+ if (!$selections) {
+ return $selectionPrices;
+ }
+
+ foreach ($selections as $selection) {
+ /** @var Mage_Bundle_Model_Selection $selection */
+ if (!$selection->isSalable()) {
+ /**
+ * @todo CatalogInventory Show out of stock Products
+ */
+ continue;
+ }
+
+ $item = $isPriceFixedType ? $product : $selection;
+
+ $selectionUnitPrice = $this->getSelectionFinalTotalPrice(
+ $product,
+ $selection,
+ 1,
+ null,
+ false,
+ $takeTierPrice,
+ );
+ $selectionQty = $selection->getSelectionQty();
+ if ($isPriceFixedType || $taxCalcMethod == Mage_Tax_Model_Calculation::CALC_TOTAL_BASE) {
+ $selectionPrice = $selectionQty * $taxHelper->getPrice(
+ $item,
+ $selectionUnitPrice,
+ $includeTax,
+ null,
+ null,
+ null,
+ null,
+ null,
+ false,
+ );
+ $selectionPrices[] = $selectionPrice;
+ } elseif ($taxCalcMethod == Mage_Tax_Model_Calculation::CALC_ROW_BASE) {
+ $selectionPrice = $taxHelper->getPrice($item, $selectionUnitPrice * $selectionQty, $includeTax);
+ $selectionPrices[] = $selectionPrice;
+ } else { //dynamic price and Mage_Tax_Model_Calculation::CALC_UNIT_BASE
+ $selectionPrice = $taxHelper->getPrice($item, $selectionUnitPrice, $includeTax) * $selectionQty;
+ $selectionPrices[] = $selectionPrice;
+ }
+ }
+ return $selectionPrices;
+ }
+
+ /**
+ * Apply group price for bundle product
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param float $finalPrice
+ * @return float
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _applyGroupPrice($product, $finalPrice)
+ {
+ $result = $finalPrice;
+ $groupPrice = $product->getGroupPrice();
+
+ if (is_numeric($groupPrice)) {
+ $groupPrice = $finalPrice - ($finalPrice * ($groupPrice / 100));
+ $groupPrice = $this->_getApp()->getStore()->roundPrice($groupPrice);
+ $result = min($finalPrice, $groupPrice);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Apply tier price for bundle
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param float $qty
+ * @param float $finalPrice
+ * @return float
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _applyTierPrice($product, $qty, $finalPrice)
+ {
+ if (is_null($qty)) {
+ return $finalPrice;
+ }
+
+ $tierPrice = $product->getTierPrice($qty);
+
+ if (is_numeric($tierPrice)) {
+ $tierPrice = $finalPrice - ($finalPrice * ($tierPrice / 100));
+ $tierPrice = $this->_getApp()->getStore()->roundPrice($tierPrice);
+ $finalPrice = min($finalPrice, $tierPrice);
+ }
+
+ return $finalPrice;
+ }
+
/**
* Get data helper
*
diff --git a/app/code/core/Mage/Bundle/Model/Product/Type.php b/app/code/core/Mage/Bundle/Model/Product/Type.php
index 5d8f1886832..a5b229c02ac 100644
--- a/app/code/core/Mage/Bundle/Model/Product/Type.php
+++ b/app/code/core/Mage/Bundle/Model/Product/Type.php
@@ -507,189 +507,6 @@ public function isSalable($product = null)
return (array_sum($requiredOptionIds) == count($requiredOptionIds) && $salableSelectionCount);
}
- /**
- * Prepare product and its configuration to be added to some products list.
- * Perform standard preparation process and then prepare of bundle selections options.
- *
- * @param Mage_Catalog_Model_Product $product
- * @param string $processMode
- * @return array|string
- */
- protected function _prepareProduct(Varien_Object $buyRequest, $product, $processMode)
- {
- $result = parent::_prepareProduct($buyRequest, $product, $processMode);
-
- if (is_string($result)) {
- return $result;
- }
-
- $selections = [];
- $product = $this->getProduct($product);
- $isStrictProcessMode = $this->_isStrictProcessMode($processMode);
-
- $skipSaleableCheck = Mage::helper('catalog/product')->getSkipSaleableCheck();
- $_appendAllSelections = (bool) $product->getSkipCheckRequiredOption() || $skipSaleableCheck;
-
- $options = $buyRequest->getBundleOption();
- if (is_array($options)) {
- $options = array_filter($options, '\intval');
- $qtys = $buyRequest->getBundleOptionQty();
- foreach ($options as $_optionId => $_selections) {
- if (empty($_selections)) {
- unset($options[$_optionId]);
- }
- }
- $optionIds = array_keys($options);
-
- if (empty($optionIds) && $isStrictProcessMode) {
- return Mage::helper('bundle')->__('Please select options for product.');
- }
-
- $product->getTypeInstance(true)->setStoreFilter($product->getStoreId(), $product);
- $optionsCollection = $this->getOptionsCollection($product);
- if (!$this->getProduct($product)->getSkipCheckRequiredOption() && $isStrictProcessMode) {
- foreach ($optionsCollection->getItems() as $option) {
- if ($option->getRequired() && !isset($options[$option->getId()])) {
- return Mage::helper('bundle')->__('Required options are not selected.');
- }
- }
- }
- $selectionIds = [];
-
- foreach ($options as $optionId => $selectionId) {
- if (!is_array($selectionId)) {
- if ($selectionId != '') {
- $selectionIds[] = (int) $selectionId;
- }
- } else {
- foreach ($selectionId as $id) {
- if ($id != '') {
- $selectionIds[] = (int) $id;
- }
- }
- }
- }
- // If product has not been configured yet then $selections array should be empty
- if (!empty($selectionIds)) {
- $selections = $this->getSelectionsByIds($selectionIds, $product);
-
- // Check if added selections are still on sale
- foreach ($selections->getItems() as $selection) {
- if (!$selection->isSalable() && !$skipSaleableCheck) {
- $selectedOption = $optionsCollection->getItemById($selection->getOptionId());
- if (is_array($options[$selectedOption->getId()]) && count($options[$selectedOption->getId()]) > 1) {
- $moreSelections = true;
- } else {
- $moreSelections = false;
- }
- if ($selectedOption->getRequired()
- && (!$selectedOption->isMultiSelection() || ($selectedOption->isMultiSelection() && !$moreSelections))
- ) {
- return Mage::helper('bundle')->__('Selected required options are not available.');
- }
- }
- }
-
- $optionsCollection->appendSelections($selections, false, $_appendAllSelections);
-
- $selections = $selections->getItems();
- } else {
- $selections = [];
- }
- } else {
- $product->setOptionsValidationFail(true);
- $product->getTypeInstance(true)->setStoreFilter($product->getStoreId(), $product);
-
- /** @var Mage_Bundle_Model_Product_Type $productType */
- $productType = $product->getTypeInstance(true);
-
- $optionCollection = $productType->getOptionsCollection($product);
-
- $optionIds = $productType->getOptionsIds($product);
-
- $selectionCollection = $productType->getSelectionsCollection(
- $optionIds,
- $product,
- );
-
- $options = $optionCollection->appendSelections($selectionCollection, false, $_appendAllSelections);
-
- foreach ($options as $option) {
- if ($option->getRequired() && count($option->getSelections()) == 1) {
- $selections = array_merge($selections, $option->getSelections());
- } else {
- $selections = [];
- break;
- }
- }
- }
- if (count($selections) > 0 || !$isStrictProcessMode) {
- $uniqueKey = [$product->getId()];
- $selectionIds = [];
-
- // Shuffle selection array by option position
- usort($selections, [$this, 'shakeSelections']);
-
- foreach ($selections as $selection) {
- if ($selection->getSelectionCanChangeQty() && isset($qtys[$selection->getOptionId()])) {
- $qty = (float) $qtys[$selection->getOptionId()] > 0 ? $qtys[$selection->getOptionId()] : 1;
- } else {
- $qty = (float) $selection->getSelectionQty() ? $selection->getSelectionQty() : 1;
- }
- $qty = (float) $qty;
-
- $product->addCustomOption('selection_qty_' . $selection->getSelectionId(), $qty, $selection);
- $selection->addCustomOption('selection_id', $selection->getSelectionId());
- $product->addCustomOption('product_qty_' . $selection->getId(), $qty, $selection);
-
- /*
- * Create extra attributes that will be converted to product options in order item
- * for selection (not for all bundle)
- */
- $price = $product->getPriceModel()->getSelectionFinalTotalPrice($product, $selection, 0, $qty);
- $attributes = [
- 'price' => Mage::app()->getStore()->convertPrice($price),
- 'qty' => $qty,
- 'option_label' => $selection->getOption()->getTitle(),
- 'option_id' => $selection->getOption()->getId(),
- ];
-
- $_result = $selection->getTypeInstance(true)->prepareForCart($buyRequest, $selection);
- if (is_string($_result) && !is_array($_result)) {
- return $_result;
- }
-
- if (!isset($_result[0])) {
- return Mage::helper('checkout')->__('Cannot add item to the shopping cart.');
- }
-
- $result[] = $_result[0]->setParentProductId($product->getId())
- ->addCustomOption('bundle_option_ids', serialize(array_map('\intval', $optionIds)))
- ->addCustomOption('bundle_selection_attributes', serialize($attributes));
-
- if ($isStrictProcessMode) {
- $_result[0]->setCartQty($qty);
- }
-
- $selectionIds[] = $_result[0]->getSelectionId();
- $uniqueKey[] = $_result[0]->getSelectionId();
- $uniqueKey[] = $qty;
- }
-
- // "unique" key for bundle selection and add it to selections and bundle for selections
- $uniqueKey = implode('_', $uniqueKey);
- foreach ($result as $item) {
- $item->addCustomOption('bundle_identity', $uniqueKey);
- }
- $product->addCustomOption('bundle_option_ids', serialize(array_map('\intval', $optionIds)));
- $product->addCustomOption('bundle_selection_ids', serialize($selectionIds));
-
- return $result;
- }
-
- return $this->getSpecifyOptionMessage();
- }
-
/**
* Retrieve message for specify option(s)
*
@@ -1070,4 +887,187 @@ public function isMapEnabledInOptions($product, $visibility = null)
return null;
}
+
+ /**
+ * Prepare product and its configuration to be added to some products list.
+ * Perform standard preparation process and then prepare of bundle selections options.
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param string $processMode
+ * @return array|string
+ */
+ protected function _prepareProduct(Varien_Object $buyRequest, $product, $processMode)
+ {
+ $result = parent::_prepareProduct($buyRequest, $product, $processMode);
+
+ if (is_string($result)) {
+ return $result;
+ }
+
+ $selections = [];
+ $product = $this->getProduct($product);
+ $isStrictProcessMode = $this->_isStrictProcessMode($processMode);
+
+ $skipSaleableCheck = Mage::helper('catalog/product')->getSkipSaleableCheck();
+ $_appendAllSelections = (bool) $product->getSkipCheckRequiredOption() || $skipSaleableCheck;
+
+ $options = $buyRequest->getBundleOption();
+ if (is_array($options)) {
+ $options = array_filter($options, '\intval');
+ $qtys = $buyRequest->getBundleOptionQty();
+ foreach ($options as $_optionId => $_selections) {
+ if (empty($_selections)) {
+ unset($options[$_optionId]);
+ }
+ }
+ $optionIds = array_keys($options);
+
+ if (empty($optionIds) && $isStrictProcessMode) {
+ return Mage::helper('bundle')->__('Please select options for product.');
+ }
+
+ $product->getTypeInstance(true)->setStoreFilter($product->getStoreId(), $product);
+ $optionsCollection = $this->getOptionsCollection($product);
+ if (!$this->getProduct($product)->getSkipCheckRequiredOption() && $isStrictProcessMode) {
+ foreach ($optionsCollection->getItems() as $option) {
+ if ($option->getRequired() && !isset($options[$option->getId()])) {
+ return Mage::helper('bundle')->__('Required options are not selected.');
+ }
+ }
+ }
+ $selectionIds = [];
+
+ foreach ($options as $optionId => $selectionId) {
+ if (!is_array($selectionId)) {
+ if ($selectionId != '') {
+ $selectionIds[] = (int) $selectionId;
+ }
+ } else {
+ foreach ($selectionId as $id) {
+ if ($id != '') {
+ $selectionIds[] = (int) $id;
+ }
+ }
+ }
+ }
+ // If product has not been configured yet then $selections array should be empty
+ if (!empty($selectionIds)) {
+ $selections = $this->getSelectionsByIds($selectionIds, $product);
+
+ // Check if added selections are still on sale
+ foreach ($selections->getItems() as $selection) {
+ if (!$selection->isSalable() && !$skipSaleableCheck) {
+ $selectedOption = $optionsCollection->getItemById($selection->getOptionId());
+ if (is_array($options[$selectedOption->getId()]) && count($options[$selectedOption->getId()]) > 1) {
+ $moreSelections = true;
+ } else {
+ $moreSelections = false;
+ }
+ if ($selectedOption->getRequired()
+ && (!$selectedOption->isMultiSelection() || ($selectedOption->isMultiSelection() && !$moreSelections))
+ ) {
+ return Mage::helper('bundle')->__('Selected required options are not available.');
+ }
+ }
+ }
+
+ $optionsCollection->appendSelections($selections, false, $_appendAllSelections);
+
+ $selections = $selections->getItems();
+ } else {
+ $selections = [];
+ }
+ } else {
+ $product->setOptionsValidationFail(true);
+ $product->getTypeInstance(true)->setStoreFilter($product->getStoreId(), $product);
+
+ /** @var Mage_Bundle_Model_Product_Type $productType */
+ $productType = $product->getTypeInstance(true);
+
+ $optionCollection = $productType->getOptionsCollection($product);
+
+ $optionIds = $productType->getOptionsIds($product);
+
+ $selectionCollection = $productType->getSelectionsCollection(
+ $optionIds,
+ $product,
+ );
+
+ $options = $optionCollection->appendSelections($selectionCollection, false, $_appendAllSelections);
+
+ foreach ($options as $option) {
+ if ($option->getRequired() && count($option->getSelections()) == 1) {
+ $selections = array_merge($selections, $option->getSelections());
+ } else {
+ $selections = [];
+ break;
+ }
+ }
+ }
+ if (count($selections) > 0 || !$isStrictProcessMode) {
+ $uniqueKey = [$product->getId()];
+ $selectionIds = [];
+
+ // Shuffle selection array by option position
+ usort($selections, [$this, 'shakeSelections']);
+
+ foreach ($selections as $selection) {
+ if ($selection->getSelectionCanChangeQty() && isset($qtys[$selection->getOptionId()])) {
+ $qty = (float) $qtys[$selection->getOptionId()] > 0 ? $qtys[$selection->getOptionId()] : 1;
+ } else {
+ $qty = (float) $selection->getSelectionQty() ? $selection->getSelectionQty() : 1;
+ }
+ $qty = (float) $qty;
+
+ $product->addCustomOption('selection_qty_' . $selection->getSelectionId(), $qty, $selection);
+ $selection->addCustomOption('selection_id', $selection->getSelectionId());
+ $product->addCustomOption('product_qty_' . $selection->getId(), $qty, $selection);
+
+ /*
+ * Create extra attributes that will be converted to product options in order item
+ * for selection (not for all bundle)
+ */
+ $price = $product->getPriceModel()->getSelectionFinalTotalPrice($product, $selection, 0, $qty);
+ $attributes = [
+ 'price' => Mage::app()->getStore()->convertPrice($price),
+ 'qty' => $qty,
+ 'option_label' => $selection->getOption()->getTitle(),
+ 'option_id' => $selection->getOption()->getId(),
+ ];
+
+ $_result = $selection->getTypeInstance(true)->prepareForCart($buyRequest, $selection);
+ if (is_string($_result) && !is_array($_result)) {
+ return $_result;
+ }
+
+ if (!isset($_result[0])) {
+ return Mage::helper('checkout')->__('Cannot add item to the shopping cart.');
+ }
+
+ $result[] = $_result[0]->setParentProductId($product->getId())
+ ->addCustomOption('bundle_option_ids', serialize(array_map('\intval', $optionIds)))
+ ->addCustomOption('bundle_selection_attributes', serialize($attributes));
+
+ if ($isStrictProcessMode) {
+ $_result[0]->setCartQty($qty);
+ }
+
+ $selectionIds[] = $_result[0]->getSelectionId();
+ $uniqueKey[] = $_result[0]->getSelectionId();
+ $uniqueKey[] = $qty;
+ }
+
+ // "unique" key for bundle selection and add it to selections and bundle for selections
+ $uniqueKey = implode('_', $uniqueKey);
+ foreach ($result as $item) {
+ $item->addCustomOption('bundle_identity', $uniqueKey);
+ }
+ $product->addCustomOption('bundle_option_ids', serialize(array_map('\intval', $optionIds)));
+ $product->addCustomOption('bundle_selection_ids', serialize($selectionIds));
+
+ return $result;
+ }
+
+ return $this->getSpecifyOptionMessage();
+ }
}
diff --git a/app/code/core/Mage/Bundle/Model/Resource/Bundle.php b/app/code/core/Mage/Bundle/Model/Resource/Bundle.php
index c9b23a96cfe..5a518fee5d5 100644
--- a/app/code/core/Mage/Bundle/Model/Resource/Bundle.php
+++ b/app/code/core/Mage/Bundle/Model/Resource/Bundle.php
@@ -22,28 +22,6 @@
*/
class Mage_Bundle_Model_Resource_Bundle extends Mage_CatalogIndex_Model_Resource_Data_Abstract
{
- /**
- * Preparing select for getting selection's raw data by product id
- * also can be specified extra parameter for limit which columns should be selected
- *
- * @param int $productId
- * @param array $columns
- * @return Zend_Db_Select
- */
- protected function _getSelect($productId, $columns = [])
- {
- return $this->_getReadAdapter()->select()
- ->from(['bundle_option' => $this->getTable('bundle/option')], ['type', 'option_id'])
- ->where('bundle_option.parent_id = ?', $productId)
- ->where('bundle_option.required = 1')
- ->joinLeft(
- [
- 'bundle_selection' => $this->getTable('bundle/selection')],
- 'bundle_selection.option_id = bundle_option.option_id',
- $columns,
- );
- }
-
/**
* Retrieve selection data for specified product id
*
@@ -112,4 +90,25 @@ public function saveProductRelations($parentId, $childIds)
return $this;
}
+ /**
+ * Preparing select for getting selection's raw data by product id
+ * also can be specified extra parameter for limit which columns should be selected
+ *
+ * @param int $productId
+ * @param array $columns
+ * @return Zend_Db_Select
+ */
+ protected function _getSelect($productId, $columns = [])
+ {
+ return $this->_getReadAdapter()->select()
+ ->from(['bundle_option' => $this->getTable('bundle/option')], ['type', 'option_id'])
+ ->where('bundle_option.parent_id = ?', $productId)
+ ->where('bundle_option.required = 1')
+ ->joinLeft(
+ [
+ 'bundle_selection' => $this->getTable('bundle/selection')],
+ 'bundle_selection.option_id = bundle_option.option_id',
+ $columns,
+ );
+ }
}
diff --git a/app/code/core/Mage/Bundle/Model/Resource/Option.php b/app/code/core/Mage/Bundle/Model/Resource/Option.php
index 34a96d0095f..bd695fa108d 100644
--- a/app/code/core/Mage/Bundle/Model/Resource/Option.php
+++ b/app/code/core/Mage/Bundle/Model/Resource/Option.php
@@ -22,6 +22,44 @@
*/
class Mage_Bundle_Model_Resource_Option extends Mage_Core_Model_Resource_Db_Abstract
{
+ /**
+ * Retrieve options searchable data
+ *
+ * @param int $productId
+ * @param int $storeId
+ * @return array
+ */
+ public function getSearchableData($productId, $storeId)
+ {
+ $adapter = $this->_getReadAdapter();
+
+ $title = $adapter->getCheckSql(
+ 'option_title_store.title IS NOT NULL',
+ 'option_title_store.title',
+ 'option_title_default.title',
+ );
+ $bind = [
+ 'store_id' => $storeId,
+ 'product_id' => $productId,
+ ];
+ $select = $adapter->select()
+ ->from(['opt' => $this->getMainTable()], [])
+ ->join(
+ ['option_title_default' => $this->getTable('bundle/option_value')],
+ 'option_title_default.option_id = opt.option_id AND option_title_default.store_id = 0',
+ [],
+ )
+ ->joinLeft(
+ ['option_title_store' => $this->getTable('bundle/option_value')],
+ 'option_title_store.option_id = opt.option_id AND option_title_store.store_id = :store_id',
+ ['title' => $title],
+ )
+ ->where('opt.parent_id=:product_id');
+ if (!$searchData = $adapter->fetchCol($select, $bind)) {
+ $searchData = [];
+ }
+ return $searchData;
+ }
protected function _construct()
{
$this->_init('bundle/option', 'option_id');
@@ -78,43 +116,4 @@ protected function _afterDelete(Mage_Core_Model_Abstract $object)
return $this;
}
-
- /**
- * Retrieve options searchable data
- *
- * @param int $productId
- * @param int $storeId
- * @return array
- */
- public function getSearchableData($productId, $storeId)
- {
- $adapter = $this->_getReadAdapter();
-
- $title = $adapter->getCheckSql(
- 'option_title_store.title IS NOT NULL',
- 'option_title_store.title',
- 'option_title_default.title',
- );
- $bind = [
- 'store_id' => $storeId,
- 'product_id' => $productId,
- ];
- $select = $adapter->select()
- ->from(['opt' => $this->getMainTable()], [])
- ->join(
- ['option_title_default' => $this->getTable('bundle/option_value')],
- 'option_title_default.option_id = opt.option_id AND option_title_default.store_id = 0',
- [],
- )
- ->joinLeft(
- ['option_title_store' => $this->getTable('bundle/option_value')],
- 'option_title_store.option_id = opt.option_id AND option_title_store.store_id = :store_id',
- ['title' => $title],
- )
- ->where('opt.parent_id=:product_id');
- if (!$searchData = $adapter->fetchCol($select, $bind)) {
- $searchData = [];
- }
- return $searchData;
- }
}
diff --git a/app/code/core/Mage/Bundle/Model/Resource/Option/Collection.php b/app/code/core/Mage/Bundle/Model/Resource/Option/Collection.php
index f6e901f5e06..c9942046107 100644
--- a/app/code/core/Mage/Bundle/Model/Resource/Option/Collection.php
+++ b/app/code/core/Mage/Bundle/Model/Resource/Option/Collection.php
@@ -39,15 +39,6 @@ class Mage_Bundle_Model_Resource_Option_Collection extends Mage_Core_Model_Resou
*/
protected $_selectionsAppended = false;
- /**
- * Init model and resource model
- *
- */
- protected function _construct()
- {
- $this->_init('bundle/option');
- }
-
/**
* Joins values to options
*
@@ -141,20 +132,6 @@ public function appendSelections($selectionsCollection, $stripBefore = false, $a
return $this->getItems();
}
- /**
- * Removes appended selections before
- *
- * @return $this
- */
- protected function _stripSelections()
- {
- foreach ($this->getItems() as $option) {
- $option->setSelections([]);
- }
- $this->_selectionsAppended = false;
- return $this;
- }
-
/**
* Sets filter by option id
*
@@ -194,4 +171,27 @@ public function getAllIds()
}
return $this->_itemIds;
}
+
+ /**
+ * Init model and resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('bundle/option');
+ }
+
+ /**
+ * Removes appended selections before
+ *
+ * @return $this
+ */
+ protected function _stripSelections()
+ {
+ foreach ($this->getItems() as $option) {
+ $option->setSelections([]);
+ }
+ $this->_selectionsAppended = false;
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Bundle/Model/Resource/Price/Index.php b/app/code/core/Mage/Bundle/Model/Resource/Price/Index.php
index 6d85e9e1369..18150eac6f3 100644
--- a/app/code/core/Mage/Bundle/Model/Resource/Price/Index.php
+++ b/app/code/core/Mage/Bundle/Model/Resource/Price/Index.php
@@ -43,56 +43,6 @@ class Mage_Bundle_Model_Resource_Price_Index extends Mage_Core_Model_Resource_Db
*/
protected $_customerGroups;
- protected function _construct()
- {
- $this->_init('bundle/price_index', 'entity_id');
- }
-
- /**
- * Retrieve attribute object
- *
- * @param string $attributeCode
- * @return Mage_Catalog_Model_Resource_Eav_Attribute
- */
- protected function _getAttribute($attributeCode)
- {
- if (!isset($this->_attributes[$attributeCode])) {
- $this->_attributes[$attributeCode] = Mage::getSingleton('catalog/config')
- ->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
- }
- return $this->_attributes[$attributeCode];
- }
-
- /**
- * Retrieve websites collection array
- *
- * @return array
- */
- protected function _getWebsites()
- {
- if (is_null($this->_websites)) {
- $this->_websites = Mage::app()->getWebsites(false);
- }
- return $this->_websites;
- }
-
- /**
- * Retrieve customer groups collection array
- *
- * @return array
- * @throws Mage_Core_Exception
- */
- protected function _getCustomerGroups()
- {
- if (is_null($this->_customerGroups)) {
- $this->_customerGroups = [];
- foreach (Mage::getModel('customer/group')->getCollection() as $group) {
- $this->_customerGroups[$group->getId()] = $group;
- }
- }
- return $this->_customerGroups;
- }
-
/**
* Retrieve product ids array by product condition
*
@@ -168,99 +118,6 @@ public function reindex($products = null)
return $this;
}
- /**
- * Reindex product price
- *
- * @param int $productId
- * @param int $priceType
- * @return $this
- * @throws Mage_Core_Exception
- */
- protected function _reindexProduct($productId, $priceType)
- {
- $options = $this->getSelections($productId);
- $selectionProducts = [];
- foreach ($options as $option) {
- foreach ($option['selections'] as $selection) {
- $selectionProducts[$selection['product_id']] = $selection['product_id'];
- }
- }
-
- $priceIndex = [];
- if ($priceType == Mage_Bundle_Model_Product_Price::PRICE_TYPE_DYNAMIC) {
- // load selection product prices from index for dynamic bundle
- $priceIndex = $this->getProductsPriceFromIndex($selectionProducts);
- }
-
- /** @var Mage_Core_Model_Website $website */
- foreach ($this->_getWebsites() as $website) {
- if (!$website->getDefaultStore()) {
- continue;
- }
- $salableStatus = $this->getProductsSalableStatus($selectionProducts, $website);
- $priceData = $this->getProductsPriceData($productId, $website);
- $priceData = $priceData[$productId];
-
- /** @var Mage_Customer_Model_Group $group */
- foreach ($this->_getCustomerGroups() as $group) {
- if ($priceType == Mage_Bundle_Model_Product_Price::PRICE_TYPE_FIXED) {
- $basePrice = $this->_getBasePrice($productId, $priceData, $website, $group);
- $customOptions = $this->getCustomOptions($productId, $website);
- } elseif ($priceType == Mage_Bundle_Model_Product_Price::PRICE_TYPE_DYNAMIC) {
- $basePrice = 0;
- }
-
- list($minPrice, $maxPrice) = $this->_calculateBundleSelections(
- $options,
- $salableStatus,
- $productId,
- $priceType,
- $basePrice,
- $priceData,
- $priceIndex,
- $website,
- $group,
- );
-
- if ($priceType == Mage_Bundle_Model_Product_Price::PRICE_TYPE_FIXED) {
- list($minPrice, $maxPrice) =
- $this->_calculateCustomOptions($customOptions, $basePrice, $minPrice, $maxPrice);
- }
-
- $this->_savePriceIndex($productId, $website->getId(), $group->getId(), $minPrice, $maxPrice);
- }
- }
-
- return $this;
- }
-
- /**
- * Save price index
- *
- * @param int $productId
- * @param int $websiteId
- * @param int $groupId
- * @param float $minPrice
- * @param float $maxPrice
- * @return $this
- * @throws Zend_Db_Exception
- */
- protected function _savePriceIndex($productId, $websiteId, $groupId, $minPrice, $maxPrice)
- {
- $adapter = $this->_getWriteAdapter();
- $adapter->beginTransaction();
- try {
- $bind = [$productId, $websiteId, $groupId, $minPrice, $maxPrice];
- $adapter->insertOnDuplicate($this->getMainTable(), $bind, ['min_price', 'max_price']);
- $adapter->commit();
- } catch (Exception $e) {
- $adapter->rollBack();
- throw $e;
- }
-
- return $this;
- }
-
/**
* Retrieve bundle options with selections and prices by product
*
@@ -450,81 +307,6 @@ public function getProductsPriceData($products, Mage_Core_Model_Website $website
return $productsData;
}
- /**
- * Add attribute data to select
- *
- * @param string $attributeCode
- * @return $this
- * @throws Mage_Core_Exception
- */
- protected function _addAttributeDataToSelect(
- Varien_Db_Select $select,
- $attributeCode,
- Mage_Core_Model_Website $website
- ) {
- $attribute = $this->_getAttribute($attributeCode);
- $store = $website->getDefaultStore();
- if ($attribute->isScopeGlobal()) {
- $table = 't_' . $attribute->getAttributeCode();
- $select->joinLeft(
- [$table => $attribute->getBackend()->getTable()],
- "e.entity_id={$table}.entity_id"
- . " AND {$table}.attribute_id={$attribute->getAttributeId()}"
- . " AND {$table}.store_id=0",
- [$attribute->getAttributeCode() => $table . '.value'],
- );
- } else {
- $tableName = $attribute->getBackend()->getTable();
- $tableGlobal = 't1_' . $attribute->getAttributeCode();
- $tableStore = 't2_' . $attribute->getAttributeCode();
-
- $attributeCond = $this->getReadConnection()->getCheckSql(
- $tableStore . '.value_id > 0',
- $tableStore . '.value',
- $tableGlobal . '.value',
- );
- $select->joinLeft(
- [$tableGlobal => $tableName],
- "e.entity_id = {$tableGlobal}.entity_id"
- . " AND {$tableGlobal}.attribute_id = {$attribute->getAttributeId()}"
- . " AND {$tableGlobal}.store_id = 0",
- [$attribute->getAttributeCode() => $attributeCond],
- )
- ->joinLeft(
- [$tableStore => $tableName],
- "{$tableGlobal}.entity_id = {$tableStore}.entity_id"
- . " AND {$tableGlobal}.attribute_id = {$tableStore}.attribute_id"
- . " AND {$tableStore}.store_id = " . $store->getId(),
- [],
- );
- }
- return $this;
- }
-
- /**
- * Retrieve fixed bundle base price (with special price and rules)
- *
- * @param int $productId
- * @param Mage_Core_Model_Website $website
- * @param Mage_Customer_Model_Group $customerGroup
- * @return float
- */
- protected function _getBasePrice($productId, array $priceData, $website, $customerGroup)
- {
- $store = $website->getDefaultStore();
- $storeTimeStamp = Mage::app()->getLocale()->storeTimeStamp($store);
- $finalPrice = $this->_calculateSpecialPrice($priceData['price'], $priceData, $website);
-
- $rulePrice = Mage::getResourceModel('catalogrule/rule')
- ->getRulePrice($storeTimeStamp, $website->getId(), $customerGroup->getId(), $productId);
-
- if ($rulePrice !== null && $rulePrice !== false) {
- $finalPrice = min($finalPrice, $rulePrice);
- }
-
- return $finalPrice;
- }
-
/**
* Retrieve custom options for product
*
@@ -860,4 +642,222 @@ public function loadPriceIndex($productIds, $websiteId, $groupId)
return $prices;
}
+
+ protected function _construct()
+ {
+ $this->_init('bundle/price_index', 'entity_id');
+ }
+
+ /**
+ * Retrieve attribute object
+ *
+ * @param string $attributeCode
+ * @return Mage_Catalog_Model_Resource_Eav_Attribute
+ */
+ protected function _getAttribute($attributeCode)
+ {
+ if (!isset($this->_attributes[$attributeCode])) {
+ $this->_attributes[$attributeCode] = Mage::getSingleton('catalog/config')
+ ->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
+ }
+ return $this->_attributes[$attributeCode];
+ }
+
+ /**
+ * Retrieve websites collection array
+ *
+ * @return array
+ */
+ protected function _getWebsites()
+ {
+ if (is_null($this->_websites)) {
+ $this->_websites = Mage::app()->getWebsites(false);
+ }
+ return $this->_websites;
+ }
+
+ /**
+ * Retrieve customer groups collection array
+ *
+ * @return array
+ * @throws Mage_Core_Exception
+ */
+ protected function _getCustomerGroups()
+ {
+ if (is_null($this->_customerGroups)) {
+ $this->_customerGroups = [];
+ foreach (Mage::getModel('customer/group')->getCollection() as $group) {
+ $this->_customerGroups[$group->getId()] = $group;
+ }
+ }
+ return $this->_customerGroups;
+ }
+
+ /**
+ * Reindex product price
+ *
+ * @param int $productId
+ * @param int $priceType
+ * @return $this
+ * @throws Mage_Core_Exception
+ */
+ protected function _reindexProduct($productId, $priceType)
+ {
+ $options = $this->getSelections($productId);
+ $selectionProducts = [];
+ foreach ($options as $option) {
+ foreach ($option['selections'] as $selection) {
+ $selectionProducts[$selection['product_id']] = $selection['product_id'];
+ }
+ }
+
+ $priceIndex = [];
+ if ($priceType == Mage_Bundle_Model_Product_Price::PRICE_TYPE_DYNAMIC) {
+ // load selection product prices from index for dynamic bundle
+ $priceIndex = $this->getProductsPriceFromIndex($selectionProducts);
+ }
+
+ /** @var Mage_Core_Model_Website $website */
+ foreach ($this->_getWebsites() as $website) {
+ if (!$website->getDefaultStore()) {
+ continue;
+ }
+ $salableStatus = $this->getProductsSalableStatus($selectionProducts, $website);
+ $priceData = $this->getProductsPriceData($productId, $website);
+ $priceData = $priceData[$productId];
+
+ /** @var Mage_Customer_Model_Group $group */
+ foreach ($this->_getCustomerGroups() as $group) {
+ if ($priceType == Mage_Bundle_Model_Product_Price::PRICE_TYPE_FIXED) {
+ $basePrice = $this->_getBasePrice($productId, $priceData, $website, $group);
+ $customOptions = $this->getCustomOptions($productId, $website);
+ } elseif ($priceType == Mage_Bundle_Model_Product_Price::PRICE_TYPE_DYNAMIC) {
+ $basePrice = 0;
+ }
+
+ list($minPrice, $maxPrice) = $this->_calculateBundleSelections(
+ $options,
+ $salableStatus,
+ $productId,
+ $priceType,
+ $basePrice,
+ $priceData,
+ $priceIndex,
+ $website,
+ $group,
+ );
+
+ if ($priceType == Mage_Bundle_Model_Product_Price::PRICE_TYPE_FIXED) {
+ list($minPrice, $maxPrice) =
+ $this->_calculateCustomOptions($customOptions, $basePrice, $minPrice, $maxPrice);
+ }
+
+ $this->_savePriceIndex($productId, $website->getId(), $group->getId(), $minPrice, $maxPrice);
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Save price index
+ *
+ * @param int $productId
+ * @param int $websiteId
+ * @param int $groupId
+ * @param float $minPrice
+ * @param float $maxPrice
+ * @return $this
+ * @throws Zend_Db_Exception
+ */
+ protected function _savePriceIndex($productId, $websiteId, $groupId, $minPrice, $maxPrice)
+ {
+ $adapter = $this->_getWriteAdapter();
+ $adapter->beginTransaction();
+ try {
+ $bind = [$productId, $websiteId, $groupId, $minPrice, $maxPrice];
+ $adapter->insertOnDuplicate($this->getMainTable(), $bind, ['min_price', 'max_price']);
+ $adapter->commit();
+ } catch (Exception $e) {
+ $adapter->rollBack();
+ throw $e;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Add attribute data to select
+ *
+ * @param string $attributeCode
+ * @return $this
+ * @throws Mage_Core_Exception
+ */
+ protected function _addAttributeDataToSelect(
+ Varien_Db_Select $select,
+ $attributeCode,
+ Mage_Core_Model_Website $website
+ ) {
+ $attribute = $this->_getAttribute($attributeCode);
+ $store = $website->getDefaultStore();
+ if ($attribute->isScopeGlobal()) {
+ $table = 't_' . $attribute->getAttributeCode();
+ $select->joinLeft(
+ [$table => $attribute->getBackend()->getTable()],
+ "e.entity_id={$table}.entity_id"
+ . " AND {$table}.attribute_id={$attribute->getAttributeId()}"
+ . " AND {$table}.store_id=0",
+ [$attribute->getAttributeCode() => $table . '.value'],
+ );
+ } else {
+ $tableName = $attribute->getBackend()->getTable();
+ $tableGlobal = 't1_' . $attribute->getAttributeCode();
+ $tableStore = 't2_' . $attribute->getAttributeCode();
+
+ $attributeCond = $this->getReadConnection()->getCheckSql(
+ $tableStore . '.value_id > 0',
+ $tableStore . '.value',
+ $tableGlobal . '.value',
+ );
+ $select->joinLeft(
+ [$tableGlobal => $tableName],
+ "e.entity_id = {$tableGlobal}.entity_id"
+ . " AND {$tableGlobal}.attribute_id = {$attribute->getAttributeId()}"
+ . " AND {$tableGlobal}.store_id = 0",
+ [$attribute->getAttributeCode() => $attributeCond],
+ )
+ ->joinLeft(
+ [$tableStore => $tableName],
+ "{$tableGlobal}.entity_id = {$tableStore}.entity_id"
+ . " AND {$tableGlobal}.attribute_id = {$tableStore}.attribute_id"
+ . " AND {$tableStore}.store_id = " . $store->getId(),
+ [],
+ );
+ }
+ return $this;
+ }
+
+ /**
+ * Retrieve fixed bundle base price (with special price and rules)
+ *
+ * @param int $productId
+ * @param Mage_Core_Model_Website $website
+ * @param Mage_Customer_Model_Group $customerGroup
+ * @return float
+ */
+ protected function _getBasePrice($productId, array $priceData, $website, $customerGroup)
+ {
+ $store = $website->getDefaultStore();
+ $storeTimeStamp = Mage::app()->getLocale()->storeTimeStamp($store);
+ $finalPrice = $this->_calculateSpecialPrice($priceData['price'], $priceData, $website);
+
+ $rulePrice = Mage::getResourceModel('catalogrule/rule')
+ ->getRulePrice($storeTimeStamp, $website->getId(), $customerGroup->getId(), $productId);
+
+ if ($rulePrice !== null && $rulePrice !== false) {
+ $finalPrice = min($finalPrice, $rulePrice);
+ }
+
+ return $finalPrice;
+ }
}
diff --git a/app/code/core/Mage/Bundle/Model/Resource/Selection.php b/app/code/core/Mage/Bundle/Model/Resource/Selection.php
index 231ba26cd57..50f20e15265 100644
--- a/app/code/core/Mage/Bundle/Model/Resource/Selection.php
+++ b/app/code/core/Mage/Bundle/Model/Resource/Selection.php
@@ -22,11 +22,6 @@
*/
class Mage_Bundle_Model_Resource_Selection extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('bundle/selection', 'selection_id');
- }
-
/**
* Retrieve Price From index
*
@@ -178,4 +173,8 @@ public function saveSelectionPrice($item)
);
}
}
+ protected function _construct()
+ {
+ $this->_init('bundle/selection', 'selection_id');
+ }
}
diff --git a/app/code/core/Mage/Bundle/Model/Resource/Selection/Collection.php b/app/code/core/Mage/Bundle/Model/Resource/Selection/Collection.php
index bcecc193e6d..1a99c892fd1 100644
--- a/app/code/core/Mage/Bundle/Model/Resource/Selection/Collection.php
+++ b/app/code/core/Mage/Bundle/Model/Resource/Selection/Collection.php
@@ -29,17 +29,6 @@ class Mage_Bundle_Model_Resource_Selection_Collection extends Mage_Catalog_Model
*/
protected $_selectionTable;
- /**
- * Initialize collection
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setRowIdFieldName('selection_id');
- $this->_selectionTable = $this->getTable('bundle/selection');
- }
-
/**
* Set store id for each collection item when collection was loaded
*
@@ -56,22 +45,6 @@ public function _afterLoad()
return $this;
}
- /**
- * Initialize collection select
- *
- */
- protected function _initSelect()
- {
- parent::_initSelect();
- $this->getSelect()->join(
- ['selection' => $this->_selectionTable],
- 'selection.product_id = e.entity_id',
- ['*'],
- );
-
- return $this;
- }
-
/**
* Join website scope prices to collection, override default prices
*
@@ -142,4 +115,31 @@ public function setPositionOrder()
->order('selection.selection_id asc');
return $this;
}
+
+ /**
+ * Initialize collection
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setRowIdFieldName('selection_id');
+ $this->_selectionTable = $this->getTable('bundle/selection');
+ }
+
+ /**
+ * Initialize collection select
+ *
+ */
+ protected function _initSelect()
+ {
+ parent::_initSelect();
+ $this->getSelect()->join(
+ ['selection' => $this->_selectionTable],
+ 'selection.product_id = e.entity_id',
+ ['*'],
+ );
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Bundle/controllers/Adminhtml/Bundle/Product/EditController.php b/app/code/core/Mage/Bundle/controllers/Adminhtml/Bundle/Product/EditController.php
index d66529f334d..c0ae053b1a5 100644
--- a/app/code/core/Mage/Bundle/controllers/Adminhtml/Bundle/Product/EditController.php
+++ b/app/code/core/Mage/Bundle/controllers/Adminhtml/Bundle/Product/EditController.php
@@ -24,11 +24,6 @@
*/
class Mage_Bundle_Adminhtml_Bundle_Product_EditController extends Mage_Adminhtml_Catalog_ProductController
{
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Bundle');
- }
-
public function formAction()
{
$product = $this->_initProduct();
@@ -38,4 +33,8 @@ public function formAction()
->toHtml(),
);
}
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Bundle');
+ }
}
diff --git a/app/code/core/Mage/Bundle/controllers/Adminhtml/Bundle/SelectionController.php b/app/code/core/Mage/Bundle/controllers/Adminhtml/Bundle/SelectionController.php
index ac44657bae6..d9162545b1a 100644
--- a/app/code/core/Mage/Bundle/controllers/Adminhtml/Bundle/SelectionController.php
+++ b/app/code/core/Mage/Bundle/controllers/Adminhtml/Bundle/SelectionController.php
@@ -28,11 +28,6 @@ class Mage_Bundle_Adminhtml_Bundle_SelectionController extends Mage_Adminhtml_Co
*/
public const ADMIN_RESOURCE = 'catalog/products';
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Bundle');
- }
-
/**
* @return Zend_Controller_Response_Abstract
*/
@@ -62,4 +57,9 @@ public function gridAction()
->toHtml(),
);
}
+
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Bundle');
+ }
}
diff --git a/app/code/core/Mage/Captcha/Block/Captcha/Zend.php b/app/code/core/Mage/Captcha/Block/Captcha/Zend.php
index 98e1bb38955..bd6eb25d15d 100644
--- a/app/code/core/Mage/Captcha/Block/Captcha/Zend.php
+++ b/app/code/core/Mage/Captcha/Block/Captcha/Zend.php
@@ -55,6 +55,16 @@ public function getRefreshUrl()
);
}
+ /**
+ * Returns captcha model
+ *
+ * @return Mage_Captcha_Model_Zend
+ */
+ public function getCaptchaModel()
+ {
+ return Mage::helper('captcha')->getCaptcha($this->getFormId());
+ }
+
/**
* Renders captcha HTML (if required)
*
@@ -68,14 +78,4 @@ protected function _toHtml()
}
return '';
}
-
- /**
- * Returns captcha model
- *
- * @return Mage_Captcha_Model_Zend
- */
- public function getCaptchaModel()
- {
- return Mage::helper('captcha')->getCaptcha($this->getFormId());
- }
}
diff --git a/app/code/core/Mage/Captcha/Model/Observer.php b/app/code/core/Mage/Captcha/Model/Observer.php
index 57b302cc680..52969228b54 100644
--- a/app/code/core/Mage/Captcha/Model/Observer.php
+++ b/app/code/core/Mage/Captcha/Model/Observer.php
@@ -161,16 +161,6 @@ public function checkUserLoginBackend($observer)
return $this;
}
- /**
- * Returns backend session
- *
- * @return Mage_Adminhtml_Model_Session
- */
- protected function _getBackendSession()
- {
- return Mage::getSingleton('adminhtml/session');
- }
-
/**
* Check Captcha On User Login Backend Page
*
@@ -252,31 +242,6 @@ public function deleteExpiredImages()
return $this;
}
- /**
- * Reset Attempts
- *
- * @param string $login
- * @return $this
- */
- protected function _resetAttempt($login)
- {
- Mage::getResourceModel('captcha/log')->deleteUserAttempts($login);
- return $this;
- }
-
- /**
- * Get Captcha String
- *
- * @param Mage_Core_Controller_Request_Http $request
- * @param string $formId
- * @return string
- */
- protected function _getCaptchaString($request, $formId)
- {
- $captchaParams = $request->getPost(Mage_Captcha_Helper_Data::INPUT_NAME_FIELD_VALUE);
- return $captchaParams[$formId] ?? '';
- }
-
/**
* Check Captcha On Share Wishlist Page
*
@@ -329,4 +294,39 @@ public function checkSendfriendSend($observer)
}
return $this;
}
+
+ /**
+ * Returns backend session
+ *
+ * @return Mage_Adminhtml_Model_Session
+ */
+ protected function _getBackendSession()
+ {
+ return Mage::getSingleton('adminhtml/session');
+ }
+
+ /**
+ * Reset Attempts
+ *
+ * @param string $login
+ * @return $this
+ */
+ protected function _resetAttempt($login)
+ {
+ Mage::getResourceModel('captcha/log')->deleteUserAttempts($login);
+ return $this;
+ }
+
+ /**
+ * Get Captcha String
+ *
+ * @param Mage_Core_Controller_Request_Http $request
+ * @param string $formId
+ * @return string
+ */
+ protected function _getCaptchaString($request, $formId)
+ {
+ $captchaParams = $request->getPost(Mage_Captcha_Helper_Data::INPUT_NAME_FIELD_VALUE);
+ return $captchaParams[$formId] ?? '';
+ }
}
diff --git a/app/code/core/Mage/Captcha/Model/Resource/Log.php b/app/code/core/Mage/Captcha/Model/Resource/Log.php
index f87ff3fab2c..474c31041c9 100644
--- a/app/code/core/Mage/Captcha/Model/Resource/Log.php
+++ b/app/code/core/Mage/Captcha/Model/Resource/Log.php
@@ -32,11 +32,6 @@ class Mage_Captcha_Model_Resource_Log extends Mage_Core_Model_Resource_Db_Abstra
*/
public const TYPE_LOGIN = 2;
- protected function _construct()
- {
- $this->_setMainTable('captcha/log');
- }
-
/**
* Save or Update count Attempts
*
@@ -138,4 +133,9 @@ public function deleteOldAttempts()
['updated_at < ?' => Mage::getSingleton('core/date')->gmtDate(null, time() - 60 * 30)],
);
}
+
+ protected function _construct()
+ {
+ $this->_setMainTable('captcha/log');
+ }
}
diff --git a/app/code/core/Mage/Captcha/Model/Zend.php b/app/code/core/Mage/Captcha/Model/Zend.php
index feaa2c2038f..ae0fbb9f572 100644
--- a/app/code/core/Mage/Captcha/Model/Zend.php
+++ b/app/code/core/Mage/Captcha/Model/Zend.php
@@ -83,17 +83,6 @@ public function __construct($params)
$this->setExpiration($this->getTimeout());
}
- /**
- * Returns key with respect of current form ID
- *
- * @param string $key
- * @return string
- */
- protected function _getFormIdKey($key)
- {
- return $this->_formId . '_' . $key;
- }
-
/**
* Get Block Name
*
@@ -125,75 +114,6 @@ public function isRequired($login = null)
);
}
- /**
- * Check is overlimit attempts
- *
- * @param string $login
- * @return bool
- */
- protected function _isOverLimitAttempts($login)
- {
- return ($this->_isOverLimitIpAttempt() || $this->_isOverLimitLoginAttempts($login));
- }
-
- /**
- * Returns number of allowed attempts for same login
- *
- * @return int
- */
- protected function _getAllowedAttemptsForSameLogin()
- {
- return (int) $this->_getHelper()->getConfigNode('failed_attempts_login');
- }
-
- /**
- * Returns number of allowed attempts from same IP
- *
- * @return int
- */
- protected function _getAllowedAttemptsFromSameIp()
- {
- return (int) $this->_getHelper()->getConfigNode('failed_attempts_ip');
- }
-
- /**
- * Check is overlimit saved attempts from one ip
- *
- * @return bool
- */
- protected function _isOverLimitIpAttempt()
- {
- $countAttemptsByIp = Mage::getResourceModel('captcha/log')->countAttemptsByRemoteAddress();
- return $countAttemptsByIp >= $this->_getAllowedAttemptsFromSameIp();
- }
-
- /**
- * Is Over Limit Login Attempts
- *
- * @param string $login
- * @return bool
- */
- protected function _isOverLimitLoginAttempts($login)
- {
- if ($login != false) {
- $countAttemptsByLogin = Mage::getResourceModel('captcha/log')->countAttemptsByUserLogin($login);
- return ($countAttemptsByLogin >= $this->_getAllowedAttemptsForSameLogin());
- }
- return false;
- }
-
- /**
- * Check is user auth
- *
- * @return bool
- */
- protected function _isUserAuth()
- {
- return Mage::app()->getStore()->isAdmin()
- ? Mage::getSingleton('admin/session')->isLoggedIn()
- : Mage::getSingleton('customer/session')->isLoggedIn();
- }
-
/**
* Whether to respect case while checking the answer
*
@@ -310,6 +230,100 @@ public function logAttempt($login)
return $this;
}
+ /**
+ * Get captcha word
+ *
+ * @return string|null
+ */
+ public function getWord()
+ {
+ $sessionData = $this->getSession()->getData($this->_getFormIdKey(self::SESSION_WORD));
+ if (!is_array($sessionData)) {
+ return null;
+ }
+ return time() < $sessionData['expires'] ? $sessionData['data'] : null;
+ }
+
+ /**
+ * Returns key with respect of current form ID
+ *
+ * @param string $key
+ * @return string
+ */
+ protected function _getFormIdKey($key)
+ {
+ return $this->_formId . '_' . $key;
+ }
+
+ /**
+ * Check is overlimit attempts
+ *
+ * @param string $login
+ * @return bool
+ */
+ protected function _isOverLimitAttempts($login)
+ {
+ return ($this->_isOverLimitIpAttempt() || $this->_isOverLimitLoginAttempts($login));
+ }
+
+ /**
+ * Returns number of allowed attempts for same login
+ *
+ * @return int
+ */
+ protected function _getAllowedAttemptsForSameLogin()
+ {
+ return (int) $this->_getHelper()->getConfigNode('failed_attempts_login');
+ }
+
+ /**
+ * Returns number of allowed attempts from same IP
+ *
+ * @return int
+ */
+ protected function _getAllowedAttemptsFromSameIp()
+ {
+ return (int) $this->_getHelper()->getConfigNode('failed_attempts_ip');
+ }
+
+ /**
+ * Check is overlimit saved attempts from one ip
+ *
+ * @return bool
+ */
+ protected function _isOverLimitIpAttempt()
+ {
+ $countAttemptsByIp = Mage::getResourceModel('captcha/log')->countAttemptsByRemoteAddress();
+ return $countAttemptsByIp >= $this->_getAllowedAttemptsFromSameIp();
+ }
+
+ /**
+ * Is Over Limit Login Attempts
+ *
+ * @param string $login
+ * @return bool
+ */
+ protected function _isOverLimitLoginAttempts($login)
+ {
+ if ($login != false) {
+ $countAttemptsByLogin = Mage::getResourceModel('captcha/log')->countAttemptsByUserLogin($login);
+ return ($countAttemptsByLogin >= $this->_getAllowedAttemptsForSameLogin());
+ }
+ return false;
+ }
+
+ /**
+ * Check is user auth
+ *
+ * @return bool
+ */
+ protected function _isUserAuth()
+ {
+ return Mage::app()->getStore()->isAdmin()
+ ? Mage::getSingleton('admin/session')->isLoggedIn()
+ : Mage::getSingleton('customer/session')->isLoggedIn();
+ }
+
/**
* Returns path for the font file, chosen to generate captcha
*
@@ -446,20 +460,6 @@ protected function _getTargetForms()
return explode(',', $formsString);
}
- /**
- * Get captcha word
- *
- * @return string|null
- */
- public function getWord()
- {
- $sessionData = $this->getSession()->getData($this->_getFormIdKey(self::SESSION_WORD));
- if (!is_array($sessionData)) {
- return null;
- }
- return time() < $sessionData['expires'] ? $sessionData['data'] : null;
- }
-
/**
* Set captcha word
*
diff --git a/app/code/core/Mage/Catalog/Block/Category/View.php b/app/code/core/Mage/Catalog/Block/Category/View.php
index de6df9c7dc1..25476db762d 100644
--- a/app/code/core/Mage/Catalog/Block/Category/View.php
+++ b/app/code/core/Mage/Catalog/Block/Category/View.php
@@ -22,47 +22,6 @@
*/
class Mage_Catalog_Block_Category_View extends Mage_Core_Block_Template
{
- /**
- * @return $this|Mage_Core_Block_Template
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
-
- $this->getLayout()->createBlock('catalog/breadcrumbs');
-
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $category = $this->getCurrentCategory();
- if ($title = $category->getMetaTitle()) {
- $headBlock->setTitle($title);
- }
- if ($description = $category->getMetaDescription()) {
- $headBlock->setDescription($description);
- }
- if ($keywords = $category->getMetaKeywords()) {
- $headBlock->setKeywords($keywords);
- }
-
- /** @var Mage_Catalog_Helper_Category $helper */
- $helper = $this->helper('catalog/category');
- if ($helper->canUseCanonicalTag()) {
- $headBlock->addLinkRel('canonical', $category->getUrl());
- }
- /*
- want to show rss feed in the url
- */
- if ($this->isRssCatalogEnable() && $this->isTopCategory()) {
- $title = $this->helper('rss')->__('%s RSS Feed', $this->getCurrentCategory()->getName());
- $headBlock->addItem('rss', $this->getRssLink(), 'title="' . $title . '"');
- }
- }
-
- return $this;
- }
-
/**
* @return string
*/
@@ -178,4 +137,44 @@ public function getCacheTags()
{
return array_merge(parent::getCacheTags(), $this->getCurrentCategory()->getCacheIdTags());
}
+ /**
+ * @return $this|Mage_Core_Block_Template
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+
+ $this->getLayout()->createBlock('catalog/breadcrumbs');
+
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $category = $this->getCurrentCategory();
+ if ($title = $category->getMetaTitle()) {
+ $headBlock->setTitle($title);
+ }
+ if ($description = $category->getMetaDescription()) {
+ $headBlock->setDescription($description);
+ }
+ if ($keywords = $category->getMetaKeywords()) {
+ $headBlock->setKeywords($keywords);
+ }
+
+ /** @var Mage_Catalog_Helper_Category $helper */
+ $helper = $this->helper('catalog/category');
+ if ($helper->canUseCanonicalTag()) {
+ $headBlock->addLinkRel('canonical', $category->getUrl());
+ }
+ /*
+ want to show rss feed in the url
+ */
+ if ($this->isRssCatalogEnable() && $this->isTopCategory()) {
+ $title = $this->helper('rss')->__('%s RSS Feed', $this->getCurrentCategory()->getName());
+ $headBlock->addItem('rss', $this->getRssLink(), 'title="' . $title . '"');
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Layer/Filter/Abstract.php b/app/code/core/Mage/Catalog/Block/Layer/Filter/Abstract.php
index 4ed822319bd..75d19f370df 100644
--- a/app/code/core/Mage/Catalog/Block/Layer/Filter/Abstract.php
+++ b/app/code/core/Mage/Catalog/Block/Layer/Filter/Abstract.php
@@ -65,34 +65,6 @@ public function init()
return $this;
}
- /**
- * Init filter model object
- *
- * @return Mage_Catalog_Block_Layer_Filter_Abstract
- */
- protected function _initFilter()
- {
- if (!$this->_filterModelName) {
- Mage::throwException(Mage::helper('catalog')->__('Filter model name must be declared.'));
- }
- $this->_filter = Mage::getModel($this->_filterModelName)
- ->setLayer($this->getLayer());
- $this->_prepareFilter();
-
- $this->_filter->apply($this->getRequest(), $this);
- return $this;
- }
-
- /**
- * Prepare filter process
- *
- * @return Mage_Catalog_Block_Layer_Filter_Abstract
- */
- protected function _prepareFilter()
- {
- return $this;
- }
-
/**
* Retrieve name of the filter block
*
@@ -144,4 +116,32 @@ public function getHtml()
{
return parent::_toHtml();
}
+
+ /**
+ * Init filter model object
+ *
+ * @return Mage_Catalog_Block_Layer_Filter_Abstract
+ */
+ protected function _initFilter()
+ {
+ if (!$this->_filterModelName) {
+ Mage::throwException(Mage::helper('catalog')->__('Filter model name must be declared.'));
+ }
+ $this->_filter = Mage::getModel($this->_filterModelName)
+ ->setLayer($this->getLayer());
+ $this->_prepareFilter();
+
+ $this->_filter->apply($this->getRequest(), $this);
+ return $this;
+ }
+
+ /**
+ * Prepare filter process
+ *
+ * @return Mage_Catalog_Block_Layer_Filter_Abstract
+ */
+ protected function _prepareFilter()
+ {
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Layer/View.php b/app/code/core/Mage/Catalog/Block/Layer/View.php
index ed731979783..2282e3fd962 100644
--- a/app/code/core/Mage/Catalog/Block/Layer/View.php
+++ b/app/code/core/Mage/Catalog/Block/Layer/View.php
@@ -57,6 +57,82 @@ class Mage_Catalog_Block_Layer_View extends Mage_Core_Block_Template
*/
protected $_decimalFilterBlockName;
+ /**
+ * Get layer object
+ *
+ * @return Mage_Catalog_Model_Layer
+ */
+ public function getLayer()
+ {
+ return Mage::getSingleton('catalog/layer');
+ }
+
+ /**
+ * Get layered navigation state html
+ *
+ * @return string
+ */
+ public function getStateHtml()
+ {
+ return $this->getChildHtml('layer_state');
+ }
+
+ /**
+ * Get all layer filters
+ *
+ * @return array
+ */
+ public function getFilters()
+ {
+ $filters = [];
+ if ($categoryFilter = $this->_getCategoryFilter()) {
+ $filters[] = $categoryFilter;
+ }
+
+ $filterableAttributes = $this->_getFilterableAttributes();
+ foreach ($filterableAttributes as $attribute) {
+ $filters[] = $this->getChild($attribute->getAttributeCode() . '_filter');
+ }
+
+ return $filters;
+ }
+
+ /**
+ * Check availability display layer options
+ *
+ * @return bool
+ */
+ public function canShowOptions()
+ {
+ foreach ($this->getFilters() as $filter) {
+ if ($filter->getItemsCount()) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Check availability display layer block
+ *
+ * @return bool
+ */
+ public function canShowBlock()
+ {
+ return $this->canShowOptions() || count($this->getLayer()->getState()->getFilters());
+ }
+
+ /**
+ * Get url for 'Clear All' link
+ *
+ * @return string
+ */
+ public function getClearUrl()
+ {
+ return $this->getChild('layer_state')->getClearUrl();
+ }
+
/**
* Internal constructor
*/
@@ -132,16 +208,6 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
- /**
- * Get layer object
- *
- * @return Mage_Catalog_Model_Layer
- */
- public function getLayer()
- {
- return Mage::getSingleton('catalog/layer');
- }
-
/**
* Get all fiterable attributes of current category
*
@@ -158,36 +224,6 @@ protected function _getFilterableAttributes()
return $attributes;
}
- /**
- * Get layered navigation state html
- *
- * @return string
- */
- public function getStateHtml()
- {
- return $this->getChildHtml('layer_state');
- }
-
- /**
- * Get all layer filters
- *
- * @return array
- */
- public function getFilters()
- {
- $filters = [];
- if ($categoryFilter = $this->_getCategoryFilter()) {
- $filters[] = $categoryFilter;
- }
-
- $filterableAttributes = $this->_getFilterableAttributes();
- foreach ($filterableAttributes as $attribute) {
- $filters[] = $this->getChild($attribute->getAttributeCode() . '_filter');
- }
-
- return $filters;
- }
-
/**
* Get category filter block
*
@@ -198,32 +234,6 @@ protected function _getCategoryFilter()
return $this->getChild('category_filter');
}
- /**
- * Check availability display layer options
- *
- * @return bool
- */
- public function canShowOptions()
- {
- foreach ($this->getFilters() as $filter) {
- if ($filter->getItemsCount()) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Check availability display layer block
- *
- * @return bool
- */
- public function canShowBlock()
- {
- return $this->canShowOptions() || count($this->getLayer()->getState()->getFilters());
- }
-
/**
* Retrieve Price Filter block
*
@@ -233,14 +243,4 @@ protected function _getPriceFilter()
{
return $this->getChild('_price_filter');
}
-
- /**
- * Get url for 'Clear All' link
- *
- * @return string
- */
- public function getClearUrl()
- {
- return $this->getChild('layer_state')->getClearUrl();
- }
}
diff --git a/app/code/core/Mage/Catalog/Block/Navigation.php b/app/code/core/Mage/Catalog/Block/Navigation.php
index df0ecf6819d..a12a22e57ca 100644
--- a/app/code/core/Mage/Catalog/Block/Navigation.php
+++ b/app/code/core/Mage/Catalog/Block/Navigation.php
@@ -50,18 +50,6 @@ class Mage_Catalog_Block_Navigation extends Mage_Core_Block_Template
*/
protected $_currentChildCategories;
- /**
- * Set cache data
- */
- protected function _construct()
- {
- $this->addData(['cache_lifetime' => false]);
- $this->addCacheTag([
- Mage_Catalog_Model_Category::CACHE_TAG,
- Mage_Core_Model_Store_Group::CACHE_TAG,
- ]);
- }
-
/**
* Get Key pieces for caching block content
*
@@ -151,19 +139,6 @@ public function isCategoryActive($category)
? in_array($category->getId(), $this->getCurrentCategory()->getPathIds()) : false;
}
- /**
- * Retrieve category instance
- *
- * @return Mage_Catalog_Model_Category
- */
- protected function _getCategoryInstance()
- {
- if (is_null($this->_categoryInstance)) {
- $this->_categoryInstance = Mage::getModel('catalog/category');
- }
- return $this->_categoryInstance;
- }
-
/**
* Get url for category data
*
@@ -183,6 +158,149 @@ public function getCategoryUrl($category)
return $url;
}
+ /**
+ * Render category to html
+ *
+ * @deprecated deprecated after 1.4
+ * @param Mage_Catalog_Model_Category $category
+ * @param int $level Nesting level number
+ * @param bool $last Whether ot not this item is last, affects list item class
+ * @return string
+ */
+ public function drawItem($category, $level = 0, $last = false)
+ {
+ return $this->_renderCategoryMenuItemHtml($category, $level, $last);
+ }
+
+ /**
+ * @return Mage_Catalog_Model_Category|false
+ */
+ public function getCurrentCategory()
+ {
+ if (Mage::getSingleton('catalog/layer')) {
+ return Mage::getSingleton('catalog/layer')->getCurrentCategory();
+ }
+ return false;
+ }
+
+ /**
+ * @return array
+ */
+ public function getCurrentCategoryPath()
+ {
+ if ($this->getCurrentCategory()) {
+ return explode(',', $this->getCurrentCategory()->getPathInStore());
+ }
+ return [];
+ }
+
+ /**
+ * @param Mage_Catalog_Model_Category $category
+ * @return string
+ */
+ public function drawOpenCategoryItem($category)
+ {
+ $html = '';
+ if (!$category->getIsActive()) {
+ return $html;
+ }
+
+ $html .= 'isCategoryActive($category)) {
+ $html .= ' class="active"';
+ }
+
+ $html .= '>' . "\n";
+ $html .= ''
+ . '' . $this->escapeHtml($category->getName()) . '' . "\n";
+
+ if (in_array($category->getId(), $this->getCurrentCategoryPath())) {
+ $children = $category->getChildren();
+ $hasChildren = $children && $children->count();
+
+ if ($hasChildren) {
+ $htmlChildren = '';
+ foreach ($children as $child) {
+ $htmlChildren .= $this->drawOpenCategoryItem($child);
+ }
+
+ if (!empty($htmlChildren)) {
+ $html .= '' . "\n" . $htmlChildren . '
';
+ }
+ }
+ }
+
+ return $html . ('' . "\n");
+ }
+
+ /**
+ * Render categories menu in HTML
+ *
+ * @param int $level Level number for list item class to start from
+ * @param string $outermostItemClass Extra class of outermost list items
+ * @param string $childrenWrapClass If specified wraps children list in div with this class
+ * @return string
+ */
+ public function renderCategoriesMenuHtml($level = 0, $outermostItemClass = '', $childrenWrapClass = '')
+ {
+ $activeCategories = [];
+ foreach ($this->getStoreCategories() as $child) {
+ if ($child->getIsActive()) {
+ $activeCategories[] = $child;
+ }
+ }
+ $activeCategoriesCount = count($activeCategories);
+ $hasActiveCategoriesCount = ($activeCategoriesCount > 0);
+
+ if (!$hasActiveCategoriesCount) {
+ return '';
+ }
+
+ $html = '';
+ $j = 0;
+ foreach ($activeCategories as $category) {
+ $html .= $this->_renderCategoryMenuItemHtml(
+ $category,
+ $level,
+ ($j == $activeCategoriesCount - 1),
+ ($j == 0),
+ true,
+ $outermostItemClass,
+ $childrenWrapClass,
+ true,
+ );
+ $j++;
+ }
+
+ return $html;
+ }
+
+ /**
+ * Set cache data
+ */
+ protected function _construct()
+ {
+ $this->addData(['cache_lifetime' => false]);
+ $this->addCacheTag([
+ Mage_Catalog_Model_Category::CACHE_TAG,
+ Mage_Core_Model_Store_Group::CACHE_TAG,
+ ]);
+ }
+
+ /**
+ * Retrieve category instance
+ *
+ * @return Mage_Catalog_Model_Category
+ */
+ protected function _getCategoryInstance()
+ {
+ if (is_null($this->_categoryInstance)) {
+ $this->_categoryInstance = Mage::getModel('catalog/category');
+ }
+ return $this->_categoryInstance;
+ }
+
/**
* Return item position representation in menu tree
*
@@ -335,122 +453,4 @@ protected function _renderCategoryMenuItemHtml(
$html[] = '';
return implode("\n", $html);
}
-
- /**
- * Render category to html
- *
- * @deprecated deprecated after 1.4
- * @param Mage_Catalog_Model_Category $category
- * @param int $level Nesting level number
- * @param bool $last Whether ot not this item is last, affects list item class
- * @return string
- */
- public function drawItem($category, $level = 0, $last = false)
- {
- return $this->_renderCategoryMenuItemHtml($category, $level, $last);
- }
-
- /**
- * @return Mage_Catalog_Model_Category|false
- */
- public function getCurrentCategory()
- {
- if (Mage::getSingleton('catalog/layer')) {
- return Mage::getSingleton('catalog/layer')->getCurrentCategory();
- }
- return false;
- }
-
- /**
- * @return array
- */
- public function getCurrentCategoryPath()
- {
- if ($this->getCurrentCategory()) {
- return explode(',', $this->getCurrentCategory()->getPathInStore());
- }
- return [];
- }
-
- /**
- * @param Mage_Catalog_Model_Category $category
- * @return string
- */
- public function drawOpenCategoryItem($category)
- {
- $html = '';
- if (!$category->getIsActive()) {
- return $html;
- }
-
- $html .= 'isCategoryActive($category)) {
- $html .= ' class="active"';
- }
-
- $html .= '>' . "\n";
- $html .= ''
- . '' . $this->escapeHtml($category->getName()) . '' . "\n";
-
- if (in_array($category->getId(), $this->getCurrentCategoryPath())) {
- $children = $category->getChildren();
- $hasChildren = $children && $children->count();
-
- if ($hasChildren) {
- $htmlChildren = '';
- foreach ($children as $child) {
- $htmlChildren .= $this->drawOpenCategoryItem($child);
- }
-
- if (!empty($htmlChildren)) {
- $html .= '' . "\n" . $htmlChildren . '
';
- }
- }
- }
-
- return $html . ('' . "\n");
- }
-
- /**
- * Render categories menu in HTML
- *
- * @param int $level Level number for list item class to start from
- * @param string $outermostItemClass Extra class of outermost list items
- * @param string $childrenWrapClass If specified wraps children list in div with this class
- * @return string
- */
- public function renderCategoriesMenuHtml($level = 0, $outermostItemClass = '', $childrenWrapClass = '')
- {
- $activeCategories = [];
- foreach ($this->getStoreCategories() as $child) {
- if ($child->getIsActive()) {
- $activeCategories[] = $child;
- }
- }
- $activeCategoriesCount = count($activeCategories);
- $hasActiveCategoriesCount = ($activeCategoriesCount > 0);
-
- if (!$hasActiveCategoriesCount) {
- return '';
- }
-
- $html = '';
- $j = 0;
- foreach ($activeCategories as $category) {
- $html .= $this->_renderCategoryMenuItemHtml(
- $category,
- $level,
- ($j == $activeCategoriesCount - 1),
- ($j == 0),
- true,
- $outermostItemClass,
- $childrenWrapClass,
- true,
- );
- $j++;
- }
-
- return $html;
- }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/Abstract.php b/app/code/core/Mage/Catalog/Block/Product/Abstract.php
index 7cc0ace7dcc..5d256932afb 100644
--- a/app/code/core/Mage/Catalog/Block/Product/Abstract.php
+++ b/app/code/core/Mage/Catalog/Block/Product/Abstract.php
@@ -115,18 +115,6 @@ public function getAddToCartUrl($product, $additional = [])
return $this->getAddToCartUrlCustom($product, $additional);
}
- /**
- * Return model instance
- *
- * @param string $className
- * @param array $arguments
- * @return Mage_Core_Model_Abstract
- */
- protected function _getSingletonModel($className, $arguments = [])
- {
- return Mage::getSingleton($className, $arguments);
- }
-
/**
* Retrieves url for form submitting:
* some objects can use setSubmitRouteData() to set route and params for form submitting,
@@ -174,42 +162,6 @@ public function getMinimalQty($product)
return $this->getProductHelper()->getMinimalQty($product);
}
- /**
- * Return price block
- *
- * @param string $productTypeId
- * @return mixed
- */
- protected function _getPriceBlock($productTypeId)
- {
- if (!isset($this->_priceBlock[$productTypeId])) {
- $block = $this->_block;
- if (isset($this->_priceBlockTypes[$productTypeId])) {
- if ($this->_priceBlockTypes[$productTypeId]['block'] != '') {
- $block = $this->_priceBlockTypes[$productTypeId]['block'];
- }
- }
- $this->_priceBlock[$productTypeId] = $this->getLayout()->createBlock($block);
- }
- return $this->_priceBlock[$productTypeId];
- }
-
- /**
- * Return Block template
- *
- * @param string $productTypeId
- * @return string
- */
- protected function _getPriceBlockTemplate($productTypeId)
- {
- if (isset($this->_priceBlockTypes[$productTypeId])) {
- if ($this->_priceBlockTypes[$productTypeId]['template'] != '') {
- return $this->_priceBlockTypes[$productTypeId]['template'];
- }
- }
- return $this->_priceBlockDefaultTemplate;
- }
-
/**
* Prepares and returns block to render some product type
*
@@ -305,26 +257,6 @@ public function addReviewSummaryTemplate($type, $template)
return '';
}
- /**
- * Create reviews summary helper block once
- *
- * @return bool
- */
- protected function _initReviewsHelperBlock()
- {
- if (!$this->_reviewsHelperBlock) {
- if (!$this->isModuleEnabled('Mage_Review', 'catalog')) {
- return false;
- }
-
- /** @var Mage_Review_Block_Helper $block */
- $block = $this->getLayout()->createBlock('review/helper');
- $this->_reviewsHelperBlock = $block;
- }
-
- return true;
- }
-
/**
* Retrieve currently viewed product object
*
@@ -372,19 +304,6 @@ public function getTierPriceHtml($product = null, $parent = null)
->callParentToHtml();
}
- /**
- * Calls the object's to Html method.
- * This method exists to make the code more testable.
- * By having a protected wrapper for the final method toHtml, we can 'mock' out this method
- * when unit testing
- *
- * @return string
- */
- protected function callParentToHtml()
- {
- return $this->toHtml();
- }
-
/**
* Get tier prices (formatted)
*
@@ -449,22 +368,6 @@ public function getTierPrices($product = null)
return $res;
}
- /**
- * Add all attributes and apply pricing logic to products collection
- * to get correct values in different products lists.
- * E.g. crosssells, upsells, new products, recently viewed
- *
- * @return Mage_Catalog_Model_Resource_Product_Collection
- */
- protected function _addProductAttributesAndPrices(Mage_Catalog_Model_Resource_Product_Collection $collection)
- {
- return $collection
- ->addPriceData()
- ->addTaxPercents()
- ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
- ->addUrlRewrite();
- }
-
/**
* Retrieve given media attribute label or product name if no label
*
@@ -652,26 +555,6 @@ public function getAddToCompareUrlCustom($product, $addFormKey = true)
return $helper->getAddUrl($product);
}
- /**
- * If exists price template block, retrieve price blocks from it
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
-
- /** @var Mage_Catalog_Block_Product_Price_Template $block */
- $block = $this->getLayout()->getBlock('catalog_product_price_template');
- if ($block) {
- foreach ($block->getPriceBlockTypes() as $type => $priceBlock) {
- $this->addPriceBlockType($type, $priceBlock['block'], $priceBlock['template']);
- }
- }
-
- return $this;
- }
-
/**
* Retrieve url for add product to cart with or without Form Key
* Will return product view page URL if product has required options
@@ -733,4 +616,121 @@ public function getSubmitUrlCustom($product, $additional = [], $addFormKey = tru
}
return $submitUrl;
}
+
+ /**
+ * Return model instance
+ *
+ * @param string $className
+ * @param array $arguments
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _getSingletonModel($className, $arguments = [])
+ {
+ return Mage::getSingleton($className, $arguments);
+ }
+
+ /**
+ * Return price block
+ *
+ * @param string $productTypeId
+ * @return mixed
+ */
+ protected function _getPriceBlock($productTypeId)
+ {
+ if (!isset($this->_priceBlock[$productTypeId])) {
+ $block = $this->_block;
+ if (isset($this->_priceBlockTypes[$productTypeId])) {
+ if ($this->_priceBlockTypes[$productTypeId]['block'] != '') {
+ $block = $this->_priceBlockTypes[$productTypeId]['block'];
+ }
+ }
+ $this->_priceBlock[$productTypeId] = $this->getLayout()->createBlock($block);
+ }
+ return $this->_priceBlock[$productTypeId];
+ }
+
+ /**
+ * Return Block template
+ *
+ * @param string $productTypeId
+ * @return string
+ */
+ protected function _getPriceBlockTemplate($productTypeId)
+ {
+ if (isset($this->_priceBlockTypes[$productTypeId])) {
+ if ($this->_priceBlockTypes[$productTypeId]['template'] != '') {
+ return $this->_priceBlockTypes[$productTypeId]['template'];
+ }
+ }
+ return $this->_priceBlockDefaultTemplate;
+ }
+
+ /**
+ * Create reviews summary helper block once
+ *
+ * @return bool
+ */
+ protected function _initReviewsHelperBlock()
+ {
+ if (!$this->_reviewsHelperBlock) {
+ if (!$this->isModuleEnabled('Mage_Review', 'catalog')) {
+ return false;
+ }
+
+ /** @var Mage_Review_Block_Helper $block */
+ $block = $this->getLayout()->createBlock('review/helper');
+ $this->_reviewsHelperBlock = $block;
+ }
+
+ return true;
+ }
+
+ /**
+ * Calls the object's to Html method.
+ * This method exists to make the code more testable.
+ * By having a protected wrapper for the final method toHtml, we can 'mock' out this method
+ * when unit testing
+ *
+ * @return string
+ */
+ protected function callParentToHtml()
+ {
+ return $this->toHtml();
+ }
+
+ /**
+ * Add all attributes and apply pricing logic to products collection
+ * to get correct values in different products lists.
+ * E.g. crosssells, upsells, new products, recently viewed
+ *
+ * @return Mage_Catalog_Model_Resource_Product_Collection
+ */
+ protected function _addProductAttributesAndPrices(Mage_Catalog_Model_Resource_Product_Collection $collection)
+ {
+ return $collection
+ ->addPriceData()
+ ->addTaxPercents()
+ ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
+ ->addUrlRewrite();
+ }
+
+ /**
+ * If exists price template block, retrieve price blocks from it
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+
+ /** @var Mage_Catalog_Block_Product_Price_Template $block */
+ $block = $this->getLayout()->getBlock('catalog_product_price_template');
+ if ($block) {
+ foreach ($block->getPriceBlockTypes() as $type => $priceBlock) {
+ $this->addPriceBlockType($type, $priceBlock['block'], $priceBlock['template']);
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/Compare/Abstract.php b/app/code/core/Mage/Catalog/Block/Product/Compare/Abstract.php
index e8cd44af8fb..338b8db0505 100644
--- a/app/code/core/Mage/Catalog/Block/Product/Compare/Abstract.php
+++ b/app/code/core/Mage/Catalog/Block/Product/Compare/Abstract.php
@@ -22,16 +22,6 @@
*/
abstract class Mage_Catalog_Block_Product_Compare_Abstract extends Mage_Catalog_Block_Product_Abstract
{
- /**
- * Retrieve Product Compare Helper
- *
- * @return Mage_Catalog_Helper_Product_Compare
- */
- protected function _getHelper()
- {
- return Mage::helper('catalog/product_compare');
- }
-
/**
* Retrieve Remove Item from Compare List URL
*
@@ -42,4 +32,13 @@ public function getRemoveUrl($item)
{
return $this->_getHelper()->getRemoveUrl($item);
}
+ /**
+ * Retrieve Product Compare Helper
+ *
+ * @return Mage_Catalog_Helper_Product_Compare
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('catalog/product_compare');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/Compare/List.php b/app/code/core/Mage/Catalog/Block/Product/Compare/List.php
index b7c68b15893..add1817867c 100644
--- a/app/code/core/Mage/Catalog/Block/Product/Compare/List.php
+++ b/app/code/core/Mage/Catalog/Block/Product/Compare/List.php
@@ -68,20 +68,6 @@ public function getAddToWishlistUrl($product)
return $this->getAddToWishlistUrlCustom($product);
}
- /**
- * Preparing layout
- *
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle(Mage::helper('catalog')->__('Products Comparison List') . ' - ' . $headBlock->getDefaultTitle());
- }
- return parent::_prepareLayout();
- }
-
/**
* Retrieve Product Compare items collection
*
@@ -200,4 +186,18 @@ public function getAddToWishlistUrlCustom($product, $addFormKey = true)
return $helper->getAddUrlWithParams($product, $params);
}
+
+ /**
+ * Preparing layout
+ *
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle(Mage::helper('catalog')->__('Products Comparison List') . ' - ' . $headBlock->getDefaultTitle());
+ }
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/Compare/Sidebar.php b/app/code/core/Mage/Catalog/Block/Product/Compare/Sidebar.php
index 6a9055510ce..9d7137a6545 100644
--- a/app/code/core/Mage/Catalog/Block/Product/Compare/Sidebar.php
+++ b/app/code/core/Mage/Catalog/Block/Product/Compare/Sidebar.php
@@ -29,15 +29,6 @@ class Mage_Catalog_Block_Product_Compare_Sidebar extends Mage_Catalog_Block_Prod
*/
protected $_itemsCollection = null;
- /**
- * Initialize block
- *
- */
- protected function _construct()
- {
- $this->setId('compare');
- }
-
/**
* Retrieve Compare Products Collection
*
@@ -109,4 +100,13 @@ public function getCacheTags()
}
return parent::getCacheTags();
}
+
+ /**
+ * Initialize block
+ *
+ */
+ protected function _construct()
+ {
+ $this->setId('compare');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/Gallery.php b/app/code/core/Mage/Catalog/Block/Product/Gallery.php
index 7a38a9a9150..b785143af11 100644
--- a/app/code/core/Mage/Catalog/Block/Product/Gallery.php
+++ b/app/code/core/Mage/Catalog/Block/Product/Gallery.php
@@ -22,17 +22,6 @@
*/
class Mage_Catalog_Block_Product_Gallery extends Mage_Core_Block_Template
{
- /**
- * @return Mage_Core_Block_Template
- */
- protected function _prepareLayout()
- {
- if ($headBlock = $this->getLayout()->getBlock('head')) {
- $headBlock->setTitle($this->getProduct()->getMetaTitle());
- }
- return parent::_prepareLayout();
- }
-
/**
* @return Mage_Catalog_Model_Product
*/
@@ -170,4 +159,14 @@ public function getNextImageUrl()
}
return false;
}
+ /**
+ * @return Mage_Core_Block_Template
+ */
+ protected function _prepareLayout()
+ {
+ if ($headBlock = $this->getLayout()->getBlock('head')) {
+ $headBlock->setTitle($this->getProduct()->getMetaTitle());
+ }
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/List.php b/app/code/core/Mage/Catalog/Block/Product/List.php
index dbf433c5118..f2e166d4896 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List.php
@@ -49,51 +49,6 @@ class Mage_Catalog_Block_Product_List extends Mage_Catalog_Block_Product_Abstrac
*/
protected $_productCollection;
- /**
- * Retrieve loaded category collection
- *
- * @return Mage_Catalog_Model_Resource_Product_Collection
- */
- protected function _getProductCollection()
- {
- if (is_null($this->_productCollection)) {
- $layer = $this->getLayer();
- /** @var Mage_Catalog_Model_Layer $layer */
- if ($this->getShowRootCategory()) {
- $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
- }
-
- if (Mage::registry('product')) {
- /** @var Mage_Catalog_Model_Resource_Category_Collection $categories */
- $categories = Mage::registry('product')->getCategoryCollection()
- ->setPage(1, 1)
- ->load();
- if ($categories->count()) {
- $this->setCategoryId($categories->getFirstItem()->getId());
- }
- }
-
- $origCategory = null;
- if ($this->getCategoryId()) {
- $category = Mage::getModel('catalog/category')->load($this->getCategoryId());
- if ($category->getId()) {
- $origCategory = $layer->getCurrentCategory();
- $layer->setCurrentCategory($category);
- $this->addModelTags($category);
- }
- }
- $this->_productCollection = $layer->getProductCollection();
-
- $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());
-
- if ($origCategory) {
- $layer->setCurrentCategory($origCategory);
- }
- }
-
- return $this->_productCollection;
- }
-
/**
* Get catalog layer model
*
@@ -128,44 +83,6 @@ public function getMode()
return $this->getChild('toolbar')->getCurrentMode();
}
- /**
- * Need use as _prepareLayout - but problem in declaring collection from
- * another block (was problem with search result)
- */
- protected function _beforeToHtml()
- {
- $toolbar = $this->getToolbarBlock();
-
- // called prepare sortable parameters
- $collection = $this->_getProductCollection();
-
- // use sortable parameters
- if ($orders = $this->getAvailableOrders()) {
- $toolbar->setAvailableOrders($orders);
- }
- if ($sort = $this->getSortBy()) {
- $toolbar->setDefaultOrder($sort);
- }
- if ($dir = $this->getDefaultDirection()) {
- $toolbar->setDefaultDirection($dir);
- }
- if ($modes = $this->getModes()) {
- $toolbar->setModes($modes);
- }
-
- // set collection to toolbar and apply sort
- $toolbar->setCollection($collection);
-
- $this->setChild('toolbar', $toolbar);
- Mage::dispatchEvent('catalog_block_product_list_collection', [
- 'collection' => $this->_getProductCollection(),
- ]);
-
- $this->_getProductCollection()->load();
-
- return parent::_beforeToHtml();
- }
-
/**
* Retrieve Toolbar block
*
@@ -230,16 +147,6 @@ public function getPriceBlockTemplate()
return $this->_getData('price_block_template');
}
- /**
- * Retrieve Catalog Config object
- *
- * @return Mage_Catalog_Model_Config
- */
- protected function _getConfig()
- {
- return Mage::getSingleton('catalog/config');
- }
-
/**
* Prepare Sort By fields from Category Data
*
@@ -278,4 +185,97 @@ public function getCacheTags()
$this->getItemsTags($this->_getProductCollection()),
);
}
+
+ /**
+ * Retrieve loaded category collection
+ *
+ * @return Mage_Catalog_Model_Resource_Product_Collection
+ */
+ protected function _getProductCollection()
+ {
+ if (is_null($this->_productCollection)) {
+ $layer = $this->getLayer();
+ /** @var Mage_Catalog_Model_Layer $layer */
+ if ($this->getShowRootCategory()) {
+ $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
+ }
+
+ if (Mage::registry('product')) {
+ /** @var Mage_Catalog_Model_Resource_Category_Collection $categories */
+ $categories = Mage::registry('product')->getCategoryCollection()
+ ->setPage(1, 1)
+ ->load();
+ if ($categories->count()) {
+ $this->setCategoryId($categories->getFirstItem()->getId());
+ }
+ }
+
+ $origCategory = null;
+ if ($this->getCategoryId()) {
+ $category = Mage::getModel('catalog/category')->load($this->getCategoryId());
+ if ($category->getId()) {
+ $origCategory = $layer->getCurrentCategory();
+ $layer->setCurrentCategory($category);
+ $this->addModelTags($category);
+ }
+ }
+ $this->_productCollection = $layer->getProductCollection();
+
+ $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());
+
+ if ($origCategory) {
+ $layer->setCurrentCategory($origCategory);
+ }
+ }
+
+ return $this->_productCollection;
+ }
+
+ /**
+ * Need use as _prepareLayout - but problem in declaring collection from
+ * another block (was problem with search result)
+ */
+ protected function _beforeToHtml()
+ {
+ $toolbar = $this->getToolbarBlock();
+
+ // called prepare sortable parameters
+ $collection = $this->_getProductCollection();
+
+ // use sortable parameters
+ if ($orders = $this->getAvailableOrders()) {
+ $toolbar->setAvailableOrders($orders);
+ }
+ if ($sort = $this->getSortBy()) {
+ $toolbar->setDefaultOrder($sort);
+ }
+ if ($dir = $this->getDefaultDirection()) {
+ $toolbar->setDefaultDirection($dir);
+ }
+ if ($modes = $this->getModes()) {
+ $toolbar->setModes($modes);
+ }
+
+ // set collection to toolbar and apply sort
+ $toolbar->setCollection($collection);
+
+ $this->setChild('toolbar', $toolbar);
+ Mage::dispatchEvent('catalog_block_product_list_collection', [
+ 'collection' => $this->_getProductCollection(),
+ ]);
+
+ $this->_getProductCollection()->load();
+
+ return parent::_beforeToHtml();
+ }
+
+ /**
+ * Retrieve Catalog Config object
+ *
+ * @return Mage_Catalog_Model_Config
+ */
+ protected function _getConfig()
+ {
+ return Mage::getSingleton('catalog/config');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/List/Crosssell.php b/app/code/core/Mage/Catalog/Block/Product/List/Crosssell.php
index fcfa8eb09f7..edf61baf530 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List/Crosssell.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List/Crosssell.php
@@ -36,6 +36,16 @@ class Mage_Catalog_Block_Product_List_Crosssell extends Mage_Catalog_Block_Produ
*/
protected $_itemCollection;
+ /**
+ * Retrieve crosssell items collection
+ *
+ * @return Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Link_Product_Collection
+ */
+ public function getItems()
+ {
+ return $this->_itemCollection;
+ }
+
/**
* Prepare crosssell items data
*
@@ -73,14 +83,4 @@ protected function _beforeToHtml()
$this->_prepareData();
return parent::_beforeToHtml();
}
-
- /**
- * Retrieve crosssell items collection
- *
- * @return Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Link_Product_Collection
- */
- public function getItems()
- {
- return $this->_itemCollection;
- }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/List/Related.php b/app/code/core/Mage/Catalog/Block/Product/List/Related.php
index 0d576d76399..f865896f166 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List/Related.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List/Related.php
@@ -31,6 +31,24 @@ class Mage_Catalog_Block_Product_List_Related extends Mage_Catalog_Block_Product
protected $_itemCollection;
+ /**
+ * @return mixed
+ */
+ public function getItems()
+ {
+ return $this->_itemCollection;
+ }
+
+ /**
+ * Get tags array for saving cache
+ *
+ * @return array
+ */
+ public function getCacheTags()
+ {
+ return array_merge(parent::getCacheTags(), $this->getItemsTags($this->getItems()));
+ }
+
/**
* @return $this
*/
@@ -71,22 +89,4 @@ protected function _beforeToHtml()
$this->_prepareData();
return parent::_beforeToHtml();
}
-
- /**
- * @return mixed
- */
- public function getItems()
- {
- return $this->_itemCollection;
- }
-
- /**
- * Get tags array for saving cache
- *
- * @return array
- */
- public function getCacheTags()
- {
- return array_merge(parent::getCacheTags(), $this->getItemsTags($this->getItems()));
- }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php b/app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php
index 61937830659..7d539a34b0c 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php
@@ -135,49 +135,6 @@ class Mage_Catalog_Block_Product_List_Toolbar extends Mage_Core_Block_Template
*/
protected $_paramsMemorizeAllowed = true;
- /**
- * Retrieve Catalog Config object
- *
- * @return Mage_Catalog_Model_Config
- */
- protected function _getConfig()
- {
- return Mage::getSingleton('catalog/config');
- }
-
- /**
- * Init Toolbar
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_orderField = Mage::getStoreConfig(
- Mage_Catalog_Model_Config::XML_PATH_LIST_DEFAULT_SORT_BY,
- );
-
- $this->_availableOrder = $this->_getConfig()->getAttributeUsedForSortByArray();
-
- switch (Mage::getStoreConfig('catalog/frontend/list_mode')) {
- case 'grid':
- $this->_availableMode = ['grid' => $this->__('Grid')];
- break;
-
- case 'list':
- $this->_availableMode = ['list' => $this->__('List')];
- break;
-
- case 'grid-list':
- $this->_availableMode = ['grid' => $this->__('Grid'), 'list' => $this->__('List')];
- break;
-
- case 'list-grid':
- $this->_availableMode = ['list' => $this->__('List'), 'grid' => $this->__('Grid')];
- break;
- }
- $this->setTemplate('catalog/product/list/toolbar.phtml');
- }
-
/**
* Disable list state params memorizing
*/
@@ -187,22 +144,6 @@ public function disableParamsMemorizing()
return $this;
}
- /**
- * Memorize parameter value for session
- *
- * @param string $param parameter name
- * @param mixed $value parameter value
- * @return $this
- */
- protected function _memorizeParam($param, $value)
- {
- $session = Mage::getSingleton('catalog/session');
- if ($this->_paramsMemorizeAllowed && !$session->getParamsMemorizeDisabled()) {
- $session->setData($param, $value);
- }
- return $this;
- }
-
/**
* Set collection to pager
*
@@ -685,28 +626,6 @@ public function getAvailableLimit()
}
}
- /**
- * Retrieve available limits for specified view mode
- *
- * @param string $mode
- * @return array
- */
- protected function _getAvailableLimit($mode)
- {
- if (isset($this->_availableLimit[$mode])) {
- return $this->_availableLimit[$mode];
- }
- $perPageConfigKey = 'catalog/frontend/' . $mode . '_per_page_values';
- $perPageValues = (string) Mage::getStoreConfig($perPageConfigKey);
- $perPageValues = explode(',', $perPageValues);
- $perPageValues = array_combine($perPageValues, $perPageValues);
- if (Mage::getStoreConfigFlag('catalog/frontend/list_allow_all')) {
- return ($perPageValues + ['all' => $this->__('All')]);
- } else {
- return $perPageValues;
- }
- }
-
/**
* Get specified products limit display per page
*
@@ -837,4 +756,85 @@ public function getPagerHtml()
return '';
}
+
+ /**
+ * Retrieve Catalog Config object
+ *
+ * @return Mage_Catalog_Model_Config
+ */
+ protected function _getConfig()
+ {
+ return Mage::getSingleton('catalog/config');
+ }
+
+ /**
+ * Init Toolbar
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_orderField = Mage::getStoreConfig(
+ Mage_Catalog_Model_Config::XML_PATH_LIST_DEFAULT_SORT_BY,
+ );
+
+ $this->_availableOrder = $this->_getConfig()->getAttributeUsedForSortByArray();
+
+ switch (Mage::getStoreConfig('catalog/frontend/list_mode')) {
+ case 'grid':
+ $this->_availableMode = ['grid' => $this->__('Grid')];
+ break;
+
+ case 'list':
+ $this->_availableMode = ['list' => $this->__('List')];
+ break;
+
+ case 'grid-list':
+ $this->_availableMode = ['grid' => $this->__('Grid'), 'list' => $this->__('List')];
+ break;
+
+ case 'list-grid':
+ $this->_availableMode = ['list' => $this->__('List'), 'grid' => $this->__('Grid')];
+ break;
+ }
+ $this->setTemplate('catalog/product/list/toolbar.phtml');
+ }
+
+ /**
+ * Memorize parameter value for session
+ *
+ * @param string $param parameter name
+ * @param mixed $value parameter value
+ * @return $this
+ */
+ protected function _memorizeParam($param, $value)
+ {
+ $session = Mage::getSingleton('catalog/session');
+ if ($this->_paramsMemorizeAllowed && !$session->getParamsMemorizeDisabled()) {
+ $session->setData($param, $value);
+ }
+ return $this;
+ }
+
+ /**
+ * Retrieve available limits for specified view mode
+ *
+ * @param string $mode
+ * @return array
+ */
+ protected function _getAvailableLimit($mode)
+ {
+ if (isset($this->_availableLimit[$mode])) {
+ return $this->_availableLimit[$mode];
+ }
+ $perPageConfigKey = 'catalog/frontend/' . $mode . '_per_page_values';
+ $perPageValues = (string) Mage::getStoreConfig($perPageConfigKey);
+ $perPageValues = explode(',', $perPageValues);
+ $perPageValues = array_combine($perPageValues, $perPageValues);
+ if (Mage::getStoreConfigFlag('catalog/frontend/list_allow_all')) {
+ return ($perPageValues + ['all' => $this->__('All')]);
+ } else {
+ return $perPageValues;
+ }
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/List/Upsell.php b/app/code/core/Mage/Catalog/Block/Product/List/Upsell.php
index 492a553ae3f..002f78822e4 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List/Upsell.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List/Upsell.php
@@ -37,58 +37,6 @@ class Mage_Catalog_Block_Product_List_Upsell extends Mage_Catalog_Block_Product_
protected $_itemLimits = [];
- /**
- * @return $this
- */
- protected function _prepareData()
- {
- $product = Mage::registry('product');
- /** @var Mage_Catalog_Model_Product $product */
- $this->_itemCollection = $product->getUpSellProductCollection()
- ->setPositionOrder()
- ->addStoreFilter()
- ;
- if ($this->isModuleEnabled('Mage_Checkout', 'catalog')) {
- Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter(
- $this->_itemCollection,
- Mage::getSingleton('checkout/session')->getQuoteId(),
- );
-
- $this->_addProductAttributesAndPrices($this->_itemCollection);
- }
- Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($this->_itemCollection);
-
- if ($this->getItemLimit('upsell') > 0) {
- $this->_itemCollection->setPageSize($this->getItemLimit('upsell'));
- }
-
- $this->_itemCollection->load();
-
- /**
- * Updating collection with desired items
- */
- Mage::dispatchEvent('catalog_product_upsell', [
- 'product' => $product,
- 'collection' => $this->_itemCollection,
- 'limit' => $this->getItemLimit(),
- ]);
-
- foreach ($this->_itemCollection as $product) {
- $product->setDoNotUseCategoryId(true);
- }
-
- return $this;
- }
-
- /**
- * @return Mage_Catalog_Block_Product_Abstract
- */
- protected function _beforeToHtml()
- {
- $this->_prepareData();
- return parent::_beforeToHtml();
- }
-
/**
* @return Mage_Catalog_Model_Resource_Product_Link_Product_Collection
*/
@@ -189,4 +137,56 @@ public function getCacheTags()
{
return array_merge(parent::getCacheTags(), $this->getItemsTags($this->getItems()));
}
+
+ /**
+ * @return $this
+ */
+ protected function _prepareData()
+ {
+ $product = Mage::registry('product');
+ /** @var Mage_Catalog_Model_Product $product */
+ $this->_itemCollection = $product->getUpSellProductCollection()
+ ->setPositionOrder()
+ ->addStoreFilter()
+ ;
+ if ($this->isModuleEnabled('Mage_Checkout', 'catalog')) {
+ Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter(
+ $this->_itemCollection,
+ Mage::getSingleton('checkout/session')->getQuoteId(),
+ );
+
+ $this->_addProductAttributesAndPrices($this->_itemCollection);
+ }
+ Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($this->_itemCollection);
+
+ if ($this->getItemLimit('upsell') > 0) {
+ $this->_itemCollection->setPageSize($this->getItemLimit('upsell'));
+ }
+
+ $this->_itemCollection->load();
+
+ /**
+ * Updating collection with desired items
+ */
+ Mage::dispatchEvent('catalog_product_upsell', [
+ 'product' => $product,
+ 'collection' => $this->_itemCollection,
+ 'limit' => $this->getItemLimit(),
+ ]);
+
+ foreach ($this->_itemCollection as $product) {
+ $product->setDoNotUseCategoryId(true);
+ }
+
+ return $this;
+ }
+
+ /**
+ * @return Mage_Catalog_Block_Product_Abstract
+ */
+ protected function _beforeToHtml()
+ {
+ $this->_prepareData();
+ return parent::_beforeToHtml();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/New.php b/app/code/core/Mage/Catalog/Block/Product/New.php
index 7bfd58d6ca4..bacb83f2350 100644
--- a/app/code/core/Mage/Catalog/Block/Product/New.php
+++ b/app/code/core/Mage/Catalog/Block/Product/New.php
@@ -34,23 +34,6 @@ class Mage_Catalog_Block_Product_New extends Mage_Catalog_Block_Product_Abstract
*/
protected $_productsCount;
- /**
- * Initialize block's cache
- */
- protected function _construct()
- {
- parent::_construct();
-
- $this->addColumnCountLayoutDepend('empty', 6)
- ->addColumnCountLayoutDepend('one_column', 5)
- ->addColumnCountLayoutDepend('two_columns_left', 4)
- ->addColumnCountLayoutDepend('two_columns_right', 4)
- ->addColumnCountLayoutDepend('three_columns', 3);
-
- $this->addData(['cache_lifetime' => 86400]);
- $this->addCacheTag(Mage_Catalog_Model_Product::CACHE_TAG);
- }
-
/**
* Get Key pieces for caching block content
*
@@ -69,6 +52,48 @@ public function getCacheKeyInfo()
];
}
+ /**
+ * Set how much product should be displayed at once.
+ *
+ * @param int $count
+ * @return $this
+ */
+ public function setProductsCount($count)
+ {
+ $this->_productsCount = $count;
+ return $this;
+ }
+
+ /**
+ * Get how much products should be displayed at once.
+ *
+ * @return int
+ */
+ public function getProductsCount()
+ {
+ if ($this->_productsCount === null) {
+ $this->_productsCount = self::DEFAULT_PRODUCTS_COUNT;
+ }
+ return $this->_productsCount;
+ }
+
+ /**
+ * Initialize block's cache
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+
+ $this->addColumnCountLayoutDepend('empty', 6)
+ ->addColumnCountLayoutDepend('one_column', 5)
+ ->addColumnCountLayoutDepend('two_columns_left', 4)
+ ->addColumnCountLayoutDepend('two_columns_right', 4)
+ ->addColumnCountLayoutDepend('three_columns', 3);
+
+ $this->addData(['cache_lifetime' => 86400]);
+ $this->addCacheTag(Mage_Catalog_Model_Product::CACHE_TAG);
+ }
+
/**
* Prepare and return product collection
*
@@ -119,29 +144,4 @@ protected function _beforeToHtml()
$this->setProductCollection($this->_getProductCollection());
return parent::_beforeToHtml();
}
-
- /**
- * Set how much product should be displayed at once.
- *
- * @param int $count
- * @return $this
- */
- public function setProductsCount($count)
- {
- $this->_productsCount = $count;
- return $this;
- }
-
- /**
- * Get how much products should be displayed at once.
- *
- * @return int
- */
- public function getProductsCount()
- {
- if ($this->_productsCount === null) {
- $this->_productsCount = self::DEFAULT_PRODUCTS_COUNT;
- }
- return $this->_productsCount;
- }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/Price.php b/app/code/core/Mage/Catalog/Block/Product/Price.php
index 8e2c7487698..9e4b790828f 100644
--- a/app/code/core/Mage/Catalog/Block/Product/Price.php
+++ b/app/code/core/Mage/Catalog/Block/Product/Price.php
@@ -176,19 +176,6 @@ public function getAddToCartUrl($product, $additional = [])
return $this->getAddToCartUrlCustom($product, $additional);
}
- /**
- * Prevent displaying if the price is not available
- *
- * @return string
- */
- protected function _toHtml()
- {
- if (!$this->getProduct() || $this->getProduct()->getCanShowPrice() === false) {
- return '';
- }
- return parent::_toHtml();
- }
-
/**
* Get Product Price valid JS string
*
@@ -242,4 +229,17 @@ public function getAddToCartUrlCustom($product, $additional = [], $addFormKey =
}
return $helper->getAddUrl($product, $additional);
}
+
+ /**
+ * Prevent displaying if the price is not available
+ *
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ if (!$this->getProduct() || $this->getProduct()->getCanShowPrice() === false) {
+ return '';
+ }
+ return parent::_toHtml();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/View.php b/app/code/core/Mage/Catalog/Block/Product/View.php
index e930ba79af0..1cc305dce92 100644
--- a/app/code/core/Mage/Catalog/Block/Product/View.php
+++ b/app/code/core/Mage/Catalog/Block/Product/View.php
@@ -36,48 +36,6 @@ class Mage_Catalog_Block_Product_View extends Mage_Catalog_Block_Product_Abstrac
*/
protected $_mapRenderer = 'msrp_item';
- /**
- * Add meta information from product to head block
- *
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->getLayout()->createBlock('catalog/breadcrumbs');
-
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $product = $this->getProduct();
- $title = $product->getMetaTitle();
- if ($title) {
- $headBlock->setTitle($title);
- }
- $keyword = $product->getMetaKeyword();
- $currentCategory = Mage::registry('current_category');
- if ($keyword) {
- $headBlock->setKeywords($keyword);
- } elseif ($currentCategory) {
- $headBlock->setKeywords($product->getName());
- }
- $description = $product->getMetaDescription();
- if ($description) {
- $headBlock->setDescription(($description));
- } else {
- $headBlock->setDescription(Mage::helper('core/string')->substr($product->getDescription(), 0, 255));
- }
-
- /** @var Mage_Catalog_Helper_Product $helper */
- $helper = $this->helper('catalog/product');
- if ($helper->canUseCanonicalTag()) {
- $params = ['_ignore_category' => true];
- $headBlock->addLinkRel('canonical', $product->getUrlModel()->getUrl($product, $params));
- }
- }
-
- return parent::_prepareLayout();
- }
-
/**
* Retrieve current product model
*
@@ -251,4 +209,46 @@ public function getAddToCartUrlCustom($product, $additional = [], $addFormKey =
}
return $helper->getAddUrl($product, $additional);
}
+
+ /**
+ * Add meta information from product to head block
+ *
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->getLayout()->createBlock('catalog/breadcrumbs');
+
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $product = $this->getProduct();
+ $title = $product->getMetaTitle();
+ if ($title) {
+ $headBlock->setTitle($title);
+ }
+ $keyword = $product->getMetaKeyword();
+ $currentCategory = Mage::registry('current_category');
+ if ($keyword) {
+ $headBlock->setKeywords($keyword);
+ } elseif ($currentCategory) {
+ $headBlock->setKeywords($product->getName());
+ }
+ $description = $product->getMetaDescription();
+ if ($description) {
+ $headBlock->setDescription(($description));
+ } else {
+ $headBlock->setDescription(Mage::helper('core/string')->substr($product->getDescription(), 0, 255));
+ }
+
+ /** @var Mage_Catalog_Helper_Product $helper */
+ $helper = $this->helper('catalog/product');
+ if ($helper->canUseCanonicalTag()) {
+ $params = ['_ignore_category' => true];
+ $headBlock->addLinkRel('canonical', $product->getUrlModel()->getUrl($product, $params));
+ }
+ }
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/View/Options.php b/app/code/core/Mage/Catalog/Block/Product/View/Options.php
index 1887da7140b..4407b49ca8f 100644
--- a/app/code/core/Mage/Catalog/Block/Product/View/Options.php
+++ b/app/code/core/Mage/Catalog/Block/Product/View/Options.php
@@ -128,24 +128,6 @@ public function hasOptions()
return false;
}
- /**
- * Get price configuration
- *
- * @param Mage_Catalog_Model_Product_Option_Value|Mage_Catalog_Model_Product_Option $option
- * @return array
- */
- protected function _getPriceConfiguration($option)
- {
- $data = [];
- $data['price'] = Mage::helper('core')->currency($option->getPrice(true), false, false);
- $data['oldPrice'] = Mage::helper('core')->currency($option->getPrice(false), false, false);
- $data['priceValue'] = $option->getPrice(false);
- $data['type'] = $option->getPriceType();
- $data['excludeTax'] = $price = Mage::helper('tax')->getPrice($option->getProduct(), $data['price'], false);
- $data['includeTax'] = $price = Mage::helper('tax')->getPrice($option->getProduct(), $data['price'], true);
- return $data;
- }
-
/**
* Get json representation of
*
@@ -193,4 +175,22 @@ public function getOptionHtml(Mage_Catalog_Model_Product_Option $option)
->setOption($option)
->toHtml();
}
+
+ /**
+ * Get price configuration
+ *
+ * @param Mage_Catalog_Model_Product_Option_Value|Mage_Catalog_Model_Product_Option $option
+ * @return array
+ */
+ protected function _getPriceConfiguration($option)
+ {
+ $data = [];
+ $data['price'] = Mage::helper('core')->currency($option->getPrice(true), false, false);
+ $data['oldPrice'] = Mage::helper('core')->currency($option->getPrice(false), false, false);
+ $data['priceValue'] = $option->getPrice(false);
+ $data['type'] = $option->getPriceType();
+ $data['excludeTax'] = $price = Mage::helper('tax')->getPrice($option->getProduct(), $data['price'], false);
+ $data['includeTax'] = $price = Mage::helper('tax')->getPrice($option->getProduct(), $data['price'], true);
+ return $data;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/View/Options/Abstract.php b/app/code/core/Mage/Catalog/Block/Product/View/Options/Abstract.php
index 491e80028b6..882faf6b3f2 100644
--- a/app/code/core/Mage/Catalog/Block/Product/View/Options/Abstract.php
+++ b/app/code/core/Mage/Catalog/Block/Product/View/Options/Abstract.php
@@ -93,6 +93,38 @@ public function getFormatedPrice()
return '';
}
+ /**
+ * Get price with including/excluding tax
+ *
+ * @param float $price
+ * @param bool $includingTax
+ * @return float
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ public function getPrice($price, $includingTax = null)
+ {
+ if (!is_null($includingTax)) {
+ $price = Mage::helper('tax')->getPrice($this->getProduct(), $price, true);
+ } else {
+ $price = Mage::helper('tax')->getPrice($this->getProduct(), $price);
+ }
+ return $price;
+ }
+
+ /**
+ * Returns price converted to current currency rate
+ *
+ * @param float $price
+ * @return float
+ */
+ public function getCurrencyPrice($price)
+ {
+ /** @var Mage_Core_Helper_Data $helper */
+ $helper = $this->helper('core');
+ $store = $this->getProduct()->getStore();
+ return $helper::currencyByStore($price, $store, false);
+ }
+
/**
* Return formatted price
*
@@ -139,36 +171,4 @@ protected function _formatPrice($value, $flag = true)
return $priceStr;
}
-
- /**
- * Get price with including/excluding tax
- *
- * @param float $price
- * @param bool $includingTax
- * @return float
- * @throws Mage_Core_Model_Store_Exception
- */
- public function getPrice($price, $includingTax = null)
- {
- if (!is_null($includingTax)) {
- $price = Mage::helper('tax')->getPrice($this->getProduct(), $price, true);
- } else {
- $price = Mage::helper('tax')->getPrice($this->getProduct(), $price);
- }
- return $price;
- }
-
- /**
- * Returns price converted to current currency rate
- *
- * @param float $price
- * @return float
- */
- public function getCurrencyPrice($price)
- {
- /** @var Mage_Core_Helper_Data $helper */
- $helper = $this->helper('core');
- $store = $this->getProduct()->getStore();
- return $helper::currencyByStore($price, $store, false);
- }
}
diff --git a/app/code/core/Mage/Catalog/Block/Product/View/Options/Type/Date.php b/app/code/core/Mage/Catalog/Block/Product/View/Options/Type/Date.php
index 477589b1610..cf0dcf0d94a 100644
--- a/app/code/core/Mage/Catalog/Block/Product/View/Options/Type/Date.php
+++ b/app/code/core/Mage/Catalog/Block/Product/View/Options/Type/Date.php
@@ -31,17 +31,6 @@ class Mage_Catalog_Block_Product_View_Options_Type_Date extends Mage_Catalog_Blo
*/
protected $_fillLeadingZeros = true;
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- if ($head = $this->getLayout()->getBlock('head')) {
- $head->setCanLoadCalendarJs(true);
- }
- return parent::_prepareLayout();
- }
-
/**
* Use JS calendar settings
*
@@ -151,6 +140,17 @@ public function getTimeHtml()
return $hoursHtml . ' : ' . $minutesHtml . ' ' . $dayPartHtml;
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ if ($head = $this->getLayout()->getBlock('head')) {
+ $head->setCanLoadCalendarJs(true);
+ }
+ return parent::_prepareLayout();
+ }
+
/**
* Return drop-down html with range of values
*
diff --git a/app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php b/app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php
index 879704f365b..84e9321310c 100644
--- a/app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php
+++ b/app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php
@@ -38,16 +38,6 @@ class Mage_Catalog_Block_Product_View_Type_Configurable extends Mage_Catalog_Blo
*/
protected $_resPrices = [];
- /**
- * Get helper for calculation purposes
- *
- * @return Mage_Catalog_Helper_Product_Type_Composite
- */
- protected function _getHelper()
- {
- return $this->helper('catalog/product_type_composite');
- }
-
/**
* Get allowed attributes
*
@@ -117,16 +107,6 @@ public function getCurrentStore()
return $this->_getHelper()->getCurrentStore();
}
- /**
- * Returns additional values for js config, con be overridden by descendants
- *
- * @return array
- */
- protected function _getAdditionalConfig()
- {
- return [];
- }
-
/**
* Composes configuration for js
*
@@ -272,6 +252,26 @@ public function getJsonConfig()
return Mage::helper('core')->jsonEncode($config);
}
+ /**
+ * Get helper for calculation purposes
+ *
+ * @return Mage_Catalog_Helper_Product_Type_Composite
+ */
+ protected function _getHelper()
+ {
+ return $this->helper('catalog/product_type_composite');
+ }
+
+ /**
+ * Returns additional values for js config, con be overridden by descendants
+ *
+ * @return array
+ */
+ protected function _getAdditionalConfig()
+ {
+ return [];
+ }
+
/**
* Validating of super product option value
*
diff --git a/app/code/core/Mage/Catalog/Block/Product/Widget/New.php b/app/code/core/Mage/Catalog/Block/Product/Widget/New.php
index c9cb5f4d146..2adfeca431a 100644
--- a/app/code/core/Mage/Catalog/Block/Product/Widget/New.php
+++ b/app/code/core/Mage/Catalog/Block/Product/Widget/New.php
@@ -57,50 +57,6 @@ class Mage_Catalog_Block_Product_Widget_New extends Mage_Catalog_Block_Product_N
*/
protected $_defaultColumnCount = 5;
- /**
- * Initialize block's cache and template settings
- */
- protected function _construct()
- {
- parent::_construct();
- $this->addPriceBlockType('bundle', 'bundle/catalog_product_price', 'bundle/catalog/product/price.phtml');
- }
-
- /**
- * Product collection initialize process
- *
- * @return Mage_Catalog_Model_Resource_Product_Collection|Object|Varien_Data_Collection
- */
- protected function _getProductCollection()
- {
- switch ($this->getDisplayType()) {
- case self::DISPLAY_TYPE_NEW_PRODUCTS:
- $collection = parent::_getProductCollection();
- break;
- default:
- $collection = $this->_getRecentlyAddedProductsCollection();
- break;
- }
- return $collection;
- }
-
- /**
- * Prepare collection for recent product list
- *
- * @return Mage_Catalog_Model_Resource_Product_Collection|Object|Varien_Data_Collection
- */
- protected function _getRecentlyAddedProductsCollection()
- {
- /** @var Mage_Catalog_Model_Resource_Product_Collection $collection */
- $collection = Mage::getResourceModel('catalog/product_collection');
- $collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
- return $this->_addProductAttributesAndPrices($collection)
- ->addStoreFilter()
- ->addAttributeToSort('created_at', 'desc')
- ->setPageSize($this->getProductsCount())
- ->setCurPage(1);
- }
-
/**
* Get key pieces for caching block content
*
@@ -193,4 +149,48 @@ public function getPagerHtml()
}
return '';
}
+
+ /**
+ * Initialize block's cache and template settings
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->addPriceBlockType('bundle', 'bundle/catalog_product_price', 'bundle/catalog/product/price.phtml');
+ }
+
+ /**
+ * Product collection initialize process
+ *
+ * @return Mage_Catalog_Model_Resource_Product_Collection|Object|Varien_Data_Collection
+ */
+ protected function _getProductCollection()
+ {
+ switch ($this->getDisplayType()) {
+ case self::DISPLAY_TYPE_NEW_PRODUCTS:
+ $collection = parent::_getProductCollection();
+ break;
+ default:
+ $collection = $this->_getRecentlyAddedProductsCollection();
+ break;
+ }
+ return $collection;
+ }
+
+ /**
+ * Prepare collection for recent product list
+ *
+ * @return Mage_Catalog_Model_Resource_Product_Collection|Object|Varien_Data_Collection
+ */
+ protected function _getRecentlyAddedProductsCollection()
+ {
+ /** @var Mage_Catalog_Model_Resource_Product_Collection $collection */
+ $collection = Mage::getResourceModel('catalog/product_collection');
+ $collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
+ return $this->_addProductAttributesAndPrices($collection)
+ ->addStoreFilter()
+ ->addAttributeToSort('created_at', 'desc')
+ ->setPageSize($this->getProductsCount())
+ ->setCurPage(1);
+ }
}
diff --git a/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Category.php b/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Category.php
index b083c7d72c7..4fabe91367e 100644
--- a/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Category.php
+++ b/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Category.php
@@ -25,29 +25,28 @@
class Mage_Catalog_Block_Seo_Sitemap_Category extends Mage_Catalog_Block_Seo_Sitemap_Abstract
{
/**
- * Initialize categories collection
+ * Get item URL
*
- * @return $this
+ * @param Mage_Catalog_Model_Category $category
+ * @return string
*/
- protected function _prepareLayout()
+ public function getItemUrl($category)
{
$helper = Mage::helper('catalog/category');
/** @var Mage_Catalog_Helper_Category $helper */
- $collection = $helper->getStoreCategories('name', true, false);
- $this->setCollection($collection);
- return $this;
+ return $helper->getCategoryUrl($category);
}
-
/**
- * Get item URL
+ * Initialize categories collection
*
- * @param Mage_Catalog_Model_Category $category
- * @return string
+ * @return $this
*/
- public function getItemUrl($category)
+ protected function _prepareLayout()
{
$helper = Mage::helper('catalog/category');
/** @var Mage_Catalog_Helper_Category $helper */
- return $helper->getCategoryUrl($category);
+ $collection = $helper->getStoreCategories('name', true, false);
+ $this->setCollection($collection);
+ return $this;
}
}
diff --git a/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Product.php b/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Product.php
index 07f0b655c6e..1b24e03eda1 100644
--- a/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Product.php
+++ b/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Product.php
@@ -24,6 +24,18 @@
*/
class Mage_Catalog_Block_Seo_Sitemap_Product extends Mage_Catalog_Block_Seo_Sitemap_Abstract
{
+ /**
+ * Get item URL
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @return string
+ */
+ public function getItemUrl($product)
+ {
+ /** @var Mage_Catalog_Helper_Product $helper */
+ $helper = Mage::helper('catalog/product');
+ return $helper->getProductUrl($product);
+ }
/**
* Initialize products collection
*
@@ -45,17 +57,4 @@ protected function _prepareLayout()
$this->setCollection($collection);
return $this;
}
-
- /**
- * Get item URL
- *
- * @param Mage_Catalog_Model_Product $product
- * @return string
- */
- public function getItemUrl($product)
- {
- /** @var Mage_Catalog_Helper_Product $helper */
- $helper = Mage::helper('catalog/product');
- return $helper->getProductUrl($product);
- }
}
diff --git a/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Tree/Category.php b/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Tree/Category.php
index 78786db529d..fe62a538b6c 100644
--- a/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Tree/Category.php
+++ b/app/code/core/Mage/Catalog/Block/Seo/Sitemap/Tree/Category.php
@@ -31,25 +31,6 @@ class Mage_Catalog_Block_Seo_Sitemap_Tree_Category extends Mage_Catalog_Block_Se
protected $_to = 0;
protected $_currentPage = 0;
protected $_categoriesToPages = [];
- /**
- * Initialize categories collection
- *
- * @return Mage_Catalog_Block_Seo_Sitemap_Category
- */
- protected function _prepareLayout()
- {
- $helper = Mage::helper('catalog/category');
- /** @var Mage_Catalog_Helper_Category $helper */
- $parent = Mage::getModel('catalog/category')
- ->setStoreId(Mage::app()->getStore()->getId())
- ->load(Mage::app()->getStore()->getRootCategoryId());
- $this->_storeRootCategoryPath = $parent->getPath();
- $this->_storeRootCategoryLevel = $parent->getLevel();
- $this->prepareCategoriesToPages();
- $collection = $this->getTreeCollection();
- $this->setCollection($collection);
- return $this;
- }
/**
* Init pager
@@ -127,6 +108,37 @@ public function getTreeCollection()
->addOrderField('path');
}
+ /**
+ * Return level of indent
+ *
+ * @param Mage_Catalog_Model_Category $item
+ * @param int $delta
+ * @return int
+ */
+ public function getLevel($item, $delta = 1)
+ {
+ return (int) ($item->getLevel() - $this->_storeRootCategoryLevel - 1) * $delta;
+ }
+ /**
+ * Initialize categories collection
+ *
+ * @return Mage_Catalog_Block_Seo_Sitemap_Category
+ */
+ protected function _prepareLayout()
+ {
+ $helper = Mage::helper('catalog/category');
+ /** @var Mage_Catalog_Helper_Category $helper */
+ $parent = Mage::getModel('catalog/category')
+ ->setStoreId(Mage::app()->getStore()->getId())
+ ->load(Mage::app()->getStore()->getRootCategoryId());
+ $this->_storeRootCategoryPath = $parent->getPath();
+ $this->_storeRootCategoryLevel = $parent->getLevel();
+ $this->prepareCategoriesToPages();
+ $collection = $this->getTreeCollection();
+ $this->setCollection($collection);
+ return $this;
+ }
+
/**
* Prepare collection filtered by paths
*
@@ -151,16 +163,4 @@ protected function _prepareCollection()
$this->_from = $_to - $collection->count();
return $this;
}
-
- /**
- * Return level of indent
- *
- * @param Mage_Catalog_Model_Category $item
- * @param int $delta
- * @return int
- */
- public function getLevel($item, $delta = 1)
- {
- return (int) ($item->getLevel() - $this->_storeRootCategoryLevel - 1) * $delta;
- }
}
diff --git a/app/code/core/Mage/Catalog/Helper/Data.php b/app/code/core/Mage/Catalog/Helper/Data.php
index 38ab381dd96..544b681b47b 100644
--- a/app/code/core/Mage/Catalog/Helper/Data.php
+++ b/app/code/core/Mage/Catalog/Helper/Data.php
@@ -111,23 +111,6 @@ public function getBreadcrumbPath()
return $this->_categoryPath;
}
- /**
- * Check is category link
- *
- * @param int $categoryId
- * @return bool
- */
- protected function _isCategoryLink($categoryId)
- {
- if ($this->getProduct()) {
- return true;
- }
- if ($categoryId != $this->getCategory()->getId()) {
- return true;
- }
- return false;
- }
-
/**
* Return current category object
*
@@ -457,4 +440,21 @@ public function shouldDisplayProductCountOnLayer($storeId = null)
{
return Mage::getStoreConfigFlag(self::XML_PATH_DISPLAY_PRODUCT_COUNT, $storeId);
}
+
+ /**
+ * Check is category link
+ *
+ * @param int $categoryId
+ * @return bool
+ */
+ protected function _isCategoryLink($categoryId)
+ {
+ if ($this->getProduct()) {
+ return true;
+ }
+ if ($categoryId != $this->getCategory()->getId()) {
+ return true;
+ }
+ return false;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Helper/Image.php b/app/code/core/Mage/Catalog/Helper/Image.php
index 2d41a6b4b74..7815d16e31d 100644
--- a/app/code/core/Mage/Catalog/Helper/Image.php
+++ b/app/code/core/Mage/Catalog/Helper/Image.php
@@ -106,23 +106,43 @@ class Mage_Catalog_Helper_Image extends Mage_Core_Helper_Abstract
protected $_placeholder;
/**
- * Reset all previous data
+ * Return Image URL
*
- * @return $this
+ * @return string
*/
- protected function _reset()
+ public function __toString()
{
- $this->_model = null;
- $this->_scheduleResize = false;
- $this->_scheduleRotate = false;
- $this->_angle = null;
- $this->_watermark = null;
- $this->_watermarkPosition = null;
- $this->_watermarkSize = null;
- $this->_watermarkImageOpacity = null;
- $this->_product = null;
- $this->_imageFile = null;
- return $this;
+ try {
+ $model = $this->_getModel();
+
+ if ($this->getImageFile()) {
+ $model->setBaseFile($this->getImageFile());
+ } else {
+ $model->setBaseFile($this->getProduct()->getData($model->getDestinationSubdir()));
+ }
+
+ if ($model->isCached()) {
+ return $model->getUrl();
+ } else {
+ if ($this->_scheduleRotate) {
+ $model->rotate($this->getAngle());
+ }
+
+ if ($this->_scheduleResize) {
+ $model->resize();
+ }
+
+ if ($this->getWatermark()) {
+ $model->setWatermark($this->getWatermark());
+ }
+
+ $url = $model->saveFile()->getUrl();
+ }
+ } catch (Exception $e) {
+ Mage::logException($e);
+ $url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
+ }
+ return $url;
}
/**
@@ -333,43 +353,123 @@ public function getPlaceholder()
}
/**
- * Return Image URL
+ * Set watermark size
+ * param size in format 100x200
*
- * @return string
+ * @param string $size
+ * @return $this
*/
- public function __toString()
+ public function setWatermarkSize($size)
{
- try {
- $model = $this->_getModel();
+ $this->_watermarkSize = $size;
+ $this->_getModel()->setWatermarkSize($this->parseSize($size));
+ return $this;
+ }
- if ($this->getImageFile()) {
- $model->setBaseFile($this->getImageFile());
- } else {
- $model->setBaseFile($this->getProduct()->getData($model->getDestinationSubdir()));
- }
+ /**
+ * Set watermark image opacity
+ *
+ * @param int $imageOpacity
+ * @return $this
+ */
+ public function setWatermarkImageOpacity($imageOpacity)
+ {
+ $this->_watermarkImageOpacity = $imageOpacity;
+ $this->_getModel()->setWatermarkImageOpacity($imageOpacity);
+ return $this;
+ }
- if ($model->isCached()) {
- return $model->getUrl();
- } else {
- if ($this->_scheduleRotate) {
- $model->rotate($this->getAngle());
- }
+ /**
+ * Retrieve original image width
+ *
+ * @return int|null
+ */
+ public function getOriginalWidth()
+ {
+ return $this->_getModel()->getImageProcessor()->getOriginalWidth();
+ }
- if ($this->_scheduleResize) {
- $model->resize();
- }
+ /**
+ * Retrieve original image height
+ *
+ * @deprecated
+ * @return int|null
+ */
+ public function getOriginalHeigh()
+ {
+ return $this->getOriginalHeight();
+ }
- if ($this->getWatermark()) {
- $model->setWatermark($this->getWatermark());
- }
+ /**
+ * Retrieve original image height
+ *
+ * @return int|null
+ */
+ public function getOriginalHeight()
+ {
+ return $this->_getModel()->getImageProcessor()->getOriginalHeight();
+ }
- $url = $model->saveFile()->getUrl();
- }
- } catch (Exception $e) {
- Mage::logException($e);
- $url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
+ /**
+ * Retrieve Original image size as array
+ * 0 - width, 1 - height
+ *
+ * @return array
+ */
+ public function getOriginalSizeArray()
+ {
+ return [
+ $this->getOriginalWidth(),
+ $this->getOriginalHeight(),
+ ];
+ }
+
+ /**
+ * Check - is this file an image
+ *
+ * @param string $filePath
+ * @return bool
+ * @throws Mage_Core_Exception
+ */
+ public function validateUploadFile($filePath)
+ {
+ $maxDimension = Mage::getStoreConfig(self::XML_NODE_PRODUCT_MAX_DIMENSION);
+ $imageInfo = getimagesize($filePath);
+ if (!$imageInfo) {
+ Mage::throwException($this->__('Disallowed file type.'));
}
- return $url;
+
+ if ($imageInfo[0] > $maxDimension || $imageInfo[1] > $maxDimension) {
+ Mage::throwException($this->__('Disallowed file format.'));
+ }
+
+ $_processor = Mage::getModel('varien/image', $filePath);
+ $mimeType = $_processor->getMimeType();
+
+ // Force garbage collection since image handler resource uses memory without counting toward memory limit
+ unset($_processor);
+
+ return $mimeType !== null;
+ }
+
+ /**
+ * Reset all previous data
+ *
+ * @return $this
+ */
+ protected function _reset()
+ {
+ $this->_model = null;
+ $this->_scheduleResize = false;
+ $this->_scheduleRotate = false;
+ $this->_angle = null;
+ $this->_watermark = null;
+ $this->_watermarkPosition = null;
+ $this->_watermarkSize = null;
+ $this->_watermarkImageOpacity = null;
+ $this->_product = null;
+ $this->_imageFile = null;
+ return $this;
}
/**
@@ -462,20 +562,6 @@ protected function getWatermarkPosition()
return $this->_watermarkPosition;
}
- /**
- * Set watermark size
- * param size in format 100x200
- *
- * @param string $size
- * @return $this
- */
- public function setWatermarkSize($size)
- {
- $this->_watermarkSize = $size;
- $this->_getModel()->setWatermarkSize($this->parseSize($size));
- return $this;
- }
-
/**
* Get watermark size
*
@@ -486,19 +572,6 @@ protected function getWatermarkSize()
return $this->_watermarkSize;
}
- /**
- * Set watermark image opacity
- *
- * @param int $imageOpacity
- * @return $this
- */
- public function setWatermarkImageOpacity($imageOpacity)
- {
- $this->_watermarkImageOpacity = $imageOpacity;
- $this->_getModel()->setWatermarkImageOpacity($imageOpacity);
- return $this;
- }
-
/**
* Get watermark image opacity
*
@@ -579,77 +652,4 @@ protected function parseSize($string)
return false;
}
-
- /**
- * Retrieve original image width
- *
- * @return int|null
- */
- public function getOriginalWidth()
- {
- return $this->_getModel()->getImageProcessor()->getOriginalWidth();
- }
-
- /**
- * Retrieve original image height
- *
- * @deprecated
- * @return int|null
- */
- public function getOriginalHeigh()
- {
- return $this->getOriginalHeight();
- }
-
- /**
- * Retrieve original image height
- *
- * @return int|null
- */
- public function getOriginalHeight()
- {
- return $this->_getModel()->getImageProcessor()->getOriginalHeight();
- }
-
- /**
- * Retrieve Original image size as array
- * 0 - width, 1 - height
- *
- * @return array
- */
- public function getOriginalSizeArray()
- {
- return [
- $this->getOriginalWidth(),
- $this->getOriginalHeight(),
- ];
- }
-
- /**
- * Check - is this file an image
- *
- * @param string $filePath
- * @return bool
- * @throws Mage_Core_Exception
- */
- public function validateUploadFile($filePath)
- {
- $maxDimension = Mage::getStoreConfig(self::XML_NODE_PRODUCT_MAX_DIMENSION);
- $imageInfo = getimagesize($filePath);
- if (!$imageInfo) {
- Mage::throwException($this->__('Disallowed file type.'));
- }
-
- if ($imageInfo[0] > $maxDimension || $imageInfo[1] > $maxDimension) {
- Mage::throwException($this->__('Disallowed file format.'));
- }
-
- $_processor = Mage::getModel('varien/image', $filePath);
- $mimeType = $_processor->getMimeType();
-
- // Force garbage collection since image handler resource uses memory without counting toward memory limit
- unset($_processor);
-
- return $mimeType !== null;
- }
}
diff --git a/app/code/core/Mage/Catalog/Helper/Output.php b/app/code/core/Mage/Catalog/Helper/Output.php
index 32c59009674..0a8a79c35ac 100644
--- a/app/code/core/Mage/Catalog/Helper/Output.php
+++ b/app/code/core/Mage/Catalog/Helper/Output.php
@@ -41,18 +41,6 @@ public function __construct()
Mage::dispatchEvent('catalog_helper_output_construct', ['helper' => $this]);
}
- /**
- * @return Varien_Filter_Template
- */
- protected function _getTemplateProcessor()
- {
- if ($this->_templateProcessor === null) {
- $this->_templateProcessor = Mage::helper('catalog')->getPageTemplateProcessor();
- }
-
- return $this->_templateProcessor;
- }
-
/**
* Adding method handler
*
@@ -167,4 +155,16 @@ public function categoryAttribute($category, $attributeHtml, $attributeName)
'attribute' => $attributeName,
]);
}
+
+ /**
+ * @return Varien_Filter_Template
+ */
+ protected function _getTemplateProcessor()
+ {
+ if ($this->_templateProcessor === null) {
+ $this->_templateProcessor = Mage::helper('catalog')->getPageTemplateProcessor();
+ }
+
+ return $this->_templateProcessor;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Helper/Product/Compare.php b/app/code/core/Mage/Catalog/Helper/Product/Compare.php
index 013c265b230..9bc0c1fb91a 100644
--- a/app/code/core/Mage/Catalog/Helper/Product/Compare.php
+++ b/app/code/core/Mage/Catalog/Helper/Product/Compare.php
@@ -95,16 +95,6 @@ public function __construct(array $data = [])
$this->_logVisitor = $data['log_visitor'] ?? Mage::getSingleton('log/visitor');
}
- /**
- * Retrieve Catalog Session instance
- *
- * @return Mage_Catalog_Model_Session
- */
- protected function _getSession()
- {
- return $this->_catalogSession;
- }
-
/**
* Retrieve compare list url
*
@@ -125,17 +115,6 @@ public function getListUrl()
return $this->_getUrl('catalog/product_compare', $params);
}
- /**
- * Get parameters used for build add product to compare list urls
- *
- * @param Mage_Catalog_Model_Product $product
- * @return array
- */
- protected function _getUrlParams($product)
- {
- return $this->_getUrlCustomParams($product);
- }
-
/**
* Retrieve url for adding product to conpare list
*
@@ -377,6 +356,27 @@ public function getAddToCartUrlCustom($product, $addFormKey = true)
return $this->_getUrl('checkout/cart/add', $params);
}
+ /**
+ * Retrieve Catalog Session instance
+ *
+ * @return Mage_Catalog_Model_Session
+ */
+ protected function _getSession()
+ {
+ return $this->_catalogSession;
+ }
+
+ /**
+ * Get parameters used for build add product to compare list urls
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @return array
+ */
+ protected function _getUrlParams($product)
+ {
+ return $this->_getUrlCustomParams($product);
+ }
+
/**
* Get parameters used for build add product to compare list urls with or without Form Key
*
diff --git a/app/code/core/Mage/Catalog/Model/Abstract.php b/app/code/core/Mage/Catalog/Model/Abstract.php
index 0df87a8797f..6f0d4ca36e2 100644
--- a/app/code/core/Mage/Catalog/Model/Abstract.php
+++ b/app/code/core/Mage/Catalog/Model/Abstract.php
@@ -290,17 +290,6 @@ public function getExistsStoreValueFlag($attributeCode)
return array_key_exists($attributeCode, $this->_storeValuesFlags);
}
- /**
- * Before save unlock attributes
- *
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- $this->unlockAttributes();
- return parent::_beforeSave();
- }
-
/**
* Checks model is deletable
*
@@ -344,4 +333,15 @@ public function setIsReadonly($value)
$this->_isReadonly = (bool) $value;
return $this;
}
+
+ /**
+ * Before save unlock attributes
+ *
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ $this->unlockAttributes();
+ return parent::_beforeSave();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Api/Resource.php b/app/code/core/Mage/Catalog/Model/Api/Resource.php
index 0aa0b6766d9..9eea06199fb 100644
--- a/app/code/core/Mage/Catalog/Model/Api/Resource.php
+++ b/app/code/core/Mage/Catalog/Model/Api/Resource.php
@@ -48,6 +48,27 @@ class Mage_Catalog_Model_Api_Resource extends Mage_Api_Model_Resource_Abstract
*/
protected $_resourceAttributeAclName = 'catalog/category/attributes/field_';
+ /**
+ * Set current store for catalog.
+ *
+ * @param string|int $store
+ * @return int
+ */
+ public function currentStore($store = null)
+ {
+ if (!is_null($store)) {
+ try {
+ $storeId = Mage::app()->getStore($store)->getId();
+ } catch (Mage_Core_Model_Store_Exception $e) {
+ $this->_fault('store_not_exists');
+ }
+
+ $this->_getSession()->setData($this->_storeIdSessionField, $storeId);
+ }
+
+ return $this->_getStoreId();
+ }
+
/**
* Check is attribute allowed
*
@@ -113,25 +134,4 @@ protected function _getProduct($productId, $store = null, $identifierType = null
}
return $product;
}
-
- /**
- * Set current store for catalog.
- *
- * @param string|int $store
- * @return int
- */
- public function currentStore($store = null)
- {
- if (!is_null($store)) {
- try {
- $storeId = Mage::app()->getStore($store)->getId();
- } catch (Mage_Core_Model_Store_Exception $e) {
- $this->_fault('store_not_exists');
- }
-
- $this->_getSession()->setData($this->_storeIdSessionField, $storeId);
- }
-
- return $this->_getStoreId();
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Api2/Product/Validator/Product.php b/app/code/core/Mage/Catalog/Model/Api2/Product/Validator/Product.php
index 146c4ac545d..119010b9522 100644
--- a/app/code/core/Mage/Catalog/Model/Api2/Product/Validator/Product.php
+++ b/app/code/core/Mage/Catalog/Model/Api2/Product/Validator/Product.php
@@ -62,26 +62,6 @@ public function __construct($options)
$this->_operation = $options['operation'];
}
- /**
- * Get validator product
- *
- * @return Mage_Catalog_Model_Product|null
- */
- protected function _getProduct()
- {
- return $this->_product;
- }
-
- /**
- * Is update mode
- *
- * @return bool
- */
- protected function _isUpdate()
- {
- return $this->_operation == Mage_Api2_Model_Resource::OPERATION_UPDATE;
- }
-
/**
* Validate product data
*
@@ -117,6 +97,26 @@ public function isValidData(array $data)
return $isSatisfied;
}
+ /**
+ * Get validator product
+ *
+ * @return Mage_Catalog_Model_Product|null
+ */
+ protected function _getProduct()
+ {
+ return $this->_product;
+ }
+
+ /**
+ * Is update mode
+ *
+ * @return bool
+ */
+ protected function _isUpdate()
+ {
+ return $this->_operation == Mage_Api2_Model_Resource::OPERATION_UPDATE;
+ }
+
/**
* Collect required EAV attributes, validate applicable attributes and validate source attributes values
*
diff --git a/app/code/core/Mage/Catalog/Model/Api2/Product/Website/Validator/Admin/Website.php b/app/code/core/Mage/Catalog/Model/Api2/Product/Website/Validator/Admin/Website.php
index 78615de8e2f..19973f15c25 100644
--- a/app/code/core/Mage/Catalog/Model/Api2/Product/Website/Validator/Admin/Website.php
+++ b/app/code/core/Mage/Catalog/Model/Api2/Product/Website/Validator/Admin/Website.php
@@ -62,6 +62,26 @@ public function isValidDataForWebsiteAssignmentToProduct(Mage_Catalog_Model_Prod
return !count($this->getErrors());
}
+ /**
+ * Validate is valid association for website unassignment from product.
+ * If fails validation, then this method returns false, and
+ * getErrors() will return an array of errors that explain why the
+ * validation failed.
+ *
+ * @return bool
+ */
+ public function isWebsiteAssignedToProduct(Mage_Core_Model_Website $website, Mage_Catalog_Model_Product $product)
+ {
+ if (!in_array($website->getId(), $product->getWebsiteIds())) {
+ $this->_addError(sprintf(
+ 'Product #%d isn\'t assigned to website #%d',
+ $product->getId(),
+ $website->getId(),
+ ));
+ }
+ return !count($this->getErrors());
+ }
+
/**
* Validate "Copy To Stores" data and associations.
*
@@ -155,24 +175,4 @@ protected function _checkStoreTo($website, $storeData)
return $this;
}
-
- /**
- * Validate is valid association for website unassignment from product.
- * If fails validation, then this method returns false, and
- * getErrors() will return an array of errors that explain why the
- * validation failed.
- *
- * @return bool
- */
- public function isWebsiteAssignedToProduct(Mage_Core_Model_Website $website, Mage_Catalog_Model_Product $product)
- {
- if (!in_array($website->getId(), $product->getWebsiteIds())) {
- $this->_addError(sprintf(
- 'Product #%d isn\'t assigned to website #%d',
- $product->getId(),
- $website->getId(),
- ));
- }
- return !count($this->getErrors());
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Category.php b/app/code/core/Mage/Catalog/Model/Category.php
index 79af38147b3..fc462388e78 100644
--- a/app/code/core/Mage/Catalog/Model/Category.php
+++ b/app/code/core/Mage/Catalog/Model/Category.php
@@ -134,21 +134,6 @@ class Mage_Catalog_Model_Category extends Mage_Catalog_Model_Abstract
*/
protected $_useFlatResource = false;
- /**
- * Category design attributes
- *
- * @var array
- */
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private $_designAttributes = [
- 'custom_design',
- 'custom_design_from',
- 'custom_design_to',
- 'page_layout',
- 'custom_layout_update',
- 'custom_apply_to_products',
- ];
-
/**
* Category tree model
*
@@ -167,22 +152,19 @@ class Mage_Catalog_Model_Category extends Mage_Catalog_Model_Abstract
protected ?string $locale = null;
/**
- * Initialize resource mode
+ * Category design attributes
+ *
+ * @var array
*/
- protected function _construct()
- {
- // If Flat Data enabled then use it but only on frontend
- /** @var Mage_Catalog_Helper_Category_Flat $flatHelper */
- $flatHelper = Mage::helper('catalog/category_flat');
- if ($flatHelper->isAccessible() && !Mage::app()->getStore()->isAdmin() && $flatHelper->isBuilt(true)
- && !$this->getDisableFlat()
- ) {
- $this->_init('catalog/category_flat');
- $this->_useFlatResource = true;
- } else {
- $this->_init('catalog/category');
- }
- }
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private $_designAttributes = [
+ 'custom_design',
+ 'custom_design_from',
+ 'custom_design_to',
+ 'page_layout',
+ 'custom_layout_update',
+ 'custom_apply_to_products',
+ ];
/**
* Retrieve URL instance
@@ -636,24 +618,6 @@ public function getDesignAttributes()
return $result;
}
- /**
- * Retrieve attribute by code
- *
- * @param string $attributeCode
- * @return Mage_Eav_Model_Entity_Attribute_Abstract
- */
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private function _getAttribute($attributeCode)
- {
- if (!$this->_useFlatResource) {
- $attribute = $this->getResource()->getAttribute($attributeCode);
- } else {
- $attribute = Mage::getSingleton('catalog/config')
- ->getAttribute(self::ENTITY, $attributeCode);
- }
- return $attribute;
- }
-
/**
* Get all children categories IDs
*
@@ -783,20 +747,6 @@ public function getName()
return $this->_getData('name');
}
- /**
- * Before delete process
- *
- * @inheritDoc
- */
- protected function _beforeDelete()
- {
- $this->_protectFromNonAdmin();
- if ($this->getResource()->isForbiddenToDelete($this->getId())) {
- Mage::throwException("Can't delete root category.");
- }
- return parent::_beforeDelete();
- }
-
/**
* Retrieve anchors above
*
@@ -1000,4 +950,54 @@ public function afterCommitCallback()
return $this;
}
+
+ /**
+ * Initialize resource mode
+ */
+ protected function _construct()
+ {
+ // If Flat Data enabled then use it but only on frontend
+ /** @var Mage_Catalog_Helper_Category_Flat $flatHelper */
+ $flatHelper = Mage::helper('catalog/category_flat');
+ if ($flatHelper->isAccessible() && !Mage::app()->getStore()->isAdmin() && $flatHelper->isBuilt(true)
+ && !$this->getDisableFlat()
+ ) {
+ $this->_init('catalog/category_flat');
+ $this->_useFlatResource = true;
+ } else {
+ $this->_init('catalog/category');
+ }
+ }
+
+ /**
+ * Before delete process
+ *
+ * @inheritDoc
+ */
+ protected function _beforeDelete()
+ {
+ $this->_protectFromNonAdmin();
+ if ($this->getResource()->isForbiddenToDelete($this->getId())) {
+ Mage::throwException("Can't delete root category.");
+ }
+ return parent::_beforeDelete();
+ }
+
+ /**
+ * Retrieve attribute by code
+ *
+ * @param string $attributeCode
+ * @return Mage_Eav_Model_Entity_Attribute_Abstract
+ */
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private function _getAttribute($attributeCode)
+ {
+ if (!$this->_useFlatResource) {
+ $attribute = $this->getResource()->getAttribute($attributeCode);
+ } else {
+ $attribute = Mage::getSingleton('catalog/config')
+ ->getAttribute(self::ENTITY, $attributeCode);
+ }
+ return $attribute;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Category/Api.php b/app/code/core/Mage/Catalog/Model/Category/Api.php
index d8684f9aee8..09d9197e4f8 100644
--- a/app/code/core/Mage/Catalog/Model/Category/Api.php
+++ b/app/code/core/Mage/Catalog/Model/Category/Api.php
@@ -143,50 +143,6 @@ public function tree($parentId = null, $store = null)
return $this->_nodeToArray($root);
}
- /**
- * Convert node to array
- *
- * @return array
- */
- protected function _nodeToArray(Varien_Data_Tree_Node $node)
- {
- // Only basic category data
- $result = [];
- $result['category_id'] = $node->getId();
- $result['parent_id'] = $node->getParentId();
- $result['name'] = $node->getName();
- $result['is_active'] = $node->getIsActive();
- $result['position'] = $node->getPosition();
- $result['level'] = $node->getLevel();
- $result['children'] = [];
-
- foreach ($node->getChildren() as $child) {
- $result['children'][] = $this->_nodeToArray($child);
- }
-
- return $result;
- }
-
- /**
- * Initialize and return category model
- *
- * @param int $categoryId
- * @param string|int $store
- * @return Mage_Catalog_Model_Category
- */
- protected function _initCategory($categoryId, $store = null)
- {
- $category = Mage::getModel('catalog/category')
- ->setStoreId($this->_getStoreId($store))
- ->load($categoryId);
-
- if (!$category->getId()) {
- $this->_fault('not_exists');
- }
-
- return $category;
- }
-
/**
* Retrieve category data
*
@@ -390,25 +346,6 @@ public function delete($categoryId)
return true;
}
- /**
- * Get the product ID from a product ID or SKU. When $identifierType is left empty the helper will try to
- * automatically parse the given $productId and determine if it is a SKU or ID value
- *
- * @param int|string $productId The product ID or SKU
- * @param null|string $identifierType Should be 'sku' when working with SKU's. Leave null when using ID's
- *
- * @return int
- * @throws Mage_Api_Exception
- */
- protected function _getProductId($productId, $identifierType = null)
- {
- $product = Mage::helper('catalog/product')->getProduct($productId, null, $identifierType);
- if (!$product->getId()) {
- $this->_fault('not_exists', 'Product not exists.');
- }
- return $product->getId();
- }
-
/**
* Retrieve list of assigned products to category
*
@@ -525,4 +462,67 @@ public function removeProduct($categoryId, $productId, $identifierType = null)
return true;
}
+
+ /**
+ * Convert node to array
+ *
+ * @return array
+ */
+ protected function _nodeToArray(Varien_Data_Tree_Node $node)
+ {
+ // Only basic category data
+ $result = [];
+ $result['category_id'] = $node->getId();
+ $result['parent_id'] = $node->getParentId();
+ $result['name'] = $node->getName();
+ $result['is_active'] = $node->getIsActive();
+ $result['position'] = $node->getPosition();
+ $result['level'] = $node->getLevel();
+ $result['children'] = [];
+
+ foreach ($node->getChildren() as $child) {
+ $result['children'][] = $this->_nodeToArray($child);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Initialize and return category model
+ *
+ * @param int $categoryId
+ * @param string|int $store
+ * @return Mage_Catalog_Model_Category
+ */
+ protected function _initCategory($categoryId, $store = null)
+ {
+ $category = Mage::getModel('catalog/category')
+ ->setStoreId($this->_getStoreId($store))
+ ->load($categoryId);
+
+ if (!$category->getId()) {
+ $this->_fault('not_exists');
+ }
+
+ return $category;
+ }
+
+ /**
+ * Get the product ID from a product ID or SKU. When $identifierType is left empty the helper will try to
+ * automatically parse the given $productId and determine if it is a SKU or ID value
+ *
+ * @param int|string $productId The product ID or SKU
+ * @param null|string $identifierType Should be 'sku' when working with SKU's. Leave null when using ID's
+ *
+ * @return int
+ * @throws Mage_Api_Exception
+ */
+ protected function _getProductId($productId, $identifierType = null)
+ {
+ $product = Mage::helper('catalog/product')->getProduct($productId, null, $identifierType);
+ if (!$product->getId()) {
+ $this->_fault('not_exists', 'Product not exists.');
+ }
+ return $product->getId();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Category/Attribute/Source/Sortby.php b/app/code/core/Mage/Catalog/Model/Category/Attribute/Source/Sortby.php
index e7df0cd86a7..b48a6e89494 100644
--- a/app/code/core/Mage/Catalog/Model/Category/Attribute/Source/Sortby.php
+++ b/app/code/core/Mage/Catalog/Model/Category/Attribute/Source/Sortby.php
@@ -22,16 +22,6 @@
*/
class Mage_Catalog_Model_Category_Attribute_Source_Sortby extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
{
- /**
- * Retrieve Catalog Config Singleton
- *
- * @return Mage_Catalog_Model_Config
- */
- protected function _getCatalogConfig()
- {
- return Mage::getSingleton('catalog/config');
- }
-
/**
* Retrieve All options
*
@@ -53,4 +43,13 @@ public function getAllOptions()
}
return $this->_options;
}
+ /**
+ * Retrieve Catalog Config Singleton
+ *
+ * @return Mage_Catalog_Model_Config
+ */
+ protected function _getCatalogConfig()
+ {
+ return Mage::getSingleton('catalog/config');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Category/Indexer/Flat.php b/app/code/core/Mage/Catalog/Model/Category/Indexer/Flat.php
index ef401e4ce82..d44a0e763ec 100644
--- a/app/code/core/Mage/Catalog/Model/Category/Indexer/Flat.php
+++ b/app/code/core/Mage/Catalog/Model/Category/Indexer/Flat.php
@@ -82,16 +82,6 @@ public function getDescription()
return Mage::helper('catalog')->__('Reorganize EAV category structure to flat structure');
}
- /**
- * Retrieve Catalog Category Flat Indexer model
- *
- * @return Mage_Catalog_Model_Resource_Category_Flat
- */
- protected function _getIndexer()
- {
- return Mage::getResourceSingleton('catalog/category_flat');
- }
-
/**
* Check if event can be matched by process
* Overwrote for check is flat catalog category is enabled and specific save
@@ -152,6 +142,25 @@ public function matchEvent(Event $event)
return $result;
}
+ /**
+ * Rebuild all index data
+ *
+ */
+ public function reindexAll()
+ {
+ $this->_getIndexer()->reindexAll();
+ }
+
+ /**
+ * Retrieve Catalog Category Flat Indexer model
+ *
+ * @return Mage_Catalog_Model_Resource_Category_Flat
+ */
+ protected function _getIndexer()
+ {
+ return Mage::getResourceSingleton('catalog/category_flat');
+ }
+
/**
* Register data required by process in event object
*/
@@ -240,13 +249,4 @@ protected function _processEvent(Event $event)
$this->_getIndexer()->deleteStores($storeId);
}
}
-
- /**
- * Rebuild all index data
- *
- */
- public function reindexAll()
- {
- $this->_getIndexer()->reindexAll();
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Category/Indexer/Product.php b/app/code/core/Mage/Catalog/Model/Category/Indexer/Product.php
index a71a53f0fd5..e3f88adede1 100644
--- a/app/code/core/Mage/Catalog/Model/Category/Indexer/Product.php
+++ b/app/code/core/Mage/Catalog/Model/Category/Indexer/Product.php
@@ -69,14 +69,6 @@ class Mage_Catalog_Model_Category_Indexer_Product extends Mage_Index_Model_Index
],
];
- /**
- * Initialize resource
- */
- protected function _construct()
- {
- $this->_init('catalog/category_indexer_product');
- }
-
/**
* Get Indexer name
*
@@ -136,6 +128,14 @@ public function matchEvent(Mage_Index_Model_Event $event)
return $result;
}
+ /**
+ * Initialize resource
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/category_indexer_product');
+ }
+
/**
* Register data required by process in event object
* Check if category ids was changed
diff --git a/app/code/core/Mage/Catalog/Model/Config.php b/app/code/core/Mage/Catalog/Model/Config.php
index e88f0a08ebb..7d1f19751ac 100644
--- a/app/code/core/Mage/Catalog/Model/Config.php
+++ b/app/code/core/Mage/Catalog/Model/Config.php
@@ -24,6 +24,8 @@ class Mage_Catalog_Model_Config extends Mage_Eav_Model_Config
{
public const XML_PATH_LIST_DEFAULT_SORT_BY = 'catalog/frontend/default_sort_by';
+ public const XML_PATH_PRODUCT_COLLECTION_ATTRIBUTES = 'frontend/product/collection/attributes';
+
protected $_attributeSetsById;
protected $_attributeSetsByName;
@@ -63,13 +65,6 @@ class Mage_Catalog_Model_Config extends Mage_Eav_Model_Config
protected $_storeId = null;
- public const XML_PATH_PRODUCT_COLLECTION_ATTRIBUTES = 'frontend/product/collection/attributes';
-
- protected function _construct()
- {
- $this->_init('catalog/config');
- }
-
/**
* @param int $storeId
* @return $this
@@ -312,16 +307,6 @@ public function getProductCollectionAttributes()
return array_keys($attributes);
}
- /**
- * Retrieve resource model
- *
- * @return Mage_Catalog_Model_Resource_Config
- */
- protected function _getResource()
- {
- return Mage::getResourceModel('catalog/config');
- }
-
/**
* Retrieve Attributes used in product listing
*
@@ -391,4 +376,19 @@ public function getProductListDefaultSortBy($store = null)
{
return Mage::getStoreConfig(self::XML_PATH_LIST_DEFAULT_SORT_BY, $store);
}
+
+ protected function _construct()
+ {
+ $this->_init('catalog/config');
+ }
+
+ /**
+ * Retrieve resource model
+ *
+ * @return Mage_Catalog_Model_Resource_Config
+ */
+ protected function _getResource()
+ {
+ return Mage::getResourceModel('catalog/config');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php b/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php
index 77267e572d9..1ecd239b18a 100644
--- a/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php
+++ b/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php
@@ -100,16 +100,6 @@ class Mage_Catalog_Model_Convert_Adapter_Product extends Mage_Eav_Model_Convert_
*/
protected $_galleryBackendModel;
- /**
- * Retrieve event prefix for adapter
- *
- * @return string
- */
- public function getEventPrefix()
- {
- return $this->_eventPrefix;
- }
-
/**
* Affected entity ids
*
@@ -117,23 +107,62 @@ public function getEventPrefix()
*/
protected $_affectedEntityIds = [];
+ protected $_productId = '';
+
/**
- * Store affected entity ids
+ * Initialize convert adapter model for products collection
*
- * @param int|array $ids
- * @return $this
*/
- protected function _addAffectedEntityIds($ids)
+ public function __construct()
{
- if (is_array($ids)) {
- foreach ($ids as $id) {
- $this->_addAffectedEntityIds($id);
+ $fieldset = Mage::getConfig()->getFieldset('catalog_product_dataflow', 'admin');
+ foreach ($fieldset as $code => $node) {
+ /** @var Mage_Core_Model_Config_Element $node */
+ if ($node->is('inventory')) {
+ foreach ($node->product_type->children() as $productType) {
+ $productType = $productType->getName();
+ $this->_inventoryFieldsProductTypes[$productType][] = $code;
+ if ($node->is('use_config')) {
+ $this->_inventoryFieldsProductTypes[$productType][] = 'use_config_' . $code;
+ }
+ }
+
+ $this->_inventoryFields[] = $code;
+ if ($node->is('use_config')) {
+ $this->_inventoryFields[] = 'use_config_' . $code;
+ }
+ }
+ if ($node->is('required')) {
+ $this->_requiredFields[] = $code;
+ }
+ if ($node->is('ignore')) {
+ $this->_ignoreFields[] = $code;
+ }
+ if ($node->is('to_number')) {
+ $this->_toNumber[] = $code;
}
- } else {
- $this->_affectedEntityIds[] = $ids;
}
- return $this;
+ $this->setVar('entity_type', 'catalog/product');
+ if (!Mage::registry('Object_Cache_Product')) {
+ $this->setProduct(Mage::getModel('catalog/product'));
+ }
+
+ if (!Mage::registry('Object_Cache_StockItem')) {
+ $this->setStockItem(Mage::getModel('cataloginventory/stock_item'));
+ }
+
+ $this->_galleryBackendModel = $this->getAttribute('media_gallery')->getBackend();
+ }
+
+ /**
+ * Retrieve event prefix for adapter
+ *
+ * @return string
+ */
+ public function getEventPrefix()
+ {
+ return $this->_eventPrefix;
}
/**
@@ -305,19 +334,6 @@ public function getProductAttributeSets()
return $this->_productAttributeSets;
}
- /**
- * Init stores
- */
- protected function _initStores()
- {
- if (is_null($this->_stores)) {
- $this->_stores = Mage::app()->getStores(true, true);
- foreach ($this->_stores as $code => $store) {
- $this->_storesIdCode[$store->getId()] = $code;
- }
- }
- }
-
/**
* Retrieve store object by code
*
@@ -377,67 +393,6 @@ public function parse()
}
}
- protected $_productId = '';
-
- /**
- * Initialize convert adapter model for products collection
- *
- */
- public function __construct()
- {
- $fieldset = Mage::getConfig()->getFieldset('catalog_product_dataflow', 'admin');
- foreach ($fieldset as $code => $node) {
- /** @var Mage_Core_Model_Config_Element $node */
- if ($node->is('inventory')) {
- foreach ($node->product_type->children() as $productType) {
- $productType = $productType->getName();
- $this->_inventoryFieldsProductTypes[$productType][] = $code;
- if ($node->is('use_config')) {
- $this->_inventoryFieldsProductTypes[$productType][] = 'use_config_' . $code;
- }
- }
-
- $this->_inventoryFields[] = $code;
- if ($node->is('use_config')) {
- $this->_inventoryFields[] = 'use_config_' . $code;
- }
- }
- if ($node->is('required')) {
- $this->_requiredFields[] = $code;
- }
- if ($node->is('ignore')) {
- $this->_ignoreFields[] = $code;
- }
- if ($node->is('to_number')) {
- $this->_toNumber[] = $code;
- }
- }
-
- $this->setVar('entity_type', 'catalog/product');
- if (!Mage::registry('Object_Cache_Product')) {
- $this->setProduct(Mage::getModel('catalog/product'));
- }
-
- if (!Mage::registry('Object_Cache_StockItem')) {
- $this->setStockItem(Mage::getModel('cataloginventory/stock_item'));
- }
-
- $this->_galleryBackendModel = $this->getAttribute('media_gallery')->getBackend();
- }
-
- /**
- * Retrieve not loaded collection
- *
- * @param string $entityType
- * @return Mage_Catalog_Model_Resource_Product_Collection
- */
- protected function _getCollectionForLoad($entityType)
- {
- return parent::_getCollectionForLoad($entityType)
- ->setStoreId($this->getStoreId())
- ->addStoreFilter($this->getStoreId());
- }
-
/**
* @throws Mage_Core_Exception
* @throws Varien_Exception
@@ -903,4 +858,49 @@ public function finish()
Mage_Index_Model_Event::TYPE_SAVE,
);
}
+
+ /**
+ * Store affected entity ids
+ *
+ * @param int|array $ids
+ * @return $this
+ */
+ protected function _addAffectedEntityIds($ids)
+ {
+ if (is_array($ids)) {
+ foreach ($ids as $id) {
+ $this->_addAffectedEntityIds($id);
+ }
+ } else {
+ $this->_affectedEntityIds[] = $ids;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Init stores
+ */
+ protected function _initStores()
+ {
+ if (is_null($this->_stores)) {
+ $this->_stores = Mage::app()->getStores(true, true);
+ foreach ($this->_stores as $code => $store) {
+ $this->_storesIdCode[$store->getId()] = $code;
+ }
+ }
+ }
+
+ /**
+ * Retrieve not loaded collection
+ *
+ * @param string $entityType
+ * @return Mage_Catalog_Model_Resource_Product_Collection
+ */
+ protected function _getCollectionForLoad($entityType)
+ {
+ return parent::_getCollectionForLoad($entityType)
+ ->setStoreId($this->getStoreId())
+ ->addStoreFilter($this->getStoreId());
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Design.php b/app/code/core/Mage/Catalog/Model/Design.php
index c561e4c3063..3053ba62046 100644
--- a/app/code/core/Mage/Catalog/Model/Design.php
+++ b/app/code/core/Mage/Catalog/Model/Design.php
@@ -59,19 +59,6 @@ public function applyDesign($object, $calledFrom = 0)
return $this;
}
- /**
- * Apply package and theme
- *
- * @param string $package
- * @param string $theme
- */
- protected function _apply($package, $theme)
- {
- Mage::getSingleton('core/design_package')
- ->setPackageName($package)
- ->setTheme($theme);
- }
-
/**
* Apply custom design
*
@@ -89,6 +76,49 @@ public function applyCustomDesign($design)
$this->_apply($package, $theme);
}
+ /**
+ * Get custom layout settings
+ *
+ * @param Mage_Catalog_Model_Category|Mage_Catalog_Model_Product $object
+ * @return Varien_Object
+ */
+ public function getDesignSettings($object)
+ {
+ if ($object instanceof Mage_Catalog_Model_Product) {
+ $currentCategory = $object->getCategory();
+ } else {
+ $currentCategory = $object;
+ }
+
+ $category = null;
+ if ($currentCategory) {
+ $category = $currentCategory->getParentDesignCategory($currentCategory);
+ }
+
+ if ($object instanceof Mage_Catalog_Model_Product) {
+ if ($category && $category->getCustomApplyToProducts()) {
+ return $this->_mergeSettings($this->_extractSettings($category), $this->_extractSettings($object));
+ } else {
+ return $this->_extractSettings($object);
+ }
+ } else {
+ return $this->_extractSettings($category);
+ }
+ }
+
+ /**
+ * Apply package and theme
+ *
+ * @param string $package
+ * @param string $theme
+ */
+ protected function _apply($package, $theme)
+ {
+ Mage::getSingleton('core/design_package')
+ ->setPackageName($package)
+ ->setTheme($theme);
+ }
+
/**
* Check is allow apply for
*
@@ -323,36 +353,6 @@ protected function _applyDesign($designUpdateData, $calledFrom = 0, $loaded = fa
return $this;
}
- /**
- * Get custom layout settings
- *
- * @param Mage_Catalog_Model_Category|Mage_Catalog_Model_Product $object
- * @return Varien_Object
- */
- public function getDesignSettings($object)
- {
- if ($object instanceof Mage_Catalog_Model_Product) {
- $currentCategory = $object->getCategory();
- } else {
- $currentCategory = $object;
- }
-
- $category = null;
- if ($currentCategory) {
- $category = $currentCategory->getParentDesignCategory($currentCategory);
- }
-
- if ($object instanceof Mage_Catalog_Model_Product) {
- if ($category && $category->getCustomApplyToProducts()) {
- return $this->_mergeSettings($this->_extractSettings($category), $this->_extractSettings($object));
- } else {
- return $this->_extractSettings($object);
- }
- } else {
- return $this->_extractSettings($category);
- }
- }
-
/**
* Extract custom layout settings from category or product object
*
diff --git a/app/code/core/Mage/Catalog/Model/Entity/Attribute.php b/app/code/core/Mage/Catalog/Model/Entity/Attribute.php
index 6ef834fed1d..cc0dcc5a6dc 100644
--- a/app/code/core/Mage/Catalog/Model/Entity/Attribute.php
+++ b/app/code/core/Mage/Catalog/Model/Entity/Attribute.php
@@ -60,9 +60,9 @@
*/
class Mage_Catalog_Model_Entity_Attribute extends Mage_Eav_Model_Entity_Attribute
{
+ public const MODULE_NAME = 'Mage_Catalog';
protected $_eventPrefix = 'catalog_entity_attribute';
protected $_eventObject = 'attribute';
- public const MODULE_NAME = 'Mage_Catalog';
/**
* Processing object before save data
diff --git a/app/code/core/Mage/Catalog/Model/Indexer/Url.php b/app/code/core/Mage/Catalog/Model/Indexer/Url.php
index d7a553b25be..ef4638bf423 100644
--- a/app/code/core/Mage/Catalog/Model/Indexer/Url.php
+++ b/app/code/core/Mage/Catalog/Model/Indexer/Url.php
@@ -132,6 +132,23 @@ public function matchEvent(Mage_Index_Model_Event $event)
return $result;
}
+ /**
+ * Rebuild all index data
+ */
+ public function reindexAll()
+ {
+ /** @var Mage_Catalog_Model_Resource_Url $resourceModel */
+ $resourceModel = Mage::getResourceSingleton('catalog/url');
+ $resourceModel->beginTransaction();
+ try {
+ Mage::getSingleton('catalog/url')->refreshRewrites();
+ $resourceModel->commit();
+ } catch (Exception $e) {
+ $resourceModel->rollBack();
+ throw $e;
+ }
+ }
+
/**
* Register data required by process in event object
*
@@ -231,21 +248,4 @@ protected function _processEvent(Mage_Index_Model_Event $event)
}
}
}
-
- /**
- * Rebuild all index data
- */
- public function reindexAll()
- {
- /** @var Mage_Catalog_Model_Resource_Url $resourceModel */
- $resourceModel = Mage::getResourceSingleton('catalog/url');
- $resourceModel->beginTransaction();
- try {
- Mage::getSingleton('catalog/url')->refreshRewrites();
- $resourceModel->commit();
- } catch (Exception $e) {
- $resourceModel->rollBack();
- throw $e;
- }
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Layer.php b/app/code/core/Mage/Catalog/Model/Layer.php
index d1b6a760b3e..0d72c398dd7 100644
--- a/app/code/core/Mage/Catalog/Model/Layer.php
+++ b/app/code/core/Mage/Catalog/Model/Layer.php
@@ -226,6 +226,24 @@ public function getFilterableAttributes()
return $attributes;
}
+ /**
+ * Retrieve layer state object
+ *
+ * @return Mage_Catalog_Model_Layer_State
+ */
+ public function getState()
+ {
+ $state = $this->getData('state');
+ if (is_null($state)) {
+ Varien_Profiler::start(__METHOD__);
+ $state = Mage::getModel('catalog/layer_state');
+ $this->setData('state', $state);
+ Varien_Profiler::stop(__METHOD__);
+ }
+
+ return $state;
+ }
+
/**
* Prepare attribute for use in layered navigation
*
@@ -259,24 +277,6 @@ protected function _filterFilterableAttributes(Mage_Catalog_Model_Resource_Eav_A
return $attribute->getIsFilterable() > 0;
}
- /**
- * Retrieve layer state object
- *
- * @return Mage_Catalog_Model_Layer_State
- */
- public function getState()
- {
- $state = $this->getData('state');
- if (is_null($state)) {
- Varien_Profiler::start(__METHOD__);
- $state = Mage::getModel('catalog/layer_state');
- $this->setData('state', $state);
- Varien_Profiler::stop(__METHOD__);
- }
-
- return $state;
- }
-
/**
* Get attribute sets identifiers of current product set
*
diff --git a/app/code/core/Mage/Catalog/Model/Layer/Filter/Abstract.php b/app/code/core/Mage/Catalog/Model/Layer/Filter/Abstract.php
index 4b8f678792e..1a5e503172e 100644
--- a/app/code/core/Mage/Catalog/Model/Layer/Filter/Abstract.php
+++ b/app/code/core/Mage/Catalog/Model/Layer/Filter/Abstract.php
@@ -112,45 +112,6 @@ public function getItems()
return $this->_items;
}
- /**
- * Get data array for building filter items
- *
- * result array should have next structure:
- * array(
- * $index => array(
- * 'label' => $label,
- * 'value' => $value,
- * 'count' => $count
- * )
- * )
- *
- * @return array
- */
- protected function _getItemsData()
- {
- return [];
- }
-
- /**
- * Initialize filter items
- *
- * @return $this
- */
- protected function _initItems()
- {
- $data = $this->_getItemsData();
- $items = [];
- foreach ($data as $itemData) {
- $items[] = $this->_createItem(
- $itemData['label'],
- $itemData['value'],
- $itemData['count'],
- );
- }
- $this->_items = $items;
- return $this;
- }
-
/**
* Retrieve layer object
*
@@ -166,43 +127,6 @@ public function getLayer()
return $layer;
}
- /**
- * Create filter item object
- *
- * @param string $label
- * @param mixed $value
- * @param int $count
- * @return Mage_Catalog_Model_Layer_Filter_Item
- */
- protected function _createItem($label, $value, $count = 0)
- {
- return Mage::getModel('catalog/layer_filter_item')
- ->setFilter($this)
- ->setLabel($label)
- ->setValue($value)
- ->setCount($count);
- }
-
- /**
- * Get all product ids from from collection with applied filters
- *
- * @return array
- */
- protected function _getFilterEntityIds()
- {
- return $this->getLayer()->getProductCollection()->getAllIdsCache();
- }
-
- /**
- * Get product collection select object with applied filters
- *
- * @return Varien_Db_Select
- */
- protected function _getBaseCollectionSql()
- {
- return $this->getLayer()->getProductCollection()->getSelect();
- }
-
/**
* Set attribute model to filter
*
@@ -299,4 +223,80 @@ public function getClearLinkText()
{
return false;
}
+
+ /**
+ * Get data array for building filter items
+ *
+ * result array should have next structure:
+ * array(
+ * $index => array(
+ * 'label' => $label,
+ * 'value' => $value,
+ * 'count' => $count
+ * )
+ * )
+ *
+ * @return array
+ */
+ protected function _getItemsData()
+ {
+ return [];
+ }
+
+ /**
+ * Initialize filter items
+ *
+ * @return $this
+ */
+ protected function _initItems()
+ {
+ $data = $this->_getItemsData();
+ $items = [];
+ foreach ($data as $itemData) {
+ $items[] = $this->_createItem(
+ $itemData['label'],
+ $itemData['value'],
+ $itemData['count'],
+ );
+ }
+ $this->_items = $items;
+ return $this;
+ }
+
+ /**
+ * Create filter item object
+ *
+ * @param string $label
+ * @param mixed $value
+ * @param int $count
+ * @return Mage_Catalog_Model_Layer_Filter_Item
+ */
+ protected function _createItem($label, $value, $count = 0)
+ {
+ return Mage::getModel('catalog/layer_filter_item')
+ ->setFilter($this)
+ ->setLabel($label)
+ ->setValue($value)
+ ->setCount($count);
+ }
+
+ /**
+ * Get all product ids from from collection with applied filters
+ *
+ * @return array
+ */
+ protected function _getFilterEntityIds()
+ {
+ return $this->getLayer()->getProductCollection()->getAllIdsCache();
+ }
+
+ /**
+ * Get product collection select object with applied filters
+ *
+ * @return Varien_Db_Select
+ */
+ protected function _getBaseCollectionSql()
+ {
+ return $this->getLayer()->getProductCollection()->getSelect();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Layer/Filter/Attribute.php b/app/code/core/Mage/Catalog/Model/Layer/Filter/Attribute.php
index ccec86a52c3..e74dc2687d5 100644
--- a/app/code/core/Mage/Catalog/Model/Layer/Filter/Attribute.php
+++ b/app/code/core/Mage/Catalog/Model/Layer/Filter/Attribute.php
@@ -41,30 +41,6 @@ public function __construct()
$this->_requestVar = 'attribute';
}
- /**
- * Retrieve resource instance
- *
- * @return Mage_Catalog_Model_Resource_Layer_Filter_Attribute
- */
- protected function _getResource()
- {
- if (is_null($this->_resource)) {
- $this->_resource = Mage::getResourceModel('catalog/layer_filter_attribute');
- }
- return $this->_resource;
- }
-
- /**
- * Get option text from frontend model by option id
- *
- * @param int $optionId
- * @return string|bool
- */
- protected function _getOptionText($optionId)
- {
- return $this->getAttributeModel()->getFrontend()->getOption($optionId);
- }
-
/**
* Apply attribute option filter to product collection
*
@@ -90,6 +66,30 @@ public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
return $this;
}
+ /**
+ * Retrieve resource instance
+ *
+ * @return Mage_Catalog_Model_Resource_Layer_Filter_Attribute
+ */
+ protected function _getResource()
+ {
+ if (is_null($this->_resource)) {
+ $this->_resource = Mage::getResourceModel('catalog/layer_filter_attribute');
+ }
+ return $this->_resource;
+ }
+
+ /**
+ * Get option text from frontend model by option id
+ *
+ * @param int $optionId
+ * @return string|bool
+ */
+ protected function _getOptionText($optionId)
+ {
+ return $this->getAttributeModel()->getFrontend()->getOption($optionId);
+ }
+
/**
* Check whether specified attribute can be used in LN
*
diff --git a/app/code/core/Mage/Catalog/Model/Layer/Filter/Category.php b/app/code/core/Mage/Catalog/Model/Layer/Filter/Category.php
index da4ded2f0ee..f9a9da95b41 100644
--- a/app/code/core/Mage/Catalog/Model/Layer/Filter/Category.php
+++ b/app/code/core/Mage/Catalog/Model/Layer/Filter/Category.php
@@ -97,17 +97,6 @@ public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
return $this;
}
- /**
- * Validate category for be using as filter
- *
- * @param Mage_Catalog_Model_Category $category
- * @return int
- */
- protected function _isValidCategory($category)
- {
- return $category->getId();
- }
-
/**
* Get filter name
*
@@ -135,6 +124,17 @@ public function getCategory()
return $this->getLayer()->getCurrentCategory();
}
+ /**
+ * Validate category for be using as filter
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @return int
+ */
+ protected function _isValidCategory($category)
+ {
+ return $category->getId();
+ }
+
/**
* Get data array for building category filter items
*
diff --git a/app/code/core/Mage/Catalog/Model/Layer/Filter/Decimal.php b/app/code/core/Mage/Catalog/Model/Layer/Filter/Decimal.php
index 7a3752d2d6f..71729496b0f 100644
--- a/app/code/core/Mage/Catalog/Model/Layer/Filter/Decimal.php
+++ b/app/code/core/Mage/Catalog/Model/Layer/Filter/Decimal.php
@@ -43,19 +43,6 @@ public function __construct()
$this->_requestVar = 'decimal';
}
- /**
- * Retrieve resource instance
- *
- * @return Mage_Catalog_Model_Resource_Layer_Filter_Decimal
- */
- protected function _getResource()
- {
- if (is_null($this->_resource)) {
- $this->_resource = Mage::getResourceModel('catalog/layer_filter_decimal');
- }
- return $this->_resource;
- }
-
/**
* Apply decimal range filter to product collection
*
@@ -94,31 +81,6 @@ public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
return $this;
}
- /**
- * Retrieve price aggreagation data cache key
- *
- * @return string
- */
- protected function _getCacheKey()
- {
- return $this->getLayer()->getStateKey()
- . '_ATTR_' . $this->getAttributeModel()->getAttributeCode();
- }
-
- /**
- * Prepare text of item label
- *
- * @param int $range
- * @param float $value
- * @return string
- */
- protected function _renderItemLabel($range, $value)
- {
- $from = Mage::app()->getStore()->formatPrice(($value - 1) * $range, false);
- $to = Mage::app()->getStore()->formatPrice($value * $range, false);
- return Mage::helper('catalog')->__('%s - %s', $from, $to);
- }
-
/**
* Retrieve maximum value from layer products set
*
@@ -190,6 +152,44 @@ public function getRangeItemCounts($range)
return $items;
}
+ /**
+ * Retrieve resource instance
+ *
+ * @return Mage_Catalog_Model_Resource_Layer_Filter_Decimal
+ */
+ protected function _getResource()
+ {
+ if (is_null($this->_resource)) {
+ $this->_resource = Mage::getResourceModel('catalog/layer_filter_decimal');
+ }
+ return $this->_resource;
+ }
+
+ /**
+ * Retrieve price aggreagation data cache key
+ *
+ * @return string
+ */
+ protected function _getCacheKey()
+ {
+ return $this->getLayer()->getStateKey()
+ . '_ATTR_' . $this->getAttributeModel()->getAttributeCode();
+ }
+
+ /**
+ * Prepare text of item label
+ *
+ * @param int $range
+ * @param float $value
+ * @return string
+ */
+ protected function _renderItemLabel($range, $value)
+ {
+ $from = Mage::app()->getStore()->formatPrice(($value - 1) * $range, false);
+ $to = Mage::app()->getStore()->formatPrice($value * $range, false);
+ return Mage::helper('catalog')->__('%s - %s', $from, $to);
+ }
+
/**
* Retrieve data for build decimal filter items
*
diff --git a/app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php b/app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php
index a1f2a69d2a8..6b87a13beb2 100644
--- a/app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php
+++ b/app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php
@@ -65,19 +65,6 @@ public function __construct()
$this->_requestVar = 'price';
}
- /**
- * Retrieve resource instance
- *
- * @return Mage_Catalog_Model_Resource_Layer_Filter_Price
- */
- protected function _getResource()
- {
- if (is_null($this->_resource)) {
- $this->_resource = Mage::getResourceModel('catalog/layer_filter_price');
- }
- return $this->_resource;
- }
-
/**
* Get price range for building filter steps
*
@@ -164,195 +151,6 @@ public function getRangeItemCounts($range)
return $items;
}
- /**
- * Prepare text of item label
- *
- * @deprecated since 1.7.0.0
- * @param int $range
- * @param float $value
- * @return string
- */
- protected function _renderItemLabel($range, $value)
- {
- $store = Mage::app()->getStore();
- $fromPrice = $store->formatPrice(($value - 1) * $range);
- $toPrice = $store->formatPrice($value * $range);
-
- return Mage::helper('catalog')->__('%s - %s', $fromPrice, $toPrice);
- }
-
- /**
- * Prepare text of range label
- *
- * @param float|string $fromPrice
- * @param float|string $toPrice
- * @return string
- */
- protected function _renderRangeLabel($fromPrice, $toPrice)
- {
- $store = Mage::app()->getStore();
- $formattedFromPrice = $store->formatPrice($fromPrice);
- if ($toPrice === '') {
- return Mage::helper('catalog')->__('%s and above', $formattedFromPrice);
- } elseif ($fromPrice == $toPrice && Mage::app()->getStore()->getConfig(self::XML_PATH_ONE_PRICE_INTERVAL)) {
- return $formattedFromPrice;
- } else {
- if ($fromPrice != $toPrice) {
- $toPrice = (float) $toPrice - .01;
- }
- return Mage::helper('catalog')->__('%s - %s', $formattedFromPrice, $store->formatPrice($toPrice));
- }
- }
-
- /**
- * Get price aggreagation data cache key
- * @deprecated after 1.4
- * @return string
- */
- protected function _getCacheKey()
- {
- $key = $this->getLayer()->getStateKey()
- . '_PRICES_GRP_' . Mage::getSingleton('customer/session')->getCustomerGroupId()
- . '_CURR_' . Mage::app()->getStore()->getCurrentCurrencyCode()
- . '_ATTR_' . $this->getAttributeModel()->getAttributeCode()
- . '_LOC_'
- ;
- $taxReq = Mage::getSingleton('tax/calculation')->getDefaultRateRequest();
-
- return $key . implode('_', $taxReq->getData());
- }
-
- /**
- * Get additional request param data
- *
- * @return string
- */
- protected function _getAdditionalRequestData()
- {
- $result = '';
- $appliedInterval = $this->getInterval();
- if ($appliedInterval) {
- $result = ',' . $appliedInterval[0] . '-' . $appliedInterval[1];
- $priorIntervals = $this->getResetValue();
- if ($priorIntervals) {
- $result .= ',' . $priorIntervals;
- }
- }
-
- return $result;
- }
-
- /**
- * Get data generated by algorithm for build price filter items
- *
- * @return array
- */
- protected function _getCalculatedItemsData()
- {
- /** @var Mage_Catalog_Model_Layer_Filter_Price_Algorithm $algorithmModel */
- $algorithmModel = Mage::getSingleton('catalog/layer_filter_price_algorithm');
- $collection = $this->getLayer()->getProductCollection();
- $appliedInterval = $this->getInterval();
- if ($appliedInterval
- && $collection->getPricesCount() <= $this->getIntervalDivisionLimit()
- ) {
- return [];
- }
- $algorithmModel->setPricesModel($this)->setStatistics(
- $collection->getMinPrice(),
- $collection->getMaxPrice(),
- $collection->getPriceStandardDeviation(),
- $collection->getPricesCount(),
- );
-
- if ($appliedInterval) {
- if ($appliedInterval[0] == $appliedInterval[1] || $appliedInterval[1] === '0') {
- return [];
- }
- $algorithmModel->setLimits($appliedInterval[0], $appliedInterval[1]);
- }
-
- $items = [];
- foreach ($algorithmModel->calculateSeparators() as $separator) {
- $items[] = [
- 'label' => $this->_renderRangeLabel($separator['from'], $separator['to']),
- 'value' => (($separator['from'] == 0) ? '' : $separator['from'])
- . '-' . $separator['to'] . $this->_getAdditionalRequestData(),
- 'count' => $separator['count'],
- ];
- }
-
- return $items;
- }
-
- /**
- * Get data for build price filter items
- *
- * @return array
- */
- protected function _getItemsData()
- {
- if (Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_CALCULATION) == self::RANGE_CALCULATION_IMPROVED) {
- return $this->_getCalculatedItemsData();
- } elseif ($this->getInterval()) {
- return [];
- }
-
- $range = $this->getPriceRange();
- $dbRanges = $this->getRangeItemCounts($range);
- $data = [];
-
- if (!empty($dbRanges)) {
- $lastIndex = array_keys($dbRanges);
- $lastIndex = $lastIndex[count($lastIndex) - 1];
-
- foreach ($dbRanges as $index => $count) {
- $fromPrice = ($index == 1) ? '' : (($index - 1) * $range);
- $toPrice = ($index == $lastIndex) ? '' : ($index * $range);
-
- $data[] = [
- 'label' => $this->_renderRangeLabel($fromPrice, $toPrice),
- 'value' => $fromPrice . '-' . $toPrice,
- 'count' => $count,
- ];
- }
- }
-
- return $data;
- }
-
- /**
- * Apply price range filter to collection
- *
- * @return $this
- */
- protected function _applyPriceRange()
- {
- $this->_getResource()->applyPriceRange($this);
- return $this;
- }
-
- /**
- * Validate and parse filter request param
- *
- * @param string $filter
- * @return array|bool
- */
- protected function _validateFilter($filter)
- {
- $filter = explode('-', $filter);
- if (count($filter) != 2) {
- return false;
- }
- foreach ($filter as $v) {
- if (($v !== '' && $v !== '0' && (float) $v <= 0) || is_infinite((float) $v)) {
- return false;
- }
- }
-
- return $filter;
- }
-
/**
* Apply price range filter
*
@@ -404,20 +202,6 @@ public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
return $this;
}
- /**
- * Apply filter value to product collection based on filter range and selected value
- *
- * @deprecated since 1.7.0.0
- * @param int $range
- * @param int $index
- * @return $this
- */
- protected function _applyToCollection($range, $index)
- {
- $this->_getResource()->applyFilterToCollection($this, $range, $index);
- return $this;
- }
-
/**
* Retrieve active customer group id
*
@@ -579,4 +363,220 @@ public function loadNextPrices($price, $rightIndex, $upperPrice = null)
return $prices;
}
+
+ /**
+ * Retrieve resource instance
+ *
+ * @return Mage_Catalog_Model_Resource_Layer_Filter_Price
+ */
+ protected function _getResource()
+ {
+ if (is_null($this->_resource)) {
+ $this->_resource = Mage::getResourceModel('catalog/layer_filter_price');
+ }
+ return $this->_resource;
+ }
+
+ /**
+ * Prepare text of item label
+ *
+ * @deprecated since 1.7.0.0
+ * @param int $range
+ * @param float $value
+ * @return string
+ */
+ protected function _renderItemLabel($range, $value)
+ {
+ $store = Mage::app()->getStore();
+ $fromPrice = $store->formatPrice(($value - 1) * $range);
+ $toPrice = $store->formatPrice($value * $range);
+
+ return Mage::helper('catalog')->__('%s - %s', $fromPrice, $toPrice);
+ }
+
+ /**
+ * Prepare text of range label
+ *
+ * @param float|string $fromPrice
+ * @param float|string $toPrice
+ * @return string
+ */
+ protected function _renderRangeLabel($fromPrice, $toPrice)
+ {
+ $store = Mage::app()->getStore();
+ $formattedFromPrice = $store->formatPrice($fromPrice);
+ if ($toPrice === '') {
+ return Mage::helper('catalog')->__('%s and above', $formattedFromPrice);
+ } elseif ($fromPrice == $toPrice && Mage::app()->getStore()->getConfig(self::XML_PATH_ONE_PRICE_INTERVAL)) {
+ return $formattedFromPrice;
+ } else {
+ if ($fromPrice != $toPrice) {
+ $toPrice = (float) $toPrice - .01;
+ }
+ return Mage::helper('catalog')->__('%s - %s', $formattedFromPrice, $store->formatPrice($toPrice));
+ }
+ }
+
+ /**
+ * Get price aggreagation data cache key
+ * @deprecated after 1.4
+ * @return string
+ */
+ protected function _getCacheKey()
+ {
+ $key = $this->getLayer()->getStateKey()
+ . '_PRICES_GRP_' . Mage::getSingleton('customer/session')->getCustomerGroupId()
+ . '_CURR_' . Mage::app()->getStore()->getCurrentCurrencyCode()
+ . '_ATTR_' . $this->getAttributeModel()->getAttributeCode()
+ . '_LOC_'
+ ;
+ $taxReq = Mage::getSingleton('tax/calculation')->getDefaultRateRequest();
+
+ return $key . implode('_', $taxReq->getData());
+ }
+
+ /**
+ * Get additional request param data
+ *
+ * @return string
+ */
+ protected function _getAdditionalRequestData()
+ {
+ $result = '';
+ $appliedInterval = $this->getInterval();
+ if ($appliedInterval) {
+ $result = ',' . $appliedInterval[0] . '-' . $appliedInterval[1];
+ $priorIntervals = $this->getResetValue();
+ if ($priorIntervals) {
+ $result .= ',' . $priorIntervals;
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Get data generated by algorithm for build price filter items
+ *
+ * @return array
+ */
+ protected function _getCalculatedItemsData()
+ {
+ /** @var Mage_Catalog_Model_Layer_Filter_Price_Algorithm $algorithmModel */
+ $algorithmModel = Mage::getSingleton('catalog/layer_filter_price_algorithm');
+ $collection = $this->getLayer()->getProductCollection();
+ $appliedInterval = $this->getInterval();
+ if ($appliedInterval
+ && $collection->getPricesCount() <= $this->getIntervalDivisionLimit()
+ ) {
+ return [];
+ }
+ $algorithmModel->setPricesModel($this)->setStatistics(
+ $collection->getMinPrice(),
+ $collection->getMaxPrice(),
+ $collection->getPriceStandardDeviation(),
+ $collection->getPricesCount(),
+ );
+
+ if ($appliedInterval) {
+ if ($appliedInterval[0] == $appliedInterval[1] || $appliedInterval[1] === '0') {
+ return [];
+ }
+ $algorithmModel->setLimits($appliedInterval[0], $appliedInterval[1]);
+ }
+
+ $items = [];
+ foreach ($algorithmModel->calculateSeparators() as $separator) {
+ $items[] = [
+ 'label' => $this->_renderRangeLabel($separator['from'], $separator['to']),
+ 'value' => (($separator['from'] == 0) ? '' : $separator['from'])
+ . '-' . $separator['to'] . $this->_getAdditionalRequestData(),
+ 'count' => $separator['count'],
+ ];
+ }
+
+ return $items;
+ }
+
+ /**
+ * Get data for build price filter items
+ *
+ * @return array
+ */
+ protected function _getItemsData()
+ {
+ if (Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_CALCULATION) == self::RANGE_CALCULATION_IMPROVED) {
+ return $this->_getCalculatedItemsData();
+ } elseif ($this->getInterval()) {
+ return [];
+ }
+
+ $range = $this->getPriceRange();
+ $dbRanges = $this->getRangeItemCounts($range);
+ $data = [];
+
+ if (!empty($dbRanges)) {
+ $lastIndex = array_keys($dbRanges);
+ $lastIndex = $lastIndex[count($lastIndex) - 1];
+
+ foreach ($dbRanges as $index => $count) {
+ $fromPrice = ($index == 1) ? '' : (($index - 1) * $range);
+ $toPrice = ($index == $lastIndex) ? '' : ($index * $range);
+
+ $data[] = [
+ 'label' => $this->_renderRangeLabel($fromPrice, $toPrice),
+ 'value' => $fromPrice . '-' . $toPrice,
+ 'count' => $count,
+ ];
+ }
+ }
+
+ return $data;
+ }
+
+ /**
+ * Apply price range filter to collection
+ *
+ * @return $this
+ */
+ protected function _applyPriceRange()
+ {
+ $this->_getResource()->applyPriceRange($this);
+ return $this;
+ }
+
+ /**
+ * Validate and parse filter request param
+ *
+ * @param string $filter
+ * @return array|bool
+ */
+ protected function _validateFilter($filter)
+ {
+ $filter = explode('-', $filter);
+ if (count($filter) != 2) {
+ return false;
+ }
+ foreach ($filter as $v) {
+ if (($v !== '' && $v !== '0' && (float) $v <= 0) || is_infinite((float) $v)) {
+ return false;
+ }
+ }
+
+ return $filter;
+ }
+
+ /**
+ * Apply filter value to product collection based on filter range and selected value
+ *
+ * @deprecated since 1.7.0.0
+ * @param int $range
+ * @param int $index
+ * @return $this
+ */
+ protected function _applyToCollection($range, $index)
+ {
+ $this->_getResource()->applyFilterToCollection($this, $range, $index);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Layer/Filter/Price/Algorithm.php b/app/code/core/Mage/Catalog/Model/Layer/Filter/Price/Algorithm.php
index fe016abe7b4..a095432ae75 100644
--- a/app/code/core/Mage/Catalog/Model/Layer/Filter/Price/Algorithm.php
+++ b/app/code/core/Mage/Catalog/Model/Layer/Filter/Price/Algorithm.php
@@ -135,48 +135,6 @@ public function setLimits($lowerLimit = null, $upperLimit = null)
return $this;
}
- /**
- * Search first index of price, that satisfy conditions to be 'greater or equal' than $value
- * Returns -1 if index was not found
- *
- * @param float $value
- * @param null|array $limits search [from, to]
- * @return int
- */
- protected function _binarySearch($value, $limits = null)
- {
- if (empty($this->_prices)) {
- return -1;
- }
-
- if (!is_array($limits)) {
- $limits = [];
- }
- if (!isset($limits[0])) {
- $limits[0] = 0;
- }
- if (!isset($limits[1])) {
- $limits[1] = count($this->_prices) - 1;
- }
-
- if ($limits[0] > $limits[1] || $this->_prices[$limits[1]] < $value) {
- return -1;
- }
-
- if ($limits[1] - $limits[0] <= 1) {
- return ($this->_prices[$limits[0]] < $value) ? $limits[1] : $limits[0];
- }
-
- $separator = floor(($limits[0] + $limits[1]) / 2);
- if ($this->_prices[$separator] < $value) {
- $limits[0] = $separator + 1;
- } else {
- $limits[1] = $separator;
- }
-
- return $this->_binarySearch($value, [$limits[0], $limits[1]]);
- }
-
/**
* Set prices statistics
*
@@ -235,6 +193,129 @@ public function getIntervalsNumber()
return 1;
}
+ /**
+ * Calculate separators, each contains 'from', 'to' and 'count'
+ *
+ * @return array
+ */
+ public function calculateSeparators()
+ {
+ $result = [];
+ $lastCount = 0;
+ $intervalFirstPrice = $this->_minPrice;
+ $lastSeparator = is_null($this->_lowerLimit) ? 0 : $this->_lowerLimit;
+
+ for ($i = 1; $i < $this->getIntervalsNumber(); ++$i) {
+ $separator = $this->_findPriceSeparator($i);
+ if (empty($separator)) {
+ continue;
+ }
+ if ($this->_quantileInterval[0] == 0) {
+ $intervalFirstPrice = $this->_prices[0];
+ }
+ $separatorCandidate = false;
+ $newIntervalFirstPrice = $intervalFirstPrice;
+ $newLastSeparator = $lastSeparator;
+
+ $pricesPerInterval = $this->_count / $this->_getCalculatedIntervalsNumber();
+ while (!empty($separator) && !array_key_exists($i, $result)) {
+ $separatorsPortion = array_shift($separator);
+ $bestSeparator = $this->_findBestSeparator($i, $separatorsPortion);
+ if ($bestSeparator && $bestSeparator[2] > 0) {
+ $isEqualPrice = ($intervalFirstPrice == $this->_prices[$bestSeparator[2] - 1])
+ ? $this->_prices[0]
+ : false;
+ $count = $bestSeparator[2] + $this->_quantileInterval[0] - $lastCount;
+ $separatorData = [
+ 'from' => ($isEqualPrice !== false) ? $isEqualPrice : $lastSeparator,
+ 'to' => ($isEqualPrice !== false) ? $isEqualPrice : $bestSeparator[1],
+ 'count' => $count,
+ ];
+ if (abs(1 - $count / $pricesPerInterval) <= self::INTERVAL_DEFLECTION_LIMIT) {
+ $newLastSeparator = $bestSeparator[1];
+ $newIntervalFirstPrice = $this->_prices[$bestSeparator[2]];
+ $result[$i] = $separatorData;
+ } elseif (!$separatorCandidate || $bestSeparator[0] < $separatorCandidate[0]) {
+ $separatorCandidate = [
+ $bestSeparator[0],
+ $separatorData,
+ $bestSeparator[1],
+ $this->_prices[$bestSeparator[2]],
+ ];
+ }
+ }
+ }
+
+ if (!array_key_exists($i, $result) && $separatorCandidate) {
+ $newLastSeparator = $separatorCandidate[2];
+ $newIntervalFirstPrice = $separatorCandidate[3];
+ $result[$i] = $separatorCandidate[1];
+ }
+
+ if (array_key_exists($i, $result)) {
+ $lastSeparator = $newLastSeparator;
+ $intervalFirstPrice = $newIntervalFirstPrice;
+ $priceIndex = $this->_binarySearch($lastSeparator);
+ $lastCount += $result[$i]['count'];
+ if ($priceIndex != -1 && $lastSeparator > $this->_lastPriceLimiter[1]) {
+ $this->_lastPriceLimiter = [$priceIndex + $this->_quantileInterval[0], $lastSeparator];
+ }
+ }
+ }
+ if ($this->_lastPriceLimiter[0] < $this->_count) {
+ $isEqualPrice = ($intervalFirstPrice == $this->_maxPrice) ? $intervalFirstPrice : false;
+ $result[$this->getIntervalsNumber()] = [
+ 'from' => $isEqualPrice ? $isEqualPrice : $lastSeparator,
+ 'to' => $isEqualPrice ? $isEqualPrice : (is_null($this->_upperLimit) ? '' : $this->_upperLimit),
+ 'count' => $this->_count - $lastCount,
+ ];
+ }
+
+ return array_values($result);
+ }
+
+ /**
+ * Search first index of price, that satisfy conditions to be 'greater or equal' than $value
+ * Returns -1 if index was not found
+ *
+ * @param float $value
+ * @param null|array $limits search [from, to]
+ * @return int
+ */
+ protected function _binarySearch($value, $limits = null)
+ {
+ if (empty($this->_prices)) {
+ return -1;
+ }
+
+ if (!is_array($limits)) {
+ $limits = [];
+ }
+ if (!isset($limits[0])) {
+ $limits[0] = 0;
+ }
+ if (!isset($limits[1])) {
+ $limits[1] = count($this->_prices) - 1;
+ }
+
+ if ($limits[0] > $limits[1] || $this->_prices[$limits[1]] < $value) {
+ return -1;
+ }
+
+ if ($limits[1] - $limits[0] <= 1) {
+ return ($this->_prices[$limits[0]] < $value) ? $limits[1] : $limits[0];
+ }
+
+ $separator = floor(($limits[0] + $limits[1]) / 2);
+ if ($this->_prices[$separator] < $value) {
+ $limits[0] = $separator + 1;
+ } else {
+ $limits[1] = $separator;
+ }
+
+ return $this->_binarySearch($value, [$limits[0], $limits[1]]);
+ }
+
/**
* Get intervals number with checking skipped quantiles
*
@@ -517,85 +598,4 @@ protected function _findBestSeparator($quantileNumber, $separators)
return $result ? $result : false;
}
-
- /**
- * Calculate separators, each contains 'from', 'to' and 'count'
- *
- * @return array
- */
- public function calculateSeparators()
- {
- $result = [];
- $lastCount = 0;
- $intervalFirstPrice = $this->_minPrice;
- $lastSeparator = is_null($this->_lowerLimit) ? 0 : $this->_lowerLimit;
-
- for ($i = 1; $i < $this->getIntervalsNumber(); ++$i) {
- $separator = $this->_findPriceSeparator($i);
- if (empty($separator)) {
- continue;
- }
- if ($this->_quantileInterval[0] == 0) {
- $intervalFirstPrice = $this->_prices[0];
- }
- $separatorCandidate = false;
- $newIntervalFirstPrice = $intervalFirstPrice;
- $newLastSeparator = $lastSeparator;
-
- $pricesPerInterval = $this->_count / $this->_getCalculatedIntervalsNumber();
- while (!empty($separator) && !array_key_exists($i, $result)) {
- $separatorsPortion = array_shift($separator);
- $bestSeparator = $this->_findBestSeparator($i, $separatorsPortion);
- if ($bestSeparator && $bestSeparator[2] > 0) {
- $isEqualPrice = ($intervalFirstPrice == $this->_prices[$bestSeparator[2] - 1])
- ? $this->_prices[0]
- : false;
- $count = $bestSeparator[2] + $this->_quantileInterval[0] - $lastCount;
- $separatorData = [
- 'from' => ($isEqualPrice !== false) ? $isEqualPrice : $lastSeparator,
- 'to' => ($isEqualPrice !== false) ? $isEqualPrice : $bestSeparator[1],
- 'count' => $count,
- ];
- if (abs(1 - $count / $pricesPerInterval) <= self::INTERVAL_DEFLECTION_LIMIT) {
- $newLastSeparator = $bestSeparator[1];
- $newIntervalFirstPrice = $this->_prices[$bestSeparator[2]];
- $result[$i] = $separatorData;
- } elseif (!$separatorCandidate || $bestSeparator[0] < $separatorCandidate[0]) {
- $separatorCandidate = [
- $bestSeparator[0],
- $separatorData,
- $bestSeparator[1],
- $this->_prices[$bestSeparator[2]],
- ];
- }
- }
- }
-
- if (!array_key_exists($i, $result) && $separatorCandidate) {
- $newLastSeparator = $separatorCandidate[2];
- $newIntervalFirstPrice = $separatorCandidate[3];
- $result[$i] = $separatorCandidate[1];
- }
-
- if (array_key_exists($i, $result)) {
- $lastSeparator = $newLastSeparator;
- $intervalFirstPrice = $newIntervalFirstPrice;
- $priceIndex = $this->_binarySearch($lastSeparator);
- $lastCount += $result[$i]['count'];
- if ($priceIndex != -1 && $lastSeparator > $this->_lastPriceLimiter[1]) {
- $this->_lastPriceLimiter = [$priceIndex + $this->_quantileInterval[0], $lastSeparator];
- }
- }
- }
- if ($this->_lastPriceLimiter[0] < $this->_count) {
- $isEqualPrice = ($intervalFirstPrice == $this->_maxPrice) ? $intervalFirstPrice : false;
- $result[$this->getIntervalsNumber()] = [
- 'from' => $isEqualPrice ? $isEqualPrice : $lastSeparator,
- 'to' => $isEqualPrice ? $isEqualPrice : (is_null($this->_upperLimit) ? '' : $this->_upperLimit),
- 'count' => $this->_count - $lastCount,
- ];
- }
-
- return array_values($result);
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Observer.php b/app/code/core/Mage/Catalog/Model/Observer.php
index 1dac955cc34..8de74babf96 100644
--- a/app/code/core/Mage/Catalog/Model/Observer.php
+++ b/app/code/core/Mage/Catalog/Model/Observer.php
@@ -193,6 +193,27 @@ public function addCatalogToTopmenuItems(Varien_Event_Observer $observer)
);
}
+ /**
+ * Checks whether attribute_code by current module is reserved
+ *
+ * @throws Mage_Core_Exception
+ */
+ public function checkReservedAttributeCodes(Varien_Event_Observer $observer)
+ {
+ /** @var Mage_Catalog_Model_Entity_Attribute $attribute */
+ $attribute = $observer->getEvent()->getAttribute();
+ if (!is_object($attribute)) {
+ return;
+ }
+ /** @var Mage_Catalog_Model_Product $product */
+ $product = Mage::getModel('catalog/product');
+ if ($product->isReservedAttribute($attribute)) {
+ throw new Mage_Core_Exception(
+ Mage::helper('catalog')->__('The attribute code \'%s\' is reserved by system. Please try another attribute code', $attribute->getAttributeCode()),
+ );
+ }
+ }
+
/**
* Recursively adds categories to top menu
*
@@ -258,25 +279,4 @@ protected function _isActiveMenuCategory($category)
$categoryPathIds = explode(',', $currentCategory->getPathInStore());
return in_array($category->getId(), $categoryPathIds);
}
-
- /**
- * Checks whether attribute_code by current module is reserved
- *
- * @throws Mage_Core_Exception
- */
- public function checkReservedAttributeCodes(Varien_Event_Observer $observer)
- {
- /** @var Mage_Catalog_Model_Entity_Attribute $attribute */
- $attribute = $observer->getEvent()->getAttribute();
- if (!is_object($attribute)) {
- return;
- }
- /** @var Mage_Catalog_Model_Product $product */
- $product = Mage::getModel('catalog/product');
- if ($product->isReservedAttribute($attribute)) {
- throw new Mage_Core_Exception(
- Mage::helper('catalog')->__('The attribute code \'%s\' is reserved by system. Please try another attribute code', $attribute->getAttributeCode()),
- );
- }
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product.php b/app/code/core/Mage/Catalog/Model/Product.php
index 6575b88c859..cb5d7f903f1 100644
--- a/app/code/core/Mage/Catalog/Model/Product.php
+++ b/app/code/core/Mage/Catalog/Model/Product.php
@@ -341,25 +341,6 @@ class Mage_Catalog_Model_Product extends Mage_Catalog_Model_Abstract
protected ?string $locale = null;
- /**
- * Initialize resources
- */
- protected function _construct()
- {
- $this->_init('catalog/product');
- }
-
- /**
- * Init mapping array of short fields to
- * its full names
- *
- * @return Varien_Object
- */
- protected function _initOldFieldsMap()
- {
- return $this;
- }
-
/**
* Retrieve Store Id
*
@@ -717,71 +698,6 @@ public function setStockItem($stockItem)
return $this;
}
- /**
- * Check product options and type options and save them, too
- *
- * @throws Mage_Core_Exception
- */
- protected function _beforeSave()
- {
- $this->cleanCache();
- $this->setTypeHasOptions(false);
- $this->setTypeHasRequiredOptions(false);
-
- $this->getTypeInstance(true)->beforeSave($this);
-
- $hasOptions = false;
- $hasRequiredOptions = false;
-
- /**
- * $this->_canAffectOptions - set by type instance only
- * $this->getCanSaveCustomOptions() - set either in controller when "Custom Options" ajax tab is loaded,
- * or in type instance as well
- */
- $this->canAffectOptions($this->_canAffectOptions && $this->getCanSaveCustomOptions());
- if ($this->getCanSaveCustomOptions()) {
- $options = $this->getProductOptions();
- if (is_array($options)) {
- $this->setIsCustomOptionChanged(true);
- foreach ($this->getProductOptions() as $option) {
- $this->getOptionInstance()->addOption($option);
- if ((!isset($option['is_delete'])) || $option['is_delete'] != '1') {
- if (!empty($option['file_extension'])) {
- $fileExtension = $option['file_extension'];
- if (strcmp($fileExtension, Mage::helper('core')->removeTags($fileExtension)) !== 0) {
- Mage::throwException(Mage::helper('catalog')->__('Invalid custom option(s).'));
- }
- }
- $hasOptions = true;
- }
- }
- foreach ($this->getOptionInstance()->getOptions() as $option) {
- if ($option['is_require'] == '1') {
- $hasRequiredOptions = true;
- break;
- }
- }
- }
- }
-
- /**
- * Set true, if any
- * Set false, ONLY if options have been affected by Options tab and Type instance tab
- */
- if ($hasOptions || (bool) $this->getTypeHasOptions()) {
- $this->setHasOptions(true);
- if ($hasRequiredOptions || (bool) $this->getTypeHasRequiredOptions()) {
- $this->setRequiredOptions(true);
- } elseif ($this->canAffectOptions()) {
- $this->setRequiredOptions(false);
- }
- } elseif ($this->canAffectOptions()) {
- $this->setHasOptions(false);
- $this->setRequiredOptions(false);
- }
- return parent::_beforeSave();
- }
-
/**
* Check/set if options can be affected when saving product
* If value specified, it will be set.
@@ -797,73 +713,6 @@ public function canAffectOptions($value = null)
return $this->_canAffectOptions;
}
- /**
- * Saving product type related data and init index
- *
- * @inheritDoc
- */
- protected function _afterSave()
- {
- $this->getLinkInstance()->saveProductRelations($this);
- $this->getTypeInstance(true)->save($this);
-
- /**
- * Product Options
- */
- $this->getOptionInstance()->setProduct($this)
- ->saveOptions();
-
- return parent::_afterSave();
- }
-
- /**
- * Clear cache related with product and protect delete from not admin
- * Register indexing event before delete product
- *
- * @inheritDoc
- */
- protected function _beforeDelete()
- {
- $this->_protectFromNonAdmin();
- $this->cleanCache();
-
- return parent::_beforeDelete();
- }
-
- /**
- * Init indexing process after product delete commit
- */
- protected function _afterDeleteCommit()
- {
- parent::_afterDeleteCommit();
-
- /** @var \Mage_Index_Model_Indexer $indexer */
- $indexer = Mage::getSingleton('index/indexer');
-
- $indexer->processEntityAction($this, self::ENTITY, Mage_Index_Model_Event::TYPE_DELETE);
- return $this;
- }
-
- /**
- * Load product options if they exists
- *
- * @return $this
- */
- protected function _afterLoad()
- {
- parent::_afterLoad();
- /**
- * Load product options
- */
- if ($this->getHasOptions()) {
- foreach ($this->getProductOptionsCollection() as $option) {
- $option->setProduct($this);
- $this->addOption($option);
- }
- }
- return $this;
- }
-
/**
* Clear cache related with product id
*
@@ -2024,16 +1873,6 @@ public function getDefaultAttributeSetId()
return $this->getResource()->getEntityType()->getDefaultAttributeSetId();
}
- /**
- * Return Catalog Product Image helper instance
- *
- * @return Mage_Catalog_Helper_Image
- */
- protected function _getImageHelper()
- {
- return Mage::helper('catalog/image');
- }
-
/**
* Return re-sized image URL
*
@@ -2247,73 +2086,6 @@ public function prepareCustomOptions()
return $this;
}
- /**
- * Clearing references on product
- *
- * @return $this
- */
- protected function _clearReferences()
- {
- $this->_clearOptionReferences();
- return $this;
- }
-
- /**
- * Clearing product's data
- *
- * @return $this
- */
- protected function _clearData()
- {
- foreach ($this->_data as $data) {
- if (is_object($data) && method_exists($data, 'reset')) {
- $data->reset();
- }
- }
-
- $this->setData([]);
- $this->setOrigData();
- $this->_customOptions = [];
- $this->_optionInstance = null;
- $this->_options = [];
- $this->_canAffectOptions = false;
- $this->_errors = [];
- $this->_defaultValues = [];
- $this->_storeValuesFlags = [];
- $this->_lockedAttributes = [];
- $this->_typeInstance = null;
- $this->_typeInstanceSingleton = null;
- $this->_linkInstance = null;
- $this->_reservedAttributes = null;
- $this->_isDuplicable = true;
- $this->_calculatePrice = true;
- $this->_stockItem = null;
- $this->_isDeleteable = true;
- $this->_isReadonly = false;
-
- return $this;
- }
-
- /**
- * Clearing references to product from product's options
- *
- * @return $this
- */
- protected function _clearOptionReferences()
- {
- /**
- * unload product options
- */
- if (!empty($this->_options)) {
- foreach ($this->_options as $key => $option) {
- $option->setProduct();
- $option->clearInstance();
- }
- }
-
- return $this;
- }
-
/**
* Retrieve product entities info as array
*
@@ -2380,4 +2152,232 @@ public function getReviewSummary($storeId = null)
}
return $this->_reviewSummary[$storeId];
}
+
+ /**
+ * Initialize resources
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product');
+ }
+
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return Varien_Object
+ */
+ protected function _initOldFieldsMap()
+ {
+ return $this;
+ }
+
+ /**
+ * Check product options and type options and save them, too
+ *
+ * @throws Mage_Core_Exception
+ */
+ protected function _beforeSave()
+ {
+ $this->cleanCache();
+ $this->setTypeHasOptions(false);
+ $this->setTypeHasRequiredOptions(false);
+
+ $this->getTypeInstance(true)->beforeSave($this);
+
+ $hasOptions = false;
+ $hasRequiredOptions = false;
+
+ /**
+ * $this->_canAffectOptions - set by type instance only
+ * $this->getCanSaveCustomOptions() - set either in controller when "Custom Options" ajax tab is loaded,
+ * or in type instance as well
+ */
+ $this->canAffectOptions($this->_canAffectOptions && $this->getCanSaveCustomOptions());
+ if ($this->getCanSaveCustomOptions()) {
+ $options = $this->getProductOptions();
+ if (is_array($options)) {
+ $this->setIsCustomOptionChanged(true);
+ foreach ($this->getProductOptions() as $option) {
+ $this->getOptionInstance()->addOption($option);
+ if ((!isset($option['is_delete'])) || $option['is_delete'] != '1') {
+ if (!empty($option['file_extension'])) {
+ $fileExtension = $option['file_extension'];
+ if (strcmp($fileExtension, Mage::helper('core')->removeTags($fileExtension)) !== 0) {
+ Mage::throwException(Mage::helper('catalog')->__('Invalid custom option(s).'));
+ }
+ }
+ $hasOptions = true;
+ }
+ }
+ foreach ($this->getOptionInstance()->getOptions() as $option) {
+ if ($option['is_require'] == '1') {
+ $hasRequiredOptions = true;
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Set true, if any
+ * Set false, ONLY if options have been affected by Options tab and Type instance tab
+ */
+ if ($hasOptions || (bool) $this->getTypeHasOptions()) {
+ $this->setHasOptions(true);
+ if ($hasRequiredOptions || (bool) $this->getTypeHasRequiredOptions()) {
+ $this->setRequiredOptions(true);
+ } elseif ($this->canAffectOptions()) {
+ $this->setRequiredOptions(false);
+ }
+ } elseif ($this->canAffectOptions()) {
+ $this->setHasOptions(false);
+ $this->setRequiredOptions(false);
+ }
+ return parent::_beforeSave();
+ }
+
+ /**
+ * Saving product type related data and init index
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave()
+ {
+ $this->getLinkInstance()->saveProductRelations($this);
+ $this->getTypeInstance(true)->save($this);
+
+ /**
+ * Product Options
+ */
+ $this->getOptionInstance()->setProduct($this)
+ ->saveOptions();
+
+ return parent::_afterSave();
+ }
+
+ /**
+ * Clear cache related with product and protect delete from not admin
+ * Register indexing event before delete product
+ *
+ * @inheritDoc
+ */
+ protected function _beforeDelete()
+ {
+ $this->_protectFromNonAdmin();
+ $this->cleanCache();
+
+ return parent::_beforeDelete();
+ }
+
+ /**
+ * Init indexing process after product delete commit
+ */
+ protected function _afterDeleteCommit()
+ {
+ parent::_afterDeleteCommit();
+
+ /** @var \Mage_Index_Model_Indexer $indexer */
+ $indexer = Mage::getSingleton('index/indexer');
+
+ $indexer->processEntityAction($this, self::ENTITY, Mage_Index_Model_Event::TYPE_DELETE);
+ return $this;
+ }
+
+ /**
+ * Load product options if they exists
+ *
+ * @return $this
+ */
+ protected function _afterLoad()
+ {
+ parent::_afterLoad();
+ /**
+ * Load product options
+ */
+ if ($this->getHasOptions()) {
+ foreach ($this->getProductOptionsCollection() as $option) {
+ $option->setProduct($this);
+ $this->addOption($option);
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Return Catalog Product Image helper instance
+ *
+ * @return Mage_Catalog_Helper_Image
+ */
+ protected function _getImageHelper()
+ {
+ return Mage::helper('catalog/image');
+ }
+
+ /**
+ * Clearing references on product
+ *
+ * @return $this
+ */
+ protected function _clearReferences()
+ {
+ $this->_clearOptionReferences();
+ return $this;
+ }
+
+ /**
+ * Clearing product's data
+ *
+ * @return $this
+ */
+ protected function _clearData()
+ {
+ foreach ($this->_data as $data) {
+ if (is_object($data) && method_exists($data, 'reset')) {
+ $data->reset();
+ }
+ }
+
+ $this->setData([]);
+ $this->setOrigData();
+ $this->_customOptions = [];
+ $this->_optionInstance = null;
+ $this->_options = [];
+ $this->_canAffectOptions = false;
+ $this->_errors = [];
+ $this->_defaultValues = [];
+ $this->_storeValuesFlags = [];
+ $this->_lockedAttributes = [];
+ $this->_typeInstance = null;
+ $this->_typeInstanceSingleton = null;
+ $this->_linkInstance = null;
+ $this->_reservedAttributes = null;
+ $this->_isDuplicable = true;
+ $this->_calculatePrice = true;
+ $this->_stockItem = null;
+ $this->_isDeleteable = true;
+ $this->_isReadonly = false;
+
+ return $this;
+ }
+
+ /**
+ * Clearing references to product from product's options
+ *
+ * @return $this
+ */
+ protected function _clearOptionReferences()
+ {
+ /**
+ * unload product options
+ */
+ if (!empty($this->_options)) {
+ foreach ($this->_options as $key => $option) {
+ $option->setProduct();
+ $option->clearInstance();
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Action.php b/app/code/core/Mage/Catalog/Model/Product/Action.php
index a0a515c4de7..d3af68e41f3 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Action.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Action.php
@@ -25,11 +25,6 @@
*/
class Mage_Catalog_Model_Product_Action extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product_action');
- }
-
/**
* Update attribute values for entity list per store
*
@@ -112,4 +107,8 @@ public function updateWebsites($productIds, $websiteIds, $type)
'action' => $type,
]);
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product_action');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Api.php b/app/code/core/Mage/Catalog/Model/Product/Api.php
index 05fe497d0d7..cbd462fe4f4 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Api.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Api.php
@@ -250,79 +250,6 @@ public function update($productId, $productData, $store = null, $identifierType
return true;
}
- /**
- * Set additional data before product saved
- *
- * @param Mage_Catalog_Model_Product $product
- * @param array $productData
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _prepareDataForSave($product, $productData)
- {
- if (isset($productData['website_ids']) && is_array($productData['website_ids'])) {
- $product->setWebsiteIds($productData['website_ids']);
- }
-
- foreach ($product->getTypeInstance(true)->getEditableAttributes($product) as $attribute) {
- //Unset data if object attribute has no value in current store
- if (Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID !== (int) $product->getStoreId()
- && !$product->getExistsStoreValueFlag($attribute->getAttributeCode())
- && !$attribute->isScopeGlobal()
- ) {
- $product->setData($attribute->getAttributeCode(), false);
- }
-
- if ($this->_isAllowedAttribute($attribute)) {
- if (isset($productData[$attribute->getAttributeCode()])) {
- $product->setData(
- $attribute->getAttributeCode(),
- $productData[$attribute->getAttributeCode()],
- );
- } elseif (isset($productData['additional_attributes']['single_data'][$attribute->getAttributeCode()])) {
- $product->setData(
- $attribute->getAttributeCode(),
- $productData['additional_attributes']['single_data'][$attribute->getAttributeCode()],
- );
- } elseif (isset($productData['additional_attributes']['multi_data'][$attribute->getAttributeCode()])) {
- $product->setData(
- $attribute->getAttributeCode(),
- $productData['additional_attributes']['multi_data'][$attribute->getAttributeCode()],
- );
- }
- }
- }
-
- if (isset($productData['categories']) && is_array($productData['categories'])) {
- $product->setCategoryIds($productData['categories']);
- }
-
- if (isset($productData['websites']) && is_array($productData['websites'])) {
- foreach ($productData['websites'] as &$website) {
- if (is_string($website)) {
- try {
- $website = Mage::app()->getWebsite($website)->getId();
- } catch (Exception $e) {
- }
- }
- }
- $product->setWebsiteIds($productData['websites']);
- }
-
- if (Mage::app()->isSingleStoreMode()) {
- $product->setWebsiteIds([Mage::app()->getStore(true)->getWebsite()->getId()]);
- }
-
- if (isset($productData['stock_data']) && is_array($productData['stock_data'])) {
- $product->setStockData($productData['stock_data']);
- }
-
- if (isset($productData['tier_price']) && is_array($productData['tier_price'])) {
- $tierPrices = Mage::getModel('catalog/product_attribute_tierprice_api')
- ->prepareTierPrices($product, $productData['tier_price']);
- $product->setData(Mage_Catalog_Model_Product_Attribute_Tierprice_Api::ATTRIBUTE_CODE, $tierPrices);
- }
- }
-
/**
* Update product special price
*
@@ -426,6 +353,79 @@ public function getAdditionalAttributes($productType, $attributeSetId)
return $result;
}
+ /**
+ * Set additional data before product saved
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param array $productData
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _prepareDataForSave($product, $productData)
+ {
+ if (isset($productData['website_ids']) && is_array($productData['website_ids'])) {
+ $product->setWebsiteIds($productData['website_ids']);
+ }
+
+ foreach ($product->getTypeInstance(true)->getEditableAttributes($product) as $attribute) {
+ //Unset data if object attribute has no value in current store
+ if (Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID !== (int) $product->getStoreId()
+ && !$product->getExistsStoreValueFlag($attribute->getAttributeCode())
+ && !$attribute->isScopeGlobal()
+ ) {
+ $product->setData($attribute->getAttributeCode(), false);
+ }
+
+ if ($this->_isAllowedAttribute($attribute)) {
+ if (isset($productData[$attribute->getAttributeCode()])) {
+ $product->setData(
+ $attribute->getAttributeCode(),
+ $productData[$attribute->getAttributeCode()],
+ );
+ } elseif (isset($productData['additional_attributes']['single_data'][$attribute->getAttributeCode()])) {
+ $product->setData(
+ $attribute->getAttributeCode(),
+ $productData['additional_attributes']['single_data'][$attribute->getAttributeCode()],
+ );
+ } elseif (isset($productData['additional_attributes']['multi_data'][$attribute->getAttributeCode()])) {
+ $product->setData(
+ $attribute->getAttributeCode(),
+ $productData['additional_attributes']['multi_data'][$attribute->getAttributeCode()],
+ );
+ }
+ }
+ }
+
+ if (isset($productData['categories']) && is_array($productData['categories'])) {
+ $product->setCategoryIds($productData['categories']);
+ }
+
+ if (isset($productData['websites']) && is_array($productData['websites'])) {
+ foreach ($productData['websites'] as &$website) {
+ if (is_string($website)) {
+ try {
+ $website = Mage::app()->getWebsite($website)->getId();
+ } catch (Exception $e) {
+ }
+ }
+ }
+ $product->setWebsiteIds($productData['websites']);
+ }
+
+ if (Mage::app()->isSingleStoreMode()) {
+ $product->setWebsiteIds([Mage::app()->getStore(true)->getWebsite()->getId()]);
+ }
+
+ if (isset($productData['stock_data']) && is_array($productData['stock_data'])) {
+ $product->setStockData($productData['stock_data']);
+ }
+
+ if (isset($productData['tier_price']) && is_array($productData['tier_price'])) {
+ $tierPrices = Mage::getModel('catalog/product_attribute_tierprice_api')
+ ->prepareTierPrices($product, $productData['tier_price']);
+ $product->setData(Mage_Catalog_Model_Product_Attribute_Tierprice_Api::ATTRIBUTE_CODE, $tierPrices);
+ }
+ }
+
/**
* Check if product type exists
*
diff --git a/app/code/core/Mage/Catalog/Model/Product/Api/V2.php b/app/code/core/Mage/Catalog/Model/Product/Api/V2.php
index b752bdca6a1..2ddcadb8d57 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Api/V2.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Api/V2.php
@@ -224,6 +224,33 @@ public function multiUpdate($productIds, $productData, $store = null, $identifie
$this->_fault('partially_updated', implode("\n", $failMessages));
}
+ /**
+ * Update product special priceim
+ *
+ * @param int|string $productId
+ * @param float $specialPrice
+ * @param string $fromDate
+ * @param string $toDate
+ * @param string|int $store
+ * @param string $identifierType OPTIONAL If 'sku' - search product by SKU, if any except for NULL - search by ID,
+ * otherwise - try to determine identifier type automatically
+ * @return bool
+ */
+ public function setSpecialPrice(
+ $productId,
+ $specialPrice = null,
+ $fromDate = null,
+ $toDate = null,
+ $store = null,
+ $identifierType = null
+ ) {
+ $obj = new stdClass();
+ $obj->special_price = $specialPrice;
+ $obj->special_from_date = $fromDate;
+ $obj->special_to_date = $toDate;
+ return $this->update($productId, $obj, $store, $identifierType);
+ }
+
/**
* Set additional data before product saved
*
@@ -311,31 +338,4 @@ protected function _prepareDataForSave($product, $productData)
$product->setData(Mage_Catalog_Model_Product_Attribute_Tierprice_Api_V2::ATTRIBUTE_CODE, $tierPrices);
}
}
-
- /**
- * Update product special priceim
- *
- * @param int|string $productId
- * @param float $specialPrice
- * @param string $fromDate
- * @param string $toDate
- * @param string|int $store
- * @param string $identifierType OPTIONAL If 'sku' - search product by SKU, if any except for NULL - search by ID,
- * otherwise - try to determine identifier type automatically
- * @return bool
- */
- public function setSpecialPrice(
- $productId,
- $specialPrice = null,
- $fromDate = null,
- $toDate = null,
- $store = null,
- $identifierType = null
- ) {
- $obj = new stdClass();
- $obj->special_price = $specialPrice;
- $obj->special_from_date = $fromDate;
- $obj->special_to_date = $toDate;
- return $this->update($productId, $obj, $store, $identifierType);
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Groupprice/Abstract.php b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Groupprice/Abstract.php
index f38f7f3ad31..4a408b6c613 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Groupprice/Abstract.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Groupprice/Abstract.php
@@ -32,79 +32,6 @@ abstract class Mage_Catalog_Model_Product_Attribute_Backend_Groupprice_Abstract
*/
protected $_rates;
- /**
- * Error message when duplicates
- *
- * @abstract
- * @return string
- */
- abstract protected function _getDuplicateErrorMessage();
-
- /**
- * Retrieve websites currency rates and base currency codes
- *
- * @param int|null $websiteId
- * @return array
- */
- protected function _getWebsiteCurrencyRates($websiteId = null)
- {
- if (is_null($this->_rates)) {
- $this->_rates = [];
- $baseCurrency = Mage::app()->getBaseCurrencyCode();
-
- if (is_numeric($websiteId)) {
- $website = Mage::app()->getWebsite($websiteId);
- $websites = [$website];
- } else {
- $websites = Mage::app()->getWebsites();
- }
-
- foreach ($websites as $website) {
- /** @var Mage_Core_Model_Website $website */
- if ($website->getBaseCurrencyCode() != $baseCurrency) {
- $rate = Mage::getModel('directory/currency')
- ->load($baseCurrency)
- ->getRate($website->getBaseCurrencyCode());
- if (!$rate) {
- $rate = 1;
- }
- $this->_rates[$website->getId()] = [
- 'code' => $website->getBaseCurrencyCode(),
- 'rate' => $rate,
- ];
- } else {
- $this->_rates[$website->getId()] = [
- 'code' => $baseCurrency,
- 'rate' => 1,
- ];
- }
- }
- }
- return $this->_rates;
- }
-
- /**
- * Get additional unique fields
- *
- * @param array $objectArray
- * @return array
- */
- protected function _getAdditionalUniqueFields($objectArray)
- {
- return [];
- }
-
- /**
- * Whether group price value fixed or percent of original price
- *
- * @param Mage_Catalog_Model_Product_Type_Price $priceObject
- * @return bool
- */
- protected function _isPriceFixed($priceObject)
- {
- return $priceObject->isGroupPriceFixed();
- }
-
/**
* Validate group price data
*
@@ -367,4 +294,77 @@ public function afterSave($object)
return $this;
}
+
+ /**
+ * Error message when duplicates
+ *
+ * @abstract
+ * @return string
+ */
+ abstract protected function _getDuplicateErrorMessage();
+
+ /**
+ * Retrieve websites currency rates and base currency codes
+ *
+ * @param int|null $websiteId
+ * @return array
+ */
+ protected function _getWebsiteCurrencyRates($websiteId = null)
+ {
+ if (is_null($this->_rates)) {
+ $this->_rates = [];
+ $baseCurrency = Mage::app()->getBaseCurrencyCode();
+
+ if (is_numeric($websiteId)) {
+ $website = Mage::app()->getWebsite($websiteId);
+ $websites = [$website];
+ } else {
+ $websites = Mage::app()->getWebsites();
+ }
+
+ foreach ($websites as $website) {
+ /** @var Mage_Core_Model_Website $website */
+ if ($website->getBaseCurrencyCode() != $baseCurrency) {
+ $rate = Mage::getModel('directory/currency')
+ ->load($baseCurrency)
+ ->getRate($website->getBaseCurrencyCode());
+ if (!$rate) {
+ $rate = 1;
+ }
+ $this->_rates[$website->getId()] = [
+ 'code' => $website->getBaseCurrencyCode(),
+ 'rate' => $rate,
+ ];
+ } else {
+ $this->_rates[$website->getId()] = [
+ 'code' => $baseCurrency,
+ 'rate' => 1,
+ ];
+ }
+ }
+ }
+ return $this->_rates;
+ }
+
+ /**
+ * Get additional unique fields
+ *
+ * @param array $objectArray
+ * @return array
+ */
+ protected function _getAdditionalUniqueFields($objectArray)
+ {
+ return [];
+ }
+
+ /**
+ * Whether group price value fixed or percent of original price
+ *
+ * @param Mage_Catalog_Model_Product_Type_Price $priceObject
+ * @return bool
+ */
+ protected function _isPriceFixed($priceObject)
+ {
+ return $priceObject->isGroupPriceFixed();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php
index 3661849c4bf..1b56d96d2dd 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php
@@ -57,16 +57,6 @@ public function afterLoad($object)
return $this;
}
- /**
- * @param string $key
- * @param array $image
- * @return string
- */
- protected function _getDefaultValue($key, &$image)
- {
- return $image[$key . '_default'] ?? '';
- }
-
/**
* Validate media_gallery attribute data
*
@@ -554,6 +544,39 @@ public function setMediaAttribute(Mage_Catalog_Model_Product $product, $mediaAtt
return $this;
}
+ /**
+ * @param Mage_Catalog_Model_Product $object
+ * @return $this
+ */
+ public function duplicate($object)
+ {
+ $attrCode = $this->getAttribute()->getAttributeCode();
+ $mediaGalleryData = $object->getData($attrCode);
+
+ if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) {
+ return $this;
+ }
+
+ $this->_getResource()->duplicate(
+ $this,
+ $mediaGalleryData['duplicate'] ?? [],
+ $object->getOriginalId(),
+ $object->getId(),
+ );
+
+ return $this;
+ }
+
+ /**
+ * @param string $key
+ * @param array $image
+ * @return string
+ */
+ protected function _getDefaultValue($key, &$image)
+ {
+ return $image[$key . '_default'] ?? '';
+ }
+
/**
* Retrieve resource model
*
@@ -688,29 +711,6 @@ protected function _copyImage($file)
return str_replace($ioObject->dirsep(), '/', $destFile);
}
- /**
- * @param Mage_Catalog_Model_Product $object
- * @return $this
- */
- public function duplicate($object)
- {
- $attrCode = $this->getAttribute()->getAttributeCode();
- $mediaGalleryData = $object->getData($attrCode);
-
- if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) {
- return $this;
- }
-
- $this->_getResource()->duplicate(
- $this,
- $mediaGalleryData['duplicate'] ?? [],
- $object->getOriginalId(),
- $object->getId(),
- );
-
- return $this;
- }
-
/**
* Get filename which is not duplicated with other files in media temporary and media directories
*
diff --git a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Startdate.php b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Startdate.php
index ecc7378d624..5b845ec3426 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Startdate.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Startdate.php
@@ -23,18 +23,6 @@
*/
class Mage_Catalog_Model_Product_Attribute_Backend_Startdate extends Mage_Eav_Model_Entity_Attribute_Backend_Datetime
{
- /**
- * Get attribute value for save.
- *
- * @param Varien_Object $object
- * @return string|bool
- */
- protected function _getValueForSave($object)
- {
- $attributeName = $this->getAttribute()->getName();
- return $object->getData($attributeName);
- }
-
/**
* Before save hook.
* Prepare attribute value for save
@@ -83,4 +71,15 @@ public function validate($object)
}
return true;
}
+ /**
+ * Get attribute value for save.
+ *
+ * @param Varien_Object $object
+ * @return string|bool
+ */
+ protected function _getValueForSave($object)
+ {
+ $attributeName = $this->getAttribute()->getName();
+ return $object->getData($attributeName);
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Startdate/Specialprice.php b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Startdate/Specialprice.php
index e939cee01da..6e45e580549 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Startdate/Specialprice.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Startdate/Specialprice.php
@@ -23,6 +23,24 @@
*/
class Mage_Catalog_Model_Product_Attribute_Backend_Startdate_Specialprice extends Mage_Catalog_Model_Product_Attribute_Backend_Startdate
{
+ /**
+ * Before save hook.
+ * Prepare attribute value for save
+ *
+ * @param Varien_Object $object
+ * @return Mage_Catalog_Model_Product_Attribute_Backend_Startdate
+ */
+ public function beforeSave($object)
+ {
+ $startDate = $this->_getValueForSave($object);
+ if ($startDate === false) {
+ return $this;
+ }
+
+ $object->setData($this->getAttribute()->getName(), $startDate);
+ parent::beforeSave($object);
+ return $this;
+ }
/**
* Get attribute value for save.
*
@@ -42,23 +60,4 @@ protected function _getValueForSave($object)
return $startDate;
}
-
- /**
- * Before save hook.
- * Prepare attribute value for save
- *
- * @param Varien_Object $object
- * @return Mage_Catalog_Model_Product_Attribute_Backend_Startdate
- */
- public function beforeSave($object)
- {
- $startDate = $this->_getValueForSave($object);
- if ($startDate === false) {
- return $this;
- }
-
- $object->setData($this->getAttribute()->getName(), $startDate);
- parent::beforeSave($object);
- return $this;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Tierprice.php b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Tierprice.php
index 90d40f26876..1a6118a3318 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Tierprice.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Tierprice.php
@@ -22,16 +22,6 @@
*/
class Mage_Catalog_Model_Product_Attribute_Backend_Tierprice extends Mage_Catalog_Model_Product_Attribute_Backend_Groupprice_Abstract
{
- /**
- * Retrieve resource instance
- *
- * @return Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice
- */
- protected function _getResource()
- {
- return Mage::getResourceSingleton('catalog/product_attribute_backend_tierprice');
- }
-
/**
* Retrieve websites rates and base currency codes
*
@@ -42,6 +32,15 @@ public function _getWebsiteRates()
{
return $this->_getWebsiteCurrencyRates();
}
+ /**
+ * Retrieve resource instance
+ *
+ * @return Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice
+ */
+ protected function _getResource()
+ {
+ return Mage::getResourceSingleton('catalog/product_attribute_backend_tierprice');
+ }
/**
* Add price qty to unique fields
diff --git a/app/code/core/Mage/Catalog/Model/Product/Compare/Item.php b/app/code/core/Mage/Catalog/Model/Product/Compare/Item.php
index 5b3633e7b1d..75f472a89b7 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Compare/Item.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Compare/Item.php
@@ -58,26 +58,6 @@ class Mage_Catalog_Model_Product_Compare_Item extends Mage_Core_Model_Abstract
*/
protected $_eventObject = 'item';
- protected function _construct()
- {
- $this->_init('catalog/product_compare_item');
- }
-
- /**
- * Set current store before save
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
- if (!$this->hasStoreId()) {
- $this->setStoreId(Mage::app()->getStore()->getId());
- }
-
- return $this;
- }
-
/**
* Save object data
*
@@ -222,4 +202,24 @@ public function getVisitorId()
}
return $this->getData('visitor_id');
}
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product_compare_item');
+ }
+
+ /**
+ * Set current store before save
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ if (!$this->hasStoreId()) {
+ $this->setStoreId(Mage::app()->getStore()->getId());
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Compare/List.php b/app/code/core/Mage/Catalog/Model/Product/Compare/List.php
index 97571b0bbd8..646ad4c4b86 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Compare/List.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Compare/List.php
@@ -89,6 +89,19 @@ public function removeProduct($product)
return $this;
}
+ /**
+ * Check has compare items by visitor/customer
+ *
+ * @param int $customerId
+ * @param int $visitorId
+ * @return bool
+ */
+ public function hasItems($customerId, $visitorId)
+ {
+ return Mage::getResourceSingleton('catalog/product_compare_item')
+ ->getCount($customerId, $visitorId);
+ }
+
/**
* Add visitor and customer data to compare item
*
@@ -104,17 +117,4 @@ protected function _addVisitorToItem($item)
return $this;
}
-
- /**
- * Check has compare items by visitor/customer
- *
- * @param int $customerId
- * @param int $visitorId
- * @return bool
- */
- public function hasItems($customerId, $visitorId)
- {
- return Mage::getResourceSingleton('catalog/product_compare_item')
- ->getCount($customerId, $visitorId);
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Flat/Indexer.php b/app/code/core/Mage/Catalog/Model/Product/Flat/Indexer.php
index 0fd0a8e7f22..15b93816bd2 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Flat/Indexer.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Flat/Indexer.php
@@ -51,15 +51,6 @@ class Mage_Catalog_Model_Product_Flat_Indexer extends Mage_Core_Model_Abstract
*/
public const EVENT_TYPE_REBUILD = 'catalog_product_flat_rebuild';
- /**
- * Standard model resource initialization
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/product_flat_indexer');
- }
-
/**
* Rebuild Catalog Product Flat Data
*
@@ -293,4 +284,13 @@ public function getAttributeCodes()
{
return $this->_getResource()->getAttributeCodes();
}
+
+ /**
+ * Standard model resource initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_flat_indexer');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Flat/Observer.php b/app/code/core/Mage/Catalog/Model/Product/Flat/Observer.php
index 283233a8bb7..09a219e2a6c 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Flat/Observer.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Flat/Observer.php
@@ -22,26 +22,6 @@
*/
class Mage_Catalog_Model_Product_Flat_Observer
{
- /**
- * Retrieve Catalog Product Flat Helper
- *
- * @return Mage_Catalog_Helper_Product_Flat
- */
- protected function _getHelper()
- {
- return Mage::helper('catalog/product_flat');
- }
-
- /**
- * Retrieve Catalog Product Flat Indexer model
- *
- * @return Mage_Catalog_Model_Product_Flat_Indexer
- */
- protected function _getIndexer()
- {
- return Mage::getSingleton('catalog/product_flat_indexer');
- }
-
/**
* Catalog Entity attribute after save process
*
@@ -275,4 +255,23 @@ public function catalogCategoryChangeProducts(Varien_Event_Observer $observer)
{
return $this;
}
+ /**
+ * Retrieve Catalog Product Flat Helper
+ *
+ * @return Mage_Catalog_Helper_Product_Flat
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('catalog/product_flat');
+ }
+
+ /**
+ * Retrieve Catalog Product Flat Indexer model
+ *
+ * @return Mage_Catalog_Model_Product_Flat_Indexer
+ */
+ protected function _getIndexer()
+ {
+ return Mage::getSingleton('catalog/product_flat_indexer');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Image.php b/app/code/core/Mage/Catalog/Model/Product/Image.php
index b39d87fdf68..f9ffce33737 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Image.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Image.php
@@ -229,94 +229,6 @@ public function setSize($size)
return $this;
}
- /**
- * @deprecated
- * @param string|null $file
- * @return bool
- */
- protected function _checkMemory($file = null)
- {
- return $this->_getMemoryLimit() > ($this->_getMemoryUsage() + $this->_getNeedMemoryForFile($file)) || $this->_getMemoryLimit() == -1;
- }
-
- /**
- * @return int
- * @deprecated
- */
- protected function _getMemoryLimit()
- {
- $memoryLimit = trim(strtoupper(ini_get('memory_limit')));
-
- if (!isset($memoryLimit[0])) {
- $memoryLimit = '128M';
- }
-
- return ini_parse_quantity($memoryLimit);
- }
-
- /**
- * @deprecated
- * @return int
- */
- protected function _getMemoryUsage()
- {
- if (function_exists('memory_get_usage')) {
- return memory_get_usage();
- }
- return 0;
- }
-
- /**
- * @deprecated
- * @param string $file
- * @return float|int
- */
- protected function _getNeedMemoryForFile($file = null)
- {
- $file = is_null($file) ? $this->getBaseFile() : $file;
- if (!$file) {
- return 0;
- }
-
- if (!file_exists($file) || !is_file($file)) {
- return 0;
- }
-
- $imageInfo = getimagesize($file);
-
- if ($imageInfo === false) {
- return 0;
- }
- if (!isset($imageInfo['channels'])) {
- // if there is no info about this parameter lets set it for maximum
- $imageInfo['channels'] = 4;
- }
- if (!isset($imageInfo['bits'])) {
- // if there is no info about this parameter lets set it for maximum
- $imageInfo['bits'] = 8;
- }
- return round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + pow(2, 16)) * 1.65);
- }
-
- /**
- * Convert array of 3 items (decimal r, g, b) to string of their hex values
- *
- * @param array $rgbArray
- * @return string
- */
- protected function _rgbToString($rgbArray)
- {
- $result = [];
- foreach ($rgbArray as $value) {
- if ($value === null) {
- $result[] = 'null';
- } else {
- $result[] = sprintf('%02s', dechex($value));
- }
- }
- return implode($result);
- }
-
/**
* Set filenames for base file and new file
*
@@ -623,40 +535,6 @@ public function getWatermarkFile()
return $this->_watermarkFile;
}
- /**
- * Get relative watermark file path
- * or false if file not found
- *
- * @return string | bool
- */
- protected function _getWatermarkFilePath()
- {
- $filePath = false;
-
- if (!$file = $this->getWatermarkFile()) {
- return $filePath;
- }
-
- $baseDir = Mage::getSingleton('catalog/product_media_config')->getBaseMediaPath();
-
- if ($this->_fileExists($baseDir . '/watermark/stores/' . Mage::app()->getStore()->getId() . $file)) {
- $filePath = $baseDir . '/watermark/stores/' . Mage::app()->getStore()->getId() . $file;
- } elseif ($this->_fileExists($baseDir . '/watermark/websites/' . Mage::app()->getWebsite()->getId() . $file)) {
- $filePath = $baseDir . '/watermark/websites/' . Mage::app()->getWebsite()->getId() . $file;
- } elseif ($this->_fileExists($baseDir . '/watermark/default/' . $file)) {
- $filePath = $baseDir . '/watermark/default/' . $file;
- } elseif ($this->_fileExists($baseDir . '/watermark/' . $file)) {
- $filePath = $baseDir . '/watermark/' . $file;
- } else {
- $baseDir = Mage::getDesign()->getSkinBaseDir();
- if ($this->_fileExists($baseDir . $file)) {
- $filePath = $baseDir . $file;
- }
- }
-
- return $filePath;
- }
-
/**
* Set watermark position
*
@@ -769,6 +647,128 @@ public function clearCache()
Mage::helper('core/file_storage_database')->deleteFolder($directory);
}
+ /**
+ * @deprecated
+ * @param string|null $file
+ * @return bool
+ */
+ protected function _checkMemory($file = null)
+ {
+ return $this->_getMemoryLimit() > ($this->_getMemoryUsage() + $this->_getNeedMemoryForFile($file)) || $this->_getMemoryLimit() == -1;
+ }
+
+ /**
+ * @return int
+ * @deprecated
+ */
+ protected function _getMemoryLimit()
+ {
+ $memoryLimit = trim(strtoupper(ini_get('memory_limit')));
+
+ if (!isset($memoryLimit[0])) {
+ $memoryLimit = '128M';
+ }
+
+ return ini_parse_quantity($memoryLimit);
+ }
+
+ /**
+ * @deprecated
+ * @return int
+ */
+ protected function _getMemoryUsage()
+ {
+ if (function_exists('memory_get_usage')) {
+ return memory_get_usage();
+ }
+ return 0;
+ }
+
+ /**
+ * @deprecated
+ * @param string $file
+ * @return float|int
+ */
+ protected function _getNeedMemoryForFile($file = null)
+ {
+ $file = is_null($file) ? $this->getBaseFile() : $file;
+ if (!$file) {
+ return 0;
+ }
+
+ if (!file_exists($file) || !is_file($file)) {
+ return 0;
+ }
+
+ $imageInfo = getimagesize($file);
+
+ if ($imageInfo === false) {
+ return 0;
+ }
+ if (!isset($imageInfo['channels'])) {
+ // if there is no info about this parameter lets set it for maximum
+ $imageInfo['channels'] = 4;
+ }
+ if (!isset($imageInfo['bits'])) {
+ // if there is no info about this parameter lets set it for maximum
+ $imageInfo['bits'] = 8;
+ }
+ return round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + pow(2, 16)) * 1.65);
+ }
+
+ /**
+ * Convert array of 3 items (decimal r, g, b) to string of their hex values
+ *
+ * @param array $rgbArray
+ * @return string
+ */
+ protected function _rgbToString($rgbArray)
+ {
+ $result = [];
+ foreach ($rgbArray as $value) {
+ if ($value === null) {
+ $result[] = 'null';
+ } else {
+ $result[] = sprintf('%02s', dechex($value));
+ }
+ }
+ return implode($result);
+ }
+
+ /**
+ * Get relative watermark file path
+ * or false if file not found
+ *
+ * @return string | bool
+ */
+ protected function _getWatermarkFilePath()
+ {
+ $filePath = false;
+
+ if (!$file = $this->getWatermarkFile()) {
+ return $filePath;
+ }
+
+ $baseDir = Mage::getSingleton('catalog/product_media_config')->getBaseMediaPath();
+
+ if ($this->_fileExists($baseDir . '/watermark/stores/' . Mage::app()->getStore()->getId() . $file)) {
+ $filePath = $baseDir . '/watermark/stores/' . Mage::app()->getStore()->getId() . $file;
+ } elseif ($this->_fileExists($baseDir . '/watermark/websites/' . Mage::app()->getWebsite()->getId() . $file)) {
+ $filePath = $baseDir . '/watermark/websites/' . Mage::app()->getWebsite()->getId() . $file;
+ } elseif ($this->_fileExists($baseDir . '/watermark/default/' . $file)) {
+ $filePath = $baseDir . '/watermark/default/' . $file;
+ } elseif ($this->_fileExists($baseDir . '/watermark/' . $file)) {
+ $filePath = $baseDir . '/watermark/' . $file;
+ } else {
+ $baseDir = Mage::getDesign()->getSkinBaseDir();
+ if ($this->_fileExists($baseDir . $file)) {
+ $filePath = $baseDir . $file;
+ }
+ }
+
+ return $filePath;
+ }
+
/**
* First check this file on FS
* If it doesn't exist - try to download it from DB
diff --git a/app/code/core/Mage/Catalog/Model/Product/Indexer/Flat.php b/app/code/core/Mage/Catalog/Model/Product/Indexer/Flat.php
index a7f31a58cf0..631dc91da84 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Indexer/Flat.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Indexer/Flat.php
@@ -86,16 +86,6 @@ public function getDescription()
return Mage::helper('catalog')->__('Reorganize EAV product structure to flat structure');
}
- /**
- * Retrieve Catalog Product Flat Indexer model
- *
- * @return Mage_Catalog_Model_Product_Flat_Indexer
- */
- protected function _getIndexer()
- {
- return Mage::getSingleton('catalog/product_flat_indexer');
- }
-
/**
* Check if event can be matched by process
* Overwrote for check is flat catalog product is enabled and specific save
@@ -174,6 +164,25 @@ public function matchEvent(Mage_Index_Model_Event $event)
return $result;
}
+ /**
+ * Rebuild all index data
+ *
+ */
+ public function reindexAll()
+ {
+ $this->_getIndexer()->reindexAll();
+ }
+
+ /**
+ * Retrieve Catalog Product Flat Indexer model
+ *
+ * @return Mage_Catalog_Model_Product_Flat_Indexer
+ */
+ protected function _getIndexer()
+ {
+ return Mage::getSingleton('catalog/product_flat_indexer');
+ }
+
/**
* Register data required by process in event object
*/
@@ -329,15 +338,6 @@ protected function _processEvent(Mage_Index_Model_Event $event)
}
}
- /**
- * Rebuild all index data
- *
- */
- public function reindexAll()
- {
- $this->_getIndexer()->reindexAll();
- }
-
/**
* Retrieve list of attribute codes, that are used in flat
*
diff --git a/app/code/core/Mage/Catalog/Model/Product/Indexer/Price.php b/app/code/core/Mage/Catalog/Model/Product/Indexer/Price.php
index 65c9971d51b..82d2634c0fd 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Indexer/Price.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Indexer/Price.php
@@ -77,11 +77,6 @@ class Mage_Catalog_Model_Product_Indexer_Price extends Mage_Index_Model_Indexer_
Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MANAGE_STOCK,
];
- protected function _construct()
- {
- $this->_init('catalog/product_indexer_price');
- }
-
/**
* Retrieve Indexer name
*
@@ -102,25 +97,6 @@ public function getDescription()
return Mage::helper('catalog')->__('Index product prices');
}
- /**
- * Retrieve attribute list has an effect on product price
- *
- * @return array
- */
- protected function _getDependentAttributes()
- {
- return [
- 'price',
- 'special_price',
- 'special_from_date',
- 'special_to_date',
- 'tax_class_id',
- 'status',
- 'required_options',
- 'force_reindex_required',
- ];
- }
-
/**
* Check if event can be matched by process.
* Rewritten for checking configuration settings save (like price scope).
@@ -152,6 +128,30 @@ public function matchEvent(Mage_Index_Model_Event $event)
return $result;
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product_indexer_price');
+ }
+
+ /**
+ * Retrieve attribute list has an effect on product price
+ *
+ * @return array
+ */
+ protected function _getDependentAttributes()
+ {
+ return [
+ 'price',
+ 'special_price',
+ 'special_from_date',
+ 'special_to_date',
+ 'tax_class_id',
+ 'status',
+ 'required_options',
+ 'force_reindex_required',
+ ];
+ }
+
/**
* Register data required by catalog product delete process
*/
diff --git a/app/code/core/Mage/Catalog/Model/Product/Link.php b/app/code/core/Mage/Catalog/Model/Product/Link.php
index 1d29f959934..8bc9b036972 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Link.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Link.php
@@ -38,14 +38,6 @@ class Mage_Catalog_Model_Product_Link extends Mage_Core_Model_Abstract
protected $_attributeCollection = null;
- /**
- * Initialize resource
- */
- protected function _construct()
- {
- $this->_init('catalog/product_link');
- }
-
/**
* @return $this
*/
@@ -162,4 +154,12 @@ public function saveGroupedLinks($product)
}
return $this;
}
+
+ /**
+ * Initialize resource
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_link');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Option.php b/app/code/core/Mage/Catalog/Model/Product/Option.php
index bb96d76b489..a5da61f94e4 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Option.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Option.php
@@ -151,11 +151,6 @@ class Mage_Catalog_Model_Product_Option extends Mage_Core_Model_Abstract
*/
protected $_values = [];
- protected function _construct()
- {
- $this->_init('catalog/product_option');
- }
-
/**
* Add value of option to values array
*
@@ -382,28 +377,6 @@ public function saveOptions()
return $this;
}
- /**
- * After save
- *
- * @return Mage_Core_Model_Abstract
- */
- protected function _afterSave()
- {
- $this->getValueInstance()->unsetValues();
- if (is_array($this->getData('values'))) {
- foreach ($this->getData('values') as $value) {
- $this->getValueInstance()->addValue($value);
- }
-
- $this->getValueInstance()->setOption($this)
- ->saveValues();
- } elseif ($this->getGroupByType($this->getType()) == self::OPTION_GROUP_SELECT) {
- Mage::throwException(Mage::helper('catalog')->__('Select type options required values rows.'));
- }
-
- return parent::_afterSave();
- }
-
/**
* Return price. If $flag is true and price is percent
* return converted percent to price
@@ -538,6 +511,48 @@ public function getSearchableData($productId, $storeId)
return $this->_getResource()->getSearchableData($productId, $storeId);
}
+ /**
+ * Check whether custom option could have multiple values
+ *
+ * @return bool
+ */
+ public function isMultipleType()
+ {
+ switch ($this->getType()) {
+ case self::OPTION_TYPE_MULTIPLE:
+ case self::OPTION_TYPE_CHECKBOX:
+ return true;
+ }
+ return false;
+ }
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product_option');
+ }
+
+ /**
+ * After save
+ *
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _afterSave()
+ {
+ $this->getValueInstance()->unsetValues();
+ if (is_array($this->getData('values'))) {
+ foreach ($this->getData('values') as $value) {
+ $this->getValueInstance()->addValue($value);
+ }
+
+ $this->getValueInstance()->setOption($this)
+ ->saveValues();
+ } elseif ($this->getGroupByType($this->getType()) == self::OPTION_GROUP_SELECT) {
+ Mage::throwException(Mage::helper('catalog')->__('Select type options required values rows.'));
+ }
+
+ return parent::_afterSave();
+ }
+
/**
* Clearing object's data
*
@@ -564,19 +579,4 @@ protected function _clearReferences()
}
return $this;
}
-
- /**
- * Check whether custom option could have multiple values
- *
- * @return bool
- */
- public function isMultipleType()
- {
- switch ($this->getType()) {
- case self::OPTION_TYPE_MULTIPLE:
- case self::OPTION_TYPE_CHECKBOX:
- return true;
- }
- return false;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Option/Api.php b/app/code/core/Mage/Catalog/Model/Product/Option/Api.php
index 02bd88c4b9e..bf629da2889 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Option/Api.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Option/Api.php
@@ -83,86 +83,6 @@ public function update($optionId, $data, $store = null)
return true;
}
- /**
- * Prepare custom option data for saving by model. Used for custom option add and update
- *
- * @param array $data
- * @param string $groupType
- */
- protected function _prepareAdditionalFields(&$data, $groupType)
- {
- if (is_array($data['additional_fields'])) {
- if ($groupType != Mage_Catalog_Model_Product_Option::OPTION_GROUP_SELECT) {
- // reset can be used as there should be the only
- // element in 'additional_fields' for options of all types except those from Select group
- $field = reset($data['additional_fields']);
- if (!(is_array($field) && count($field))) {
- $this->_fault('invalid_data');
- } else {
- foreach ($field as $key => $value) {
- $data[$key] = $value;
- }
- }
- } else {
- // convert Select rows array to appropriate format for saving in the model
- foreach ($data['additional_fields'] as $row) {
- if (!(is_array($row) && count($row))) {
- $this->_fault('invalid_data');
- } else {
- foreach ($row as $key => $value) {
- $row[$key] = Mage::helper('catalog')->stripTags($value);
- }
- if (!empty($row['value_id'])) {
- // map 'value_id' to 'option_type_id'
- $row['option_type_id'] = $row['value_id'];
- unset($row['value_id']);
- $data['values'][$row['option_type_id']] = $row;
- } else {
- $data['values'][] = $row;
- }
- }
- }
- }
- }
- unset($data['additional_fields']);
- }
-
- /**
- * Save product custom option data. Used for custom option add and update.
- *
- * @param Mage_Catalog_Model_Product $product
- * @param array $data
- */
- protected function _saveProductCustomOption($product, $data)
- {
- foreach ($data as $key => $value) {
- if (is_string($value)) {
- $data[$key] = Mage::helper('catalog')->stripTags($value);
- }
- }
-
- try {
- if (!$product->getOptionsReadonly()) {
- $product
- ->getOptionInstance()
- ->setOptions([$data]);
-
- $product->setHasOptions(true);
-
- // an empty request can be set as event parameter
- // because it is not used for options changing in observers
- Mage::dispatchEvent(
- 'catalog_product_prepare_save',
- ['product' => $product, 'request' => new Mage_Core_Controller_Request_Http()],
- );
-
- $product->save();
- }
- } catch (Exception $e) {
- $this->_fault('save_option_error', $e->getMessage());
- }
- }
-
/**
* Read list of possible custom option types from module config
*
@@ -294,6 +214,86 @@ public function remove($optionId)
return true;
}
+ /**
+ * Prepare custom option data for saving by model. Used for custom option add and update
+ *
+ * @param array $data
+ * @param string $groupType
+ */
+ protected function _prepareAdditionalFields(&$data, $groupType)
+ {
+ if (is_array($data['additional_fields'])) {
+ if ($groupType != Mage_Catalog_Model_Product_Option::OPTION_GROUP_SELECT) {
+ // reset can be used as there should be the only
+ // element in 'additional_fields' for options of all types except those from Select group
+ $field = reset($data['additional_fields']);
+ if (!(is_array($field) && count($field))) {
+ $this->_fault('invalid_data');
+ } else {
+ foreach ($field as $key => $value) {
+ $data[$key] = $value;
+ }
+ }
+ } else {
+ // convert Select rows array to appropriate format for saving in the model
+ foreach ($data['additional_fields'] as $row) {
+ if (!(is_array($row) && count($row))) {
+ $this->_fault('invalid_data');
+ } else {
+ foreach ($row as $key => $value) {
+ $row[$key] = Mage::helper('catalog')->stripTags($value);
+ }
+ if (!empty($row['value_id'])) {
+ // map 'value_id' to 'option_type_id'
+ $row['option_type_id'] = $row['value_id'];
+ unset($row['value_id']);
+ $data['values'][$row['option_type_id']] = $row;
+ } else {
+ $data['values'][] = $row;
+ }
+ }
+ }
+ }
+ }
+ unset($data['additional_fields']);
+ }
+
+ /**
+ * Save product custom option data. Used for custom option add and update.
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param array $data
+ */
+ protected function _saveProductCustomOption($product, $data)
+ {
+ foreach ($data as $key => $value) {
+ if (is_string($value)) {
+ $data[$key] = Mage::helper('catalog')->stripTags($value);
+ }
+ }
+
+ try {
+ if (!$product->getOptionsReadonly()) {
+ $product
+ ->getOptionInstance()
+ ->setOptions([$data]);
+
+ $product->setHasOptions(true);
+
+ // an empty request can be set as event parameter
+ // because it is not used for options changing in observers
+ Mage::dispatchEvent(
+ 'catalog_product_prepare_save',
+ ['product' => $product, 'request' => new Mage_Core_Controller_Request_Http()],
+ );
+
+ $product->save();
+ }
+ } catch (Exception $e) {
+ $this->_fault('save_option_error', $e->getMessage());
+ }
+ }
+
/**
* Check is type in allowed set
*
diff --git a/app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php b/app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php
index 8c6e5a97caa..0348729f21d 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php
@@ -59,94 +59,314 @@ public function getCustomizedView($optionInfo)
}
/**
- * Returns additional params for processing options
+ * Validate user input for option
*
- * @return Varien_Object
+ * @param array $values All product option values, i.e. array (option_id => mixed, option_id => mixed...)
+ * @return $this
+ * @throws Mage_Core_Exception|Zend_Validate_Exception
*/
- protected function _getProcessingParams()
+ public function validateUserValue($values)
{
- $buyRequest = $this->getRequest();
- $params = $buyRequest->getData('_processing_params');
+ Mage::getSingleton('checkout/session')->setUseNotice(false);
+
+ $this->setIsValid(true);
+ $option = $this->getOption();
+
/*
- * Notice check for params to be Varien_Object - by using object we protect from
- * params being forged and contain data from user frontend input
+ * Check whether we receive uploaded file or restore file by: reorder/edit configuration or
+ * previous configuration with no newly uploaded file
*/
- if ($params instanceof Varien_Object) {
- return $params;
+
+ $fileInfo = $this->_getCurrentConfigFileInfo();
+
+ if ($fileInfo !== null) {
+ if (is_array($fileInfo) && $this->_validateFile($fileInfo)) {
+ $value = $fileInfo;
+ } else {
+ $value = null;
+ }
+ $this->setUserValue($value);
+ return $this;
}
- return new Varien_Object();
+
+ // Process new uploaded file
+ try {
+ $this->_validateUploadedFile();
+ } catch (Exception $e) {
+ if ($this->getSkipCheckRequiredOption()) {
+ $this->setUserValue(null);
+ return $this;
+ } else {
+ Mage::throwException($e->getMessage());
+ }
+ }
+ return $this;
}
/**
- * Returns file info array if we need to get file from already existing file.
- * Or returns null, if we need to get file from uploaded array.
+ * Prepare option value for cart
*
- * @return null|array
+ * @return mixed Prepared option value
* @throws Mage_Core_Exception
*/
- protected function _getCurrentConfigFileInfo()
+ public function prepareForCart()
{
$option = $this->getOption();
$optionId = $option->getId();
- $processingParams = $this->_getProcessingParams();
$buyRequest = $this->getRequest();
- // Check maybe restore file from config requested
+ // Prepare value and fill buyRequest with option
+ $requestOptions = $buyRequest->getOptions();
+ if ($this->getIsValid() && $this->getUserValue() !== null) {
+ $value = $this->getUserValue();
+
+ // Save option in request, because we have no $_FILES['options']
+ $requestOptions[$this->getOption()->getId()] = $value;
+ $result = serialize($value);
+ try {
+ Mage::helper('core/unserializeArray')->unserialize($result);
+ } catch (Exception $e) {
+ Mage::throwException(Mage::helper('catalog')->__('File options format is not valid.'));
+ }
+ } else {
+ /*
+ * Clear option info from request, so it won't be stored in our db upon
+ * unsuccessful validation. Otherwise some bad file data can happen in buyRequest
+ * and be used later in reorders and reconfigurations.
+ */
+ if (is_array($requestOptions)) {
+ unset($requestOptions[$this->getOption()->getId()]);
+ }
+ $result = null;
+ }
+ $buyRequest->setOptions($requestOptions);
+
+ // Clear action key from buy request - we won't need it anymore
$optionActionKey = 'options_' . $optionId . '_file_action';
- if ($buyRequest->getData($optionActionKey) === 'save_old') {
- $fileInfo = [];
- $currentConfig = $processingParams->getCurrentConfig();
- if ($currentConfig) {
- $fileInfo = $currentConfig->getData('options/' . $optionId);
+ $buyRequest->unsetData($optionActionKey);
+
+ return $result;
+ }
+
+ /**
+ * Return formatted option value for quote option
+ *
+ * @param string $optionValue Prepared for cart option value
+ * @return string
+ */
+ public function getFormattedOptionValue($optionValue)
+ {
+ if ($this->_formattedOptionValue === null) {
+ try {
+ $value = Mage::helper('core/unserializeArray')->unserialize($optionValue);
+
+ $customOptionUrlParams = $this->getCustomOptionUrlParams() ?: [
+ 'id' => $this->getConfigurationItemOption()->getId(),
+ 'key' => $value['secret_key'],
+ ];
+
+ $value['url'] = ['route' => $this->_customOptionDownloadUrl, 'params' => $customOptionUrlParams];
+
+ $this->_formattedOptionValue = $this->_getOptionHtml($value);
+ $this->getConfigurationItemOption()->setValue(serialize($value));
+ return $this->_formattedOptionValue;
+ } catch (Exception $e) {
+ return $optionValue;
}
- return $fileInfo;
}
- return null;
+ return $this->_formattedOptionValue;
}
/**
- * Validate user input for option
+ * Return printable option value
*
- * @param array $values All product option values, i.e. array (option_id => mixed, option_id => mixed...)
- * @return $this
- * @throws Mage_Core_Exception|Zend_Validate_Exception
+ * @param string $optionValue Prepared for cart option value
+ * @return string
*/
- public function validateUserValue($values)
+ public function getPrintableOptionValue($optionValue)
{
- Mage::getSingleton('checkout/session')->setUseNotice(false);
+ $value = $this->getFormattedOptionValue($optionValue);
+ return $value === null ? '' : strip_tags($value);
+ }
- $this->setIsValid(true);
- $option = $this->getOption();
+ /**
+ * Return formatted option value ready to edit, ready to parse
+ *
+ * @param string $optionValue Prepared for cart option value
+ * @return string
+ */
+ public function getEditableOptionValue($optionValue)
+ {
+ try {
+ $value = Mage::helper('core/unserializeArray')->unserialize($optionValue);
+ return sprintf(
+ '%s [%d]',
+ Mage::helper('core')->escapeHtml($value['title']),
+ $this->getConfigurationItemOption()->getId(),
+ );
+ } catch (Exception $e) {
+ return $optionValue;
+ }
+ }
- /*
- * Check whether we receive uploaded file or restore file by: reorder/edit configuration or
- * previous configuration with no newly uploaded file
- */
+ /**
+ * Parse user input value and return cart prepared value
+ *
+ * @param string $optionValue
+ * @param array $productOptionValues Values for product option
+ * @return string|null
+ */
+ public function parseOptionValue($optionValue, $productOptionValues)
+ {
+ // search quote item option Id in option value
+ if (preg_match('/\[([0-9]+)\]/', $optionValue, $matches)) {
+ $confItemOptionId = $matches[1];
+ $option = Mage::getModel('sales/quote_item_option')->load($confItemOptionId);
+ try {
+ return $option->getValue();
+ } catch (Exception $e) {
+ return null;
+ }
+ } else {
+ return null;
+ }
+ }
- $fileInfo = $this->_getCurrentConfigFileInfo();
+ /**
+ * Prepare option value for info buy request
+ *
+ * @param string $optionValue
+ * @return mixed
+ */
+ public function prepareOptionValueForRequest($optionValue)
+ {
+ try {
+ return Mage::helper('core/unserializeArray')->unserialize($optionValue);
+ } catch (Exception $e) {
+ return null;
+ }
+ }
- if ($fileInfo !== null) {
- if (is_array($fileInfo) && $this->_validateFile($fileInfo)) {
- $value = $fileInfo;
- } else {
- $value = null;
+ /**
+ * Quote item to order item copy process
+ *
+ * @return $this
+ *
+ * @SuppressWarnings("PHPMD.ErrorControlOperator")
+ */
+ public function copyQuoteToOrder()
+ {
+ $quoteOption = $this->getQuoteItemOption();
+ try {
+ $value = Mage::helper('core/unserializeArray')->unserialize($quoteOption->getValue());
+ if (!isset($value['quote_path'])) {
+ throw new Exception();
}
- $this->setUserValue($value);
+ $quoteFileFullPath = Mage::getBaseDir() . $value['quote_path'];
+ if (!is_file($quoteFileFullPath) || !is_readable($quoteFileFullPath)) {
+ throw new Exception();
+ }
+ $orderFileFullPath = Mage::getBaseDir() . $value['order_path'];
+ $dir = pathinfo($orderFileFullPath, PATHINFO_DIRNAME);
+ $this->_createWriteableDir($dir);
+ Mage::helper('core/file_storage_database')->copyFile($quoteFileFullPath, $orderFileFullPath);
+ @copy($quoteFileFullPath, $orderFileFullPath);
+ } catch (Exception $e) {
return $this;
}
+ return $this;
+ }
+
+ /**
+ * Main Destination directory
+ *
+ * @param bool $relative If true - returns relative path to the webroot
+ * @return string
+ */
+ public function getTargetDir($relative = false)
+ {
+ $fullPath = Mage::getBaseDir('media') . DS . 'custom_options';
+ return $relative ? str_replace(Mage::getBaseDir(), '', $fullPath) : $fullPath;
+ }
+
+ /**
+ * Quote items destination directory
+ *
+ * @param bool $relative If true - returns relative path to the webroot
+ * @return string
+ */
+ public function getQuoteTargetDir($relative = false)
+ {
+ return $this->getTargetDir($relative) . DS . 'quote';
+ }
+
+ /**
+ * Order items destination directory
+ *
+ * @param bool $relative If true - returns relative path to the webroot
+ * @return string
+ */
+ public function getOrderTargetDir($relative = false)
+ {
+ return $this->getTargetDir($relative) . DS . 'order';
+ }
+
+ /**
+ * Set url to custom option download controller
+ *
+ * @param string $url
+ * @return $this
+ */
+ public function setCustomOptionDownloadUrl($url)
+ {
+ $this->_customOptionDownloadUrl = $url;
+ return $this;
+ }
+
+ /**
+ * Returns additional params for processing options
+ *
+ * @return Varien_Object
+ */
+ protected function _getProcessingParams()
+ {
+ $buyRequest = $this->getRequest();
+ $params = $buyRequest->getData('_processing_params');
+ /*
+ * Notice check for params to be Varien_Object - by using object we protect from
+ * params being forged and contain data from user frontend input
+ */
+ if ($params instanceof Varien_Object) {
+ return $params;
+ }
+ return new Varien_Object();
+ }
- // Process new uploaded file
- try {
- $this->_validateUploadedFile();
- } catch (Exception $e) {
- if ($this->getSkipCheckRequiredOption()) {
- $this->setUserValue(null);
- return $this;
- } else {
- Mage::throwException($e->getMessage());
+ /**
+ * Returns file info array if we need to get file from already existing file.
+ * Or returns null, if we need to get file from uploaded array.
+ *
+ * @return null|array
+ * @throws Mage_Core_Exception
+ */
+ protected function _getCurrentConfigFileInfo()
+ {
+ $option = $this->getOption();
+ $optionId = $option->getId();
+ $processingParams = $this->_getProcessingParams();
+ $buyRequest = $this->getRequest();
+
+ // Check maybe restore file from config requested
+ $optionActionKey = 'options_' . $optionId . '_file_action';
+ if ($buyRequest->getData($optionActionKey) === 'save_old') {
+ $fileInfo = [];
+ $currentConfig = $processingParams->getCurrentConfig();
+ if ($currentConfig) {
+ $fileInfo = $currentConfig->getData('options/' . $optionId);
}
+ return $fileInfo;
}
- return $this;
+ return null;
}
/**
@@ -413,80 +633,6 @@ protected function _getValidatorErrors($errors, $fileInfo)
return $result;
}
- /**
- * Prepare option value for cart
- *
- * @return mixed Prepared option value
- * @throws Mage_Core_Exception
- */
- public function prepareForCart()
- {
- $option = $this->getOption();
- $optionId = $option->getId();
- $buyRequest = $this->getRequest();
-
- // Prepare value and fill buyRequest with option
- $requestOptions = $buyRequest->getOptions();
- if ($this->getIsValid() && $this->getUserValue() !== null) {
- $value = $this->getUserValue();
-
- // Save option in request, because we have no $_FILES['options']
- $requestOptions[$this->getOption()->getId()] = $value;
- $result = serialize($value);
- try {
- Mage::helper('core/unserializeArray')->unserialize($result);
- } catch (Exception $e) {
- Mage::throwException(Mage::helper('catalog')->__('File options format is not valid.'));
- }
- } else {
- /*
- * Clear option info from request, so it won't be stored in our db upon
- * unsuccessful validation. Otherwise some bad file data can happen in buyRequest
- * and be used later in reorders and reconfigurations.
- */
- if (is_array($requestOptions)) {
- unset($requestOptions[$this->getOption()->getId()]);
- }
- $result = null;
- }
- $buyRequest->setOptions($requestOptions);
-
- // Clear action key from buy request - we won't need it anymore
- $optionActionKey = 'options_' . $optionId . '_file_action';
- $buyRequest->unsetData($optionActionKey);
-
- return $result;
- }
-
- /**
- * Return formatted option value for quote option
- *
- * @param string $optionValue Prepared for cart option value
- * @return string
- */
- public function getFormattedOptionValue($optionValue)
- {
- if ($this->_formattedOptionValue === null) {
- try {
- $value = Mage::helper('core/unserializeArray')->unserialize($optionValue);
-
- $customOptionUrlParams = $this->getCustomOptionUrlParams() ?: [
- 'id' => $this->getConfigurationItemOption()->getId(),
- 'key' => $value['secret_key'],
- ];
-
- $value['url'] = ['route' => $this->_customOptionDownloadUrl, 'params' => $customOptionUrlParams];
-
- $this->_formattedOptionValue = $this->_getOptionHtml($value);
- $this->getConfigurationItemOption()->setValue(serialize($value));
- return $this->_formattedOptionValue;
- } catch (Exception $e) {
- return $optionValue;
- }
- }
- return $this->_formattedOptionValue;
- }
-
/**
* Format File option html
*
@@ -539,152 +685,6 @@ protected function _unserializeValue($value)
}
}
- /**
- * Return printable option value
- *
- * @param string $optionValue Prepared for cart option value
- * @return string
- */
- public function getPrintableOptionValue($optionValue)
- {
- $value = $this->getFormattedOptionValue($optionValue);
- return $value === null ? '' : strip_tags($value);
- }
-
- /**
- * Return formatted option value ready to edit, ready to parse
- *
- * @param string $optionValue Prepared for cart option value
- * @return string
- */
- public function getEditableOptionValue($optionValue)
- {
- try {
- $value = Mage::helper('core/unserializeArray')->unserialize($optionValue);
- return sprintf(
- '%s [%d]',
- Mage::helper('core')->escapeHtml($value['title']),
- $this->getConfigurationItemOption()->getId(),
- );
- } catch (Exception $e) {
- return $optionValue;
- }
- }
-
- /**
- * Parse user input value and return cart prepared value
- *
- * @param string $optionValue
- * @param array $productOptionValues Values for product option
- * @return string|null
- */
- public function parseOptionValue($optionValue, $productOptionValues)
- {
- // search quote item option Id in option value
- if (preg_match('/\[([0-9]+)\]/', $optionValue, $matches)) {
- $confItemOptionId = $matches[1];
- $option = Mage::getModel('sales/quote_item_option')->load($confItemOptionId);
- try {
- return $option->getValue();
- } catch (Exception $e) {
- return null;
- }
- } else {
- return null;
- }
- }
-
- /**
- * Prepare option value for info buy request
- *
- * @param string $optionValue
- * @return mixed
- */
- public function prepareOptionValueForRequest($optionValue)
- {
- try {
- return Mage::helper('core/unserializeArray')->unserialize($optionValue);
- } catch (Exception $e) {
- return null;
- }
- }
-
- /**
- * Quote item to order item copy process
- *
- * @return $this
- *
- * @SuppressWarnings("PHPMD.ErrorControlOperator")
- */
- public function copyQuoteToOrder()
- {
- $quoteOption = $this->getQuoteItemOption();
- try {
- $value = Mage::helper('core/unserializeArray')->unserialize($quoteOption->getValue());
- if (!isset($value['quote_path'])) {
- throw new Exception();
- }
- $quoteFileFullPath = Mage::getBaseDir() . $value['quote_path'];
- if (!is_file($quoteFileFullPath) || !is_readable($quoteFileFullPath)) {
- throw new Exception();
- }
- $orderFileFullPath = Mage::getBaseDir() . $value['order_path'];
- $dir = pathinfo($orderFileFullPath, PATHINFO_DIRNAME);
- $this->_createWriteableDir($dir);
- Mage::helper('core/file_storage_database')->copyFile($quoteFileFullPath, $orderFileFullPath);
- @copy($quoteFileFullPath, $orderFileFullPath);
- } catch (Exception $e) {
- return $this;
- }
- return $this;
- }
-
- /**
- * Main Destination directory
- *
- * @param bool $relative If true - returns relative path to the webroot
- * @return string
- */
- public function getTargetDir($relative = false)
- {
- $fullPath = Mage::getBaseDir('media') . DS . 'custom_options';
- return $relative ? str_replace(Mage::getBaseDir(), '', $fullPath) : $fullPath;
- }
-
- /**
- * Quote items destination directory
- *
- * @param bool $relative If true - returns relative path to the webroot
- * @return string
- */
- public function getQuoteTargetDir($relative = false)
- {
- return $this->getTargetDir($relative) . DS . 'quote';
- }
-
- /**
- * Order items destination directory
- *
- * @param bool $relative If true - returns relative path to the webroot
- * @return string
- */
- public function getOrderTargetDir($relative = false)
- {
- return $this->getTargetDir($relative) . DS . 'order';
- }
-
- /**
- * Set url to custom option download controller
- *
- * @param string $url
- * @return $this
- */
- public function setCustomOptionDownloadUrl($url)
- {
- $this->_customOptionDownloadUrl = $url;
- return $this;
- }
-
/**
* Directory structure initializing
* @throws Mage_Core_Exception
diff --git a/app/code/core/Mage/Catalog/Model/Product/Option/Type/Select.php b/app/code/core/Mage/Catalog/Model/Product/Option/Type/Select.php
index a044e781b28..b5c7770bcf9 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Option/Type/Select.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Option/Type/Select.php
@@ -93,16 +93,6 @@ public function getPrintableOptionValue($optionValue)
return $this->getFormattedOptionValue($optionValue);
}
- /**
- * Return currently unavailable product configuration message
- *
- * @return string
- */
- protected function _getWrongConfigurationMessage()
- {
- return Mage::helper('catalog')->__('Some of the selected item options are not currently available.');
- }
-
/**
* Return formatted option value ready to edit, ready to parse
*
@@ -290,6 +280,16 @@ public function getOptionSku($optionValue, $skuDelimiter)
return $result;
}
+ /**
+ * Return currently unavailable product configuration message
+ *
+ * @return string
+ */
+ protected function _getWrongConfigurationMessage()
+ {
+ return Mage::helper('catalog')->__('Some of the selected item options are not currently available.');
+ }
+
/**
* Check if option has single or multiple values selection
*
diff --git a/app/code/core/Mage/Catalog/Model/Product/Option/Value.php b/app/code/core/Mage/Catalog/Model/Product/Option/Value.php
index 4e5ee68bc18..5db96d0cb19 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Option/Value.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Option/Value.php
@@ -44,11 +44,6 @@ class Mage_Catalog_Model_Product_Option_Value extends Mage_Core_Model_Abstract
protected $_option;
- protected function _construct()
- {
- $this->_init('catalog/product_option_value');
- }
-
/**
* @param array $value
* @return $this
@@ -248,4 +243,9 @@ public function duplicate($oldOptionId, $newOptionId)
$this->getResource()->duplicate($this, $oldOptionId, $newOptionId);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product_option_value');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Status.php b/app/code/core/Mage/Catalog/Model/Product/Status.php
index 6afc769a3b1..ca2117c60bf 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Status.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Status.php
@@ -41,11 +41,6 @@ class Mage_Catalog_Model_Product_Status extends Mage_Core_Model_Abstract
*/
protected $_attribute;
- protected function _construct()
- {
- $this->_init('catalog/product_status');
- }
-
/**
* Retrieve Product Attribute by code
*
@@ -354,4 +349,9 @@ public function addValueSortToCollection($collection, $dir = 'asc')
$collection->getSelect()->order($valueExpr . ' ' . $dir);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product_status');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php b/app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php
index a2a574e9758..010a80595f9 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php
@@ -22,6 +22,35 @@
*/
abstract class Mage_Catalog_Model_Product_Type_Abstract
{
+ public const CALCULATE_CHILD = 0;
+ public const CALCULATE_PARENT = 1;
+
+ /**
+ * values for shipment type (invoice etc)
+ *
+ */
+ public const SHIPMENT_SEPARATELY = 1;
+ public const SHIPMENT_TOGETHER = 0;
+
+ /**
+ * Process modes
+ *
+ * Full validation - all required options must be set, whole configuration
+ * must be valid
+ */
+ public const PROCESS_MODE_FULL = 'full';
+
+ /**
+ * Process modes
+ *
+ * Lite validation - only received options are validated
+ */
+ public const PROCESS_MODE_LITE = 'lite';
+
+ /**
+ * Item options prefix
+ */
+ public const OPTION_PREFIX = 'option_';
/**
* Product model instance
*
@@ -86,36 +115,6 @@ abstract class Mage_Catalog_Model_Product_Type_Abstract
*/
protected $_fileQueue = [];
- public const CALCULATE_CHILD = 0;
- public const CALCULATE_PARENT = 1;
-
- /**
- * values for shipment type (invoice etc)
- *
- */
- public const SHIPMENT_SEPARATELY = 1;
- public const SHIPMENT_TOGETHER = 0;
-
- /**
- * Process modes
- *
- * Full validation - all required options must be set, whole configuration
- * must be valid
- */
- public const PROCESS_MODE_FULL = 'full';
-
- /**
- * Process modes
- *
- * Lite validation - only received options are validated
- */
- public const PROCESS_MODE_LITE = 'lite';
-
- /**
- * Item options prefix
- */
- public const OPTION_PREFIX = 'option_';
-
/**
* Specify type instance product
*
@@ -294,76 +293,6 @@ public function isSalable($product = null)
return (bool) (int) $salable;
}
- /**
- * Prepare product and its configuration to be added to some products list.
- * Perform standard preparation process and then prepare options belonging to specific product type.
- *
- * @param Mage_Catalog_Model_Product $product
- * @param string $processMode
- * @return array|string
- */
- protected function _prepareProduct(Varien_Object $buyRequest, $product, $processMode)
- {
- $product = $this->getProduct($product);
- /** @var Mage_Catalog_Model_Product $product */
- // try to add custom options
- try {
- $options = $this->_prepareOptions($buyRequest, $product, $processMode);
- } catch (Mage_Core_Exception $e) {
- return $e->getMessage();
- }
-
- if (is_string($options)) {
- return $options;
- }
- // try to found super product configuration
- // (if product was buying within grouped product)
- $superProductConfig = $buyRequest->getSuperProductConfig();
- if (!empty($superProductConfig['product_id'])
- && !empty($superProductConfig['product_type'])
- ) {
- $superProductId = (int) $superProductConfig['product_id'];
- if ($superProductId) {
- if (!$superProduct = Mage::registry('used_super_product_' . $superProductId)) {
- $superProduct = Mage::getModel('catalog/product')->load($superProductId);
- Mage::register('used_super_product_' . $superProductId, $superProduct);
- }
- if ($superProduct->getId()) {
- $assocProductIds = $superProduct->getTypeInstance(true)->getAssociatedProductIds($superProduct);
- if (in_array($product->getId(), $assocProductIds)) {
- $productType = $superProductConfig['product_type'];
- $product->addCustomOption('product_type', $productType, $superProduct);
-
- $buyRequest->setData('super_product_config', [
- 'product_type' => $productType,
- 'product_id' => $superProduct->getId(),
- ]);
- }
- }
- }
- }
-
- $product->prepareCustomOptions();
- $buyRequest->unsetData('_processing_params'); // One-time params only
- $product->addCustomOption('info_buyRequest', serialize($buyRequest->getData()));
-
- if ($options) {
- $optionIds = array_keys($options);
- $product->addCustomOption('option_ids', implode(',', $optionIds));
- foreach ($options as $optionId => $optionValue) {
- $product->addCustomOption(self::OPTION_PREFIX . $optionId, $optionValue);
- }
- }
-
- // set quantity in cart
- if ($this->_isStrictProcessMode($processMode)) {
- $product->setCartQty($buyRequest->getQty());
- }
- $product->setQty($buyRequest->getQty());
-
- return [$product];
- }
-
/**
* Process product configuration
*
@@ -478,17 +407,6 @@ public function addFileQueue($queueOptions)
$this->_fileQueue[] = $queueOptions;
}
- /**
- * Check if current process mode is strict
- *
- * @param string $processMode
- * @return bool
- */
- protected function _isStrictProcessMode($processMode)
- {
- return $processMode == self::PROCESS_MODE_FULL;
- }
-
/**
* Retrieve message for specify option(s)
*
@@ -499,55 +417,6 @@ public function getSpecifyOptionMessage()
return Mage::helper('catalog')->__('Please specify the product\'s required option(s).');
}
- /**
- * Process custom defined options for product
- *
- * @param Mage_Catalog_Model_Product $product
- * @param string $processMode
- * @return array
- */
- protected function _prepareOptions(Varien_Object $buyRequest, $product, $processMode)
- {
- $transport = new stdClass();
- $transport->options = [];
- foreach ($this->getProduct($product)->getOptions() as $option) {
- /** @var Mage_Catalog_Model_Product_Option $option */
- $group = $option->groupFactory($option->getType())
- ->setOption($option)
- ->setProduct($this->getProduct($product))
- ->setRequest($buyRequest)
- ->setProcessMode($processMode)
- ->validateUserValue($buyRequest->getOptions());
-
- $preparedValue = $group->prepareForCart();
- if ($preparedValue !== null) {
- $transport->options[$option->getId()] = $preparedValue;
- }
- }
-
- $eventName = sprintf('catalog_product_type_prepare_%s_options', $processMode);
- Mage::dispatchEvent($eventName, [
- 'transport' => $transport,
- 'buy_request' => $buyRequest,
- 'product' => $product,
- ]);
- return $transport->options;
- }
-
- /**
- * Process product custom defined options for cart
- *
- * @deprecated after 1.4.2.0
- * @see _prepareOptions()
- *
- * @param Mage_Catalog_Model_Product $product
- * @return array
- */
- protected function _prepareOptionsForCart(Varien_Object $buyRequest, $product = null)
- {
- return $this->_prepareOptions($buyRequest, $product, self::PROCESS_MODE_FULL);
- }
-
/**
* Check if product can be bought
*
@@ -635,25 +504,6 @@ public function save($product = null)
return $this;
}
- /**
- * Remove don't applicable attributes data
- *
- * @param Mage_Catalog_Model_Product $product
- */
- protected function _removeNotApplicableAttributes($product = null)
- {
- $product = $this->getProduct($product);
- $eavConfig = Mage::getSingleton('eav/config');
- $entityType = $product->getResource()->getEntityType();
- foreach ($eavConfig->getEntityAttributeCodes($entityType, $product) as $attributeCode) {
- $attribute = $eavConfig->getAttribute($entityType, $attributeCode);
- $applyTo = $attribute->getApplyTo();
- if (is_array($applyTo) && count($applyTo) > 0 && !in_array($product->getTypeId(), $applyTo)) {
- $product->unsetData($attribute->getAttributeCode());
- }
- }
- }
-
/**
* Before save type related data
*
@@ -983,4 +833,153 @@ public function isMapEnabledInOptions($product, $visibility = null)
{
return false;
}
+
+ /**
+ * Prepare product and its configuration to be added to some products list.
+ * Perform standard preparation process and then prepare options belonging to specific product type.
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param string $processMode
+ * @return array|string
+ */
+ protected function _prepareProduct(Varien_Object $buyRequest, $product, $processMode)
+ {
+ $product = $this->getProduct($product);
+ /** @var Mage_Catalog_Model_Product $product */
+ // try to add custom options
+ try {
+ $options = $this->_prepareOptions($buyRequest, $product, $processMode);
+ } catch (Mage_Core_Exception $e) {
+ return $e->getMessage();
+ }
+
+ if (is_string($options)) {
+ return $options;
+ }
+ // try to found super product configuration
+ // (if product was buying within grouped product)
+ $superProductConfig = $buyRequest->getSuperProductConfig();
+ if (!empty($superProductConfig['product_id'])
+ && !empty($superProductConfig['product_type'])
+ ) {
+ $superProductId = (int) $superProductConfig['product_id'];
+ if ($superProductId) {
+ if (!$superProduct = Mage::registry('used_super_product_' . $superProductId)) {
+ $superProduct = Mage::getModel('catalog/product')->load($superProductId);
+ Mage::register('used_super_product_' . $superProductId, $superProduct);
+ }
+ if ($superProduct->getId()) {
+ $assocProductIds = $superProduct->getTypeInstance(true)->getAssociatedProductIds($superProduct);
+ if (in_array($product->getId(), $assocProductIds)) {
+ $productType = $superProductConfig['product_type'];
+ $product->addCustomOption('product_type', $productType, $superProduct);
+
+ $buyRequest->setData('super_product_config', [
+ 'product_type' => $productType,
+ 'product_id' => $superProduct->getId(),
+ ]);
+ }
+ }
+ }
+ }
+
+ $product->prepareCustomOptions();
+ $buyRequest->unsetData('_processing_params'); // One-time params only
+ $product->addCustomOption('info_buyRequest', serialize($buyRequest->getData()));
+
+ if ($options) {
+ $optionIds = array_keys($options);
+ $product->addCustomOption('option_ids', implode(',', $optionIds));
+ foreach ($options as $optionId => $optionValue) {
+ $product->addCustomOption(self::OPTION_PREFIX . $optionId, $optionValue);
+ }
+ }
+
+ // set quantity in cart
+ if ($this->_isStrictProcessMode($processMode)) {
+ $product->setCartQty($buyRequest->getQty());
+ }
+ $product->setQty($buyRequest->getQty());
+
+ return [$product];
+ }
+
+ /**
+ * Check if current process mode is strict
+ *
+ * @param string $processMode
+ * @return bool
+ */
+ protected function _isStrictProcessMode($processMode)
+ {
+ return $processMode == self::PROCESS_MODE_FULL;
+ }
+
+ /**
+ * Process custom defined options for product
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param string $processMode
+ * @return array
+ */
+ protected function _prepareOptions(Varien_Object $buyRequest, $product, $processMode)
+ {
+ $transport = new stdClass();
+ $transport->options = [];
+ foreach ($this->getProduct($product)->getOptions() as $option) {
+ /** @var Mage_Catalog_Model_Product_Option $option */
+ $group = $option->groupFactory($option->getType())
+ ->setOption($option)
+ ->setProduct($this->getProduct($product))
+ ->setRequest($buyRequest)
+ ->setProcessMode($processMode)
+ ->validateUserValue($buyRequest->getOptions());
+
+ $preparedValue = $group->prepareForCart();
+ if ($preparedValue !== null) {
+ $transport->options[$option->getId()] = $preparedValue;
+ }
+ }
+
+ $eventName = sprintf('catalog_product_type_prepare_%s_options', $processMode);
+ Mage::dispatchEvent($eventName, [
+ 'transport' => $transport,
+ 'buy_request' => $buyRequest,
+ 'product' => $product,
+ ]);
+ return $transport->options;
+ }
+
+ /**
+ * Process product custom defined options for cart
+ *
+ * @deprecated after 1.4.2.0
+ * @see _prepareOptions()
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @return array
+ */
+ protected function _prepareOptionsForCart(Varien_Object $buyRequest, $product = null)
+ {
+ return $this->_prepareOptions($buyRequest, $product, self::PROCESS_MODE_FULL);
+ }
+
+ /**
+ * Remove don't applicable attributes data
+ *
+ * @param Mage_Catalog_Model_Product $product
+ */
+ protected function _removeNotApplicableAttributes($product = null)
+ {
+ $product = $this->getProduct($product);
+ $eavConfig = Mage::getSingleton('eav/config');
+ $entityType = $product->getResource()->getEntityType();
+ foreach ($eavConfig->getEntityAttributeCodes($entityType, $product) as $attributeCode) {
+ $attribute = $eavConfig->getAttribute($entityType, $attributeCode);
+ $applyTo = $attribute->getApplyTo();
+ if (is_array($applyTo) && count($applyTo) > 0 && !in_array($product->getTypeId(), $applyTo)) {
+ $product->unsetData($attribute->getAttributeCode());
+ }
+ }
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php b/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php
index 31caa7cc3b5..eed76dc8b02 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php
@@ -26,6 +26,13 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
{
public const TYPE_CODE = 'configurable';
+ /**
+ * Product attributes to include on the children of configurable products
+ *
+ * @var string
+ */
+ public const XML_PATH_PRODUCT_CONFIGURABLE_CHILD_ATTRIBUTES = 'frontend/product/configurable/child/attributes';
+
/**
* Cache key for Used Product Attribute Ids
*
@@ -82,13 +89,6 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
*/
protected $_canConfigure = true;
- /**
- * Product attributes to include on the children of configurable products
- *
- * @var string
- */
- public const XML_PATH_PRODUCT_CONFIGURABLE_CHILD_ATTRIBUTES = 'frontend/product/configurable/child/attributes';
-
/**
* Return relation info about used products
*
@@ -561,99 +561,6 @@ public function getSelectedAttributesInfo($product = null)
return $attributes;
}
- /**
- * Prepare product and its configuration to be added to some products list.
- * Perform standard preparation process and then add Configurable specific options.
- *
- * @param Mage_Catalog_Model_Product $product
- * @param string $processMode
- * @return array|string
- */
- protected function _prepareProduct(Varien_Object $buyRequest, $product, $processMode)
- {
- $attributes = $buyRequest->getSuperAttribute();
- if ($attributes || !$this->_isStrictProcessMode($processMode)) {
- if (!$this->_isStrictProcessMode($processMode)) {
- if (is_array($attributes)) {
- foreach ($attributes as $key => $val) {
- if (empty($val)) {
- unset($attributes[$key]);
- }
- }
- } else {
- $attributes = [];
- }
- }
-
- $result = parent::_prepareProduct($buyRequest, $product, $processMode);
- if (is_array($result)) {
- $product = $this->getProduct($product);
- /**
- * $attributes = array($attributeId=>$attributeValue)
- */
- $subProduct = true;
- if ($this->_isStrictProcessMode($processMode)) {
- foreach ($this->getConfigurableAttributes($product) as $attributeItem) {
- $attrId = $attributeItem->getData('attribute_id');
- if (!isset($attributes[$attrId]) || empty($attributes[$attrId])) {
- $subProduct = null;
- break;
- }
- }
- }
- if ($subProduct) {
- $subProduct = $this->getProductByAttributes($attributes, $product);
- }
-
- if ($subProduct) {
- $product->addCustomOption('attributes', serialize($attributes));
- $product->addCustomOption('product_qty_' . $subProduct->getId(), 1, $subProduct);
- $product->addCustomOption('simple_product', $subProduct->getId(), $subProduct);
-
- $_result = $subProduct->getTypeInstance(true)->_prepareProduct(
- $buyRequest,
- $subProduct,
- $processMode,
- );
- if (is_string($_result) && !is_array($_result)) {
- return $_result;
- }
-
- if (!isset($_result[0])) {
- return Mage::helper('checkout')->__('Cannot add the item to shopping cart');
- }
-
- /**
- * Adding parent product custom options to child product
- * to be sure that it will be unique as its parent
- */
- if ($optionIds = $product->getCustomOption('option_ids')) {
- $optionIds = explode(',', $optionIds->getValue());
- foreach ($optionIds as $optionId) {
- if ($option = $product->getCustomOption('option_' . $optionId)) {
- $_result[0]->addCustomOption('option_' . $optionId, $option->getValue());
- }
- }
- }
-
- $_result[0]->setParentProductId($product->getId())
- // add custom option to simple product for protection of process
- //when we add simple product separately
- ->addCustomOption('parent_product_id', $product->getId());
- if ($this->_isStrictProcessMode($processMode)) {
- $_result[0]->setCartQty(1);
- }
- $result[] = $_result[0];
- return $result;
- } elseif (!$this->_isStrictProcessMode($processMode)) {
- return $result;
- }
- }
- }
-
- return $this->getSpecifyOptionMessage();
- }
-
/**
* Check if product can be bought
*
@@ -873,4 +780,97 @@ public function getConfigurableOptions($product)
return Mage::getResourceSingleton('catalog/product_type_configurable')
->getConfigurableOptions($product, $this->getUsedProductAttributes($product));
}
+
+ /**
+ * Prepare product and its configuration to be added to some products list.
+ * Perform standard preparation process and then add Configurable specific options.
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param string $processMode
+ * @return array|string
+ */
+ protected function _prepareProduct(Varien_Object $buyRequest, $product, $processMode)
+ {
+ $attributes = $buyRequest->getSuperAttribute();
+ if ($attributes || !$this->_isStrictProcessMode($processMode)) {
+ if (!$this->_isStrictProcessMode($processMode)) {
+ if (is_array($attributes)) {
+ foreach ($attributes as $key => $val) {
+ if (empty($val)) {
+ unset($attributes[$key]);
+ }
+ }
+ } else {
+ $attributes = [];
+ }
+ }
+
+ $result = parent::_prepareProduct($buyRequest, $product, $processMode);
+ if (is_array($result)) {
+ $product = $this->getProduct($product);
+ /**
+ * $attributes = array($attributeId=>$attributeValue)
+ */
+ $subProduct = true;
+ if ($this->_isStrictProcessMode($processMode)) {
+ foreach ($this->getConfigurableAttributes($product) as $attributeItem) {
+ $attrId = $attributeItem->getData('attribute_id');
+ if (!isset($attributes[$attrId]) || empty($attributes[$attrId])) {
+ $subProduct = null;
+ break;
+ }
+ }
+ }
+ if ($subProduct) {
+ $subProduct = $this->getProductByAttributes($attributes, $product);
+ }
+
+ if ($subProduct) {
+ $product->addCustomOption('attributes', serialize($attributes));
+ $product->addCustomOption('product_qty_' . $subProduct->getId(), 1, $subProduct);
+ $product->addCustomOption('simple_product', $subProduct->getId(), $subProduct);
+
+ $_result = $subProduct->getTypeInstance(true)->_prepareProduct(
+ $buyRequest,
+ $subProduct,
+ $processMode,
+ );
+ if (is_string($_result) && !is_array($_result)) {
+ return $_result;
+ }
+
+ if (!isset($_result[0])) {
+ return Mage::helper('checkout')->__('Cannot add the item to shopping cart');
+ }
+
+ /**
+ * Adding parent product custom options to child product
+ * to be sure that it will be unique as its parent
+ */
+ if ($optionIds = $product->getCustomOption('option_ids')) {
+ $optionIds = explode(',', $optionIds->getValue());
+ foreach ($optionIds as $optionId) {
+ if ($option = $product->getCustomOption('option_' . $optionId)) {
+ $_result[0]->addCustomOption('option_' . $optionId, $option->getValue());
+ }
+ }
+ }
+
+ $_result[0]->setParentProductId($product->getId())
+ // add custom option to simple product for protection of process
+ //when we add simple product separately
+ ->addCustomOption('parent_product_id', $product->getId());
+ if ($this->_isStrictProcessMode($processMode)) {
+ $_result[0]->setCartQty(1);
+ }
+ $result[] = $_result[0];
+ return $result;
+ } elseif (!$this->_isStrictProcessMode($processMode)) {
+ return $result;
+ }
+ }
+ }
+
+ return $this->getSpecifyOptionMessage();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Type/Configurable/Attribute.php b/app/code/core/Mage/Catalog/Model/Product/Type/Configurable/Attribute.php
index 1d74f4ddbf4..73cbf0ee577 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Type/Configurable/Attribute.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Type/Configurable/Attribute.php
@@ -44,11 +44,6 @@
*/
class Mage_Catalog_Model_Product_Type_Configurable_Attribute extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product_type_configurable_attribute');
- }
-
/**
* Add price data to attribute
*
@@ -81,6 +76,10 @@ public function getLabel()
return $this->getData('label');
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product_type_configurable_attribute');
+ }
/**
* After save process
diff --git a/app/code/core/Mage/Catalog/Model/Product/Type/Grouped.php b/app/code/core/Mage/Catalog/Model/Product/Type/Grouped.php
index 3b575d62227..06a6173ce41 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Type/Grouped.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Type/Grouped.php
@@ -284,6 +284,34 @@ public function save($product = null)
return $this;
}
+ /**
+ * Retrieve products divided into groups required to purchase
+ * At least one product in each group has to be purchased
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @return array
+ */
+ public function getProductsToPurchaseByReqGroups($product = null)
+ {
+ $product = $this->getProduct($product);
+ return [$this->getAssociatedProducts($product)];
+ }
+
+ /**
+ * Prepare selected qty for grouped product's options
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param Varien_Object $buyRequest
+ * @return array
+ */
+ public function processBuyRequest($product, $buyRequest)
+ {
+ $superGroup = $buyRequest->getSuperGroup();
+ $superGroup = (is_array($superGroup)) ? array_filter($superGroup, '\intval') : [];
+
+ return ['super_group' => $superGroup];
+ }
+
/**
* Prepare product and its configuration to be added to some products list.
* Perform standard preparation process and add logic specific to Grouped product type.
@@ -354,32 +382,4 @@ protected function _prepareProduct(Varien_Object $buyRequest, $product, $process
return Mage::helper('catalog')->__('Please specify the quantity of product(s).');
}
-
- /**
- * Retrieve products divided into groups required to purchase
- * At least one product in each group has to be purchased
- *
- * @param Mage_Catalog_Model_Product $product
- * @return array
- */
- public function getProductsToPurchaseByReqGroups($product = null)
- {
- $product = $this->getProduct($product);
- return [$this->getAssociatedProducts($product)];
- }
-
- /**
- * Prepare selected qty for grouped product's options
- *
- * @param Mage_Catalog_Model_Product $product
- * @param Varien_Object $buyRequest
- * @return array
- */
- public function processBuyRequest($product, $buyRequest)
- {
- $superGroup = $buyRequest->getSuperGroup();
- $superGroup = (is_array($superGroup)) ? array_filter($superGroup, '\intval') : [];
-
- return ['super_group' => $superGroup];
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Type/Price.php b/app/code/core/Mage/Catalog/Model/Product/Type/Price.php
index 765f4f3b170..6a3799180ca 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Type/Price.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Type/Price.php
@@ -92,22 +92,6 @@ public function getChildFinalPrice($product, $productQty, $childProduct, $childP
return $this->getFinalPrice($childProductQty, $childProduct);
}
- /**
- * Apply group price for product
- *
- * @param Mage_Catalog_Model_Product $product
- * @param float $finalPrice
- * @return float
- */
- protected function _applyGroupPrice($product, $finalPrice)
- {
- $groupPrice = $product->getGroupPrice();
- if (is_numeric($groupPrice)) {
- $finalPrice = min($finalPrice, $groupPrice);
- }
- return $finalPrice;
- }
-
/**
* Get product group price
*
@@ -143,27 +127,6 @@ public function getGroupPrice($product)
return $matchedPrice;
}
- /**
- * Apply tier price for product if not return price that was before
- *
- * @param Mage_Catalog_Model_Product $product
- * @param float|null $qty
- * @param float $finalPrice
- * @return float
- */
- protected function _applyTierPrice($product, $qty, $finalPrice)
- {
- if (is_null($qty)) {
- return $finalPrice;
- }
-
- $tierPrice = $product->getTierPrice($qty);
- if (is_numeric($tierPrice)) {
- $finalPrice = min($finalPrice, $tierPrice);
- }
- return $finalPrice;
- }
-
/**
* Get product tier price by qty
*
@@ -248,36 +211,6 @@ public function getTierPrice($qty, $product)
return ($prices) ? $prices : [];
}
- /**
- * @param Mage_Catalog_Model_Product $product
- * @return int
- */
- protected function _getCustomerGroupId($product)
- {
- if ($product->getCustomerGroupId()) {
- return $product->getCustomerGroupId();
- }
- return Mage::getSingleton('customer/session')->getCustomerGroupId();
- }
-
- /**
- * Apply special price for product if not return price that was before
- *
- * @param Mage_Catalog_Model_Product $product
- * @param float $finalPrice
- * @return float
- */
- protected function _applySpecialPrice($product, $finalPrice)
- {
- return static::calculateSpecialPrice(
- $finalPrice,
- $product->getSpecialPrice(),
- $product->getSpecialFromDate(),
- $product->getSpecialToDate(),
- $product->getStore(),
- );
- }
-
/**
* Count how many tier prices we have for the product
*
@@ -326,33 +259,6 @@ public function getFormatedPrice($product)
return Mage::app()->getStore()->formatPrice($product->getFinalPrice());
}
- /**
- * Apply options price
- *
- * @param Mage_Catalog_Model_Product $product
- * @param int $qty
- * @param float $finalPrice
- * @return float
- */
- protected function _applyOptionsPrice($product, $qty, $finalPrice)
- {
- if ($optionIds = $product->getCustomOption('option_ids')) {
- $basePrice = $finalPrice;
- foreach (explode(',', $optionIds->getValue()) as $optionId) {
- if ($option = $product->getOptionById($optionId)) {
- $confItemOption = $product->getCustomOption('option_' . $option->getId());
-
- $group = $option->groupFactory($option->getType())
- ->setOption($option)
- ->setConfigurationItemOption($confItemOption);
- $finalPrice += $group->getOptionPrice($confItemOption->getValue(), $basePrice);
- }
- }
- }
-
- return $finalPrice;
- }
-
/**
* Calculate product price based on special price data and price rules
*
@@ -450,4 +356,98 @@ public function isGroupPriceFixed()
{
return true;
}
+
+ /**
+ * Apply group price for product
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param float $finalPrice
+ * @return float
+ */
+ protected function _applyGroupPrice($product, $finalPrice)
+ {
+ $groupPrice = $product->getGroupPrice();
+ if (is_numeric($groupPrice)) {
+ $finalPrice = min($finalPrice, $groupPrice);
+ }
+ return $finalPrice;
+ }
+
+ /**
+ * Apply tier price for product if not return price that was before
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param float|null $qty
+ * @param float $finalPrice
+ * @return float
+ */
+ protected function _applyTierPrice($product, $qty, $finalPrice)
+ {
+ if (is_null($qty)) {
+ return $finalPrice;
+ }
+
+ $tierPrice = $product->getTierPrice($qty);
+ if (is_numeric($tierPrice)) {
+ $finalPrice = min($finalPrice, $tierPrice);
+ }
+ return $finalPrice;
+ }
+
+ /**
+ * @param Mage_Catalog_Model_Product $product
+ * @return int
+ */
+ protected function _getCustomerGroupId($product)
+ {
+ if ($product->getCustomerGroupId()) {
+ return $product->getCustomerGroupId();
+ }
+ return Mage::getSingleton('customer/session')->getCustomerGroupId();
+ }
+
+ /**
+ * Apply special price for product if not return price that was before
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param float $finalPrice
+ * @return float
+ */
+ protected function _applySpecialPrice($product, $finalPrice)
+ {
+ return static::calculateSpecialPrice(
+ $finalPrice,
+ $product->getSpecialPrice(),
+ $product->getSpecialFromDate(),
+ $product->getSpecialToDate(),
+ $product->getStore(),
+ );
+ }
+
+ /**
+ * Apply options price
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param int $qty
+ * @param float $finalPrice
+ * @return float
+ */
+ protected function _applyOptionsPrice($product, $qty, $finalPrice)
+ {
+ if ($optionIds = $product->getCustomOption('option_ids')) {
+ $basePrice = $finalPrice;
+ foreach (explode(',', $optionIds->getValue()) as $optionId) {
+ if ($option = $product->getOptionById($optionId)) {
+ $confItemOption = $product->getCustomOption('option_' . $option->getId());
+
+ $group = $option->groupFactory($option->getType())
+ ->setOption($option)
+ ->setConfigurationItemOption($confItemOption);
+ $finalPrice += $group->getOptionPrice($confItemOption->getValue(), $basePrice);
+ }
+ }
+ }
+
+ return $finalPrice;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Product/Url.php b/app/code/core/Mage/Catalog/Model/Product/Url.php
index d03d36db4e1..4c99df6d9f6 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Url.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Url.php
@@ -38,20 +38,6 @@ public function __construct(array $args = [])
$this->_store = !empty($args['store']) ? $args['store'] : Mage::app()->getStore();
}
- /**
- * 'no_selection' shouldn't be a valid image attribute value
- *
- * @param string $image
- * @return string
- */
- protected function _validImage($image)
- {
- if ($image == 'no_selection') {
- $image = null;
- }
- return $image;
- }
-
/**
* Retrieve URL in current store
*
@@ -148,6 +134,20 @@ public function getUrl(Mage_Catalog_Model_Product $product, $params = [])
return $product->getData('url');
}
+ /**
+ * 'no_selection' shouldn't be a valid image attribute value
+ *
+ * @param string $image
+ * @return string
+ */
+ protected function _validImage($image)
+ {
+ if ($image == 'no_selection') {
+ $image = null;
+ }
+ return $image;
+ }
+
/**
* Returns checked store_id value
*
diff --git a/app/code/core/Mage/Catalog/Model/Product/Website.php b/app/code/core/Mage/Catalog/Model/Product/Website.php
index aef6425addc..f05db04eb01 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Website.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Website.php
@@ -27,14 +27,6 @@
*/
class Mage_Catalog_Model_Product_Website extends Mage_Core_Model_Abstract
{
- /**
- * Initialize resource model
- */
- protected function _construct()
- {
- $this->_init('catalog/product_website');
- }
-
/**
* Removes products from websites
*
@@ -84,4 +76,11 @@ public function getWebsites($productIds)
{
return $this->_getResource()->getWebsites($productIds);
}
+ /**
+ * Initialize resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_website');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Abstract.php b/app/code/core/Mage/Catalog/Model/Resource/Abstract.php
index 298ad27dd21..2f7430c39c2 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Abstract.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Abstract.php
@@ -33,23 +33,197 @@ abstract class Mage_Catalog_Model_Resource_Abstract extends Mage_Eav_Model_Entit
protected $_attributes = [];
/**
- * Redeclare attribute model
+ * Returns default Store ID
*
- * @return string
+ * @return int
*/
- protected function _getDefaultAttributeModel()
+ public function getDefaultStoreId()
{
- return 'catalog/resource_eav_attribute';
+ return Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID;
}
/**
- * Returns default Store ID
+ * Retrieve attribute's raw value from DB.
*
- * @return int
+ * @param int $entityId
+ * @param int|string|array $attribute attribute's ids or codes
+ * @param int|Mage_Core_Model_Store $store
+ * @return bool|string|null|array
*/
- public function getDefaultStoreId()
+ public function getAttributeRawValue($entityId, $attribute, $store)
{
- return Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID;
+ if (!$entityId || empty($attribute)) {
+ return false;
+ }
+
+ $returnArray = false;
+
+ if (!is_array($attribute)) {
+ $attribute = [$attribute];
+ } elseif (count($attribute) > 1) {
+ $returnArray = true;
+ }
+
+ $attributesData = [];
+ $staticAttributes = [];
+ $typedAttributes = [];
+ $staticTable = null;
+ $adapter = $this->_getReadAdapter();
+ $getPerStore = false;
+
+ foreach ($attribute as $_attribute) {
+ /** @var Mage_Catalog_Model_Entity_Attribute $attribute */
+ $_attribute = $this->getAttribute($_attribute);
+ if (!$_attribute) {
+ continue;
+ }
+ $attributeCode = $_attribute->getAttributeCode();
+ $attrTable = $_attribute->getBackend()->getTable();
+ $isStatic = $_attribute->getBackend()->isStatic();
+
+ if (!$getPerStore && $_attribute->getIsGlobal() != Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL) {
+ $getPerStore = true;
+ }
+
+ if ($isStatic) {
+ $staticAttributes[] = $attributeCode;
+ $staticTable = $attrTable;
+ } else {
+ /**
+ * That structure needed to avoid farther sql joins for getting attribute's code by id
+ */
+ $typedAttributes[$attrTable][$_attribute->getId()] = $attributeCode;
+ }
+ }
+
+ /**
+ * Collecting static attributes
+ */
+ if ($staticAttributes) {
+ $select = $adapter->select()->from($staticTable, $staticAttributes)
+ ->where($this->getEntityIdField() . ' = :entity_id');
+ $attributesData = $adapter->fetchRow($select, ['entity_id' => $entityId]) ?: [];
+ }
+
+ /**
+ * Collecting typed attributes, performing separate SQL query for each attribute type table
+ */
+ if ($typedAttributes) {
+ if ($store instanceof Mage_Core_Model_Store) {
+ $store = $store->getId();
+ }
+
+ $store = (int) $store;
+
+ foreach ($typedAttributes as $table => $_attributes) {
+ $select = $adapter->select()
+ ->from(['default_value' => $table], ['attribute_id'])
+ ->where('default_value.attribute_id IN (?)', array_keys($_attributes))
+ ->where('default_value.entity_type_id = :entity_type_id')
+ ->where('default_value.entity_id = :entity_id')
+ ->where('default_value.store_id = ?', 0);
+ $bind = [
+ 'entity_type_id' => $this->getTypeId(),
+ 'entity_id' => $entityId,
+ ];
+
+ if ($getPerStore && $store != $this->getDefaultStoreId()) {
+ $valueExpr = $adapter->getCheckSql(
+ 'store_value.value IS NULL',
+ 'default_value.value',
+ 'store_value.value',
+ );
+ $joinCondition = [
+ 'store_value.attribute_id = default_value.attribute_id',
+ 'store_value.entity_type_id = :entity_type_id',
+ 'store_value.entity_id = :entity_id',
+ 'store_value.store_id = :store_id',
+ ];
+
+ $select->joinLeft(
+ ['store_value' => $table],
+ implode(' AND ', $joinCondition),
+ ['attr_value' => $valueExpr],
+ );
+
+ $bind['store_id'] = $store;
+ } else {
+ $select->columns(['attr_value' => 'value'], 'default_value');
+ }
+
+ $result = $adapter->fetchPairs($select, $bind);
+ foreach ($result as $attrId => $value) {
+ $attrCode = $typedAttributes[$table][$attrId];
+ $attributesData[$attrCode] = $value;
+ }
+ }
+ }
+
+ if (count($attributesData) === 1 && !$returnArray) {
+ return reset($attributesData);
+ }
+
+ return $attributesData ? $attributesData : false;
+ }
+
+ /**
+ * Retrieve attribute's raw value from DB using its source model if available.
+ *
+ * @param int $entityId
+ * @param int|string|array $attribute attribute's ids or codes
+ * @param int|Mage_Core_Model_Store $store
+ * @return bool|string|array
+ */
+ public function getAttributeRawText($entityId, $attribute, $store)
+ {
+ if (!$entityId || empty($attribute)) {
+ return false;
+ }
+
+ if ($store instanceof Mage_Core_Model_Store) {
+ $store = $store->getId();
+ }
+
+ $store = (int) $store;
+ $attribute = is_array($attribute) ? $attribute : [$attribute];
+ $value = $this->getAttributeRawValue($entityId, $attribute, $store);
+
+ if (!$value) {
+ return false;
+ }
+
+ // Ensure we have an associative array of attribute => values
+ $values = is_array($value) ? $value : array_combine($attribute, [$value]);
+
+ foreach ($values as $_attribute => &$optionText) {
+ $_attribute = (clone $this->getAttribute($_attribute))->setStoreId($store);
+ if ($_attribute->getSourceModel() || $_attribute->getFrontendInput() === 'select' || $_attribute->getFrontendInput() === 'multiselect') {
+ $optionText = $_attribute->getSource()->getOptionText($optionText);
+ }
+ }
+
+ return count($values) === 1 ? reset($values) : $values;
+ }
+
+ /**
+ * Reset firstly loaded attributes
+ *
+ * @inheritDoc
+ */
+ public function load($object, $entityId, $attributes = [])
+ {
+ $this->_attributes = [];
+ return parent::load($object, $entityId, $attributes);
+ }
+
+ /**
+ * Redeclare attribute model
+ *
+ * @return string
+ */
+ protected function _getDefaultAttributeModel()
+ {
+ return 'catalog/resource_eav_attribute';
}
/**
@@ -560,178 +734,4 @@ protected function _prepareValueForSave($value, Mage_Eav_Model_Entity_Attribute_
return parent::_prepareValueForSave($value, $attribute);
}
-
- /**
- * Retrieve attribute's raw value from DB.
- *
- * @param int $entityId
- * @param int|string|array $attribute attribute's ids or codes
- * @param int|Mage_Core_Model_Store $store
- * @return bool|string|null|array
- */
- public function getAttributeRawValue($entityId, $attribute, $store)
- {
- if (!$entityId || empty($attribute)) {
- return false;
- }
-
- $returnArray = false;
-
- if (!is_array($attribute)) {
- $attribute = [$attribute];
- } elseif (count($attribute) > 1) {
- $returnArray = true;
- }
-
- $attributesData = [];
- $staticAttributes = [];
- $typedAttributes = [];
- $staticTable = null;
- $adapter = $this->_getReadAdapter();
- $getPerStore = false;
-
- foreach ($attribute as $_attribute) {
- /** @var Mage_Catalog_Model_Entity_Attribute $attribute */
- $_attribute = $this->getAttribute($_attribute);
- if (!$_attribute) {
- continue;
- }
- $attributeCode = $_attribute->getAttributeCode();
- $attrTable = $_attribute->getBackend()->getTable();
- $isStatic = $_attribute->getBackend()->isStatic();
-
- if (!$getPerStore && $_attribute->getIsGlobal() != Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL) {
- $getPerStore = true;
- }
-
- if ($isStatic) {
- $staticAttributes[] = $attributeCode;
- $staticTable = $attrTable;
- } else {
- /**
- * That structure needed to avoid farther sql joins for getting attribute's code by id
- */
- $typedAttributes[$attrTable][$_attribute->getId()] = $attributeCode;
- }
- }
-
- /**
- * Collecting static attributes
- */
- if ($staticAttributes) {
- $select = $adapter->select()->from($staticTable, $staticAttributes)
- ->where($this->getEntityIdField() . ' = :entity_id');
- $attributesData = $adapter->fetchRow($select, ['entity_id' => $entityId]) ?: [];
- }
-
- /**
- * Collecting typed attributes, performing separate SQL query for each attribute type table
- */
- if ($typedAttributes) {
- if ($store instanceof Mage_Core_Model_Store) {
- $store = $store->getId();
- }
-
- $store = (int) $store;
-
- foreach ($typedAttributes as $table => $_attributes) {
- $select = $adapter->select()
- ->from(['default_value' => $table], ['attribute_id'])
- ->where('default_value.attribute_id IN (?)', array_keys($_attributes))
- ->where('default_value.entity_type_id = :entity_type_id')
- ->where('default_value.entity_id = :entity_id')
- ->where('default_value.store_id = ?', 0);
- $bind = [
- 'entity_type_id' => $this->getTypeId(),
- 'entity_id' => $entityId,
- ];
-
- if ($getPerStore && $store != $this->getDefaultStoreId()) {
- $valueExpr = $adapter->getCheckSql(
- 'store_value.value IS NULL',
- 'default_value.value',
- 'store_value.value',
- );
- $joinCondition = [
- 'store_value.attribute_id = default_value.attribute_id',
- 'store_value.entity_type_id = :entity_type_id',
- 'store_value.entity_id = :entity_id',
- 'store_value.store_id = :store_id',
- ];
-
- $select->joinLeft(
- ['store_value' => $table],
- implode(' AND ', $joinCondition),
- ['attr_value' => $valueExpr],
- );
-
- $bind['store_id'] = $store;
- } else {
- $select->columns(['attr_value' => 'value'], 'default_value');
- }
-
- $result = $adapter->fetchPairs($select, $bind);
- foreach ($result as $attrId => $value) {
- $attrCode = $typedAttributes[$table][$attrId];
- $attributesData[$attrCode] = $value;
- }
- }
- }
-
- if (count($attributesData) === 1 && !$returnArray) {
- return reset($attributesData);
- }
-
- return $attributesData ? $attributesData : false;
- }
-
- /**
- * Retrieve attribute's raw value from DB using its source model if available.
- *
- * @param int $entityId
- * @param int|string|array $attribute attribute's ids or codes
- * @param int|Mage_Core_Model_Store $store
- * @return bool|string|array
- */
- public function getAttributeRawText($entityId, $attribute, $store)
- {
- if (!$entityId || empty($attribute)) {
- return false;
- }
-
- if ($store instanceof Mage_Core_Model_Store) {
- $store = $store->getId();
- }
-
- $store = (int) $store;
- $attribute = is_array($attribute) ? $attribute : [$attribute];
- $value = $this->getAttributeRawValue($entityId, $attribute, $store);
-
- if (!$value) {
- return false;
- }
-
- // Ensure we have an associative array of attribute => values
- $values = is_array($value) ? $value : array_combine($attribute, [$value]);
-
- foreach ($values as $_attribute => &$optionText) {
- $_attribute = (clone $this->getAttribute($_attribute))->setStoreId($store);
- if ($_attribute->getSourceModel() || $_attribute->getFrontendInput() === 'select' || $_attribute->getFrontendInput() === 'multiselect') {
- $optionText = $_attribute->getSource()->getOptionText($optionText);
- }
- }
-
- return count($values) === 1 ? reset($values) : $values;
- }
-
- /**
- * Reset firstly loaded attributes
- *
- * @inheritDoc
- */
- public function load($object, $entityId, $attributes = [])
- {
- $this->_attributes = [];
- return parent::load($object, $entityId, $attributes);
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Attribute.php b/app/code/core/Mage/Catalog/Model/Resource/Attribute.php
index eeb7f02af73..807f61a5b4e 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Attribute.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Attribute.php
@@ -22,59 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Attribute extends Mage_Eav_Model_Resource_Entity_Attribute
{
- /**
- * Perform actions before object save
- *
- * @inheritDoc
- */
- protected function _beforeSave(Mage_Core_Model_Abstract $object)
- {
- $applyTo = $object->getApplyTo();
- if (is_array($applyTo)) {
- $object->setApplyTo(implode(',', $applyTo));
- }
- return parent::_beforeSave($object);
- }
-
- /**
- * Perform actions after object save
- *
- * @inheritDoc
- */
- protected function _afterSave(Mage_Core_Model_Abstract $object)
- {
- $this->_clearUselessAttributeValues($object);
- return parent::_afterSave($object);
- }
-
- /**
- * Clear useless attribute values
- *
- * @param Mage_Catalog_Model_Resource_Eav_Attribute $object
- * @return $this
- */
- protected function _clearUselessAttributeValues(Mage_Core_Model_Abstract $object)
- {
- $origData = $object->getOrigData();
-
- if ($object->isScopeGlobal()
- && isset($origData['is_global'])
- && Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL != $origData['is_global']
- ) {
- $attributeStoreIds = array_keys(Mage::app()->getStores());
- if (!empty($attributeStoreIds)) {
- $delCondition = [
- 'entity_type_id=?' => $object->getEntityTypeId(),
- 'attribute_id = ?' => $object->getId(),
- 'store_id IN(?)' => $attributeStoreIds,
- ];
- $this->_getWriteAdapter()->delete($object->getBackendTable(), $delCondition);
- }
- }
-
- return $this;
- }
-
/**
* Delete entity
*
@@ -150,4 +97,56 @@ public function isUsedBySuperProducts(Mage_Core_Model_Abstract $object, $attribu
$query = $helper->getQueryUsingAnalyticFunction($select);
return $adapter->fetchOne($query, $bind);
}
+ /**
+ * Perform actions before object save
+ *
+ * @inheritDoc
+ */
+ protected function _beforeSave(Mage_Core_Model_Abstract $object)
+ {
+ $applyTo = $object->getApplyTo();
+ if (is_array($applyTo)) {
+ $object->setApplyTo(implode(',', $applyTo));
+ }
+ return parent::_beforeSave($object);
+ }
+
+ /**
+ * Perform actions after object save
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave(Mage_Core_Model_Abstract $object)
+ {
+ $this->_clearUselessAttributeValues($object);
+ return parent::_afterSave($object);
+ }
+
+ /**
+ * Clear useless attribute values
+ *
+ * @param Mage_Catalog_Model_Resource_Eav_Attribute $object
+ * @return $this
+ */
+ protected function _clearUselessAttributeValues(Mage_Core_Model_Abstract $object)
+ {
+ $origData = $object->getOrigData();
+
+ if ($object->isScopeGlobal()
+ && isset($origData['is_global'])
+ && Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL != $origData['is_global']
+ ) {
+ $attributeStoreIds = array_keys(Mage::app()->getStores());
+ if (!empty($attributeStoreIds)) {
+ $delCondition = [
+ 'entity_type_id=?' => $object->getEntityTypeId(),
+ 'attribute_id = ?' => $object->getId(),
+ 'store_id IN(?)' => $attributeStoreIds,
+ ];
+ $this->_getWriteAdapter()->delete($object->getBackendTable(), $delCondition);
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Category.php b/app/code/core/Mage/Catalog/Model/Resource/Category.php
index caa3af299c3..40e5a52a9e6 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Category.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category.php
@@ -87,45 +87,6 @@ public function getStoreId()
return $this->_storeId ?? Mage::app()->getStore()->getId();
}
- /**
- * Retrieve category tree object
- *
- * @return Varien_Data_Tree_Db
- */
- protected function _getTree()
- {
- if (!$this->_tree) {
- $this->_tree = Mage::getResourceModel('catalog/category_tree')
- ->load();
- }
- return $this->_tree;
- }
-
- /**
- * Process category data before delete
- * update children count for parent category
- * delete child categories
- *
- * @return $this
- */
- protected function _beforeDelete(Varien_Object $object)
- {
- parent::_beforeDelete($object);
-
- /**
- * Update children count for all parent categories
- */
- $parentIds = $object->getParentIds();
- if ($parentIds) {
- $childDecrease = $object->getChildrenCount() + 1; // +1 is itself
- $data = ['children_count' => new Zend_Db_Expr('children_count - ' . $childDecrease)];
- $where = ['entity_id IN(?)' => $parentIds];
- $this->_getWriteAdapter()->update($this->getEntityTable(), $data, $where);
- }
- $this->deleteChildren($object);
- return $this;
- }
-
/**
* Delete children categories of specific category
*
@@ -157,209 +118,6 @@ public function deleteChildren(Varien_Object $object)
return $this;
}
- /**
- * Process category data before saving
- * prepare path and increment children count for parent categories
- *
- * @return $this
- */
- protected function _beforeSave(Varien_Object $object)
- {
- parent::_beforeSave($object);
-
- if (!$object->getChildrenCount()) {
- $object->setChildrenCount(0);
- }
- if ($object->getLevel() === null) {
- $object->setLevel(1);
- }
-
- if (!$object->getId()) {
- $object->setPosition($this->_getMaxPosition($object->getPath()) + 1);
- $path = explode('/', $object->getPath());
- $level = count($path);
- $object->setLevel($level);
- if ($level) {
- $object->setParentId($path[$level - 1]);
- }
- $object->setPath($object->getPath() . '/');
-
- $toUpdateChild = explode('/', $object->getPath());
-
- $this->_getWriteAdapter()->update(
- $this->getEntityTable(),
- ['children_count' => new Zend_Db_Expr('children_count+1')],
- ['entity_id IN(?)' => $toUpdateChild],
- );
- }
- return $this;
- }
-
- /**
- * Process category data after save category object
- * save related products ids and update path value
- *
- * @param Mage_Catalog_Model_Category $object
- * @inheritDoc
- */
- protected function _afterSave(Varien_Object $object)
- {
- /**
- * Add identifier for new category
- */
- if (substr($object->getPath(), -1) == '/') {
- $object->setPath($object->getPath() . $object->getId());
- $this->_savePath($object);
- }
-
- $this->_saveCategoryProducts($object);
- return parent::_afterSave($object);
- }
-
- /**
- * Update path field
- *
- * @param Mage_Catalog_Model_Category $object
- * @return $this
- */
- protected function _savePath($object)
- {
- if ($object->getId()) {
- $this->_getWriteAdapter()->update(
- $this->getEntityTable(),
- ['path' => $object->getPath()],
- ['entity_id = ?' => $object->getId()],
- );
- }
- return $this;
- }
-
- /**
- * Get maximum position of child categories by specific tree path
- *
- * @param string $path
- * @return int
- */
- protected function _getMaxPosition($path)
- {
- $adapter = $this->getReadConnection();
- $positionField = $adapter->quoteIdentifier('position');
- $level = count(explode('/', $path));
- $bind = [
- 'c_level' => $level,
- 'c_path' => $path . '/%',
- ];
- $select = $adapter->select()
- ->from($this->getTable('catalog/category'), 'MAX(' . $positionField . ')')
- ->where($adapter->quoteIdentifier('path') . ' LIKE :c_path')
- ->where($adapter->quoteIdentifier('level') . ' = :c_level');
-
- $position = $adapter->fetchOne($select, $bind);
- if (!$position) {
- $position = 0;
- }
- return $position;
- }
-
- /**
- * Save category products relation
- *
- * @param Mage_Catalog_Model_Category $category
- * @return $this
- */
- protected function _saveCategoryProducts($category)
- {
- $category->setIsChangedProductList(false);
- $id = $category->getId();
- /**
- * new category-product relationships
- */
- $products = $category->getPostedProducts();
-
- /**
- * Example re-save category
- */
- if ($products === null) {
- return $this;
- }
-
- /**
- * old category-product relationships
- */
- $oldProducts = $category->getProductsPosition();
-
- $insert = array_diff_key($products, $oldProducts);
- $delete = array_diff_key($oldProducts, $products);
-
- /**
- * Find product ids which are presented in both arrays
- * and saved before (check $oldProducts array)
- */
- $update = array_intersect_key($products, $oldProducts);
- $update = array_diff_assoc($update, $oldProducts);
-
- $adapter = $this->_getWriteAdapter();
-
- /**
- * Delete products from category
- */
- if (!empty($delete)) {
- $cond = [
- 'product_id IN(?)' => array_keys($delete),
- 'category_id=?' => $id,
- ];
- $adapter->delete($this->_categoryProductTable, $cond);
- }
-
- /**
- * Add products to category
- */
- if (!empty($insert)) {
- $data = [];
- foreach ($insert as $productId => $position) {
- $data[] = [
- 'category_id' => (int) $id,
- 'product_id' => (int) $productId,
- 'position' => (int) $position,
- ];
- }
- $adapter->insertMultiple($this->_categoryProductTable, $data);
- }
-
- /**
- * Update product positions in category
- */
- if (!empty($update)) {
- foreach ($update as $productId => $position) {
- $where = [
- 'category_id = ?' => (int) $id,
- 'product_id = ?' => (int) $productId,
- ];
- $bind = ['position' => (int) $position];
- $adapter->update($this->_categoryProductTable, $bind, $where);
- }
- }
-
- if (!empty($insert) || !empty($delete)) {
- $productIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
- Mage::dispatchEvent('catalog_category_change_products', [
- 'category' => $category,
- 'product_ids' => $productIds,
- ]);
- }
-
- if (!empty($insert) || !empty($update) || !empty($delete)) {
- $category->setIsChangedProductList(true);
-
- /**
- * Setting affected products to category for third party engine index refresh
- */
- $productIds = array_keys($insert + $delete + $update);
- $category->setAffectedProductIds($productIds);
- }
- return $this;
- }
-
/**
* Get positions of associated to category products
*
@@ -466,34 +224,14 @@ public function getChildrenAmount($category, $isActiveFlag = true)
}
/**
- * Get "is_active" attribute identifier
+ * Return entities where attribute value is
*
- * @return int
+ * @param array|int $entityIdsFilter
+ * @param Mage_Eav_Model_Entity_Attribute $attribute
+ * @param mixed $expectedValue
+ * @return array
*/
- protected function _getIsActiveAttributeId()
- {
- if ($this->_isActiveAttributeId === null) {
- $attributeId = Mage::getSingleton('eav/config')
- ->getAttribute(Mage_Catalog_Model_Category::ENTITY, 'is_active')
- ->getId();
- if (!is_int($attributeId)) {
- Mage::throwException('Failed to find category attribute is_active');
- }
- $this->_isActiveAttributeId = $attributeId;
- }
-
- return $this->_isActiveAttributeId;
- }
-
- /**
- * Return entities where attribute value is
- *
- * @param array|int $entityIdsFilter
- * @param Mage_Eav_Model_Entity_Attribute $attribute
- * @param mixed $expectedValue
- * @return array
- */
- public function findWhereAttributeIs($entityIdsFilter, $attribute, $expectedValue)
+ public function findWhereAttributeIs($entityIdsFilter, $attribute, $expectedValue)
{
$bind = [
'attribute_id' => $attribute->getId(),
@@ -601,25 +339,6 @@ public function getParentDesignCategory($category)
return $collection->getFirstItem();
}
- /**
- * Prepare base collection setup for get categories list
- *
- * @param Mage_Catalog_Model_Category $category
- * @return Mage_Catalog_Model_Resource_Category_Collection
- */
- protected function _getChildrenCategoriesBase($category)
- {
- $collection = $category->getCollection();
- $collection->addAttributeToSelect('url_key')
- ->addAttributeToSelect('name')
- ->addAttributeToSelect('all_children')
- ->addAttributeToSelect('is_anchor')
- ->setOrder('position', Varien_Db_Select::SQL_ASC)
- ->joinUrlRewrite();
-
- return $collection;
- }
-
/**
* Return child categories
*
@@ -650,26 +369,6 @@ public function getChildrenCategoriesWithInactive($category)
return $collection;
}
- /**
- * Returns select for category's children.
- *
- * @param Mage_Catalog_Model_Category $category
- * @param bool $recursive
- * @return Varien_Db_Select
- */
- protected function _getChildrenIdSelect($category, $recursive = true)
- {
- $adapter = $this->_getReadAdapter();
- $select = $adapter->select()
- ->from(['m' => $this->getEntityTable()], 'entity_id')
- ->where($adapter->quoteIdentifier('path') . ' LIKE ?', $category->getPath() . '/%');
-
- if (!$recursive) {
- $select->where($adapter->quoteIdentifier('level') . ' <= ?', $category->getLevel() + 1);
- }
- return $select;
- }
-
/**
* Return children ids of category
*
@@ -852,6 +551,307 @@ public function changeParent(
return $this;
}
+ /**
+ * Retrieve category tree object
+ *
+ * @return Varien_Data_Tree_Db
+ */
+ protected function _getTree()
+ {
+ if (!$this->_tree) {
+ $this->_tree = Mage::getResourceModel('catalog/category_tree')
+ ->load();
+ }
+ return $this->_tree;
+ }
+
+ /**
+ * Process category data before delete
+ * update children count for parent category
+ * delete child categories
+ *
+ * @return $this
+ */
+ protected function _beforeDelete(Varien_Object $object)
+ {
+ parent::_beforeDelete($object);
+
+ /**
+ * Update children count for all parent categories
+ */
+ $parentIds = $object->getParentIds();
+ if ($parentIds) {
+ $childDecrease = $object->getChildrenCount() + 1; // +1 is itself
+ $data = ['children_count' => new Zend_Db_Expr('children_count - ' . $childDecrease)];
+ $where = ['entity_id IN(?)' => $parentIds];
+ $this->_getWriteAdapter()->update($this->getEntityTable(), $data, $where);
+ }
+ $this->deleteChildren($object);
+ return $this;
+ }
+
+ /**
+ * Process category data before saving
+ * prepare path and increment children count for parent categories
+ *
+ * @return $this
+ */
+ protected function _beforeSave(Varien_Object $object)
+ {
+ parent::_beforeSave($object);
+
+ if (!$object->getChildrenCount()) {
+ $object->setChildrenCount(0);
+ }
+ if ($object->getLevel() === null) {
+ $object->setLevel(1);
+ }
+
+ if (!$object->getId()) {
+ $object->setPosition($this->_getMaxPosition($object->getPath()) + 1);
+ $path = explode('/', $object->getPath());
+ $level = count($path);
+ $object->setLevel($level);
+ if ($level) {
+ $object->setParentId($path[$level - 1]);
+ }
+ $object->setPath($object->getPath() . '/');
+
+ $toUpdateChild = explode('/', $object->getPath());
+
+ $this->_getWriteAdapter()->update(
+ $this->getEntityTable(),
+ ['children_count' => new Zend_Db_Expr('children_count+1')],
+ ['entity_id IN(?)' => $toUpdateChild],
+ );
+ }
+ return $this;
+ }
+
+ /**
+ * Process category data after save category object
+ * save related products ids and update path value
+ *
+ * @param Mage_Catalog_Model_Category $object
+ * @inheritDoc
+ */
+ protected function _afterSave(Varien_Object $object)
+ {
+ /**
+ * Add identifier for new category
+ */
+ if (substr($object->getPath(), -1) == '/') {
+ $object->setPath($object->getPath() . $object->getId());
+ $this->_savePath($object);
+ }
+
+ $this->_saveCategoryProducts($object);
+ return parent::_afterSave($object);
+ }
+
+ /**
+ * Update path field
+ *
+ * @param Mage_Catalog_Model_Category $object
+ * @return $this
+ */
+ protected function _savePath($object)
+ {
+ if ($object->getId()) {
+ $this->_getWriteAdapter()->update(
+ $this->getEntityTable(),
+ ['path' => $object->getPath()],
+ ['entity_id = ?' => $object->getId()],
+ );
+ }
+ return $this;
+ }
+
+ /**
+ * Get maximum position of child categories by specific tree path
+ *
+ * @param string $path
+ * @return int
+ */
+ protected function _getMaxPosition($path)
+ {
+ $adapter = $this->getReadConnection();
+ $positionField = $adapter->quoteIdentifier('position');
+ $level = count(explode('/', $path));
+ $bind = [
+ 'c_level' => $level,
+ 'c_path' => $path . '/%',
+ ];
+ $select = $adapter->select()
+ ->from($this->getTable('catalog/category'), 'MAX(' . $positionField . ')')
+ ->where($adapter->quoteIdentifier('path') . ' LIKE :c_path')
+ ->where($adapter->quoteIdentifier('level') . ' = :c_level');
+
+ $position = $adapter->fetchOne($select, $bind);
+ if (!$position) {
+ $position = 0;
+ }
+ return $position;
+ }
+
+ /**
+ * Save category products relation
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @return $this
+ */
+ protected function _saveCategoryProducts($category)
+ {
+ $category->setIsChangedProductList(false);
+ $id = $category->getId();
+ /**
+ * new category-product relationships
+ */
+ $products = $category->getPostedProducts();
+
+ /**
+ * Example re-save category
+ */
+ if ($products === null) {
+ return $this;
+ }
+
+ /**
+ * old category-product relationships
+ */
+ $oldProducts = $category->getProductsPosition();
+
+ $insert = array_diff_key($products, $oldProducts);
+ $delete = array_diff_key($oldProducts, $products);
+
+ /**
+ * Find product ids which are presented in both arrays
+ * and saved before (check $oldProducts array)
+ */
+ $update = array_intersect_key($products, $oldProducts);
+ $update = array_diff_assoc($update, $oldProducts);
+
+ $adapter = $this->_getWriteAdapter();
+
+ /**
+ * Delete products from category
+ */
+ if (!empty($delete)) {
+ $cond = [
+ 'product_id IN(?)' => array_keys($delete),
+ 'category_id=?' => $id,
+ ];
+ $adapter->delete($this->_categoryProductTable, $cond);
+ }
+
+ /**
+ * Add products to category
+ */
+ if (!empty($insert)) {
+ $data = [];
+ foreach ($insert as $productId => $position) {
+ $data[] = [
+ 'category_id' => (int) $id,
+ 'product_id' => (int) $productId,
+ 'position' => (int) $position,
+ ];
+ }
+ $adapter->insertMultiple($this->_categoryProductTable, $data);
+ }
+
+ /**
+ * Update product positions in category
+ */
+ if (!empty($update)) {
+ foreach ($update as $productId => $position) {
+ $where = [
+ 'category_id = ?' => (int) $id,
+ 'product_id = ?' => (int) $productId,
+ ];
+ $bind = ['position' => (int) $position];
+ $adapter->update($this->_categoryProductTable, $bind, $where);
+ }
+ }
+
+ if (!empty($insert) || !empty($delete)) {
+ $productIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
+ Mage::dispatchEvent('catalog_category_change_products', [
+ 'category' => $category,
+ 'product_ids' => $productIds,
+ ]);
+ }
+
+ if (!empty($insert) || !empty($update) || !empty($delete)) {
+ $category->setIsChangedProductList(true);
+
+ /**
+ * Setting affected products to category for third party engine index refresh
+ */
+ $productIds = array_keys($insert + $delete + $update);
+ $category->setAffectedProductIds($productIds);
+ }
+ return $this;
+ }
+
+ /**
+ * Get "is_active" attribute identifier
+ *
+ * @return int
+ */
+ protected function _getIsActiveAttributeId()
+ {
+ if ($this->_isActiveAttributeId === null) {
+ $attributeId = Mage::getSingleton('eav/config')
+ ->getAttribute(Mage_Catalog_Model_Category::ENTITY, 'is_active')
+ ->getId();
+ if (!is_int($attributeId)) {
+ Mage::throwException('Failed to find category attribute is_active');
+ }
+ $this->_isActiveAttributeId = $attributeId;
+ }
+
+ return $this->_isActiveAttributeId;
+ }
+
+ /**
+ * Prepare base collection setup for get categories list
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @return Mage_Catalog_Model_Resource_Category_Collection
+ */
+ protected function _getChildrenCategoriesBase($category)
+ {
+ $collection = $category->getCollection();
+ $collection->addAttributeToSelect('url_key')
+ ->addAttributeToSelect('name')
+ ->addAttributeToSelect('all_children')
+ ->addAttributeToSelect('is_anchor')
+ ->setOrder('position', Varien_Db_Select::SQL_ASC)
+ ->joinUrlRewrite();
+
+ return $collection;
+ }
+
+ /**
+ * Returns select for category's children.
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @param bool $recursive
+ * @return Varien_Db_Select
+ */
+ protected function _getChildrenIdSelect($category, $recursive = true)
+ {
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from(['m' => $this->getEntityTable()], 'entity_id')
+ ->where($adapter->quoteIdentifier('path') . ' LIKE ?', $category->getPath() . '/%');
+
+ if (!$recursive) {
+ $select->where($adapter->quoteIdentifier('level') . ' <= ?', $category->getLevel() + 1);
+ }
+ return $select;
+ }
+
/**
* Process positions of old parent category children and new parent category children.
* Get position for moved category
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Category/Attribute/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Category/Attribute/Collection.php
index e8d8354d4d0..6e6d5d43dc6 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Category/Attribute/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category/Attribute/Collection.php
@@ -22,6 +22,16 @@
*/
class Mage_Catalog_Model_Resource_Category_Attribute_Collection extends Mage_Eav_Model_Resource_Entity_Attribute_Collection
{
+ /**
+ * Specify attribute entity type filter
+ *
+ * @param int $typeId
+ * @return $this
+ */
+ public function setEntityTypeFilter($typeId)
+ {
+ return $this;
+ }
/**
* Main select object initialization.
* Joins catalog/eav_attribute table
@@ -38,15 +48,4 @@ protected function _initSelect()
);
return $this;
}
-
- /**
- * Specify attribute entity type filter
- *
- * @param int $typeId
- * @return $this
- */
- public function setEntityTypeFilter($typeId)
- {
- return $this;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Category/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Category/Collection.php
index 66dbb48267e..50372567d44 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Category/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category/Collection.php
@@ -89,18 +89,6 @@ public function __construct($resource = null, array $args = [])
$this->_factory = !empty($args['factory']) ? $args['factory'] : Mage::getSingleton('catalog/factory');
}
- /**
- * Init collection and determine table names
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/category');
-
- $this->_productWebsiteTable = $this->getTable('catalog/product_website');
- $this->_productTable = $this->getTable('catalog/category_product');
- }
-
/**
* Add Id filter
*
@@ -141,35 +129,6 @@ public function setLoadProductCount($flag)
return $this;
}
- /**
- * Before collection load
- *
- * @inheritDoc
- */
- protected function _beforeLoad()
- {
- Mage::dispatchEvent(
- $this->_eventPrefix . '_load_before',
- [$this->_eventObject => $this],
- );
- return parent::_beforeLoad();
- }
-
- /**
- * After collection load
- *
- * @inheritDoc
- */
- protected function _afterLoad()
- {
- Mage::dispatchEvent(
- $this->_eventPrefix . '_load_after',
- [$this->_eventObject => $this],
- );
-
- return parent::_afterLoad();
- }
-
/**
* Set id of the store that we should count products on
*
@@ -222,15 +181,6 @@ public function load($printQuery = false, $logQuery = false)
return $this;
}
- /**
- * Load categories product count
- *
- */
- protected function _loadProductCount()
- {
- $this->loadProductCount($this->_items, true, true);
- }
-
/**
* Load product count for specified items
*
@@ -345,16 +295,6 @@ public function joinUrlRewrite()
return $this;
}
- /**
- * Retrieves store_id from current store
- *
- * @return int
- */
- protected function _getCurrentStoreId()
- {
- return (int) Mage::app()->getStore()->getId();
- }
-
/**
* Add filter by path to collection
*
@@ -503,4 +443,64 @@ public function getNewEmptyItem()
{
return new $this->_itemObjectClass(['disable_flat' => $this->getDisableFlat()]);
}
+
+ /**
+ * Init collection and determine table names
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/category');
+
+ $this->_productWebsiteTable = $this->getTable('catalog/product_website');
+ $this->_productTable = $this->getTable('catalog/category_product');
+ }
+
+ /**
+ * Before collection load
+ *
+ * @inheritDoc
+ */
+ protected function _beforeLoad()
+ {
+ Mage::dispatchEvent(
+ $this->_eventPrefix . '_load_before',
+ [$this->_eventObject => $this],
+ );
+ return parent::_beforeLoad();
+ }
+
+ /**
+ * After collection load
+ *
+ * @inheritDoc
+ */
+ protected function _afterLoad()
+ {
+ Mage::dispatchEvent(
+ $this->_eventPrefix . '_load_after',
+ [$this->_eventObject => $this],
+ );
+
+ return parent::_afterLoad();
+ }
+
+ /**
+ * Load categories product count
+ *
+ */
+ protected function _loadProductCount()
+ {
+ $this->loadProductCount($this->_items, true, true);
+ }
+
+ /**
+ * Retrieves store_id from current store
+ *
+ * @return int
+ */
+ protected function _getCurrentStoreId()
+ {
+ return (int) Mage::app()->getStore()->getId();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php b/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php
index 4646733b124..212e6fde218 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php
@@ -122,11 +122,6 @@ public function __construct(array $args = [])
parent::__construct();
}
- protected function _construct()
- {
- $this->_init('catalog/category_flat', 'entity_id');
- }
-
/**
* Set store id
*
@@ -208,18 +203,6 @@ public function addInactiveCategoryIds($ids)
return $this;
}
- /**
- * Retrieve inactive categories ids
- *
- * @return $this
- */
- protected function _initInactiveCategoryIds()
- {
- $this->_inactiveCategoryIds = [];
- Mage::dispatchEvent('catalog_category_tree_init_inactive_category_ids', ['tree' => $this]);
- return $this;
- }
-
/**
* Retrieve inactive categories ids
*
@@ -234,82 +217,6 @@ public function getInactiveCategoryIds()
return $this->_inactiveCategoryIds;
}
- /**
- * Load nodes by parent id
- *
- * @param Mage_Catalog_Model_Category|int $parentNode
- * @param int $recursionLevel
- * @param int $storeId
- * @param bool $onlyActive
- * @return array
- */
- protected function _loadNodes($parentNode = null, $recursionLevel = 0, $storeId = 0, $onlyActive = true)
- {
- $_conn = $this->_getReadAdapter();
- $startLevel = 1;
- $parentPath = '';
- if ($parentNode instanceof Mage_Catalog_Model_Category) {
- $parentPath = $parentNode->getPath();
- $startLevel = $parentNode->getLevel();
- } elseif (is_numeric($parentNode)) {
- $selectParent = $_conn->select()
- ->from($this->getMainStoreTable($storeId))
- ->where('entity_id = ?', $parentNode)
- ->where('store_id = ?', $storeId);
- $parentNode = $_conn->fetchRow($selectParent);
- if ($parentNode) {
- $parentPath = $parentNode['path'];
- $startLevel = $parentNode['level'];
- }
- }
- $select = $_conn->select()
- ->from(
- ['main_table' => $this->getMainStoreTable($storeId)],
- ['entity_id',
- new Zend_Db_Expr('main_table.' . $_conn->quoteIdentifier('name')),
- new Zend_Db_Expr('main_table.' . $_conn->quoteIdentifier('path')),
- 'is_active',
- 'is_anchor'],
- )
-
- ->where('main_table.include_in_menu = ?', '1')
- ->order('main_table.position');
-
- if ($onlyActive) {
- $select->where('main_table.is_active = ?', '1');
- }
-
- /** @var Mage_Catalog_Helper_Category_Url_Rewrite_Interface $urlRewrite */
- $urlRewrite = $this->_factory->getCategoryUrlRewriteHelper();
- $urlRewrite->joinTableToSelect($select, $storeId);
-
- if ($parentPath) {
- $select->where($_conn->quoteInto('main_table.path like ?', "$parentPath/%"));
- }
- if ($recursionLevel != 0) {
- $levelField = $_conn->quoteIdentifier('level');
- $select->where($levelField . ' <= ?', $startLevel + $recursionLevel);
- }
-
- $inactiveCategories = $this->getInactiveCategoryIds();
-
- if (!empty($inactiveCategories)) {
- $select->where('main_table.entity_id NOT IN (?)', $inactiveCategories);
- }
-
- // Allow extensions to modify select (e.g. add custom category attributes to select)
- Mage::dispatchEvent('catalog_category_flat_loadnodes_before', ['select' => $select]);
-
- $arrNodes = $_conn->fetchAll($select);
- $nodes = [];
- foreach ($arrNodes as $node) {
- $node['id'] = $node['entity_id'];
- $nodes[$node['id']] = Mage::getModel('catalog/category')->setData($node);
- }
-
- return $nodes;
- }
-
/**
* Creating sorted array of nodes
*
@@ -525,948 +432,1083 @@ public function rebuild($stores = null)
}
/**
- * Prepare array of column and columnValue pairs
+ * Create Flat Table(s)
*
- * @param array $data
- * @return array
+ * @param array|int $stores
+ * @return $this
*/
- protected function _prepareValuesToInsert($data)
+ public function createTable($stores)
{
- $values = [];
- foreach (array_keys($this->_columns) as $key => $column) {
- if (isset($data[$column])) {
- $values[$column] = $data[$column];
- } else {
- $values[$column] = null;
- }
- }
- return $values;
+ return $this->_createTable($stores);
}
/**
- * Create Flat Table(s)
+ * Delete store table(s) of given stores;
*
* @param array|int $stores
* @return $this
*/
- public function createTable($stores)
+ public function deleteStores($stores)
{
- return $this->_createTable($stores);
+ $this->_deleteTable($stores);
+ return $this;
}
/**
- * Creating table and adding attributes as fields to table
+ * Synchronize flat data with eav model.
*
- * @param array|int $store
+ * @param Mage_Catalog_Model_Category|int $category
+ * @param array $storeIds
* @return $this
*/
- protected function _createTable($store)
+ public function synchronize($category = null, $storeIds = [])
{
- $tableName = $this->getMainStoreTable($store);
- $_writeAdapter = $this->_getWriteAdapter();
- $_writeAdapter->dropTable($tableName);
- $table = $this->_getWriteAdapter()
- ->newTable($tableName)
- ->setComment(sprintf('Catalog Category Flat (Store %d)', $store));
+ if (is_null($category)) {
+ if (empty($storeIds)) {
+ $storeIds = null;
+ }
+ $stores = $this->getStoresRootCategories($storeIds);
- //Adding columns
- if ($this->_columnsSql === null) {
- $this->_columns = array_merge($this->_getStaticColumns(), $this->_getEavColumns());
- foreach ($this->_columns as $fieldName => $fieldProp) {
- $default = $fieldProp['default'];
- if ($fieldProp['type'][0] == Varien_Db_Ddl_Table::TYPE_TIMESTAMP
- && $default === 'CURRENT_TIMESTAMP'
- ) {
- $default = Varien_Db_Ddl_Table::TIMESTAMP_INIT;
+ $storesObjects = [];
+ foreach ($stores as $storeId => $rootCategoryId) {
+ $_store = new Varien_Object([
+ 'store_id' => $storeId,
+ 'root_category_id' => $rootCategoryId,
+ ]);
+ $_store->setIdFieldName('store_id');
+ $storesObjects[] = $_store;
+ }
+
+ $this->rebuild($storesObjects);
+ } elseif ($category instanceof Mage_Catalog_Model_Category) {
+ $categoryId = $category->getId();
+ foreach ($category->getStoreIds() as $storeId) {
+ if ($storeId == Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID) {
+ continue;
}
- $table->addColumn($fieldName, $fieldProp['type'][0], $fieldProp['type'][1], [
- 'nullable' => $fieldProp['nullable'],
- 'unsigned' => $fieldProp['unsigned'],
- 'default' => $default,
- 'primary' => $fieldProp['primary'] ?? false,
- ], ($fieldProp['comment'] != '') ?
- $fieldProp['comment'] :
- ucwords(str_replace('_', ' ', $fieldName)));
+
+ $attributeValues = $this->_getAttributeValues($categoryId, $storeId);
+ $data = new Varien_Object($category->getData());
+ $data->addData($attributeValues[$categoryId])
+ ->setStoreId($storeId);
+ $this->_synchronize($data);
+ }
+ } elseif (is_numeric($category)) {
+ $write = $this->_getWriteAdapter();
+ $select = $write->select()
+ ->from($this->getTable('catalog/category'))
+ ->where('entity_id=?', $category);
+ $row = $write->fetchRow($select);
+ if (!$row) {
+ return $this;
}
- }
- // Adding indexes
- $table->addIndex(
- $_writeAdapter->getIndexName($tableName, ['entity_id']),
- ['entity_id'],
- ['type' => 'primary'],
- );
- $table->addIndex(
- $_writeAdapter->getIndexName($tableName, ['store_id']),
- ['store_id'],
- ['type' => 'index'],
- );
- $table->addIndex(
- $_writeAdapter->getIndexName($tableName, ['path']),
- ['path'],
- ['type' => 'index'],
- );
- $table->addIndex(
- $_writeAdapter->getIndexName($tableName, ['level']),
- ['level'],
- ['type' => 'index'],
- );
+ $stores = $this->getStoresRootCategories();
+ $path = explode('/', $row['path']);
+ foreach ($stores as $storeId => $rootCategoryId) {
+ if (in_array($rootCategoryId, $path)) {
+ $attributeValues = $this->_getAttributeValues($category, $storeId);
+ $data = new Varien_Object($row);
+ $data->addData($attributeValues[$category])
+ ->setStoreId($storeId);
+ $this->_synchronize($data);
+ } else {
+ $where = $write->quoteInto('entity_id = ?', $category);
+ $write->delete($this->getMainStoreTable($storeId), $where);
+ }
+ }
+ }
- // Adding foreign keys
- $table->addForeignKey(
- $_writeAdapter->getForeignKeyName(
- $tableName,
- 'entity_id',
- $this->getTable('catalog/category'),
- 'entity_id',
- ),
- 'entity_id',
- $this->getTable('catalog/category'),
- 'entity_id',
- Varien_Db_Ddl_Table::ACTION_CASCADE,
- Varien_Db_Ddl_Table::ACTION_CASCADE,
- );
- $table->addForeignKey(
- $_writeAdapter->getForeignKeyName($tableName, 'store_id', $this->getTable('core/store'), 'store_id'),
- 'store_id',
- $this->getTable('core/store'),
- 'store_id',
- Varien_Db_Ddl_Table::ACTION_CASCADE,
- Varien_Db_Ddl_Table::ACTION_CASCADE,
- );
- $_writeAdapter->createTable($table);
return $this;
}
/**
- * Return array of static columns
+ * Remove table of given stores
*
- * @return array
+ * @param int|array $stores
+ * @return $this
*/
- protected function _getStaticColumns()
+ public function removeStores($stores)
{
- /** @var Mage_Eav_Model_Resource_Helper_Mysql4 $helper */
- $helper = Mage::getResourceHelper('catalog');
- $columns = [];
- $columnsToSkip = ['entity_type_id', 'attribute_set_id'];
- $describe = $this->_getReadAdapter()->describeTable($this->getTable('catalog/category'));
+ $this->_deleteTable($stores);
+ return $this;
+ }
- foreach ($describe as $column) {
- if (in_array($column['COLUMN_NAME'], $columnsToSkip)) {
- continue;
+ /**
+ * Synchronize flat category data after move by affected category ids
+ *
+ * @return $this
+ */
+ public function move(array $affectedCategoryIds)
+ {
+ $write = $this->_getWriteAdapter();
+ $select = $write->select()
+ ->from($this->getTable('catalog/category'), ['entity_id', 'path'])
+ ->where('entity_id IN(?)', $affectedCategoryIds);
+ $pairs = $write->fetchPairs($select);
+
+ $pathCond = [$write->quoteInto('entity_id IN(?)', $affectedCategoryIds)];
+ $parentIds = [];
+
+ foreach ($pairs as $path) {
+ $pathCond[] = $write->quoteInto('path LIKE ?', $path . '/%');
+ $parentIds = array_merge($parentIds, explode('/', $path));
+ }
+
+ $stores = $this->getStoresRootCategories();
+ $where = implode(' OR ', $pathCond);
+ $lastId = 0;
+ while (true) {
+ $select = $write->select()
+ ->from($this->getTable('catalog/category'))
+ ->where('entity_id>?', $lastId)
+ ->where($where)
+ ->order('entity_id')
+ ->limit(500);
+ $rowSet = $write->fetchAll($select);
+
+ if (!$rowSet) {
+ break;
}
- $isUnsigned = '';
- $ddlType = $helper->getDdlTypeByColumnType($column['DATA_TYPE']);
- $column['DEFAULT'] = empty($column['DEFAULT']) ? $column['DEFAULT'] : trim($column['DEFAULT'], "' ");
- switch ($ddlType) {
- case Varien_Db_Ddl_Table::TYPE_SMALLINT:
- case Varien_Db_Ddl_Table::TYPE_INTEGER:
- case Varien_Db_Ddl_Table::TYPE_BIGINT:
- $isUnsigned = (bool) $column['UNSIGNED'];
- if ($column['DEFAULT'] === '') {
- $column['DEFAULT'] = null;
- }
- $options = null;
- if ($column['SCALE'] > 0) {
- $ddlType = Varien_Db_Ddl_Table::TYPE_DECIMAL;
+ $addStores = [];
+ $remStores = [];
+
+ foreach ($rowSet as &$row) {
+ $lastId = $row['entity_id'];
+ $path = explode('/', $row['path']);
+ foreach ($stores as $storeId => $rootCategoryId) {
+ if (in_array($rootCategoryId, $path)) {
+ $addStores[$storeId][$row['entity_id']] = $row;
} else {
- break;
- }
- // no break
- case Varien_Db_Ddl_Table::TYPE_DECIMAL:
- $options = $column['PRECISION'] . ',' . $column['SCALE'];
- $isUnsigned = null;
- if ($column['DEFAULT'] === '') {
- $column['DEFAULT'] = null;
+ $remStores[$storeId][] = $row['entity_id'];
}
- break;
- case Varien_Db_Ddl_Table::TYPE_TEXT:
- $options = $column['LENGTH'];
- $isUnsigned = null;
- break;
- case Varien_Db_Ddl_Table::TYPE_TIMESTAMP:
- $options = null;
- $isUnsigned = null;
- break;
- case Varien_Db_Ddl_Table::TYPE_DATETIME:
- $isUnsigned = null;
- break;
+ }
+ }
+
+ // remove
+ foreach ($remStores as $storeId => $categoryIds) {
+ $where = $write->quoteInto('entity_id IN(?)', $categoryIds);
+ $write->delete($this->getMainStoreTable($storeId), $where);
+ }
+
+ // add/update
+ foreach ($addStores as $storeId => $storeCategoryIds) {
+ $attributeValues = $this->_getAttributeValues(array_keys($storeCategoryIds), $storeId);
+ foreach ($storeCategoryIds as $row) {
+ $data = new Varien_Object($row);
+ $data->addData($attributeValues[$row['entity_id']])
+ ->setStoreId($storeId);
+ $this->_synchronize($data);
+ }
}
- $columns[$column['COLUMN_NAME']] = [
- 'type' => [$ddlType, $options],
- 'unsigned' => $isUnsigned,
- 'nullable' => $column['NULLABLE'],
- 'default' => $column['DEFAULT'] ?? false,
- 'comment' => $column['COLUMN_NAME'],
- ];
}
- $columns['store_id'] = [
- 'type' => [Varien_Db_Ddl_Table::TYPE_SMALLINT, 5],
- 'unsigned' => true,
- 'nullable' => false,
- 'default' => '0',
- 'comment' => 'Store Id',
- ];
- return $columns;
+
+ return $this;
}
/**
- * Return array of eav columns, skip attribute with static type
+ * Synchronize flat data with eav after moving category
*
- * @return array
+ * @param int $categoryId
+ * @param int $prevParentId
+ * @param int $parentId
+ * @return $this
*/
- protected function _getEavColumns()
+ public function moveold($categoryId, $prevParentId, $parentId)
{
- $columns = [];
- $attributes = $this->_getAttributes();
- foreach ($attributes as $attribute) {
- if ($attribute['backend_type'] === 'static') {
- continue;
+ $catalogCategoryTable = $this->getTable('catalog/category');
+ $_staticFields = [
+ 'parent_id',
+ 'path',
+ 'level',
+ 'position',
+ 'children_count',
+ 'updated_at',
+ ];
+ $prevParent = Mage::getModel('catalog/category')->load($prevParentId);
+ $parent = Mage::getModel('catalog/category')->load($parentId);
+ if ($prevParent->getStore()->getWebsiteId() != $parent->getStore()->getWebsiteId()) {
+ foreach ($prevParent->getStoreIds() as $storeId) {
+ $this->_getWriteAdapter()->delete(
+ $this->getMainStoreTable($storeId),
+ $this->_getWriteAdapter()->quoteInto('entity_id = ?', $categoryId),
+ );
}
- $columns[$attribute['attribute_code']] = [];
- switch ($attribute['backend_type']) {
- case 'varchar':
- $columns[$attribute['attribute_code']] = [
- 'type' => [Varien_Db_Ddl_Table::TYPE_TEXT, 255],
- 'unsigned' => null,
- 'nullable' => true,
- 'default' => null,
- 'comment' => (string) $attribute['frontend_label'],
- ];
- break;
- case 'int':
- $columns[$attribute['attribute_code']] = [
- 'type' => [Varien_Db_Ddl_Table::TYPE_INTEGER, null],
- 'unsigned' => null,
- 'nullable' => true,
- 'default' => null,
- 'comment' => (string) $attribute['frontend_label'],
- ];
- break;
- case 'text':
- $columns[$attribute['attribute_code']] = [
- 'type' => [Varien_Db_Ddl_Table::TYPE_TEXT, '64k'],
- 'unsigned' => null,
- 'nullable' => true,
- 'default' => null,
- 'comment' => (string) $attribute['frontend_label'],
- ];
- break;
- case 'datetime':
- $columns[$attribute['attribute_code']] = [
- 'type' => [Varien_Db_Ddl_Table::TYPE_DATETIME, null],
- 'unsigned' => null,
- 'nullable' => true,
- 'default' => null,
- 'comment' => (string) $attribute['frontend_label'],
- ];
- break;
- case 'decimal':
- $columns[$attribute['attribute_code']] = [
- 'type' => [Varien_Db_Ddl_Table::TYPE_DECIMAL, '12,4'],
- 'unsigned' => null,
- 'nullable' => true,
- 'default' => null,
- 'comment' => (string) $attribute['frontend_label'],
- ];
- break;
+ $select = $this->_getReadAdapter()->select()
+ ->from($catalogCategoryTable, 'path')
+ ->where('entity_id = ?', $categoryId);
+
+ $categoryPath = $this->_getWriteAdapter()->fetchOne($select);
+
+ $select = $this->_getWriteAdapter()->select()
+ ->from($catalogCategoryTable, 'entity_id')
+ ->where('path LIKE ?', "$categoryPath/%")
+ ->orWhere('path = ?', $categoryPath);
+ $_categories = $this->_getWriteAdapter()->fetchAll($select);
+ foreach ($_categories as $_category) {
+ foreach ($parent->getStoreIds() as $storeId) {
+ $_tmpCategory = Mage::getModel('catalog/category')
+ ->setStoreId($storeId)
+ ->load($_category['entity_id']);
+ $this->_synchronize($_tmpCategory);
+ }
+ }
+ } else {
+ foreach ($parent->getStoreIds() as $store) {
+ $mainStoreTable = $this->getMainStoreTable($store);
+
+ $update = "UPDATE {$mainStoreTable}, {$catalogCategoryTable} SET";
+ foreach ($_staticFields as $field) {
+ $update .= " {$mainStoreTable}." . $field . "={$catalogCategoryTable}." . $field . ',';
+ }
+ $update = substr($update, 0, -1);
+ $update .= " WHERE {$mainStoreTable}.entity_id = {$catalogCategoryTable}.entity_id AND " .
+ "($catalogCategoryTable}.path like '{$parent->getPath()}/%' OR " .
+ "{$catalogCategoryTable}.path like '{$prevParent->getPath()}/%')";
+ $this->_getWriteAdapter()->query($update);
}
}
- return $columns;
+ $prevParent = null;
+ $parent = null;
+ $_tmpCategory = null;
+ return $this;
}
/**
- * Return array of attribute codes for entity type 'catalog_category'
+ * Retrieve attribute instance
+ * Special for non static flat table
*
- * @return array
+ * @param mixed $attribute
+ * @return Mage_Eav_Model_Entity_Attribute_Abstract
*/
- protected function _getAttributes()
+ public function getAttribute($attribute)
{
- if ($this->_attributeCodes === null) {
- $select = $this->_getWriteAdapter()->select()
- ->from($this->getTable('eav/entity_type'), [])
- ->join(
- $this->getTable('eav/attribute'),
- $this->getTable('eav/attribute')
- . '.entity_type_id = ' . $this->getTable('eav/entity_type') . '.entity_type_id',
- $this->getTable('eav/attribute') . '.*',
- )
- ->where(
- $this->getTable('eav/entity_type') . '.entity_type_code = ?',
- Mage_Catalog_Model_Category::ENTITY,
- );
- $this->_attributeCodes = [];
- foreach ($this->_getWriteAdapter()->fetchAll($select) as $attribute) {
- $this->_attributeCodes[$attribute['attribute_id']] = $attribute;
- }
- }
- return $this->_attributeCodes;
+ return Mage::getSingleton('catalog/config')
+ ->getAttribute(Mage_Catalog_Model_Category::ENTITY, $attribute);
}
/**
- * Return attribute values for given entities and store
+ * Get count of active/not active children categories
*
- * @param int|string|array $entityIds
- * @param int $storeId
- * @return array
+ * @param Mage_Catalog_Model_Category $category
+ * @param bool $isActiveFlag
+ * @return int
*/
- protected function _getAttributeValues($entityIds, $storeId)
+ public function getChildrenAmount($category, $isActiveFlag = true)
{
- if (!is_array($entityIds)) {
- $entityIds = [$entityIds];
- }
- $values = [];
+ $_table = $this->getMainStoreTable($category->getStoreId());
+ $select = $this->_getReadAdapter()->select()
+ ->from($_table, "COUNT({$_table}.entity_id)")
+ ->where("{$_table}.path LIKE ?", $category->getPath() . '/%')
+ ->where("{$_table}.is_active = ?", (int) $isActiveFlag);
+ return (int) $this->_getReadAdapter()->fetchOne($select);
+ }
- foreach ($entityIds as $entityId) {
- $values[$entityId] = [];
- }
- $attributes = $this->_getAttributes();
- $attributesType = [
- 'varchar',
- 'int',
- 'decimal',
- 'text',
- 'datetime',
- ];
- foreach ($attributesType as $type) {
- foreach ($this->_getAttributeTypeValues($type, $entityIds, $storeId) as $row) {
- if (isset($attributes[$row['attribute_id']])) {
- $values[$row['entity_id']][$attributes[$row['attribute_id']]['attribute_code']] = $row['value'];
- }
- }
- }
- return $values;
+ /**
+ * Get products count in category
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @return int
+ */
+ public function getProductCount($category)
+ {
+ $select = $this->_getReadAdapter()->select()
+ ->from(
+ $this->getTable('catalog/category_product'),
+ "COUNT({$this->getTable('catalog/category_product')}.product_id)",
+ )
+ ->where("{$this->getTable('catalog/category_product')}.category_id = ?", $category->getId())
+ ->group("{$this->getTable('catalog/category_product')}.category_id");
+ return (int) $this->_getReadAdapter()->fetchOne($select);
}
/**
- * Return attribute values for given entities and store of specific attribute type
+ * Get positions of associated to category products
*
- * @param string $type
- * @param array $entityIds
- * @param int $storeId
+ * @param Mage_Catalog_Model_Category $category
* @return array
*/
- protected function _getAttributeTypeValues($type, $entityIds, $storeId)
+ public function getProductsPosition($category)
{
- $select = $this->_getWriteAdapter()->select()
+ $select = $this->_getReadAdapter()->select()
->from(
- ['def' => $this->getTable(['catalog/category', $type])],
- ['entity_id', 'attribute_id'],
+ $this->getTable('catalog/category_product'),
+ ['product_id', 'position'],
)
- ->joinLeft(
- ['store' => $this->getTable(['catalog/category', $type])],
- 'store.entity_id = def.entity_id AND store.attribute_id = def.attribute_id '
- . 'AND store.store_id = ' . $storeId,
- ['value' => $this->_getWriteAdapter()->getCheckSql(
- 'store.value_id > 0',
- $this->_getWriteAdapter()->quoteIdentifier('store.value'),
- $this->_getWriteAdapter()->quoteIdentifier('def.value'),
- )],
+ ->where('category_id = :category_id');
+ $bind = ['category_id' => (int) $category->getId()];
+ return $this->_getReadAdapter()->fetchPairs($select, $bind);
+ }
+
+ /**
+ * Return parent categories of category
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @param bool $isActive
+ * @return array
+ */
+ public function getParentCategories($category, $isActive = true)
+ {
+ $categories = [];
+ $select = $this->_getReadAdapter()->select()
+ ->from(
+ ['main_table' => $this->getMainStoreTable($category->getStoreId())],
+ ['main_table.entity_id', 'main_table.name'],
)
- ->where('def.entity_id IN (?)', $entityIds)
- ->where('def.store_id IN (?)', [Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID, $storeId]);
- return $this->_getWriteAdapter()->fetchAll($select);
+ ->where('main_table.entity_id IN (?)', array_reverse(explode(',', $category->getPathInStore())));
+ if ($isActive) {
+ $select->where('main_table.is_active = ?', '1');
+ }
+ $select->order('main_table.path ASC');
+
+ $urlRewrite = $this->_factory->getCategoryUrlRewriteHelper();
+ $urlRewrite->joinTableToSelect($select, $category->getStoreId());
+
+ $result = $this->_getReadAdapter()->fetchAll($select);
+ foreach ($result as $row) {
+ $row['id'] = $row['entity_id'];
+ $categories[$row['entity_id']] = Mage::getModel('catalog/category')->setData($row);
+ }
+ return $categories;
+ }
+
+ /**
+ * Return parent category of current category with own custom design settings
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @return Mage_Catalog_Model_Category
+ */
+ public function getParentDesignCategory($category)
+ {
+ $adapter = $this->_getReadAdapter();
+ $levelField = $adapter->quoteIdentifier('level');
+ $pathIds = array_reverse($category->getPathIds());
+ $select = $adapter->select()
+ ->from(['main_table' => $this->getMainStoreTable($category->getStoreId())], '*')
+ ->where('entity_id IN (?)', $pathIds)
+ ->where('custom_use_parent_settings = ?', 0)
+ ->where($levelField . ' != ?', 0)
+ ->order('level ' . Varien_Db_Select::SQL_DESC);
+ $result = $adapter->fetchRow($select);
+ return Mage::getModel('catalog/category')->setData($result);
+ }
+
+ /**
+ * Return children categories of category
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @return array
+ */
+ public function getChildrenCategories($category)
+ {
+ return $this->_loadNodes($category, 1, $category->getStoreId());
}
/**
- * Delete store table(s) of given stores;
+ * Return children categories of category with inactive
*
- * @param array|int $stores
- * @return $this
+ * @param Mage_Catalog_Model_Category $category
+ * @return array
*/
- public function deleteStores($stores)
+ public function getChildrenCategoriesWithInactive($category)
{
- $this->_deleteTable($stores);
- return $this;
+ return $this->_loadNodes($category, 1, $category->getStoreId(), false);
}
/**
- * Delete table(s) of given stores.
+ * Check is category in list of store categories
*
- * @param array|int $stores
- * @return $this
+ * @param Mage_Catalog_Model_Category $category
+ * @return bool
*/
- protected function _deleteTable($stores)
+ public function isInRootCategoryList($category)
{
- if (!is_array($stores)) {
- $stores = [$stores];
- }
- foreach ($stores as $store) {
- $this->_getWriteAdapter()->dropTable($this->getMainStoreTable($store));
- }
- return $this;
+ $pathIds = $category->getParentIds();
+ return in_array(Mage::app()->getStore()->getRootCategoryId(), $pathIds);
}
/**
- * Synchronize flat data with eav model for category
+ * Return children ids of category
*
- * @param Varien_Object $category
- * @return $this
+ * @param Mage_Catalog_Model_Category $category
+ * @param bool $recursive
+ * @param bool $isActive
+ * @return array
*/
- protected function _synchronize($category)
+ public function getChildren($category, $recursive = true, $isActive = true)
{
- $table = $this->getMainStoreTable($category->getStoreId());
- $data = $this->_prepareDataForAllFields($category);
- $this->_getWriteAdapter()->insertOnDuplicate($table, $data);
- return $this;
+ $maintable = $this->getMainStoreTable($category->getStoreId());
+ $select = $this->_getReadAdapter()->select()
+ ->from($maintable, 'entity_id')
+ ->where('path LIKE ?', "{$category->getPath()}/%")
+ ->order($maintable . '.position ASC');
+ if (!$recursive) {
+ $select->where('level <= ?', $category->getLevel() + 1);
+ }
+ if ($isActive) {
+ $select->where('is_active = ?', '1');
+ }
+
+ $_categories = $this->_getReadAdapter()->fetchAll($select);
+ $categoriesIds = [];
+ foreach ($_categories as $_category) {
+ $categoriesIds[] = $_category['entity_id'];
+ }
+ return $categoriesIds;
}
/**
- * Synchronize flat data with eav model.
+ * Return all children ids of category (with category id)
*
- * @param Mage_Catalog_Model_Category|int $category
- * @param array $storeIds
- * @return $this
+ * @param Mage_Catalog_Model_Category $category
+ * @return array
*/
- public function synchronize($category = null, $storeIds = [])
+ public function getAllChildren($category)
{
- if (is_null($category)) {
- if (empty($storeIds)) {
- $storeIds = null;
- }
- $stores = $this->getStoresRootCategories($storeIds);
-
- $storesObjects = [];
- foreach ($stores as $storeId => $rootCategoryId) {
- $_store = new Varien_Object([
- 'store_id' => $storeId,
- 'root_category_id' => $rootCategoryId,
- ]);
- $_store->setIdFieldName('store_id');
- $storesObjects[] = $_store;
- }
+ $categoriesIds = $this->getChildren($category);
+ $myId = [$category->getId()];
- $this->rebuild($storesObjects);
- } elseif ($category instanceof Mage_Catalog_Model_Category) {
- $categoryId = $category->getId();
- foreach ($category->getStoreIds() as $storeId) {
- if ($storeId == Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID) {
- continue;
- }
+ return array_merge($myId, $categoriesIds);
+ }
- $attributeValues = $this->_getAttributeValues($categoryId, $storeId);
- $data = new Varien_Object($category->getData());
- $data->addData($attributeValues[$categoryId])
- ->setStoreId($storeId);
- $this->_synchronize($data);
- }
- } elseif (is_numeric($category)) {
- $write = $this->_getWriteAdapter();
- $select = $write->select()
- ->from($this->getTable('catalog/category'))
- ->where('entity_id=?', $category);
- $row = $write->fetchRow($select);
- if (!$row) {
- return $this;
- }
+ /**
+ * Check if category id exist
+ *
+ * @param int $id
+ * @return bool
+ */
+ public function checkId($id)
+ {
+ $select = $this->_getReadAdapter()->select()
+ ->from($this->getMainStoreTable($this->getStoreId()), 'entity_id')
+ ->where('entity_id=?', $id);
+ return $this->_getReadAdapter()->fetchOne($select);
+ }
- $stores = $this->getStoresRootCategories();
- $path = explode('/', $row['path']);
- foreach ($stores as $storeId => $rootCategoryId) {
- if (in_array($rootCategoryId, $path)) {
- $attributeValues = $this->_getAttributeValues($category, $storeId);
- $data = new Varien_Object($row);
- $data->addData($attributeValues[$category])
- ->setStoreId($storeId);
- $this->_synchronize($data);
- } else {
- $where = $write->quoteInto('entity_id = ?', $category);
- $write->delete($this->getMainStoreTable($storeId), $where);
- }
+ /**
+ * Get design update data of parent categories
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @return array
+ */
+ public function getDesignUpdateData($category)
+ {
+ $categories = [];
+ $pathIds = [];
+ foreach (array_reverse($category->getParentIds()) as $pathId) {
+ if ($pathId == Mage::app()->getStore()->getRootCategoryId()) {
+ $pathIds[] = $pathId;
+ break;
}
+ $pathIds[] = $pathId;
}
-
- return $this;
+ $select = $this->_getReadAdapter()->select()
+ ->from(
+ ['main_table' => $this->getMainStoreTable($category->getStoreId())],
+ [
+ 'main_table.entity_id',
+ 'main_table.custom_design',
+ 'main_table.custom_design_apply',
+ 'main_table.custom_design_from',
+ 'main_table.custom_design_to',
+ ],
+ )
+ ->where('main_table.entity_id IN (?)', $pathIds)
+ ->where('main_table.is_active = ?', '1')
+ ->order('main_table.path ' . Varien_Db_Select::SQL_DESC);
+ $result = $this->_getReadAdapter()->fetchAll($select);
+ foreach ($result as $row) {
+ $row['id'] = $row['entity_id'];
+ $categories[$row['entity_id']] = Mage::getModel('catalog/category')->setData($row);
+ }
+ return $categories;
}
/**
- * Remove table of given stores
+ * Retrieve anchors above
*
- * @param int|array $stores
- * @return $this
+ * @param int $storeId
+ * @return array
*/
- public function removeStores($stores)
+ public function getAnchorsAbove(array $filterIds, $storeId = 0)
{
- $this->_deleteTable($stores);
- return $this;
+ $select = $this->_getReadAdapter()->select()
+ ->from(['e' => $this->getMainStoreTable($storeId)], 'entity_id')
+ ->where('is_anchor = ?', 1)
+ ->where('entity_id IN (?)', $filterIds);
+
+ return $this->_getReadAdapter()->fetchCol($select);
}
/**
- * Synchronize flat category data after move by affected category ids
+ * Retrieve array with root category id per store
*
- * @return $this
+ * @param int|array $storeIds result limitation
+ * @return array
*/
- public function move(array $affectedCategoryIds)
+ public function getStoresRootCategories($storeIds = null)
{
- $write = $this->_getWriteAdapter();
- $select = $write->select()
- ->from($this->getTable('catalog/category'), ['entity_id', 'path'])
- ->where('entity_id IN(?)', $affectedCategoryIds);
- $pairs = $write->fetchPairs($select);
-
- $pathCond = [$write->quoteInto('entity_id IN(?)', $affectedCategoryIds)];
- $parentIds = [];
-
- foreach ($pairs as $path) {
- $pathCond[] = $write->quoteInto('path LIKE ?', $path . '/%');
- $parentIds = array_merge($parentIds, explode('/', $path));
+ if (is_null($this->_storesRootCategories)) {
+ $select = $this->_getWriteAdapter()->select()
+ ->from(['cs' => $this->getTable('core/store')], ['store_id'])
+ ->join(
+ ['csg' => $this->getTable('core/store_group')],
+ 'csg.group_id = cs.group_id',
+ ['root_category_id'],
+ )
+ ->where('cs.store_id <> ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID);
+ $this->_storesRootCategories = $this->_getWriteAdapter()->fetchPairs($select);
}
- $stores = $this->getStoresRootCategories();
- $where = implode(' OR ', $pathCond);
- $lastId = 0;
- while (true) {
- $select = $write->select()
- ->from($this->getTable('catalog/category'))
- ->where('entity_id>?', $lastId)
- ->where($where)
- ->order('entity_id')
- ->limit(500);
- $rowSet = $write->fetchAll($select);
-
- if (!$rowSet) {
- break;
- }
-
- $addStores = [];
- $remStores = [];
-
- foreach ($rowSet as &$row) {
- $lastId = $row['entity_id'];
- $path = explode('/', $row['path']);
- foreach ($stores as $storeId => $rootCategoryId) {
- if (in_array($rootCategoryId, $path)) {
- $addStores[$storeId][$row['entity_id']] = $row;
- } else {
- $remStores[$storeId][] = $row['entity_id'];
- }
- }
- }
-
- // remove
- foreach ($remStores as $storeId => $categoryIds) {
- $where = $write->quoteInto('entity_id IN(?)', $categoryIds);
- $write->delete($this->getMainStoreTable($storeId), $where);
+ if (!is_null($storeIds)) {
+ if (!is_array($storeIds)) {
+ $storeIds = [$storeIds];
}
- // add/update
- foreach ($addStores as $storeId => $storeCategoryIds) {
- $attributeValues = $this->_getAttributeValues(array_keys($storeCategoryIds), $storeId);
- foreach ($storeCategoryIds as $row) {
- $data = new Varien_Object($row);
- $data->addData($attributeValues[$row['entity_id']])
- ->setStoreId($storeId);
- $this->_synchronize($data);
+ $stores = [];
+ foreach ($this->_storesRootCategories as $storeId => $rootId) {
+ if (in_array($storeId, $storeIds)) {
+ $stores[$storeId] = $rootId;
}
}
+ return $stores;
}
- return $this;
+ return $this->_storesRootCategories;
}
/**
- * Synchronize flat data with eav after moving category
+ * Transactional rebuild flat data from eav
*
- * @param int $categoryId
- * @param int $prevParentId
- * @param int $parentId
+ * @throws Exception
* @return $this
*/
- public function moveold($categoryId, $prevParentId, $parentId)
+ public function reindexAll()
{
- $catalogCategoryTable = $this->getTable('catalog/category');
- $_staticFields = [
- 'parent_id',
- 'path',
- 'level',
- 'position',
- 'children_count',
- 'updated_at',
- ];
- $prevParent = Mage::getModel('catalog/category')->load($prevParentId);
- $parent = Mage::getModel('catalog/category')->load($parentId);
- if ($prevParent->getStore()->getWebsiteId() != $parent->getStore()->getWebsiteId()) {
- foreach ($prevParent->getStoreIds() as $storeId) {
- $this->_getWriteAdapter()->delete(
- $this->getMainStoreTable($storeId),
- $this->_getWriteAdapter()->quoteInto('entity_id = ?', $categoryId),
- );
- }
- $select = $this->_getReadAdapter()->select()
- ->from($catalogCategoryTable, 'path')
- ->where('entity_id = ?', $categoryId);
-
- $categoryPath = $this->_getWriteAdapter()->fetchOne($select);
-
- $select = $this->_getWriteAdapter()->select()
- ->from($catalogCategoryTable, 'entity_id')
- ->where('path LIKE ?', "$categoryPath/%")
- ->orWhere('path = ?', $categoryPath);
- $_categories = $this->_getWriteAdapter()->fetchAll($select);
- foreach ($_categories as $_category) {
- foreach ($parent->getStoreIds() as $storeId) {
- $_tmpCategory = Mage::getModel('catalog/category')
- ->setStoreId($storeId)
- ->load($_category['entity_id']);
- $this->_synchronize($_tmpCategory);
- }
+ $this->_createTables();
+ $allowTableChanges = $this->_allowTableChanges;
+ if ($allowTableChanges) {
+ $this->_allowTableChanges = false;
+ }
+ $this->beginTransaction();
+ try {
+ $this->rebuild();
+ $this->commit();
+ if ($allowTableChanges) {
+ $this->_allowTableChanges = true;
}
- } else {
- foreach ($parent->getStoreIds() as $store) {
- $mainStoreTable = $this->getMainStoreTable($store);
-
- $update = "UPDATE {$mainStoreTable}, {$catalogCategoryTable} SET";
- foreach ($_staticFields as $field) {
- $update .= " {$mainStoreTable}." . $field . "={$catalogCategoryTable}." . $field . ',';
- }
- $update = substr($update, 0, -1);
- $update .= " WHERE {$mainStoreTable}.entity_id = {$catalogCategoryTable}.entity_id AND " .
- "($catalogCategoryTable}.path like '{$parent->getPath()}/%' OR " .
- "{$catalogCategoryTable}.path like '{$prevParent->getPath()}/%')";
- $this->_getWriteAdapter()->query($update);
+ } catch (Exception $e) {
+ $this->rollBack();
+ if ($allowTableChanges) {
+ $this->_allowTableChanges = true;
}
+ throw $e;
}
- $prevParent = null;
- $parent = null;
- $_tmpCategory = null;
return $this;
}
/**
- * Prepare array of category data to insert or update.
- * array(
- * 'field_name' => 'value'
- * )
+ * Check if Catalog Category Flat Data has been initialized
*
- * @param Varien_Object $category
- * @param array $replaceFields
- * @return array
- */
- protected function _prepareDataForAllFields($category, $replaceFields = [])
- {
- $table = $this->getMainStoreTable($category->getStoreId());
- $this->_getWriteAdapter()->resetDdlCache($table);
- $table = $this->_getReadAdapter()->describeTable($table);
- $data = [];
- $idFieldName = Mage::getSingleton('catalog/category')->getIdFieldName();
- foreach (array_keys($table) as $column) {
- if ($column != $idFieldName || $category->getData($column) !== null) {
- if (array_key_exists($column, $replaceFields)) {
- $value = $category->getData($replaceFields[$column]);
- } else {
- $value = $category->getData($column);
- }
- if (is_array($value)) {
- $value = implode(',', $value);
- }
- $data[$column] = $value;
- }
- }
- return $data;
- }
-
- /**
- * Retrieve attribute instance
- * Special for non static flat table
+ * @deprecated use Mage_Catalog_Model_Resource_Category_Flat::isBuilt() instead
*
- * @param mixed $attribute
- * @return Mage_Eav_Model_Entity_Attribute_Abstract
+ * @return bool
*/
- public function getAttribute($attribute)
+ public function isRebuilt()
{
- return Mage::getSingleton('catalog/config')
- ->getAttribute(Mage_Catalog_Model_Category::ENTITY, $attribute);
+ return $this->isBuilt();
}
- /**
- * Get count of active/not active children categories
- *
- * @param Mage_Catalog_Model_Category $category
- * @param bool $isActiveFlag
- * @return int
- */
- public function getChildrenAmount($category, $isActiveFlag = true)
+ protected function _construct()
{
- $_table = $this->getMainStoreTable($category->getStoreId());
- $select = $this->_getReadAdapter()->select()
- ->from($_table, "COUNT({$_table}.entity_id)")
- ->where("{$_table}.path LIKE ?", $category->getPath() . '/%')
- ->where("{$_table}.is_active = ?", (int) $isActiveFlag);
- return (int) $this->_getReadAdapter()->fetchOne($select);
+ $this->_init('catalog/category_flat', 'entity_id');
}
/**
- * Get products count in category
+ * Retrieve inactive categories ids
*
- * @param Mage_Catalog_Model_Category $category
- * @return int
+ * @return $this
*/
- public function getProductCount($category)
+ protected function _initInactiveCategoryIds()
{
- $select = $this->_getReadAdapter()->select()
- ->from(
- $this->getTable('catalog/category_product'),
- "COUNT({$this->getTable('catalog/category_product')}.product_id)",
- )
- ->where("{$this->getTable('catalog/category_product')}.category_id = ?", $category->getId())
- ->group("{$this->getTable('catalog/category_product')}.category_id");
- return (int) $this->_getReadAdapter()->fetchOne($select);
+ $this->_inactiveCategoryIds = [];
+ Mage::dispatchEvent('catalog_category_tree_init_inactive_category_ids', ['tree' => $this]);
+ return $this;
}
/**
- * Get positions of associated to category products
+ * Load nodes by parent id
*
- * @param Mage_Catalog_Model_Category $category
+ * @param Mage_Catalog_Model_Category|int $parentNode
+ * @param int $recursionLevel
+ * @param int $storeId
+ * @param bool $onlyActive
* @return array
*/
- public function getProductsPosition($category)
+ protected function _loadNodes($parentNode = null, $recursionLevel = 0, $storeId = 0, $onlyActive = true)
{
- $select = $this->_getReadAdapter()->select()
+ $_conn = $this->_getReadAdapter();
+ $startLevel = 1;
+ $parentPath = '';
+ if ($parentNode instanceof Mage_Catalog_Model_Category) {
+ $parentPath = $parentNode->getPath();
+ $startLevel = $parentNode->getLevel();
+ } elseif (is_numeric($parentNode)) {
+ $selectParent = $_conn->select()
+ ->from($this->getMainStoreTable($storeId))
+ ->where('entity_id = ?', $parentNode)
+ ->where('store_id = ?', $storeId);
+ $parentNode = $_conn->fetchRow($selectParent);
+ if ($parentNode) {
+ $parentPath = $parentNode['path'];
+ $startLevel = $parentNode['level'];
+ }
+ }
+ $select = $_conn->select()
->from(
- $this->getTable('catalog/category_product'),
- ['product_id', 'position'],
+ ['main_table' => $this->getMainStoreTable($storeId)],
+ ['entity_id',
+ new Zend_Db_Expr('main_table.' . $_conn->quoteIdentifier('name')),
+ new Zend_Db_Expr('main_table.' . $_conn->quoteIdentifier('path')),
+ 'is_active',
+ 'is_anchor'],
)
- ->where('category_id = :category_id');
- $bind = ['category_id' => (int) $category->getId()];
- return $this->_getReadAdapter()->fetchPairs($select, $bind);
- }
- /**
- * Return parent categories of category
- *
- * @param Mage_Catalog_Model_Category $category
- * @param bool $isActive
- * @return array
- */
- public function getParentCategories($category, $isActive = true)
- {
- $categories = [];
- $select = $this->_getReadAdapter()->select()
- ->from(
- ['main_table' => $this->getMainStoreTable($category->getStoreId())],
- ['main_table.entity_id', 'main_table.name'],
- )
- ->where('main_table.entity_id IN (?)', array_reverse(explode(',', $category->getPathInStore())));
- if ($isActive) {
+ ->where('main_table.include_in_menu = ?', '1')
+ ->order('main_table.position');
+
+ if ($onlyActive) {
$select->where('main_table.is_active = ?', '1');
}
- $select->order('main_table.path ASC');
+ /** @var Mage_Catalog_Helper_Category_Url_Rewrite_Interface $urlRewrite */
$urlRewrite = $this->_factory->getCategoryUrlRewriteHelper();
- $urlRewrite->joinTableToSelect($select, $category->getStoreId());
+ $urlRewrite->joinTableToSelect($select, $storeId);
- $result = $this->_getReadAdapter()->fetchAll($select);
- foreach ($result as $row) {
- $row['id'] = $row['entity_id'];
- $categories[$row['entity_id']] = Mage::getModel('catalog/category')->setData($row);
+ if ($parentPath) {
+ $select->where($_conn->quoteInto('main_table.path like ?', "$parentPath/%"));
+ }
+ if ($recursionLevel != 0) {
+ $levelField = $_conn->quoteIdentifier('level');
+ $select->where($levelField . ' <= ?', $startLevel + $recursionLevel);
+ }
+
+ $inactiveCategories = $this->getInactiveCategoryIds();
+
+ if (!empty($inactiveCategories)) {
+ $select->where('main_table.entity_id NOT IN (?)', $inactiveCategories);
+ }
+
+ // Allow extensions to modify select (e.g. add custom category attributes to select)
+ Mage::dispatchEvent('catalog_category_flat_loadnodes_before', ['select' => $select]);
+
+ $arrNodes = $_conn->fetchAll($select);
+ $nodes = [];
+ foreach ($arrNodes as $node) {
+ $node['id'] = $node['entity_id'];
+ $nodes[$node['id']] = Mage::getModel('catalog/category')->setData($node);
}
- return $categories;
+
+ return $nodes;
}
/**
- * Return parent category of current category with own custom design settings
+ * Prepare array of column and columnValue pairs
*
- * @param Mage_Catalog_Model_Category $category
- * @return Mage_Catalog_Model_Category
+ * @param array $data
+ * @return array
*/
- public function getParentDesignCategory($category)
+ protected function _prepareValuesToInsert($data)
{
- $adapter = $this->_getReadAdapter();
- $levelField = $adapter->quoteIdentifier('level');
- $pathIds = array_reverse($category->getPathIds());
- $select = $adapter->select()
- ->from(['main_table' => $this->getMainStoreTable($category->getStoreId())], '*')
- ->where('entity_id IN (?)', $pathIds)
- ->where('custom_use_parent_settings = ?', 0)
- ->where($levelField . ' != ?', 0)
- ->order('level ' . Varien_Db_Select::SQL_DESC);
- $result = $adapter->fetchRow($select);
- return Mage::getModel('catalog/category')->setData($result);
+ $values = [];
+ foreach (array_keys($this->_columns) as $key => $column) {
+ if (isset($data[$column])) {
+ $values[$column] = $data[$column];
+ } else {
+ $values[$column] = null;
+ }
+ }
+ return $values;
}
/**
- * Return children categories of category
+ * Creating table and adding attributes as fields to table
*
- * @param Mage_Catalog_Model_Category $category
- * @return array
+ * @param array|int $store
+ * @return $this
*/
- public function getChildrenCategories($category)
+ protected function _createTable($store)
{
- return $this->_loadNodes($category, 1, $category->getStoreId());
+ $tableName = $this->getMainStoreTable($store);
+ $_writeAdapter = $this->_getWriteAdapter();
+ $_writeAdapter->dropTable($tableName);
+ $table = $this->_getWriteAdapter()
+ ->newTable($tableName)
+ ->setComment(sprintf('Catalog Category Flat (Store %d)', $store));
+
+ //Adding columns
+ if ($this->_columnsSql === null) {
+ $this->_columns = array_merge($this->_getStaticColumns(), $this->_getEavColumns());
+ foreach ($this->_columns as $fieldName => $fieldProp) {
+ $default = $fieldProp['default'];
+ if ($fieldProp['type'][0] == Varien_Db_Ddl_Table::TYPE_TIMESTAMP
+ && $default === 'CURRENT_TIMESTAMP'
+ ) {
+ $default = Varien_Db_Ddl_Table::TIMESTAMP_INIT;
+ }
+ $table->addColumn($fieldName, $fieldProp['type'][0], $fieldProp['type'][1], [
+ 'nullable' => $fieldProp['nullable'],
+ 'unsigned' => $fieldProp['unsigned'],
+ 'default' => $default,
+ 'primary' => $fieldProp['primary'] ?? false,
+ ], ($fieldProp['comment'] != '') ?
+ $fieldProp['comment'] :
+ ucwords(str_replace('_', ' ', $fieldName)));
+ }
+ }
+
+ // Adding indexes
+ $table->addIndex(
+ $_writeAdapter->getIndexName($tableName, ['entity_id']),
+ ['entity_id'],
+ ['type' => 'primary'],
+ );
+ $table->addIndex(
+ $_writeAdapter->getIndexName($tableName, ['store_id']),
+ ['store_id'],
+ ['type' => 'index'],
+ );
+ $table->addIndex(
+ $_writeAdapter->getIndexName($tableName, ['path']),
+ ['path'],
+ ['type' => 'index'],
+ );
+ $table->addIndex(
+ $_writeAdapter->getIndexName($tableName, ['level']),
+ ['level'],
+ ['type' => 'index'],
+ );
+
+ // Adding foreign keys
+ $table->addForeignKey(
+ $_writeAdapter->getForeignKeyName(
+ $tableName,
+ 'entity_id',
+ $this->getTable('catalog/category'),
+ 'entity_id',
+ ),
+ 'entity_id',
+ $this->getTable('catalog/category'),
+ 'entity_id',
+ Varien_Db_Ddl_Table::ACTION_CASCADE,
+ Varien_Db_Ddl_Table::ACTION_CASCADE,
+ );
+ $table->addForeignKey(
+ $_writeAdapter->getForeignKeyName($tableName, 'store_id', $this->getTable('core/store'), 'store_id'),
+ 'store_id',
+ $this->getTable('core/store'),
+ 'store_id',
+ Varien_Db_Ddl_Table::ACTION_CASCADE,
+ Varien_Db_Ddl_Table::ACTION_CASCADE,
+ );
+ $_writeAdapter->createTable($table);
+ return $this;
}
/**
- * Return children categories of category with inactive
+ * Return array of static columns
*
- * @param Mage_Catalog_Model_Category $category
* @return array
*/
- public function getChildrenCategoriesWithInactive($category)
+ protected function _getStaticColumns()
{
- return $this->_loadNodes($category, 1, $category->getStoreId(), false);
+ /** @var Mage_Eav_Model_Resource_Helper_Mysql4 $helper */
+ $helper = Mage::getResourceHelper('catalog');
+ $columns = [];
+ $columnsToSkip = ['entity_type_id', 'attribute_set_id'];
+ $describe = $this->_getReadAdapter()->describeTable($this->getTable('catalog/category'));
+
+ foreach ($describe as $column) {
+ if (in_array($column['COLUMN_NAME'], $columnsToSkip)) {
+ continue;
+ }
+ $isUnsigned = '';
+ $ddlType = $helper->getDdlTypeByColumnType($column['DATA_TYPE']);
+ $column['DEFAULT'] = empty($column['DEFAULT']) ? $column['DEFAULT'] : trim($column['DEFAULT'], "' ");
+ switch ($ddlType) {
+ case Varien_Db_Ddl_Table::TYPE_SMALLINT:
+ case Varien_Db_Ddl_Table::TYPE_INTEGER:
+ case Varien_Db_Ddl_Table::TYPE_BIGINT:
+ $isUnsigned = (bool) $column['UNSIGNED'];
+ if ($column['DEFAULT'] === '') {
+ $column['DEFAULT'] = null;
+ }
+
+ $options = null;
+ if ($column['SCALE'] > 0) {
+ $ddlType = Varien_Db_Ddl_Table::TYPE_DECIMAL;
+ } else {
+ break;
+ }
+ // no break
+ case Varien_Db_Ddl_Table::TYPE_DECIMAL:
+ $options = $column['PRECISION'] . ',' . $column['SCALE'];
+ $isUnsigned = null;
+ if ($column['DEFAULT'] === '') {
+ $column['DEFAULT'] = null;
+ }
+ break;
+ case Varien_Db_Ddl_Table::TYPE_TEXT:
+ $options = $column['LENGTH'];
+ $isUnsigned = null;
+ break;
+ case Varien_Db_Ddl_Table::TYPE_TIMESTAMP:
+ $options = null;
+ $isUnsigned = null;
+ break;
+ case Varien_Db_Ddl_Table::TYPE_DATETIME:
+ $isUnsigned = null;
+ break;
+ }
+ $columns[$column['COLUMN_NAME']] = [
+ 'type' => [$ddlType, $options],
+ 'unsigned' => $isUnsigned,
+ 'nullable' => $column['NULLABLE'],
+ 'default' => $column['DEFAULT'] ?? false,
+ 'comment' => $column['COLUMN_NAME'],
+ ];
+ }
+ $columns['store_id'] = [
+ 'type' => [Varien_Db_Ddl_Table::TYPE_SMALLINT, 5],
+ 'unsigned' => true,
+ 'nullable' => false,
+ 'default' => '0',
+ 'comment' => 'Store Id',
+ ];
+ return $columns;
}
/**
- * Check is category in list of store categories
+ * Return array of eav columns, skip attribute with static type
*
- * @param Mage_Catalog_Model_Category $category
- * @return bool
+ * @return array
*/
- public function isInRootCategoryList($category)
+ protected function _getEavColumns()
{
- $pathIds = $category->getParentIds();
- return in_array(Mage::app()->getStore()->getRootCategoryId(), $pathIds);
+ $columns = [];
+ $attributes = $this->_getAttributes();
+ foreach ($attributes as $attribute) {
+ if ($attribute['backend_type'] === 'static') {
+ continue;
+ }
+ $columns[$attribute['attribute_code']] = [];
+ switch ($attribute['backend_type']) {
+ case 'varchar':
+ $columns[$attribute['attribute_code']] = [
+ 'type' => [Varien_Db_Ddl_Table::TYPE_TEXT, 255],
+ 'unsigned' => null,
+ 'nullable' => true,
+ 'default' => null,
+ 'comment' => (string) $attribute['frontend_label'],
+ ];
+ break;
+ case 'int':
+ $columns[$attribute['attribute_code']] = [
+ 'type' => [Varien_Db_Ddl_Table::TYPE_INTEGER, null],
+ 'unsigned' => null,
+ 'nullable' => true,
+ 'default' => null,
+ 'comment' => (string) $attribute['frontend_label'],
+ ];
+ break;
+ case 'text':
+ $columns[$attribute['attribute_code']] = [
+ 'type' => [Varien_Db_Ddl_Table::TYPE_TEXT, '64k'],
+ 'unsigned' => null,
+ 'nullable' => true,
+ 'default' => null,
+ 'comment' => (string) $attribute['frontend_label'],
+ ];
+ break;
+ case 'datetime':
+ $columns[$attribute['attribute_code']] = [
+ 'type' => [Varien_Db_Ddl_Table::TYPE_DATETIME, null],
+ 'unsigned' => null,
+ 'nullable' => true,
+ 'default' => null,
+ 'comment' => (string) $attribute['frontend_label'],
+ ];
+ break;
+ case 'decimal':
+ $columns[$attribute['attribute_code']] = [
+ 'type' => [Varien_Db_Ddl_Table::TYPE_DECIMAL, '12,4'],
+ 'unsigned' => null,
+ 'nullable' => true,
+ 'default' => null,
+ 'comment' => (string) $attribute['frontend_label'],
+ ];
+ break;
+ }
+ }
+ return $columns;
}
/**
- * Return children ids of category
+ * Return array of attribute codes for entity type 'catalog_category'
*
- * @param Mage_Catalog_Model_Category $category
- * @param bool $recursive
- * @param bool $isActive
* @return array
*/
- public function getChildren($category, $recursive = true, $isActive = true)
+ protected function _getAttributes()
{
- $maintable = $this->getMainStoreTable($category->getStoreId());
- $select = $this->_getReadAdapter()->select()
- ->from($maintable, 'entity_id')
- ->where('path LIKE ?', "{$category->getPath()}/%")
- ->order($maintable . '.position ASC');
- if (!$recursive) {
- $select->where('level <= ?', $category->getLevel() + 1);
- }
- if ($isActive) {
- $select->where('is_active = ?', '1');
- }
-
- $_categories = $this->_getReadAdapter()->fetchAll($select);
- $categoriesIds = [];
- foreach ($_categories as $_category) {
- $categoriesIds[] = $_category['entity_id'];
+ if ($this->_attributeCodes === null) {
+ $select = $this->_getWriteAdapter()->select()
+ ->from($this->getTable('eav/entity_type'), [])
+ ->join(
+ $this->getTable('eav/attribute'),
+ $this->getTable('eav/attribute')
+ . '.entity_type_id = ' . $this->getTable('eav/entity_type') . '.entity_type_id',
+ $this->getTable('eav/attribute') . '.*',
+ )
+ ->where(
+ $this->getTable('eav/entity_type') . '.entity_type_code = ?',
+ Mage_Catalog_Model_Category::ENTITY,
+ );
+ $this->_attributeCodes = [];
+ foreach ($this->_getWriteAdapter()->fetchAll($select) as $attribute) {
+ $this->_attributeCodes[$attribute['attribute_id']] = $attribute;
+ }
}
- return $categoriesIds;
+ return $this->_attributeCodes;
}
/**
- * Return all children ids of category (with category id)
+ * Return attribute values for given entities and store
*
- * @param Mage_Catalog_Model_Category $category
+ * @param int|string|array $entityIds
+ * @param int $storeId
* @return array
*/
- public function getAllChildren($category)
+ protected function _getAttributeValues($entityIds, $storeId)
{
- $categoriesIds = $this->getChildren($category);
- $myId = [$category->getId()];
+ if (!is_array($entityIds)) {
+ $entityIds = [$entityIds];
+ }
+ $values = [];
- return array_merge($myId, $categoriesIds);
+ foreach ($entityIds as $entityId) {
+ $values[$entityId] = [];
+ }
+ $attributes = $this->_getAttributes();
+ $attributesType = [
+ 'varchar',
+ 'int',
+ 'decimal',
+ 'text',
+ 'datetime',
+ ];
+ foreach ($attributesType as $type) {
+ foreach ($this->_getAttributeTypeValues($type, $entityIds, $storeId) as $row) {
+ if (isset($attributes[$row['attribute_id']])) {
+ $values[$row['entity_id']][$attributes[$row['attribute_id']]['attribute_code']] = $row['value'];
+ }
+ }
+ }
+ return $values;
}
/**
- * Check if category id exist
+ * Return attribute values for given entities and store of specific attribute type
*
- * @param int $id
- * @return bool
+ * @param string $type
+ * @param array $entityIds
+ * @param int $storeId
+ * @return array
*/
- public function checkId($id)
+ protected function _getAttributeTypeValues($type, $entityIds, $storeId)
{
- $select = $this->_getReadAdapter()->select()
- ->from($this->getMainStoreTable($this->getStoreId()), 'entity_id')
- ->where('entity_id=?', $id);
- return $this->_getReadAdapter()->fetchOne($select);
+ $select = $this->_getWriteAdapter()->select()
+ ->from(
+ ['def' => $this->getTable(['catalog/category', $type])],
+ ['entity_id', 'attribute_id'],
+ )
+ ->joinLeft(
+ ['store' => $this->getTable(['catalog/category', $type])],
+ 'store.entity_id = def.entity_id AND store.attribute_id = def.attribute_id '
+ . 'AND store.store_id = ' . $storeId,
+ ['value' => $this->_getWriteAdapter()->getCheckSql(
+ 'store.value_id > 0',
+ $this->_getWriteAdapter()->quoteIdentifier('store.value'),
+ $this->_getWriteAdapter()->quoteIdentifier('def.value'),
+ )],
+ )
+ ->where('def.entity_id IN (?)', $entityIds)
+ ->where('def.store_id IN (?)', [Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID, $storeId]);
+ return $this->_getWriteAdapter()->fetchAll($select);
}
/**
- * Get design update data of parent categories
+ * Delete table(s) of given stores.
*
- * @param Mage_Catalog_Model_Category $category
- * @return array
+ * @param array|int $stores
+ * @return $this
*/
- public function getDesignUpdateData($category)
+ protected function _deleteTable($stores)
{
- $categories = [];
- $pathIds = [];
- foreach (array_reverse($category->getParentIds()) as $pathId) {
- if ($pathId == Mage::app()->getStore()->getRootCategoryId()) {
- $pathIds[] = $pathId;
- break;
- }
- $pathIds[] = $pathId;
+ if (!is_array($stores)) {
+ $stores = [$stores];
}
- $select = $this->_getReadAdapter()->select()
- ->from(
- ['main_table' => $this->getMainStoreTable($category->getStoreId())],
- [
- 'main_table.entity_id',
- 'main_table.custom_design',
- 'main_table.custom_design_apply',
- 'main_table.custom_design_from',
- 'main_table.custom_design_to',
- ],
- )
- ->where('main_table.entity_id IN (?)', $pathIds)
- ->where('main_table.is_active = ?', '1')
- ->order('main_table.path ' . Varien_Db_Select::SQL_DESC);
- $result = $this->_getReadAdapter()->fetchAll($select);
- foreach ($result as $row) {
- $row['id'] = $row['entity_id'];
- $categories[$row['entity_id']] = Mage::getModel('catalog/category')->setData($row);
+ foreach ($stores as $store) {
+ $this->_getWriteAdapter()->dropTable($this->getMainStoreTable($store));
}
- return $categories;
+ return $this;
}
/**
- * Retrieve anchors above
+ * Synchronize flat data with eav model for category
*
- * @param int $storeId
- * @return array
+ * @param Varien_Object $category
+ * @return $this
*/
- public function getAnchorsAbove(array $filterIds, $storeId = 0)
+ protected function _synchronize($category)
{
- $select = $this->_getReadAdapter()->select()
- ->from(['e' => $this->getMainStoreTable($storeId)], 'entity_id')
- ->where('is_anchor = ?', 1)
- ->where('entity_id IN (?)', $filterIds);
-
- return $this->_getReadAdapter()->fetchCol($select);
+ $table = $this->getMainStoreTable($category->getStoreId());
+ $data = $this->_prepareDataForAllFields($category);
+ $this->_getWriteAdapter()->insertOnDuplicate($table, $data);
+ return $this;
}
/**
- * Retrieve array with root category id per store
+ * Prepare array of category data to insert or update.
+ * array(
+ * 'field_name' => 'value'
+ * )
*
- * @param int|array $storeIds result limitation
+ * @param Varien_Object $category
+ * @param array $replaceFields
* @return array
*/
- public function getStoresRootCategories($storeIds = null)
+ protected function _prepareDataForAllFields($category, $replaceFields = [])
{
- if (is_null($this->_storesRootCategories)) {
- $select = $this->_getWriteAdapter()->select()
- ->from(['cs' => $this->getTable('core/store')], ['store_id'])
- ->join(
- ['csg' => $this->getTable('core/store_group')],
- 'csg.group_id = cs.group_id',
- ['root_category_id'],
- )
- ->where('cs.store_id <> ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID);
- $this->_storesRootCategories = $this->_getWriteAdapter()->fetchPairs($select);
- }
-
- if (!is_null($storeIds)) {
- if (!is_array($storeIds)) {
- $storeIds = [$storeIds];
- }
-
- $stores = [];
- foreach ($this->_storesRootCategories as $storeId => $rootId) {
- if (in_array($storeId, $storeIds)) {
- $stores[$storeId] = $rootId;
+ $table = $this->getMainStoreTable($category->getStoreId());
+ $this->_getWriteAdapter()->resetDdlCache($table);
+ $table = $this->_getReadAdapter()->describeTable($table);
+ $data = [];
+ $idFieldName = Mage::getSingleton('catalog/category')->getIdFieldName();
+ foreach (array_keys($table) as $column) {
+ if ($column != $idFieldName || $category->getData($column) !== null) {
+ if (array_key_exists($column, $replaceFields)) {
+ $value = $category->getData($replaceFields[$column]);
+ } else {
+ $value = $category->getData($column);
+ }
+ if (is_array($value)) {
+ $value = implode(',', $value);
}
+ $data[$column] = $value;
}
- return $stores;
}
-
- return $this->_storesRootCategories;
+ return $data;
}
/**
@@ -1483,46 +1525,4 @@ protected function _createTables()
}
return $this;
}
-
- /**
- * Transactional rebuild flat data from eav
- *
- * @throws Exception
- * @return $this
- */
- public function reindexAll()
- {
- $this->_createTables();
- $allowTableChanges = $this->_allowTableChanges;
- if ($allowTableChanges) {
- $this->_allowTableChanges = false;
- }
- $this->beginTransaction();
- try {
- $this->rebuild();
- $this->commit();
- if ($allowTableChanges) {
- $this->_allowTableChanges = true;
- }
- } catch (Exception $e) {
- $this->rollBack();
- if ($allowTableChanges) {
- $this->_allowTableChanges = true;
- }
- throw $e;
- }
- return $this;
- }
-
- /**
- * Check if Catalog Category Flat Data has been initialized
- *
- * @deprecated use Mage_Catalog_Model_Resource_Category_Flat::isBuilt() instead
- *
- * @return bool
- */
- public function isRebuilt()
- {
- return $this->isBuilt();
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Category/Flat/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Category/Flat/Collection.php
index 675350509e9..45b7b53c6b5 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Category/Flat/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category/Flat/Collection.php
@@ -57,28 +57,6 @@ public function __construct($resource = null, array $args = [])
$this->_factory = !empty($args['factory']) ? $args['factory'] : Mage::getSingleton('catalog/factory');
}
- /**
- * Collection initialization
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/category_flat');
- $this->setModel('catalog/category');
- }
-
- /**
- * @return $this
- */
- protected function _initSelect()
- {
- $this->getSelect()->from(
- ['main_table' => $this->getResource()->getMainStoreTable($this->getStoreId())],
- ['entity_id', 'level', 'path', 'position', 'is_active', 'is_anchor'],
- );
- return $this;
- }
-
/**
* Add filter by entity id(s).
*
@@ -292,16 +270,6 @@ public function joinUrlRewrite()
return $this->addUrlRewriteToResult();
}
- /**
- * Retrieves store_id from current store
- *
- * @return int
- */
- protected function _getCurrentStoreId()
- {
- return (int) Mage::app()->getStore()->getId();
- }
-
/**
* Add category path filter
*
@@ -361,4 +329,36 @@ public function setPage($pageNum, $pageSize)
->setPageSize($pageSize);
return $this;
}
+
+ /**
+ * Collection initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/category_flat');
+ $this->setModel('catalog/category');
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _initSelect()
+ {
+ $this->getSelect()->from(
+ ['main_table' => $this->getResource()->getMainStoreTable($this->getStoreId())],
+ ['entity_id', 'level', 'path', 'position', 'is_active', 'is_anchor'],
+ );
+ return $this;
+ }
+
+ /**
+ * Retrieves store_id from current store
+ *
+ * @return int
+ */
+ protected function _getCurrentStoreId()
+ {
+ return (int) Mage::app()->getStore()->getId();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Category/Indexer/Product.php b/app/code/core/Mage/Catalog/Model/Resource/Category/Indexer/Product.php
index e7903f65d7b..e86720e9108 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Category/Indexer/Product.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category/Indexer/Product.php
@@ -64,16 +64,6 @@ class Mage_Catalog_Model_Resource_Category_Indexer_Product extends Mage_Index_Mo
*/
protected $_storesInfo;
- protected function _construct()
- {
- $this->_init('catalog/category_product_index', 'category_id');
- $this->_categoryTable = $this->getTable('catalog/category');
- $this->_categoryProductTable = $this->getTable('catalog/category_product');
- $this->_productWebsiteTable = $this->getTable('catalog/product_website');
- $this->_storeTable = $this->getTable('core/store');
- $this->_groupTable = $this->getTable('core/store_group');
- }
-
/**
* Process product save.
* Method is responsible for index support
@@ -184,24 +174,6 @@ public function catalogProductMassAction(Mage_Index_Model_Event $event)
return $this;
}
- /**
- * Return array of used root category id - path pairs
- *
- * @return array
- */
- protected function _getRootCategories()
- {
- $rootCategories = [];
- $stores = $this->_getStoresInfo();
- foreach ($stores as $storeInfo) {
- if ($storeInfo['root_id']) {
- $rootCategories[$storeInfo['root_id']] = $storeInfo['root_path'];
- }
- }
-
- return $rootCategories;
- }
-
/**
* Process category index after category save
*/
@@ -301,6 +273,236 @@ public function catalogCategorySave(Mage_Index_Model_Event $event)
}
}
+ /**
+ * Rebuild all index data
+ *
+ * @return $this
+ */
+ public function reindexAll()
+ {
+ $this->useIdxTable(true);
+ $this->beginTransaction();
+ try {
+ $this->clearTemporaryIndexTable();
+ $idxTable = $this->getIdxTable();
+ $idxAdapter = $this->_getIndexAdapter();
+ $stores = $this->_getStoresInfo();
+ /**
+ * Build index for each store
+ */
+ foreach ($stores as $storeData) {
+ $storeId = $storeData['store_id'];
+ $websiteId = $storeData['website_id'];
+ $rootPath = $storeData['root_path'];
+ $rootId = $storeData['root_id'];
+ /**
+ * Prepare visibility for all enabled store products
+ */
+ $enabledTable = $this->_prepareEnabledProductsVisibility($websiteId, $storeId);
+ /**
+ * Select information about anchor categories
+ */
+ $anchorTable = $this->_prepareAnchorCategories($storeId, $rootPath);
+ /**
+ * Add relations between not anchor categories and products
+ */
+ $select = $idxAdapter->select();
+ $select->from(
+ ['cp' => $this->_categoryProductTable],
+ ['category_id', 'product_id', 'position', 'is_parent' => new Zend_Db_Expr('1'),
+ 'store_id' => new Zend_Db_Expr($storeId)],
+ )
+ ->joinInner(['pv' => $enabledTable], 'pv.product_id=cp.product_id', ['visibility'])
+ ->joinLeft(['ac' => $anchorTable], 'ac.category_id=cp.category_id', [])
+ ->where('ac.category_id IS NULL');
+
+ $query = $select->insertFromSelect(
+ $idxTable,
+ ['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
+ false,
+ );
+ $idxAdapter->query($query);
+
+ /**
+ * Assign products not associated to any category to root category in index
+ */
+
+ $select = $idxAdapter->select();
+ $select->from(
+ ['pv' => $enabledTable],
+ [new Zend_Db_Expr($rootId), 'product_id', new Zend_Db_Expr('0'), new Zend_Db_Expr('1'),
+ new Zend_Db_Expr($storeId), 'visibility'],
+ )
+ ->joinLeft(['cp' => $this->_categoryProductTable], 'pv.product_id=cp.product_id', [])
+ ->where('cp.product_id IS NULL');
+
+ $query = $select->insertFromSelect(
+ $idxTable,
+ ['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
+ false,
+ );
+ $idxAdapter->query($query);
+
+ /**
+ * Prepare anchor categories products
+ */
+ $anchorProductsTable = $this->_getAnchorCategoriesProductsTemporaryTable();
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $idxAdapter->delete($anchorProductsTable);
+
+ $position = 'MIN(' .
+ $idxAdapter->getCheckSql(
+ 'ca.category_id = ce.entity_id',
+ $idxAdapter->quoteIdentifier('cp.position'),
+ '(' . $idxAdapter->quoteIdentifier('ce.position') . ' + 1) * '
+ . '(' . $idxAdapter->quoteIdentifier('ce.level') . ' + 1 * 10000)'
+ . ' + ' . $idxAdapter->quoteIdentifier('cp.position'),
+ )
+ . ')';
+
+ $select = $idxAdapter->select()
+ ->useStraightJoin(true)
+ ->distinct()
+ ->from(['ca' => $anchorTable], ['category_id'])
+ ->joinInner(
+ ['ce' => $this->_categoryTable],
+ $idxAdapter->quoteIdentifier('ce.path') . ' LIKE ' .
+ $idxAdapter->quoteIdentifier('ca.path') . ' OR ce.entity_id = ca.category_id',
+ [],
+ )
+ ->joinInner(
+ ['cp' => $this->_categoryProductTable],
+ 'cp.category_id = ce.entity_id',
+ ['product_id'],
+ )
+ ->joinInner(
+ ['pv' => $enabledTable],
+ 'pv.product_id = cp.product_id',
+ ['position' => $position],
+ )
+ ->group(['ca.category_id', 'cp.product_id']);
+ $query = $select->insertFromSelect(
+ $anchorProductsTable,
+ ['category_id', 'product_id', 'position'],
+ false,
+ );
+ $idxAdapter->query($query);
+
+ /**
+ * Add anchor categories products to index
+ */
+ $select = $idxAdapter->select()
+ ->from(
+ ['ap' => $anchorProductsTable],
+ ['category_id', 'product_id',
+ 'position', // => new Zend_Db_Expr('MIN('. $idxAdapter->quoteIdentifier('ap.position').')'),
+ 'is_parent' => $idxAdapter->getCheckSql('cp.product_id > 0', '1', '0'),
+ 'store_id' => new Zend_Db_Expr($storeId)],
+ )
+ ->joinLeft(
+ ['cp' => $this->_categoryProductTable],
+ 'cp.category_id=ap.category_id AND cp.product_id=ap.product_id',
+ [],
+ )
+ ->joinInner(['pv' => $enabledTable], 'pv.product_id = ap.product_id', ['visibility']);
+
+ $query = $select->insertFromSelect(
+ $idxTable,
+ ['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
+ false,
+ );
+ $idxAdapter->query($query);
+
+ $select = $idxAdapter->select()
+ ->from(['e' => $this->getTable('catalog/product')], null)
+ ->join(
+ ['ei' => $enabledTable],
+ 'ei.product_id = e.entity_id',
+ [],
+ )
+ ->joinLeft(
+ ['i' => $idxTable],
+ 'i.product_id = e.entity_id AND i.category_id = :category_id AND i.store_id = :store_id',
+ [],
+ )
+ ->where('i.product_id IS NULL')
+ ->columns([
+ 'category_id' => new Zend_Db_Expr($rootId),
+ 'product_id' => 'e.entity_id',
+ 'position' => new Zend_Db_Expr('0'),
+ 'is_parent' => new Zend_Db_Expr('1'),
+ 'store_id' => new Zend_Db_Expr($storeId),
+ 'visibility' => 'ei.visibility',
+ ]);
+
+ $query = $select->insertFromSelect(
+ $idxTable,
+ ['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
+ false,
+ );
+
+ $idxAdapter->query($query, ['store_id' => $storeId, 'category_id' => $rootId]);
+ }
+
+ $this->syncData();
+
+ /**
+ * Clean up temporary tables
+ */
+ $this->clearTemporaryIndexTable();
+ $idxAdapter->delete($enabledTable);
+ $idxAdapter->delete($anchorTable);
+ $idxAdapter->delete($anchorProductsTable);
+ $this->commit();
+ } catch (Exception $e) {
+ $this->rollBack();
+ throw $e;
+ }
+ return $this;
+ }
+
+ /**
+ * Retrieve temporary decimal index table name
+ *
+ * @param string $table
+ * @return string
+ */
+ public function getIdxTable($table = null)
+ {
+ if ($this->useIdxTable()) {
+ return $this->getTable('catalog/category_product_indexer_idx');
+ }
+ return $this->getTable('catalog/category_product_indexer_tmp');
+ }
+
+ protected function _construct()
+ {
+ $this->_init('catalog/category_product_index', 'category_id');
+ $this->_categoryTable = $this->getTable('catalog/category');
+ $this->_categoryProductTable = $this->getTable('catalog/category_product');
+ $this->_productWebsiteTable = $this->getTable('catalog/product_website');
+ $this->_storeTable = $this->getTable('core/store');
+ $this->_groupTable = $this->getTable('core/store_group');
+ }
+
+ /**
+ * Return array of used root category id - path pairs
+ *
+ * @return array
+ */
+ protected function _getRootCategories()
+ {
+ $rootCategories = [];
+ $stores = $this->_getStoresInfo();
+ foreach ($stores as $storeInfo) {
+ if ($storeInfo['root_id']) {
+ $rootCategories[$storeInfo['root_id']] = $storeInfo['root_path'];
+ }
+ }
+
+ return $rootCategories;
+ }
+
/**
* Reindex not anchor root categories
*
@@ -787,194 +989,6 @@ protected function _getStatusAttributeInfo()
];
}
- /**
- * Rebuild all index data
- *
- * @return $this
- */
- public function reindexAll()
- {
- $this->useIdxTable(true);
- $this->beginTransaction();
- try {
- $this->clearTemporaryIndexTable();
- $idxTable = $this->getIdxTable();
- $idxAdapter = $this->_getIndexAdapter();
- $stores = $this->_getStoresInfo();
- /**
- * Build index for each store
- */
- foreach ($stores as $storeData) {
- $storeId = $storeData['store_id'];
- $websiteId = $storeData['website_id'];
- $rootPath = $storeData['root_path'];
- $rootId = $storeData['root_id'];
- /**
- * Prepare visibility for all enabled store products
- */
- $enabledTable = $this->_prepareEnabledProductsVisibility($websiteId, $storeId);
- /**
- * Select information about anchor categories
- */
- $anchorTable = $this->_prepareAnchorCategories($storeId, $rootPath);
- /**
- * Add relations between not anchor categories and products
- */
- $select = $idxAdapter->select();
- $select->from(
- ['cp' => $this->_categoryProductTable],
- ['category_id', 'product_id', 'position', 'is_parent' => new Zend_Db_Expr('1'),
- 'store_id' => new Zend_Db_Expr($storeId)],
- )
- ->joinInner(['pv' => $enabledTable], 'pv.product_id=cp.product_id', ['visibility'])
- ->joinLeft(['ac' => $anchorTable], 'ac.category_id=cp.category_id', [])
- ->where('ac.category_id IS NULL');
-
- $query = $select->insertFromSelect(
- $idxTable,
- ['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
- false,
- );
- $idxAdapter->query($query);
-
- /**
- * Assign products not associated to any category to root category in index
- */
-
- $select = $idxAdapter->select();
- $select->from(
- ['pv' => $enabledTable],
- [new Zend_Db_Expr($rootId), 'product_id', new Zend_Db_Expr('0'), new Zend_Db_Expr('1'),
- new Zend_Db_Expr($storeId), 'visibility'],
- )
- ->joinLeft(['cp' => $this->_categoryProductTable], 'pv.product_id=cp.product_id', [])
- ->where('cp.product_id IS NULL');
-
- $query = $select->insertFromSelect(
- $idxTable,
- ['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
- false,
- );
- $idxAdapter->query($query);
-
- /**
- * Prepare anchor categories products
- */
- $anchorProductsTable = $this->_getAnchorCategoriesProductsTemporaryTable();
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $idxAdapter->delete($anchorProductsTable);
-
- $position = 'MIN(' .
- $idxAdapter->getCheckSql(
- 'ca.category_id = ce.entity_id',
- $idxAdapter->quoteIdentifier('cp.position'),
- '(' . $idxAdapter->quoteIdentifier('ce.position') . ' + 1) * '
- . '(' . $idxAdapter->quoteIdentifier('ce.level') . ' + 1 * 10000)'
- . ' + ' . $idxAdapter->quoteIdentifier('cp.position'),
- )
- . ')';
-
- $select = $idxAdapter->select()
- ->useStraightJoin(true)
- ->distinct()
- ->from(['ca' => $anchorTable], ['category_id'])
- ->joinInner(
- ['ce' => $this->_categoryTable],
- $idxAdapter->quoteIdentifier('ce.path') . ' LIKE ' .
- $idxAdapter->quoteIdentifier('ca.path') . ' OR ce.entity_id = ca.category_id',
- [],
- )
- ->joinInner(
- ['cp' => $this->_categoryProductTable],
- 'cp.category_id = ce.entity_id',
- ['product_id'],
- )
- ->joinInner(
- ['pv' => $enabledTable],
- 'pv.product_id = cp.product_id',
- ['position' => $position],
- )
- ->group(['ca.category_id', 'cp.product_id']);
- $query = $select->insertFromSelect(
- $anchorProductsTable,
- ['category_id', 'product_id', 'position'],
- false,
- );
- $idxAdapter->query($query);
-
- /**
- * Add anchor categories products to index
- */
- $select = $idxAdapter->select()
- ->from(
- ['ap' => $anchorProductsTable],
- ['category_id', 'product_id',
- 'position', // => new Zend_Db_Expr('MIN('. $idxAdapter->quoteIdentifier('ap.position').')'),
- 'is_parent' => $idxAdapter->getCheckSql('cp.product_id > 0', '1', '0'),
- 'store_id' => new Zend_Db_Expr($storeId)],
- )
- ->joinLeft(
- ['cp' => $this->_categoryProductTable],
- 'cp.category_id=ap.category_id AND cp.product_id=ap.product_id',
- [],
- )
- ->joinInner(['pv' => $enabledTable], 'pv.product_id = ap.product_id', ['visibility']);
-
- $query = $select->insertFromSelect(
- $idxTable,
- ['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
- false,
- );
- $idxAdapter->query($query);
-
- $select = $idxAdapter->select()
- ->from(['e' => $this->getTable('catalog/product')], null)
- ->join(
- ['ei' => $enabledTable],
- 'ei.product_id = e.entity_id',
- [],
- )
- ->joinLeft(
- ['i' => $idxTable],
- 'i.product_id = e.entity_id AND i.category_id = :category_id AND i.store_id = :store_id',
- [],
- )
- ->where('i.product_id IS NULL')
- ->columns([
- 'category_id' => new Zend_Db_Expr($rootId),
- 'product_id' => 'e.entity_id',
- 'position' => new Zend_Db_Expr('0'),
- 'is_parent' => new Zend_Db_Expr('1'),
- 'store_id' => new Zend_Db_Expr($storeId),
- 'visibility' => 'ei.visibility',
- ]);
-
- $query = $select->insertFromSelect(
- $idxTable,
- ['category_id', 'product_id', 'position', 'is_parent', 'store_id', 'visibility'],
- false,
- );
-
- $idxAdapter->query($query, ['store_id' => $storeId, 'category_id' => $rootId]);
- }
-
- $this->syncData();
-
- /**
- * Clean up temporary tables
- */
- $this->clearTemporaryIndexTable();
- $idxAdapter->delete($enabledTable);
- $idxAdapter->delete($anchorTable);
- $idxAdapter->delete($anchorProductsTable);
- $this->commit();
- } catch (Exception $e) {
- $this->rollBack();
- throw $e;
- }
- return $this;
- }
-
/**
* Create temporary table with enabled products visibility info
*
@@ -1162,18 +1176,4 @@ protected function _getAnchorCategoriesProductsTemporaryTable()
}
return $this->getTable('catalog/category_anchor_products_indexer_tmp');
}
-
- /**
- * Retrieve temporary decimal index table name
- *
- * @param string $table
- * @return string
- */
- public function getIdxTable($table = null)
- {
- if ($this->useIdxTable()) {
- return $this->getTable('catalog/category_product_indexer_idx');
- }
- return $this->getTable('catalog/category_product_indexer_tmp');
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Category/Tree.php b/app/code/core/Mage/Catalog/Model/Resource/Category/Tree.php
index 5bb30691bb5..1b6d615a479 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Category/Tree.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category/Tree.php
@@ -195,27 +195,197 @@ public function addInactiveCategoryIds($ids)
/**
* Retrieve inactive categories ids
*
+ * @return array
+ */
+ public function getInactiveCategoryIds()
+ {
+ if (!is_array($this->_inactiveCategoryIds)) {
+ $this->_initInactiveCategoryIds();
+ }
+
+ return $this->_inactiveCategoryIds;
+ }
+
+ /**
+ * Get categories collection
+ *
+ * @param bool $sorted
+ * @return Mage_Catalog_Model_Resource_Category_Collection
+ */
+ public function getCollection($sorted = false)
+ {
+ if (is_null($this->_collection)) {
+ $this->_collection = $this->_getDefaultCollection($sorted);
+ }
+ return $this->_collection;
+ }
+
+ /**
+ * @param Mage_Catalog_Model_Resource_Category_Collection $collection
* @return $this
*/
- protected function _initInactiveCategoryIds()
+ public function setCollection($collection)
{
- $this->_inactiveCategoryIds = [];
- Mage::dispatchEvent('catalog_category_tree_init_inactive_category_ids', ['tree' => $this]);
+ if (!is_null($this->_collection)) {
+ destruct($this->_collection);
+ }
+ $this->_collection = $collection;
return $this;
}
/**
- * Retrieve inactive categories ids
+ * Executing parents move method and cleaning cache after it
+ *
+ * @param Mage_Catalog_Model_Category $category
+ * @param Varien_Data_Tree_Node $newParent
+ * @param Varien_Data_Tree_Node $prevNode
+ */
+ public function move($category, $newParent, $prevNode = null)
+ {
+ $this->_beforeMove($category, $newParent, $prevNode);
+ Mage::getResourceSingleton('catalog/category')->move($category->getId(), $newParent->getId());
+ parent::move($category, $newParent, $prevNode);
+
+ $this->_afterMove($category, $newParent, $prevNode);
+ }
+
+ /**
+ * Load whole category tree, that will include specified categories ids.
+ *
+ * @param array $ids
+ * @param bool $addCollectionData
+ * @param bool $updateAnchorProductCount
+ * @return $this|false
+ */
+ public function loadByIds($ids, $addCollectionData = true, $updateAnchorProductCount = true)
+ {
+ $levelField = $this->_conn->quoteIdentifier('level');
+ $pathField = $this->_conn->quoteIdentifier('path');
+ // load first two levels, if no ids specified
+ if (empty($ids)) {
+ $select = $this->_conn->select()
+ ->from($this->_table, 'entity_id')
+ ->where($levelField . ' <= 2');
+ $ids = $this->_conn->fetchCol($select);
+ }
+ if (!is_array($ids)) {
+ $ids = [$ids];
+ }
+ foreach ($ids as $key => $id) {
+ $ids[$key] = (int) $id;
+ }
+
+ // collect paths of specified IDs and prepare to collect all their parents and neighbours
+ $select = $this->_conn->select()
+ ->from($this->_table, ['path', 'level'])
+ ->where('entity_id IN (?)', $ids);
+ $where = [$levelField . '=0' => true];
+
+ foreach ($this->_conn->fetchAll($select) as $item) {
+ if (!preg_match("#^[0-9\/]+$#", $item['path'])) {
+ $item['path'] = '';
+ }
+ $pathIds = explode('/', $item['path']);
+ $level = (int) $item['level'];
+ while ($level > 0) {
+ // phpcs:ignore Ecg.Performance.Loop.ArraySize
+ $pathIds[count($pathIds) - 1] = '%';
+ $path = implode('/', $pathIds);
+ $where["$levelField=$level AND $pathField LIKE '$path'"] = true;
+ array_pop($pathIds);
+ $level--;
+ }
+ }
+ $where = array_keys($where);
+
+ // get all required records
+ if ($addCollectionData) {
+ $select = $this->_createCollectionDataSelect();
+ } else {
+ $select = clone $this->_select;
+ $select->order($this->_orderField . ' ' . Varien_Db_Select::SQL_ASC);
+ }
+ $select->where(implode(' OR ', $where));
+
+ // get array of records and add them as nodes to the tree
+ $arrNodes = $this->_conn->fetchAll($select);
+ if (!$arrNodes) {
+ return false;
+ }
+ if ($updateAnchorProductCount) {
+ $this->_updateAnchorProductCount($arrNodes);
+ }
+ $childrenItems = [];
+ foreach ($arrNodes as $key => $nodeInfo) {
+ $pathToParent = explode('/', $nodeInfo[$this->_pathField]);
+ array_pop($pathToParent);
+ $pathToParent = implode('/', $pathToParent);
+ $childrenItems[$pathToParent][] = $nodeInfo;
+ }
+ $this->addChildNodes($childrenItems, '', null);
+ return $this;
+ }
+
+ /**
+ * Load array of category parents
*
+ * @param string $path
+ * @param bool $addCollectionData
+ * @param bool $withRootNode
* @return array
*/
- public function getInactiveCategoryIds()
+ public function loadBreadcrumbsArray($path, $addCollectionData = true, $withRootNode = false)
{
- if (!is_array($this->_inactiveCategoryIds)) {
- $this->_initInactiveCategoryIds();
+ $pathIds = explode('/', $path);
+ if (!$withRootNode) {
+ array_shift($pathIds);
+ }
+ $result = [];
+ if (!empty($pathIds)) {
+ if ($addCollectionData) {
+ $select = $this->_createCollectionDataSelect(false);
+ } else {
+ $select = clone $this->_select;
+ }
+ $select
+ ->where('e.entity_id IN(?)', $pathIds)
+ ->order($this->_conn->getLengthSql('e.path') . ' ' . Varien_Db_Select::SQL_ASC);
+ $result = $this->_conn->fetchAll($select);
+ $this->_updateAnchorProductCount($result);
}
+ return $result;
+ }
- return $this->_inactiveCategoryIds;
+ /**
+ * Get real existing category ids by specified ids
+ *
+ * @param array $ids
+ * @return array
+ */
+ public function getExistingCategoryIdsBySpecifiedIds($ids)
+ {
+ if (empty($ids)) {
+ return [];
+ }
+ if (!is_array($ids)) {
+ $ids = [$ids];
+ }
+ $select = $this->_conn->select()
+ ->from($this->_table, ['entity_id'])
+ ->where('entity_id IN (?)', $ids);
+ return $this->_conn->fetchCol($select);
+ }
+
+ /**
+ * Retrieve inactive categories ids
+ *
+ * @return $this
+ */
+ protected function _initInactiveCategoryIds()
+ {
+ $this->_inactiveCategoryIds = [];
+ Mage::dispatchEvent('catalog_category_tree_init_inactive_category_ids', ['tree' => $this]);
+ return $this;
}
/**
@@ -324,33 +494,6 @@ protected function _getItemIsActive($id)
return false;
}
- /**
- * Get categories collection
- *
- * @param bool $sorted
- * @return Mage_Catalog_Model_Resource_Category_Collection
- */
- public function getCollection($sorted = false)
- {
- if (is_null($this->_collection)) {
- $this->_collection = $this->_getDefaultCollection($sorted);
- }
- return $this->_collection;
- }
-
- /**
- * @param Mage_Catalog_Model_Resource_Category_Collection $collection
- * @return $this
- */
- public function setCollection($collection)
- {
- if (!is_null($this->_collection)) {
- destruct($this->_collection);
- }
- $this->_collection = $collection;
- return $this;
- }
-
/**
* @param bool $sorted
* @return Mage_Catalog_Model_Resource_Category_Collection
@@ -399,22 +542,6 @@ protected function _beforeMove($category, $newParent, $prevNode)
return $this;
}
- /**
- * Executing parents move method and cleaning cache after it
- *
- * @param Mage_Catalog_Model_Category $category
- * @param Varien_Data_Tree_Node $newParent
- * @param Varien_Data_Tree_Node $prevNode
- */
- public function move($category, $newParent, $prevNode = null)
- {
- $this->_beforeMove($category, $newParent, $prevNode);
- Mage::getResourceSingleton('catalog/category')->move($category->getId(), $newParent->getId());
- parent::move($category, $newParent, $prevNode);
-
- $this->_afterMove($category, $newParent, $prevNode);
- }
-
/**
* Move tree after
*
@@ -436,113 +563,6 @@ protected function _afterMove($category, $newParent, $prevNode)
return $this;
}
- /**
- * Load whole category tree, that will include specified categories ids.
- *
- * @param array $ids
- * @param bool $addCollectionData
- * @param bool $updateAnchorProductCount
- * @return $this|false
- */
- public function loadByIds($ids, $addCollectionData = true, $updateAnchorProductCount = true)
- {
- $levelField = $this->_conn->quoteIdentifier('level');
- $pathField = $this->_conn->quoteIdentifier('path');
- // load first two levels, if no ids specified
- if (empty($ids)) {
- $select = $this->_conn->select()
- ->from($this->_table, 'entity_id')
- ->where($levelField . ' <= 2');
- $ids = $this->_conn->fetchCol($select);
- }
- if (!is_array($ids)) {
- $ids = [$ids];
- }
- foreach ($ids as $key => $id) {
- $ids[$key] = (int) $id;
- }
-
- // collect paths of specified IDs and prepare to collect all their parents and neighbours
- $select = $this->_conn->select()
- ->from($this->_table, ['path', 'level'])
- ->where('entity_id IN (?)', $ids);
- $where = [$levelField . '=0' => true];
-
- foreach ($this->_conn->fetchAll($select) as $item) {
- if (!preg_match("#^[0-9\/]+$#", $item['path'])) {
- $item['path'] = '';
- }
- $pathIds = explode('/', $item['path']);
- $level = (int) $item['level'];
- while ($level > 0) {
- // phpcs:ignore Ecg.Performance.Loop.ArraySize
- $pathIds[count($pathIds) - 1] = '%';
- $path = implode('/', $pathIds);
- $where["$levelField=$level AND $pathField LIKE '$path'"] = true;
- array_pop($pathIds);
- $level--;
- }
- }
- $where = array_keys($where);
-
- // get all required records
- if ($addCollectionData) {
- $select = $this->_createCollectionDataSelect();
- } else {
- $select = clone $this->_select;
- $select->order($this->_orderField . ' ' . Varien_Db_Select::SQL_ASC);
- }
- $select->where(implode(' OR ', $where));
-
- // get array of records and add them as nodes to the tree
- $arrNodes = $this->_conn->fetchAll($select);
- if (!$arrNodes) {
- return false;
- }
- if ($updateAnchorProductCount) {
- $this->_updateAnchorProductCount($arrNodes);
- }
- $childrenItems = [];
- foreach ($arrNodes as $key => $nodeInfo) {
- $pathToParent = explode('/', $nodeInfo[$this->_pathField]);
- array_pop($pathToParent);
- $pathToParent = implode('/', $pathToParent);
- $childrenItems[$pathToParent][] = $nodeInfo;
- }
- $this->addChildNodes($childrenItems, '', null);
- return $this;
- }
-
- /**
- * Load array of category parents
- *
- * @param string $path
- * @param bool $addCollectionData
- * @param bool $withRootNode
- * @return array
- */
- public function loadBreadcrumbsArray($path, $addCollectionData = true, $withRootNode = false)
- {
- $pathIds = explode('/', $path);
- if (!$withRootNode) {
- array_shift($pathIds);
- }
- $result = [];
- if (!empty($pathIds)) {
- if ($addCollectionData) {
- $select = $this->_createCollectionDataSelect(false);
- } else {
- $select = clone $this->_select;
- }
- $select
- ->where('e.entity_id IN(?)', $pathIds)
- ->order($this->_conn->getLengthSql('e.path') . ' ' . Varien_Db_Select::SQL_ASC);
- $result = $this->_conn->fetchAll($select);
- $this->_updateAnchorProductCount($result);
- }
- return $result;
- }
-
/**
* Replace products count with self products count, if category is non-anchor
*
@@ -636,24 +656,4 @@ protected function _createCollectionDataSelect($sorted = true, $optionalAttribut
return $select;
}
-
- /**
- * Get real existing category ids by specified ids
- *
- * @param array $ids
- * @return array
- */
- public function getExistingCategoryIdsBySpecifiedIds($ids)
- {
- if (empty($ids)) {
- return [];
- }
- if (!is_array($ids)) {
- $ids = [$ids];
- }
- $select = $this->_conn->select()
- ->from($this->_table, ['entity_id'])
- ->where('entity_id IN (?)', $ids);
- return $this->_conn->fetchCol($select);
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Config.php b/app/code/core/Mage/Catalog/Model/Resource/Config.php
index 333592dd9f7..13509e3c2ed 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Config.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Config.php
@@ -36,11 +36,6 @@ class Mage_Catalog_Model_Resource_Config extends Mage_Core_Model_Resource_Db_Abs
*/
protected $_storeId = null;
- protected function _construct()
- {
- $this->_init('eav/attribute', 'attribute_id');
- }
-
/**
* Set store id
*
@@ -130,4 +125,9 @@ public function getAttributesUsedForSortBy()
return $adapter->fetchAll($select);
}
+
+ protected function _construct()
+ {
+ $this->_init('eav/attribute', 'attribute_id');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Eav/Attribute.php b/app/code/core/Mage/Catalog/Model/Resource/Eav/Attribute.php
index 4ac2d25ec69..e86a953281e 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Eav/Attribute.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Eav/Attribute.php
@@ -87,91 +87,6 @@ class Mage_Catalog_Model_Resource_Eav_Attribute extends Mage_Eav_Model_Entity_At
*/
protected static $_labels = null;
- protected function _construct()
- {
- $this->_init('catalog/attribute');
- }
-
- /**
- * Processing object before save data
- *
- * @throws Mage_Core_Exception
- * @return Mage_Core_Model_Abstract
- */
- protected function _beforeSave()
- {
- $this->setData('modulePrefix', self::MODULE_NAME);
- if (isset($this->_origData['is_global'])) {
- if (!isset($this->_data['is_global'])) {
- $this->_data['is_global'] = self::SCOPE_GLOBAL;
- }
- if (($this->_data['is_global'] != $this->_origData['is_global'])
- && $this->_getResource()->isUsedBySuperProducts($this)
- ) {
- Mage::throwException(Mage::helper('catalog')->__('Scope must not be changed, because the attribute is used in configurable products.'));
- }
- }
- if ($this->getFrontendInput() == 'price') {
- if (!$this->getBackendModel()) {
- $this->setBackendModel('catalog/product_attribute_backend_price');
- }
- }
- if ($this->getFrontendInput() == 'textarea') {
- if ($this->getIsWysiwygEnabled()) {
- $this->setIsHtmlAllowedOnFront(1);
- }
- }
- return parent::_beforeSave();
- }
-
- /**
- * Processing object after save data
- *
- * @inheritDoc
- */
- protected function _afterSave()
- {
- /**
- * Fix saving attribute in admin
- */
- Mage::getSingleton('eav/config')->clear();
-
- return parent::_afterSave();
- }
-
- /**
- * Register indexing event before delete catalog eav attribute
- *
- * @inheritDoc
- */
- protected function _beforeDelete()
- {
- if ($this->_getResource()->isUsedBySuperProducts($this)) {
- Mage::throwException(Mage::helper('catalog')->__('This attribute is used in configurable products.'));
- }
- Mage::getSingleton('index/indexer')->logEvent(
- $this,
- self::ENTITY,
- Mage_Index_Model_Event::TYPE_DELETE,
- );
- return parent::_beforeDelete();
- }
-
- /**
- * Init indexing process after catalog eav attribute delete commit
- *
- * @return $this
- */
- protected function _afterDeleteCommit()
- {
- parent::_afterDeleteCommit();
- Mage::getSingleton('index/indexer')->indexEvents(
- self::ENTITY,
- Mage_Index_Model_Event::TYPE_DELETE,
- );
- return $this;
- }
-
/**
* Return is attribute global
*
@@ -292,17 +207,6 @@ public function getIsFilterable()
return $this->_getData('is_filterable');
}
- /**
- * Get Attribute translated label for store
- *
- * @deprecated
- * @return string
- */
- protected function _getLabelForStore()
- {
- return $this->getFrontendLabel();
- }
-
/**
* Initialize store Labels for attributes
*
@@ -400,4 +304,100 @@ public function afterCommitCallback()
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('catalog/attribute');
+ }
+
+ /**
+ * Processing object before save data
+ *
+ * @throws Mage_Core_Exception
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _beforeSave()
+ {
+ $this->setData('modulePrefix', self::MODULE_NAME);
+ if (isset($this->_origData['is_global'])) {
+ if (!isset($this->_data['is_global'])) {
+ $this->_data['is_global'] = self::SCOPE_GLOBAL;
+ }
+ if (($this->_data['is_global'] != $this->_origData['is_global'])
+ && $this->_getResource()->isUsedBySuperProducts($this)
+ ) {
+ Mage::throwException(Mage::helper('catalog')->__('Scope must not be changed, because the attribute is used in configurable products.'));
+ }
+ }
+ if ($this->getFrontendInput() == 'price') {
+ if (!$this->getBackendModel()) {
+ $this->setBackendModel('catalog/product_attribute_backend_price');
+ }
+ }
+ if ($this->getFrontendInput() == 'textarea') {
+ if ($this->getIsWysiwygEnabled()) {
+ $this->setIsHtmlAllowedOnFront(1);
+ }
+ }
+ return parent::_beforeSave();
+ }
+
+ /**
+ * Processing object after save data
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave()
+ {
+ /**
+ * Fix saving attribute in admin
+ */
+ Mage::getSingleton('eav/config')->clear();
+
+ return parent::_afterSave();
+ }
+
+ /**
+ * Register indexing event before delete catalog eav attribute
+ *
+ * @inheritDoc
+ */
+ protected function _beforeDelete()
+ {
+ if ($this->_getResource()->isUsedBySuperProducts($this)) {
+ Mage::throwException(Mage::helper('catalog')->__('This attribute is used in configurable products.'));
+ }
+ Mage::getSingleton('index/indexer')->logEvent(
+ $this,
+ self::ENTITY,
+ Mage_Index_Model_Event::TYPE_DELETE,
+ );
+ return parent::_beforeDelete();
+ }
+
+ /**
+ * Init indexing process after catalog eav attribute delete commit
+ *
+ * @return $this
+ */
+ protected function _afterDeleteCommit()
+ {
+ parent::_afterDeleteCommit();
+ Mage::getSingleton('index/indexer')->indexEvents(
+ self::ENTITY,
+ Mage_Index_Model_Event::TYPE_DELETE,
+ );
+ return $this;
+ }
+
+ /**
+ * Get Attribute translated label for store
+ *
+ * @deprecated
+ * @return string
+ */
+ protected function _getLabelForStore()
+ {
+ return $this->getFrontendLabel();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Attribute.php b/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Attribute.php
index 3a22736ed6c..6047d8ad53c 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Attribute.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Attribute.php
@@ -22,11 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Layer_Filter_Attribute extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product_index_eav', 'entity_id');
- }
-
/**
* Apply attribute filter to product collection
*
@@ -91,4 +86,8 @@ public function getCount($filter)
return $connection->fetchPairs($select);
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product_index_eav', 'entity_id');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Decimal.php b/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Decimal.php
index e7a3db911d7..a2df13e9d68 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Decimal.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Decimal.php
@@ -22,11 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Layer_Filter_Decimal extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product_index_eav_decimal', 'entity_id');
- }
-
/**
* Apply attribute filter to product collection
*
@@ -81,6 +76,34 @@ public function getMinMax($filter)
return [$result['min_value'], $result['max_value']];
}
+ /**
+ * Retrieve array with products counts per range
+ *
+ * @param Mage_Catalog_Model_Layer_Filter_Decimal $filter
+ * @param int $range
+ * @return array
+ */
+ public function getCount($filter, $range)
+ {
+ $select = $this->_getSelect($filter);
+ $adapter = $this->_getReadAdapter();
+
+ $countExpr = new Zend_Db_Expr('COUNT(*)');
+ $rangeExpr = new Zend_Db_Expr("FLOOR(decimal_index.value / {$range}) + 1");
+
+ $select->columns([
+ 'decimal_range' => $rangeExpr,
+ 'count' => $countExpr,
+ ]);
+ $select->group($rangeExpr);
+
+ return $adapter->fetchPairs($select);
+ }
+ protected function _construct()
+ {
+ $this->_init('catalog/product_index_eav_decimal', 'entity_id');
+ }
+
/**
* Retrieve clean select with joined index table
* Joined table has index
@@ -113,28 +136,4 @@ protected function _getSelect($filter)
return $select;
}
-
- /**
- * Retrieve array with products counts per range
- *
- * @param Mage_Catalog_Model_Layer_Filter_Decimal $filter
- * @param int $range
- * @return array
- */
- public function getCount($filter, $range)
- {
- $select = $this->_getSelect($filter);
- $adapter = $this->_getReadAdapter();
-
- $countExpr = new Zend_Db_Expr('COUNT(*)');
- $rangeExpr = new Zend_Db_Expr("FLOOR(decimal_index.value / {$range}) + 1");
-
- $select->columns([
- 'decimal_range' => $rangeExpr,
- 'count' => $countExpr,
- ]);
- $select->group($rangeExpr);
-
- return $adapter->fetchPairs($select);
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Price.php b/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Price.php
index f1e50ea90d8..fe75015e2da 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Price.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Price.php
@@ -27,6 +27,200 @@ class Mage_Catalog_Model_Resource_Layer_Filter_Price extends Mage_Core_Model_Res
*/
public const MIN_POSSIBLE_PRICE = .01;
+ /**
+ * Retrieve maximal price for attribute
+ *
+ * @deprecated since 1.7.0.0
+ * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+ * @return float
+ */
+ public function getMaxPrice($filter)
+ {
+ return $filter->getLayer()->getProductCollection()->getMaxPrice();
+ }
+
+ /**
+ * Retrieve array with products counts per price range
+ *
+ * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+ * @param int $range
+ * @return array
+ */
+ public function getCount($filter, $range)
+ {
+ $select = $this->_getSelect($filter);
+ $priceExpression = $this->_getFullPriceExpression($filter, $select);
+
+ /**
+ * Check and set correct variable values to prevent SQL-injections
+ */
+ $range = (float) $range;
+ if ($range == 0) {
+ $range = 1;
+ }
+ $countExpr = new Zend_Db_Expr('COUNT(*)');
+ $rangeExpr = new Zend_Db_Expr("FLOOR(({$priceExpression}) / {$range}) + 1");
+ $rangeOrderExpr = new Zend_Db_Expr("FLOOR(({$priceExpression}) / {$range}) + 1 ASC");
+
+ $select->columns([
+ 'range' => $rangeExpr,
+ 'count' => $countExpr,
+ ]);
+ $select->group($rangeExpr)->order($rangeOrderExpr);
+
+ return $this->_getReadAdapter()->fetchPairs($select);
+ }
+
+ /**
+ * Apply attribute filter to product collection
+ *
+ * @deprecated since 1.7.0.0
+ * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+ * @param int $range
+ * @param int $index the range factor
+ * @return $this
+ */
+ public function applyFilterToCollection($filter, $range, $index)
+ {
+ $select = $filter->getLayer()->getProductCollection()->getSelect();
+ $priceExpr = $this->_getPriceExpression($filter, $select);
+ $filter->getLayer()->getProductCollection()
+ ->getSelect()
+ ->where($priceExpr . ' >= ' . $this->_getComparingValue(($range * ($index - 1)), $filter))
+ ->where($priceExpr . ' < ' . $this->_getComparingValue(($range * $index), $filter));
+
+ return $this;
+ }
+
+ /**
+ * Load range of product prices
+ *
+ * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+ * @param int $limit
+ * @param null|int $offset
+ * @param null|float $lowerPrice
+ * @param null|float $upperPrice
+ * @return array
+ */
+ public function loadPrices($filter, $limit, $offset = null, $lowerPrice = null, $upperPrice = null)
+ {
+ $select = $this->_getSelect($filter);
+ $priceExpression = $this->_getPriceExpression($filter, $select);
+ $select->columns([
+ 'min_price_expr' => $this->_getFullPriceExpression($filter, $select),
+ ]);
+ if (!is_null($lowerPrice)) {
+ $select->where("$priceExpression >= " . $this->_getComparingValue($lowerPrice, $filter));
+ }
+ if (!is_null($upperPrice)) {
+ $select->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter));
+ }
+ $select->order(new Zend_Db_Expr("$priceExpression ASC"))->limit($limit, $offset);
+
+ return $this->_getReadAdapter()->fetchCol($select);
+ }
+
+ /**
+ * Load range of product prices, preceding the price
+ *
+ * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+ * @param float $price
+ * @param int $index
+ * @param float|null $lowerPrice
+ * @return array|false
+ */
+ public function loadPreviousPrices($filter, $price, $index, $lowerPrice = null)
+ {
+ $select = $this->_getSelect($filter);
+ $priceExpression = $this->_getPriceExpression($filter, $select);
+ $select->columns('COUNT(*)')->where("$priceExpression < " . $this->_getComparingValue($price, $filter));
+ if (!is_null($lowerPrice)) {
+ $select->where("$priceExpression >= " . $this->_getComparingValue($lowerPrice, $filter));
+ }
+ $offset = $this->_getReadAdapter()->fetchOne($select);
+ if (!$offset) {
+ return false;
+ }
+
+ return $this->loadPrices($filter, $index - $offset + 1, $offset - 1, $lowerPrice);
+ }
+
+ /**
+ * Load range of product prices, next to the price
+ *
+ * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+ * @param float $price
+ * @param int $rightIndex
+ * @param null|int $upperPrice
+ * @return array|false
+ */
+ public function loadNextPrices($filter, $price, $rightIndex, $upperPrice = null)
+ {
+ $select = $this->_getSelect($filter);
+
+ $pricesSelect = clone $select;
+ $priceExpression = $this->_getPriceExpression($filter, $pricesSelect);
+
+ $select->columns('COUNT(*)')->where("$priceExpression > " . $this->_getComparingValue($price, $filter, false));
+ if (!is_null($upperPrice)) {
+ $select->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter));
+ }
+ $offset = $this->_getReadAdapter()->fetchOne($select);
+ if (!$offset) {
+ return false;
+ }
+
+ $pricesSelect
+ ->columns([
+ 'min_price_expr' => $this->_getFullPriceExpression($filter, $pricesSelect),
+ ])
+ ->where("$priceExpression >= " . $this->_getComparingValue($price, $filter));
+ if (!is_null($upperPrice)) {
+ $pricesSelect->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter));
+ }
+ $pricesSelect->order(new Zend_Db_Expr("$priceExpression DESC"))->limit($rightIndex - $offset + 1, $offset - 1);
+
+ return array_reverse($this->_getReadAdapter()->fetchCol($pricesSelect));
+ }
+
+ /**
+ * Apply price range filter to product collection
+ *
+ * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+ * @return $this
+ */
+ public function applyPriceRange($filter)
+ {
+ $interval = $filter->getInterval();
+ if (!$interval) {
+ return $this;
+ }
+
+ list($from, $to) = $interval;
+ if ($from === '' && $to === '') {
+ return $this;
+ }
+
+ $select = $filter->getLayer()->getProductCollection()->getSelect();
+ $priceExpr = $this->_getPriceExpression($filter, $select, false);
+
+ if ($to !== '') {
+ $to = (float) $to;
+ if ($from == $to) {
+ $to += self::MIN_POSSIBLE_PRICE;
+ }
+ }
+
+ if ($from !== '') {
+ $select->where($priceExpr . ' >= ' . $this->_getComparingValue($from, $filter));
+ }
+ if ($to !== '') {
+ $select->where($priceExpr . ' < ' . $this->_getComparingValue($to, $filter));
+ }
+
+ return $this;
+ }
+
protected function _construct()
{
$this->_init('catalog/product_index_price', 'entity_id');
@@ -168,18 +362,6 @@ protected function _dispatchPreparePriceEvent($filter, $select)
return $response;
}
- /**
- * Retrieve maximal price for attribute
- *
- * @deprecated since 1.7.0.0
- * @param Mage_Catalog_Model_Layer_Filter_Price $filter
- * @return float
- */
- public function getMaxPrice($filter)
- {
- return $filter->getLayer()->getProductCollection()->getMaxPrice();
- }
-
/**
* Price expression generated by products collection
*
@@ -233,186 +415,4 @@ protected function _getFullPriceExpression($filter, $select)
return new Zend_Db_Expr('ROUND((' . $this->_getPriceExpression($filter, $select) . ') * '
. $filter->getLayer()->getProductCollection()->getCurrencyRate() . ', 2)');
}
-
- /**
- * Retrieve array with products counts per price range
- *
- * @param Mage_Catalog_Model_Layer_Filter_Price $filter
- * @param int $range
- * @return array
- */
- public function getCount($filter, $range)
- {
- $select = $this->_getSelect($filter);
- $priceExpression = $this->_getFullPriceExpression($filter, $select);
-
- /**
- * Check and set correct variable values to prevent SQL-injections
- */
- $range = (float) $range;
- if ($range == 0) {
- $range = 1;
- }
- $countExpr = new Zend_Db_Expr('COUNT(*)');
- $rangeExpr = new Zend_Db_Expr("FLOOR(({$priceExpression}) / {$range}) + 1");
- $rangeOrderExpr = new Zend_Db_Expr("FLOOR(({$priceExpression}) / {$range}) + 1 ASC");
-
- $select->columns([
- 'range' => $rangeExpr,
- 'count' => $countExpr,
- ]);
- $select->group($rangeExpr)->order($rangeOrderExpr);
-
- return $this->_getReadAdapter()->fetchPairs($select);
- }
-
- /**
- * Apply attribute filter to product collection
- *
- * @deprecated since 1.7.0.0
- * @param Mage_Catalog_Model_Layer_Filter_Price $filter
- * @param int $range
- * @param int $index the range factor
- * @return $this
- */
- public function applyFilterToCollection($filter, $range, $index)
- {
- $select = $filter->getLayer()->getProductCollection()->getSelect();
- $priceExpr = $this->_getPriceExpression($filter, $select);
- $filter->getLayer()->getProductCollection()
- ->getSelect()
- ->where($priceExpr . ' >= ' . $this->_getComparingValue(($range * ($index - 1)), $filter))
- ->where($priceExpr . ' < ' . $this->_getComparingValue(($range * $index), $filter));
-
- return $this;
- }
-
- /**
- * Load range of product prices
- *
- * @param Mage_Catalog_Model_Layer_Filter_Price $filter
- * @param int $limit
- * @param null|int $offset
- * @param null|float $lowerPrice
- * @param null|float $upperPrice
- * @return array
- */
- public function loadPrices($filter, $limit, $offset = null, $lowerPrice = null, $upperPrice = null)
- {
- $select = $this->_getSelect($filter);
- $priceExpression = $this->_getPriceExpression($filter, $select);
- $select->columns([
- 'min_price_expr' => $this->_getFullPriceExpression($filter, $select),
- ]);
- if (!is_null($lowerPrice)) {
- $select->where("$priceExpression >= " . $this->_getComparingValue($lowerPrice, $filter));
- }
- if (!is_null($upperPrice)) {
- $select->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter));
- }
- $select->order(new Zend_Db_Expr("$priceExpression ASC"))->limit($limit, $offset);
-
- return $this->_getReadAdapter()->fetchCol($select);
- }
-
- /**
- * Load range of product prices, preceding the price
- *
- * @param Mage_Catalog_Model_Layer_Filter_Price $filter
- * @param float $price
- * @param int $index
- * @param float|null $lowerPrice
- * @return array|false
- */
- public function loadPreviousPrices($filter, $price, $index, $lowerPrice = null)
- {
- $select = $this->_getSelect($filter);
- $priceExpression = $this->_getPriceExpression($filter, $select);
- $select->columns('COUNT(*)')->where("$priceExpression < " . $this->_getComparingValue($price, $filter));
- if (!is_null($lowerPrice)) {
- $select->where("$priceExpression >= " . $this->_getComparingValue($lowerPrice, $filter));
- }
- $offset = $this->_getReadAdapter()->fetchOne($select);
- if (!$offset) {
- return false;
- }
-
- return $this->loadPrices($filter, $index - $offset + 1, $offset - 1, $lowerPrice);
- }
-
- /**
- * Load range of product prices, next to the price
- *
- * @param Mage_Catalog_Model_Layer_Filter_Price $filter
- * @param float $price
- * @param int $rightIndex
- * @param null|int $upperPrice
- * @return array|false
- */
- public function loadNextPrices($filter, $price, $rightIndex, $upperPrice = null)
- {
- $select = $this->_getSelect($filter);
-
- $pricesSelect = clone $select;
- $priceExpression = $this->_getPriceExpression($filter, $pricesSelect);
-
- $select->columns('COUNT(*)')->where("$priceExpression > " . $this->_getComparingValue($price, $filter, false));
- if (!is_null($upperPrice)) {
- $select->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter));
- }
- $offset = $this->_getReadAdapter()->fetchOne($select);
- if (!$offset) {
- return false;
- }
-
- $pricesSelect
- ->columns([
- 'min_price_expr' => $this->_getFullPriceExpression($filter, $pricesSelect),
- ])
- ->where("$priceExpression >= " . $this->_getComparingValue($price, $filter));
- if (!is_null($upperPrice)) {
- $pricesSelect->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter));
- }
- $pricesSelect->order(new Zend_Db_Expr("$priceExpression DESC"))->limit($rightIndex - $offset + 1, $offset - 1);
-
- return array_reverse($this->_getReadAdapter()->fetchCol($pricesSelect));
- }
-
- /**
- * Apply price range filter to product collection
- *
- * @param Mage_Catalog_Model_Layer_Filter_Price $filter
- * @return $this
- */
- public function applyPriceRange($filter)
- {
- $interval = $filter->getInterval();
- if (!$interval) {
- return $this;
- }
-
- list($from, $to) = $interval;
- if ($from === '' && $to === '') {
- return $this;
- }
-
- $select = $filter->getLayer()->getProductCollection()->getSelect();
- $priceExpr = $this->_getPriceExpression($filter, $select, false);
-
- if ($to !== '') {
- $to = (float) $to;
- if ($from == $to) {
- $to += self::MIN_POSSIBLE_PRICE;
- }
- }
-
- if ($from !== '') {
- $select->where($priceExpr . ' >= ' . $this->_getComparingValue($from, $filter));
- }
- if ($to !== '') {
- $select->where($priceExpr . ' < ' . $this->_getComparingValue($to, $filter));
- }
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product.php b/app/code/core/Mage/Catalog/Model/Resource/Product.php
index 8e4984c7e56..59d81408904 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product.php
@@ -48,16 +48,6 @@ public function __construct()
$this->_productCategoryTable = $this->getTable('catalog/category_product');
}
- /**
- * Default product attributes
- *
- * @return array
- */
- protected function _getDefaultAttributes()
- {
- return ['entity_id', 'entity_type_id', 'attribute_set_id', 'type_id', 'created_at', 'updated_at'];
- }
-
/**
* Retrieve product website identifiers
*
@@ -140,157 +130,6 @@ public function getIdBySku($sku)
return $adapter->fetchOne($select, $bind);
}
- /**
- * Process product data before save
- *
- * @param Mage_Catalog_Model_Product $object
- * @inheritDoc
- */
- protected function _beforeSave(Varien_Object $object)
- {
- /**
- * Try to detect product id by sku if id is not declared
- */
- if (!$object->getId() && $object->getSku()) {
- $object->setId($this->getIdBySku($object->getSku()));
- }
-
- /**
- * Check if declared category ids in object data.
- */
- if ($object->hasCategoryIds()) {
- $categoryIds = Mage::getResourceSingleton('catalog/category')->verifyIds(
- $object->getCategoryIds(),
- );
- $object->setCategoryIds($categoryIds);
- }
-
- return parent::_beforeSave($object);
- }
-
- /**
- * Save data related with product
- *
- * @param Mage_Catalog_Model_Product $product
- * @inheritDoc
- */
- protected function _afterSave(Varien_Object $product)
- {
- $this->_saveWebsiteIds($product)
- ->_saveCategories($product);
-
- return parent::_afterSave($product);
- }
-
- /**
- * Save product website relations
- *
- * @param Mage_Catalog_Model_Product $product
- * @return $this
- */
- protected function _saveWebsiteIds($product)
- {
- $websiteIds = $product->getWebsiteIds();
- $oldWebsiteIds = [];
-
- $product->setIsChangedWebsites(false);
-
- $adapter = $this->_getWriteAdapter();
-
- $oldWebsiteIds = $this->getWebsiteIds($product);
-
- $insert = array_diff($websiteIds, $oldWebsiteIds);
- $delete = array_diff($oldWebsiteIds, $websiteIds);
-
- if (!empty($insert)) {
- $data = [];
- foreach ($insert as $websiteId) {
- $data[] = [
- 'product_id' => (int) $product->getId(),
- 'website_id' => (int) $websiteId,
- ];
- }
- $adapter->insertMultiple($this->_productWebsiteTable, $data);
- }
-
- if (!empty($delete)) {
- foreach ($delete as $websiteId) {
- $condition = [
- 'product_id = ?' => (int) $product->getId(),
- 'website_id = ?' => (int) $websiteId,
- ];
-
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $adapter->delete($this->_productWebsiteTable, $condition);
- }
- }
-
- if (!empty($insert) || !empty($delete)) {
- $product->setIsChangedWebsites(true);
- }
-
- return $this;
- }
-
- /**
- * Save product category relations
- *
- * @return $this
- */
- protected function _saveCategories(Varien_Object $object)
- {
- /**
- * If category ids data is not declared we haven't do manipulations
- */
- if (!$object->hasCategoryIds()) {
- return $this;
- }
- $categoryIds = $object->getCategoryIds();
- $oldCategoryIds = $this->getCategoryIds($object);
-
- $object->setIsChangedCategories(false);
-
- $insert = array_diff($categoryIds, $oldCategoryIds);
- $delete = array_diff($oldCategoryIds, $categoryIds);
-
- $write = $this->_getWriteAdapter();
- if (!empty($insert)) {
- $data = [];
- foreach ($insert as $categoryId) {
- if (empty($categoryId)) {
- continue;
- }
- $data[] = [
- 'category_id' => (int) $categoryId,
- 'product_id' => (int) $object->getId(),
- 'position' => 1,
- ];
- }
- if ($data) {
- $write->insertMultiple($this->_productCategoryTable, $data);
- }
- }
-
- if (!empty($delete)) {
- foreach ($delete as $categoryId) {
- $where = [
- 'product_id = ?' => (int) $object->getId(),
- 'category_id = ?' => (int) $categoryId,
- ];
-
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $write->delete($this->_productCategoryTable, $where);
- }
- }
-
- if (!empty($insert) || !empty($delete)) {
- $object->setAffectedCategoryIds(array_merge($insert, $delete));
- $object->setIsChangedCategories(true);
- }
-
- return $this;
- }
-
/**
* Refresh Product Enabled Index
*
@@ -714,4 +553,165 @@ public function getCategoryIdsWithAnchors($object)
return $this->_getReadAdapter()->fetchCol($select);
}
+
+ /**
+ * Default product attributes
+ *
+ * @return array
+ */
+ protected function _getDefaultAttributes()
+ {
+ return ['entity_id', 'entity_type_id', 'attribute_set_id', 'type_id', 'created_at', 'updated_at'];
+ }
+
+ /**
+ * Process product data before save
+ *
+ * @param Mage_Catalog_Model_Product $object
+ * @inheritDoc
+ */
+ protected function _beforeSave(Varien_Object $object)
+ {
+ /**
+ * Try to detect product id by sku if id is not declared
+ */
+ if (!$object->getId() && $object->getSku()) {
+ $object->setId($this->getIdBySku($object->getSku()));
+ }
+
+ /**
+ * Check if declared category ids in object data.
+ */
+ if ($object->hasCategoryIds()) {
+ $categoryIds = Mage::getResourceSingleton('catalog/category')->verifyIds(
+ $object->getCategoryIds(),
+ );
+ $object->setCategoryIds($categoryIds);
+ }
+
+ return parent::_beforeSave($object);
+ }
+
+ /**
+ * Save data related with product
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @inheritDoc
+ */
+ protected function _afterSave(Varien_Object $product)
+ {
+ $this->_saveWebsiteIds($product)
+ ->_saveCategories($product);
+
+ return parent::_afterSave($product);
+ }
+
+ /**
+ * Save product website relations
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @return $this
+ */
+ protected function _saveWebsiteIds($product)
+ {
+ $websiteIds = $product->getWebsiteIds();
+ $oldWebsiteIds = [];
+
+ $product->setIsChangedWebsites(false);
+
+ $adapter = $this->_getWriteAdapter();
+
+ $oldWebsiteIds = $this->getWebsiteIds($product);
+
+ $insert = array_diff($websiteIds, $oldWebsiteIds);
+ $delete = array_diff($oldWebsiteIds, $websiteIds);
+
+ if (!empty($insert)) {
+ $data = [];
+ foreach ($insert as $websiteId) {
+ $data[] = [
+ 'product_id' => (int) $product->getId(),
+ 'website_id' => (int) $websiteId,
+ ];
+ }
+ $adapter->insertMultiple($this->_productWebsiteTable, $data);
+ }
+
+ if (!empty($delete)) {
+ foreach ($delete as $websiteId) {
+ $condition = [
+ 'product_id = ?' => (int) $product->getId(),
+ 'website_id = ?' => (int) $websiteId,
+ ];
+
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $adapter->delete($this->_productWebsiteTable, $condition);
+ }
+ }
+
+ if (!empty($insert) || !empty($delete)) {
+ $product->setIsChangedWebsites(true);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Save product category relations
+ *
+ * @return $this
+ */
+ protected function _saveCategories(Varien_Object $object)
+ {
+ /**
+ * If category ids data is not declared we haven't do manipulations
+ */
+ if (!$object->hasCategoryIds()) {
+ return $this;
+ }
+ $categoryIds = $object->getCategoryIds();
+ $oldCategoryIds = $this->getCategoryIds($object);
+
+ $object->setIsChangedCategories(false);
+
+ $insert = array_diff($categoryIds, $oldCategoryIds);
+ $delete = array_diff($oldCategoryIds, $categoryIds);
+
+ $write = $this->_getWriteAdapter();
+ if (!empty($insert)) {
+ $data = [];
+ foreach ($insert as $categoryId) {
+ if (empty($categoryId)) {
+ continue;
+ }
+ $data[] = [
+ 'category_id' => (int) $categoryId,
+ 'product_id' => (int) $object->getId(),
+ 'position' => 1,
+ ];
+ }
+ if ($data) {
+ $write->insertMultiple($this->_productCategoryTable, $data);
+ }
+ }
+
+ if (!empty($delete)) {
+ foreach ($delete as $categoryId) {
+ $where = [
+ 'product_id = ?' => (int) $object->getId(),
+ 'category_id = ?' => (int) $categoryId,
+ ];
+
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $write->delete($this->_productCategoryTable, $where);
+ }
+ }
+
+ if (!empty($insert) || !empty($delete)) {
+ $object->setAffectedCategoryIds(array_merge($insert, $delete));
+ $object->setIsChangedCategories(true);
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Action.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Action.php
index 1a6851866a3..8d5a0cff2a9 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Action.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Action.php
@@ -22,20 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Product_Action extends Mage_Catalog_Model_Resource_Abstract
{
- /**
- * Initialize connection
- *
- */
- protected function _construct()
- {
- $resource = Mage::getSingleton('core/resource');
- $this->setType(Mage_Catalog_Model_Product::ENTITY)
- ->setConnection(
- $resource->getConnection('catalog_read'),
- $resource->getConnection('catalog_write'),
- );
- }
-
/**
* Update attribute values for entity list per store
*
@@ -84,6 +70,19 @@ public function updateAttributes($entityIds, $attrData, $storeId)
return $this;
}
+ /**
+ * Initialize connection
+ *
+ */
+ protected function _construct()
+ {
+ $resource = Mage::getSingleton('core/resource');
+ $this->setType(Mage_Catalog_Model_Product::ENTITY)
+ ->setConnection(
+ $resource->getConnection('catalog_read'),
+ $resource->getConnection('catalog_write'),
+ );
+ }
/**
* Update the "updated_at" field for all entity_ids passed
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Groupprice/Abstract.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Groupprice/Abstract.php
index 1dc7c655751..8cc04e34310 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Groupprice/Abstract.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Groupprice/Abstract.php
@@ -60,28 +60,6 @@ public function loadPriceData($productId, $websiteId = null)
return $adapter->fetchAll($select);
}
- /**
- * Load specific sql columns
- *
- * @param array $columns
- * @return array
- */
- protected function _loadPriceDataColumns($columns)
- {
- return $columns;
- }
-
- /**
- * Load specific db-select data
- *
- * @param Varien_Db_Select $select
- * @return Varien_Db_Select
- */
- protected function _loadPriceDataSelect($select)
- {
- return $select;
- }
-
/**
* Delete Tier Prices for product
*
@@ -130,4 +108,26 @@ public function savePriceData(Varien_Object $priceObject)
}
return $this;
}
+
+ /**
+ * Load specific sql columns
+ *
+ * @param array $columns
+ * @return array
+ */
+ protected function _loadPriceDataColumns($columns)
+ {
+ return $columns;
+ }
+
+ /**
+ * Load specific db-select data
+ *
+ * @param Varien_Db_Select $select
+ * @return Varien_Db_Select
+ */
+ protected function _loadPriceDataSelect($select)
+ {
+ return $select;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Media.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Media.php
index 74fdbf5ebf0..1b1fa634ca2 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Media.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Media.php
@@ -30,11 +30,6 @@ class Mage_Catalog_Model_Resource_Product_Attribute_Backend_Media extends Mage_C
// phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
private $_attributeId = null;
- protected function _construct()
- {
- $this->_init(self::GALLERY_TABLE, 'value_id');
- }
-
/**
* Load gallery images for product using reusable select method
*
@@ -69,29 +64,6 @@ public function loadGallery($product, $object)
return $result;
}
- /**
- * Remove duplicates
- *
- * @param array $result
- * @return $this
- */
- protected function _removeDuplicates(&$result)
- {
- $fileToId = [];
-
- foreach (array_keys($result) as $index) {
- if (!isset($fileToId[$result[$index]['file']])) {
- $fileToId[$result[$index]['file']] = $result[$index]['value_id'];
- } elseif ($fileToId[$result[$index]['file']] != $result[$index]['value_id']) {
- $this->deleteGallery($result[$index]['value_id']);
- unset($result[$index]);
- }
- }
-
- $result = array_values($result);
- return $this;
- }
-
/**
* Insert gallery value to db and retrieve last id
*
@@ -207,6 +179,50 @@ public function duplicate($object, $newFiles, $originalProductId, $newProductId)
return $this;
}
+ /**
+ * Get media gallery set for given product IDs
+ *
+ * @param int $storeId
+ * @return array
+ */
+ public function loadGallerySet(array $productIds, $storeId)
+ {
+ $select = $this->_getLoadGallerySelect($productIds, $storeId, $this->_getAttributeId());
+
+ $adapter = $this->_getReadAdapter();
+ $result = $adapter->fetchAll($select);
+ $this->_removeDuplicates($result);
+ return $result;
+ }
+
+ protected function _construct()
+ {
+ $this->_init(self::GALLERY_TABLE, 'value_id');
+ }
+
+ /**
+ * Remove duplicates
+ *
+ * @param array $result
+ * @return $this
+ */
+ protected function _removeDuplicates(&$result)
+ {
+ $fileToId = [];
+
+ foreach (array_keys($result) as $index) {
+ if (!isset($fileToId[$result[$index]['file']])) {
+ $fileToId[$result[$index]['file']] = $result[$index]['value_id'];
+ } elseif ($fileToId[$result[$index]['file']] != $result[$index]['value_id']) {
+ $this->deleteGallery($result[$index]['value_id']);
+ unset($result[$index]);
+ }
+ }
+
+ $result = array_values($result);
+ return $this;
+ }
+
/**
* Get select to retrieve media gallery images
* for given product IDs.
@@ -261,20 +277,4 @@ protected function _getAttributeId()
}
return $this->_attributeId;
}
-
- /**
- * Get media gallery set for given product IDs
- *
- * @param int $storeId
- * @return array
- */
- public function loadGallerySet(array $productIds, $storeId)
- {
- $select = $this->_getLoadGallerySelect($productIds, $storeId, $this->_getAttributeId());
-
- $adapter = $this->_getReadAdapter();
- $result = $adapter->fetchAll($select);
- $this->_removeDuplicates($result);
- return $result;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Tierprice.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Tierprice.php
index 476c87ae7b8..3db8792d766 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Tierprice.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Tierprice.php
@@ -22,36 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice extends Mage_Catalog_Model_Resource_Product_Attribute_Backend_Groupprice_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product_attribute_tier_price', 'value_id');
- }
-
- /**
- * Add qty column
- *
- * @param array $columns
- * @return array
- */
- protected function _loadPriceDataColumns($columns)
- {
- $columns = parent::_loadPriceDataColumns($columns);
- $columns['price_qty'] = 'qty';
- return $columns;
- }
-
- /**
- * Order by qty
- *
- * @param Varien_Db_Select $select
- * @return Varien_Db_Select
- */
- protected function _loadPriceDataSelect($select)
- {
- $select->order('qty');
- return $select;
- }
-
/**
* Load product tier prices
*
@@ -113,4 +83,33 @@ public function insertProductPrice($product, $data)
return $this->savePriceData($priceObject);
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product_attribute_tier_price', 'value_id');
+ }
+
+ /**
+ * Add qty column
+ *
+ * @param array $columns
+ * @return array
+ */
+ protected function _loadPriceDataColumns($columns)
+ {
+ $columns = parent::_loadPriceDataColumns($columns);
+ $columns['price_qty'] = 'qty';
+ return $columns;
+ }
+
+ /**
+ * Order by qty
+ *
+ * @param Varien_Db_Select $select
+ * @return Varien_Db_Select
+ */
+ protected function _loadPriceDataSelect($select)
+ {
+ $select->order('qty');
+ return $select;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Collection.php
index 8cf405b2911..c8b9eeb4988 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Collection.php
@@ -22,44 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Product_Attribute_Collection extends Mage_Eav_Model_Resource_Entity_Attribute_Collection
{
- /**
- * Resource model initialization
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/resource_eav_attribute', 'eav/entity_attribute');
- }
-
- /**
- * initialize select object
- *
- * @return $this
- */
- protected function _initSelect()
- {
- $entityTypeId = (int) Mage::getModel('eav/entity')->setType(Mage_Catalog_Model_Product::ENTITY)->getTypeId();
- $columns = $this->getConnection()->describeTable($this->getResource()->getMainTable());
- unset($columns['attribute_id']);
- $retColumns = [];
- /** @var Mage_Core_Model_Resource_Helper_Mysql4 $helper */
- $helper = Mage::getResourceHelper('core');
- foreach ($columns as $labelColumn => $columnData) {
- $retColumns[$labelColumn] = $labelColumn;
- if ($columnData['DATA_TYPE'] == Varien_Db_Ddl_Table::TYPE_TEXT) {
- $retColumns[$labelColumn] = $helper->castField('main_table.' . $labelColumn);
- }
- }
- $this->getSelect()
- ->from(['main_table' => $this->getResource()->getMainTable()], $retColumns)
- ->join(
- ['additional_table' => $this->getTable('catalog/eav_attribute')],
- 'additional_table.attribute_id = main_table.attribute_id',
- )
- ->where('main_table.entity_type_id = ?', $entityTypeId);
- return $this;
- }
-
/**
* Specify attribute entity type filter.
* Entity type is defined.
@@ -72,23 +34,6 @@ public function setEntityTypeFilter($typeId)
return $this;
}
- /**
- * Return array of fields to load attribute values
- *
- * @return array
- */
- protected function _getLoadDataFields()
- {
- return array_merge(
- parent::_getLoadDataFields(),
- [
- 'additional_table.is_global',
- 'additional_table.is_html_allowed_on_front',
- 'additional_table.is_wysiwyg_enabled',
- ],
- );
- }
-
/**
* Remove price from attribute list
*
@@ -191,4 +136,58 @@ public function addSearchableAttributeFilter()
return $this;
}
+ /**
+ * Resource model initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/resource_eav_attribute', 'eav/entity_attribute');
+ }
+
+ /**
+ * initialize select object
+ *
+ * @return $this
+ */
+ protected function _initSelect()
+ {
+ $entityTypeId = (int) Mage::getModel('eav/entity')->setType(Mage_Catalog_Model_Product::ENTITY)->getTypeId();
+ $columns = $this->getConnection()->describeTable($this->getResource()->getMainTable());
+ unset($columns['attribute_id']);
+ $retColumns = [];
+ /** @var Mage_Core_Model_Resource_Helper_Mysql4 $helper */
+ $helper = Mage::getResourceHelper('core');
+ foreach ($columns as $labelColumn => $columnData) {
+ $retColumns[$labelColumn] = $labelColumn;
+ if ($columnData['DATA_TYPE'] == Varien_Db_Ddl_Table::TYPE_TEXT) {
+ $retColumns[$labelColumn] = $helper->castField('main_table.' . $labelColumn);
+ }
+ }
+ $this->getSelect()
+ ->from(['main_table' => $this->getResource()->getMainTable()], $retColumns)
+ ->join(
+ ['additional_table' => $this->getTable('catalog/eav_attribute')],
+ 'additional_table.attribute_id = main_table.attribute_id',
+ )
+ ->where('main_table.entity_type_id = ?', $entityTypeId);
+ return $this;
+ }
+
+ /**
+ * Return array of fields to load attribute values
+ *
+ * @return array
+ */
+ protected function _getLoadDataFields()
+ {
+ return array_merge(
+ parent::_getLoadDataFields(),
+ [
+ 'additional_table.is_global',
+ 'additional_table.is_html_allowed_on_front',
+ 'additional_table.is_wysiwyg_enabled',
+ ],
+ );
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php
index 719b8830bd8..11487e9c3ee 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php
@@ -225,42 +225,6 @@ public function getCatalogPreparedSelect()
return $this->_catalogPreparePriceSelect;
}
- /**
- * Prepare additional price expression sql part
- *
- * @param Varien_Db_Select $select
- * @return $this
- */
- protected function _preparePriceExpressionParameters($select)
- {
- // prepare response object for event
- $response = new Varien_Object();
- $response->setAdditionalCalculations([]);
- $tableAliases = array_keys($select->getPart(Zend_Db_Select::FROM));
- if (in_array(self::INDEX_TABLE_ALIAS, $tableAliases)) {
- $table = self::INDEX_TABLE_ALIAS;
- } else {
- $table = reset($tableAliases);
- }
-
- // prepare event arguments
- $eventArgs = [
- 'select' => $select,
- 'table' => $table,
- 'store_id' => $this->getStoreId(),
- 'response_object' => $response,
- ];
-
- Mage::dispatchEvent('catalog_prepare_price_select', $eventArgs);
-
- $additional = implode('', $response->getAdditionalCalculations());
- $this->_priceExpression = $table . '.min_price';
- $this->_additionalPriceExpression = $additional;
- $this->_catalogPreparePriceSelect = clone $select;
-
- return $this;
- }
-
/**
* Get price expression sql part
*
@@ -329,57 +293,6 @@ public function isEnabledFlat()
return $this->_flatEnabled[$storeId];
}
- /**
- * Initialize resources
- *
- */
- protected function _construct()
- {
- if ($this->isEnabledFlat()) {
- $this->_init('catalog/product', 'catalog/product_flat');
- } else {
- $this->_init('catalog/product');
- }
- $this->_initTables();
- }
-
- /**
- * Define product website and category product tables
- *
- */
- protected function _initTables()
- {
- $this->_productWebsiteTable = $this->getResource()->getTable('catalog/product_website');
- $this->_productCategoryTable = $this->getResource()->getTable('catalog/category_product');
- }
-
- /**
- * Standard resource collection initialization
- *
- * @inheritDoc
- */
- protected function _init($model, $entityModel = null)
- {
- if ($this->isEnabledFlat()) {
- $entityModel = 'catalog/product_flat';
- }
-
- return parent::_init($model, $entityModel);
- }
-
- /**
- * Prepare static entity fields
- *
- * @inheritDoc
- */
- protected function _prepareStaticFields()
- {
- if ($this->isEnabledFlat()) {
- return $this;
- }
- return parent::_prepareStaticFields();
- }
-
/**
* Retrieve collection empty item
* Redeclared for specifying id field name without getting resource model inside model
@@ -424,31 +337,6 @@ public function setStore($store)
return $this;
}
- /**
- * Initialize collection select
- * Redeclared for remove entity_type_id condition
- * in catalog_product_entity we store just products
- *
- * @return $this
- */
- protected function _initSelect()
- {
- if ($this->isEnabledFlat()) {
- $this->getSelect()
- ->from([self::MAIN_TABLE_ALIAS => $this->getEntity()->getFlatTableName()], null)
- ->where('e.status = ?', new Zend_Db_Expr((string) Mage_Catalog_Model_Product_Status::STATUS_ENABLED));
- $this->addAttributeToSelect(['entity_id', 'type_id', 'attribute_set_id']);
- if ($this->getFlatHelper()->isAddChildData()) {
- $this->getSelect()
- ->where('e.is_child = ?', 0);
- $this->addAttributeToSelect(['child_id', 'is_child']);
- }
- } else {
- $this->getSelect()->from([self::MAIN_TABLE_ALIAS => $this->getEntity()->getEntityTable()]);
- }
- return $this;
- }
-
/**
* Load attributes into loaded entities
*
@@ -497,76 +385,6 @@ public function addAttributeToSelect($attribute, $joinType = false)
return parent::addAttributeToSelect($attribute, $joinType);
}
- /**
- * Add tax class id attribute to select and join price rules data if needed
- *
- * @inheritDoc
- */
- protected function _beforeLoad()
- {
- Mage::dispatchEvent('catalog_product_collection_load_before', ['collection' => $this]);
-
- return parent::_beforeLoad();
- }
-
- /**
- * Processing collection items after loading
- * Adding url rewrites, minimal prices, final prices, tax percents
- *
- * @return $this
- */
- protected function _afterLoad()
- {
- if ($this->_addUrlRewrite) {
- $this->_addUrlRewrite($this->_urlRewriteCategory);
- }
-
- if (count($this) > 0) {
- Mage::dispatchEvent('catalog_product_collection_load_after', ['collection' => $this]);
- }
-
- foreach ($this as $product) {
- if ($product->isRecurring() && $profile = $product->getRecurringProfile()) {
- $product->setRecurringProfile(Mage::helper('core/unserializeArray')->unserialize($profile));
- }
- }
-
- return $this;
- }
-
- /**
- * Prepare Url Data object
- *
- * @return $this
- * @deprecated after 1.7.0.2
- */
- protected function _prepareUrlDataObject()
- {
- $objects = [];
- /** @var Mage_Catalog_Model_Product $item */
- foreach ($this->_items as $item) {
- if ($this->getFlag('do_not_use_category_id')) {
- $item->setDoNotUseCategoryId(true);
- }
- if (!$item->isVisibleInSiteVisibility() && $item->getItemStoreId()) {
- $objects[$item->getEntityId()] = $item->getItemStoreId();
- }
- }
-
- if ($objects && $this->hasFlag('url_data_object')) {
- $objects = Mage::getResourceSingleton('catalog/url')
- ->getRewriteByProductStore($objects);
- foreach ($this->_items as $item) {
- if (isset($objects[$item->getEntityId()])) {
- $object = new Varien_Object($objects[$item->getEntityId()]);
- $item->setUrlDataObject($object);
- }
- }
- }
-
- return $this;
- }
-
/**
* Add collection filters by identifiers
*
@@ -868,134 +686,57 @@ public function getSelectCountSql()
}
/**
- * Get SQL for get record count
+ * Retrieve all ids for collection
*
- * @param Varien_Db_Select|null $select
- * @param bool $resetLeftJoins
- * @return Varien_Db_Select
+ * @inheritDoc
*/
- protected function _getSelectCountSql($select = null, $resetLeftJoins = true)
+ public function getAllIds($limit = null, $offset = null)
{
- $this->_renderFilters();
- $countSelect = (is_null($select)) ?
- $this->_getClearSelect() :
- $this->_buildClearSelect($select);
- // Clear GROUP condition for count method
- $countSelect->reset(Zend_Db_Select::GROUP);
- $countSelect->columns('COUNT(DISTINCT e.entity_id)');
- if ($resetLeftJoins) {
- $countSelect->resetJoinLeft();
- }
- return $countSelect;
+ $idsSelect = $this->_getClearSelect();
+ $idsSelect->columns('e.' . $this->getEntity()->getIdFieldName());
+ $idsSelect->limit($limit, $offset);
+ $idsSelect->resetJoinLeft();
+
+ return $this->getConnection()->fetchCol($idsSelect, $this->_bindParams);
}
/**
- * Prepare statistics data
+ * Retrieve product count select for categories
*
- * @return $this
+ * @return Varien_Db_Select
*/
- protected function _prepareStatisticsData()
+ public function getProductCountSelect()
{
- $select = clone $this->getSelect();
- $priceExpression = $this->getPriceExpression($select) . ' ' . $this->getAdditionalPriceExpression($select);
- $sqlEndPart = ') * ' . $this->getCurrencyRate() . ', 2)';
- $select = $this->_getSelectCountSql($select, false);
- $select->columns([
- 'max' => 'ROUND(MAX(' . $priceExpression . $sqlEndPart,
- 'min' => 'ROUND(MIN(' . $priceExpression . $sqlEndPart,
- 'std' => $this->getConnection()->getStandardDeviationSql('ROUND((' . $priceExpression . $sqlEndPart),
- ]);
- $select->where($this->getPriceExpression($select) . ' IS NOT NULL');
- $row = $this->getConnection()->fetchRow($select, $this->_bindParams, Zend_Db::FETCH_NUM);
- $this->_pricesCount = (int) $row[0];
- $this->_maxPrice = (float) $row[1];
- $this->_minPrice = (float) $row[2];
- $this->_priceStandardDeviation = (float) $row[3];
+ if ($this->_productCountSelect === null) {
+ $this->_productCountSelect = clone $this->getSelect();
+ $this->_productCountSelect->reset(Zend_Db_Select::COLUMNS)
+ ->reset(Zend_Db_Select::GROUP)
+ ->reset(Zend_Db_Select::ORDER)
+ ->distinct(false)
+ ->join(
+ ['count_table' => $this->getTable('catalog/category_product_index')],
+ 'count_table.product_id = e.entity_id',
+ [
+ 'count_table.category_id',
+ 'product_count' => new Zend_Db_Expr('COUNT(DISTINCT count_table.product_id)'),
+ ],
+ )
+ ->where('count_table.store_id = ?', $this->getStoreId())
+ ->group('count_table.category_id');
+ }
- return $this;
+ return $this->_productCountSelect;
}
/**
- * Retrieve clear select
+ * Destruct product count select
*
- * @return Varien_Db_Select
+ * @return $this
*/
- protected function _getClearSelect()
+ public function unsProductCountSelect()
{
- return $this->_buildClearSelect();
- }
-
- /**
- * Build clear select
- *
- * @param Varien_Db_Select $select
- * @return Varien_Db_Select
- */
- protected function _buildClearSelect($select = null)
- {
- if (is_null($select)) {
- $select = clone $this->getSelect();
- }
- $select->reset(Zend_Db_Select::ORDER);
- $select->reset(Zend_Db_Select::LIMIT_COUNT);
- $select->reset(Zend_Db_Select::LIMIT_OFFSET);
- $select->reset(Zend_Db_Select::COLUMNS);
-
- return $select;
- }
-
- /**
- * Retrieve all ids for collection
- *
- * @inheritDoc
- */
- public function getAllIds($limit = null, $offset = null)
- {
- $idsSelect = $this->_getClearSelect();
- $idsSelect->columns('e.' . $this->getEntity()->getIdFieldName());
- $idsSelect->limit($limit, $offset);
- $idsSelect->resetJoinLeft();
-
- return $this->getConnection()->fetchCol($idsSelect, $this->_bindParams);
- }
-
- /**
- * Retrieve product count select for categories
- *
- * @return Varien_Db_Select
- */
- public function getProductCountSelect()
- {
- if ($this->_productCountSelect === null) {
- $this->_productCountSelect = clone $this->getSelect();
- $this->_productCountSelect->reset(Zend_Db_Select::COLUMNS)
- ->reset(Zend_Db_Select::GROUP)
- ->reset(Zend_Db_Select::ORDER)
- ->distinct(false)
- ->join(
- ['count_table' => $this->getTable('catalog/category_product_index')],
- 'count_table.product_id = e.entity_id',
- [
- 'count_table.category_id',
- 'product_count' => new Zend_Db_Expr('COUNT(DISTINCT count_table.product_id)'),
- ],
- )
- ->where('count_table.store_id = ?', $this->getStoreId())
- ->group('count_table.category_id');
- }
-
- return $this->_productCountSelect;
- }
-
- /**
- * Destruct product count select
- *
- * @return $this
- */
- public function unsProductCountSelect()
- {
- $this->_productCountSelect = null;
- return $this;
+ $this->_productCountSelect = null;
+ return $this;
}
/**
@@ -1121,62 +862,6 @@ public function addUrlRewrite($categoryId = '')
return $this;
}
- /**
- * Add URL rewrites to collection
- *
- */
- protected function _addUrlRewrite()
- {
- $urlRewrites = null;
- if ($this->_cacheConf) {
- if (!($urlRewrites = Mage::app()->loadCache($this->_cacheConf['prefix'] . 'urlrewrite'))) {
- $urlRewrites = null;
- } else {
- $urlRewrites = unserialize($urlRewrites, ['allowed_classes' => false]);
- }
- }
-
- if (!$urlRewrites) {
- $productIds = [];
- foreach ($this->getItems() as $item) {
- $productIds[] = $item->getEntityId();
- }
- if (!count($productIds)) {
- return;
- }
-
- $select = $this->_factory->getProductUrlRewriteHelper()
- ->getTableSelect($productIds, $this->_urlRewriteCategory, Mage::app()->getStore($this->getStoreId())->getId());
-
- $urlRewrites = [];
- foreach ($this->getConnection()->fetchAll($select) as $row) {
- if (!isset($urlRewrites[$row['product_id']])) {
- $urlRewrites[$row['product_id']] = $row['request_path'];
- }
- }
-
- if ($this->_cacheConf) {
- Mage::app()->saveCache(
- serialize($urlRewrites),
- $this->_cacheConf['prefix'] . 'urlrewrite',
- array_merge($this->_cacheConf['tags'], [Mage_Catalog_Model_Product_Url::CACHE_TAG]),
- $this->_cacheLifetime,
- );
- }
- }
-
- foreach ($this->getItems() as $item) {
- if (empty($this->_urlRewriteCategory)) {
- $item->setDoNotUseCategoryId(true);
- }
- if (isset($urlRewrites[$item->getEntityId()])) {
- $item->setData('request_path', $urlRewrites[$item->getEntityId()]);
- } else {
- $item->setData('request_path', false);
- }
- }
- }
-
/**
* Add minimal price data to result
*
@@ -1190,19 +875,6 @@ public function addMinimalPrice()
return $this->addPriceData();
}
- /**
- * Add minimal price to product collection
- *
- * @deprecated since 1.3.2.2
- * @see Mage_Catalog_Model_Resource_Product_Collection::addPriceData
- *
- * @return $this
- */
- protected function _addMinimalPrice()
- {
- return $this;
- }
-
/**
* Add price data for calculate final price
*
@@ -1216,78 +888,6 @@ public function addFinalPrice()
return $this->addPriceData();
}
- /**
- * Join prices from price rules to products collection
- *
- * @return $this
- */
- protected function _joinPriceRules()
- {
- if ($this->isEnabledFlat()) {
- $customerGroup = Mage::getSingleton('customer/session')->getCustomerGroupId();
- $priceColumn = 'e.display_price_group_' . $customerGroup;
- $this->getSelect()->columns(['_rule_price' => $priceColumn]);
-
- return $this;
- }
- if (!$this->isModuleEnabled('Mage_CatalogRule', 'catalog')) {
- return $this;
- }
- $wId = Mage::app()->getWebsite()->getId();
- $gId = Mage::getSingleton('customer/session')->getCustomerGroupId();
-
- $storeDate = Mage::app()->getLocale()->storeTimeStamp($this->getStoreId());
- $conditions = 'price_rule.product_id = e.entity_id AND ';
- $conditions .= "price_rule.rule_date = '" . $this->getResource()->formatDate($storeDate, false) . "' AND ";
- $conditions .= $this->getConnection()->quoteInto('price_rule.website_id = ? AND', $wId);
- $conditions .= $this->getConnection()->quoteInto('price_rule.customer_group_id = ?', $gId);
-
- $this->getSelect()->joinLeft(
- ['price_rule' => $this->getTable('catalogrule/rule_product_price')],
- $conditions,
- ['rule_price' => 'rule_price'],
- );
- return $this;
- }
-
- /**
- * Add final price to the product
- *
- * @return $this
- */
- protected function _addFinalPrice()
- {
- foreach ($this->_items as $product) {
- $basePrice = $product->getPrice();
- $specialPrice = $product->getSpecialPrice();
- $specialPriceFrom = $product->getSpecialFromDate();
- $specialPriceTo = $product->getSpecialToDate();
- if ($this->isEnabledFlat()) {
- $rulePrice = null;
- if ($product->getData('_rule_price') != $basePrice) {
- $rulePrice = $product->getData('_rule_price');
- }
- } else {
- $rulePrice = $product->getData('_rule_price');
- }
-
- $finalPrice = $product->getPriceModel()->calculatePrice(
- $basePrice,
- $specialPrice,
- $specialPriceFrom,
- $specialPriceTo,
- $rulePrice,
- null,
- null,
- $product->getId(),
- );
-
- $product->setCalculatedFinalPrice($finalPrice);
- }
-
- return $this;
- }
-
/**
* Retrieve all ids
*
@@ -1431,26 +1031,6 @@ public function requireTaxPercent()
return $this->_addTaxPercents;
}
- /**
- * @deprecated from 1.3.0
- *
- */
- protected function _addTaxPercents()
- {
- $classToRate = [];
- $request = Mage::getSingleton('tax/calculation')->getRateRequest();
- foreach ($this as &$item) {
- if ($item->getTaxClassId() === null) {
- $item->setTaxClassId($item->getMinimalTaxClassId());
- }
- if (!isset($classToRate[$item->getTaxClassId()])) {
- $request->setProductClassId($item->getTaxClassId());
- $classToRate[$item->getTaxClassId()] = Mage::getSingleton('tax/calculation')->getRate($request);
- }
- $item->setTaxPercent($classToRate[$item->getTaxClassId()]);
- }
- }
-
/**
* Adding product custom options to result collection
*
@@ -1562,25 +1142,707 @@ public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC)
}
/**
- * Prepare limitation filters
+ * Apply front-end price limitation filters to the collection
*
* @return $this
*/
- protected function _prepareProductLimitationFilters()
+ public function applyFrontendPriceLimitations()
{
- if (isset($this->_productLimitationFilters['visibility'])
- && !isset($this->_productLimitationFilters['store_id'])
- ) {
- $this->_productLimitationFilters['store_id'] = $this->getStoreId();
+ $this->_productLimitationFilters['use_price_index'] = true;
+ if (!isset($this->_productLimitationFilters['customer_group_id'])) {
+ $customerGroupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
+ $this->_productLimitationFilters['customer_group_id'] = $customerGroupId;
}
- if (isset($this->_productLimitationFilters['category_id'])
- && !isset($this->_productLimitationFilters['store_id'])
- ) {
- $this->_productLimitationFilters['store_id'] = $this->getStoreId();
+ if (!isset($this->_productLimitationFilters['website_id'])) {
+ $websiteId = Mage::app()->getStore($this->getStoreId())->getWebsiteId();
+ $this->_productLimitationFilters['website_id'] = $websiteId;
}
- if (isset($this->_productLimitationFilters['store_id'])
- && isset($this->_productLimitationFilters['visibility'])
- && !isset($this->_productLimitationFilters['category_id'])
+ $this->_applyProductLimitations();
+ return $this;
+ }
+
+ /**
+ * Add category ids to loaded items
+ *
+ * @return $this
+ */
+ public function addCategoryIds()
+ {
+ if ($this->getFlag('category_ids_added')) {
+ return $this;
+ }
+ $ids = array_keys($this->_items);
+ if (empty($ids)) {
+ return $this;
+ }
+
+ $select = $this->getConnection()->select();
+
+ $select->from($this->_productCategoryTable, ['product_id', 'category_id']);
+ $select->where('product_id IN (?)', $ids);
+
+ $data = $this->getConnection()->fetchAll($select);
+
+ $categoryIds = [];
+ foreach ($data as $info) {
+ if (isset($categoryIds[$info['product_id']])) {
+ $categoryIds[$info['product_id']][] = $info['category_id'];
+ } else {
+ $categoryIds[$info['product_id']] = [$info['category_id']];
+ }
+ }
+
+ foreach ($this->getItems() as $item) {
+ $productId = $item->getId();
+ if (isset($categoryIds[$productId])) {
+ $item->setCategoryIds($categoryIds[$productId]);
+ } else {
+ $item->setCategoryIds([]);
+ }
+ }
+
+ $this->setFlag('category_ids_added', true);
+ return $this;
+ }
+
+ /**
+ * Add tier price data to loaded items
+ *
+ * @return $this
+ */
+ public function addTierPriceData()
+ {
+ if ($this->getFlag('tier_price_added')) {
+ return $this;
+ }
+
+ $tierPrices = [];
+ $productIds = [];
+ foreach ($this->getItems() as $item) {
+ $productIds[] = $item->getId();
+ $tierPrices[$item->getId()] = [];
+ }
+ if (!$productIds) {
+ return $this;
+ }
+
+ /** @var Mage_Catalog_Model_Resource_Eav_Attribute $attribute */
+ $attribute = $this->getAttribute('tier_price');
+ if ($attribute->isScopeGlobal()) {
+ $websiteId = 0;
+ } elseif ($this->getStoreId()) {
+ $websiteId = Mage::app()->getStore($this->getStoreId())->getWebsiteId();
+ }
+
+ $adapter = $this->getConnection();
+ $columns = [
+ 'price_id' => 'value_id',
+ 'website_id' => 'website_id',
+ 'all_groups' => 'all_groups',
+ 'cust_group' => 'customer_group_id',
+ 'price_qty' => 'qty',
+ 'price' => 'value',
+ 'product_id' => 'entity_id',
+ ];
+ $select = $adapter->select()
+ ->from($this->getTable('catalog/product_attribute_tier_price'), $columns)
+ ->where('entity_id IN(?)', $productIds)
+ ->order(['entity_id','qty']);
+
+ if ($websiteId == '0') {
+ $select->where('website_id = ?', $websiteId);
+ } else {
+ $select->where('website_id IN(?)', ['0', $websiteId]);
+ }
+
+ foreach ($adapter->fetchAll($select) as $row) {
+ $tierPrices[$row['product_id']][] = [
+ 'website_id' => $row['website_id'],
+ 'cust_group' => $row['all_groups'] ? Mage_Customer_Model_Group::CUST_GROUP_ALL : $row['cust_group'],
+ 'price_qty' => $row['price_qty'],
+ 'price' => $row['price'],
+ 'website_price' => $row['price'],
+
+ ];
+ }
+
+ /** @var Mage_Catalog_Model_Product_Attribute_Backend_Tierprice $backend */
+ $backend = $attribute->getBackend();
+
+ foreach ($this->getItems() as $item) {
+ $data = $tierPrices[$item->getId()];
+ if (!empty($data) && $websiteId) {
+ $data = $backend->preparePriceData($data, $item->getTypeId(), $websiteId);
+ }
+ $item->setData('tier_price', $data);
+ }
+
+ $this->setFlag('tier_price_added', true);
+ return $this;
+ }
+
+ /**
+ * Add field comparison expression
+ *
+ * @param string $comparisonFormat - expression for sprintf()
+ * @param array $fields - list of fields
+ * @return $this
+ * @throws Exception
+ */
+ public function addPriceDataFieldFilter($comparisonFormat, $fields)
+ {
+ if (!preg_match('/^%s( (<|>|=|<=|>=|<>) %s)*$/', $comparisonFormat)) {
+ throw new Exception('Invalid comparison format.');
+ }
+
+ if (!is_array($fields)) {
+ $fields = [$fields];
+ }
+ foreach ($fields as $key => $field) {
+ $fields[$key] = $this->_getMappedField($field);
+ }
+
+ $this->_priceDataFieldFilters[] = array_merge([$comparisonFormat], $fields);
+ return $this;
+ }
+
+ /**
+ * Clear collection
+ *
+ * @inheritDoc
+ */
+ public function clear()
+ {
+ foreach ($this->_items as $i => $item) {
+ if ($item->hasStockItem()) {
+ $item->unsStockItem();
+ }
+ $item = $this->_items[$i] = null;
+ }
+
+ foreach ($this->_itemsById as $i => $item) {
+ $item = $this->_itemsById[$i] = null;
+ }
+
+ unset($this->_items, $this->_data, $this->_itemsById);
+ $this->_data = [];
+ $this->_itemsById = [];
+ return parent::clear();
+ }
+
+ /**
+ * Set Order field
+ *
+ * @param string $attribute
+ * @param string $dir
+ * @return $this
+ */
+ public function setOrder($attribute, $dir = 'desc')
+ {
+ if ($attribute == 'price') {
+ $this->addAttributeToSort($attribute, $dir);
+ } else {
+ parent::setOrder($attribute, $dir);
+ }
+ return $this;
+ }
+
+ /**
+ * Get products max price
+ *
+ * @return float
+ */
+ public function getMaxPrice()
+ {
+ if (is_null($this->_maxPrice)) {
+ $this->_prepareStatisticsData();
+ }
+
+ return $this->_maxPrice;
+ }
+
+ /**
+ * Get products min price
+ *
+ * @return float
+ */
+ public function getMinPrice()
+ {
+ if (is_null($this->_minPrice)) {
+ $this->_prepareStatisticsData();
+ }
+
+ return $this->_minPrice;
+ }
+
+ /**
+ * Get standard deviation of products price
+ *
+ * @return float
+ */
+ public function getPriceStandardDeviation()
+ {
+ if (is_null($this->_priceStandardDeviation)) {
+ $this->_prepareStatisticsData();
+ }
+
+ return $this->_priceStandardDeviation;
+ }
+
+ /**
+ * Get count of product prices
+ *
+ * @return int
+ */
+ public function getPricesCount()
+ {
+ if (is_null($this->_pricesCount)) {
+ $this->_prepareStatisticsData();
+ }
+
+ return $this->_pricesCount;
+ }
+
+ /**
+ * Prepare additional price expression sql part
+ *
+ * @param Varien_Db_Select $select
+ * @return $this
+ */
+ protected function _preparePriceExpressionParameters($select)
+ {
+ // prepare response object for event
+ $response = new Varien_Object();
+ $response->setAdditionalCalculations([]);
+ $tableAliases = array_keys($select->getPart(Zend_Db_Select::FROM));
+ if (in_array(self::INDEX_TABLE_ALIAS, $tableAliases)) {
+ $table = self::INDEX_TABLE_ALIAS;
+ } else {
+ $table = reset($tableAliases);
+ }
+
+ // prepare event arguments
+ $eventArgs = [
+ 'select' => $select,
+ 'table' => $table,
+ 'store_id' => $this->getStoreId(),
+ 'response_object' => $response,
+ ];
+
+ Mage::dispatchEvent('catalog_prepare_price_select', $eventArgs);
+
+ $additional = implode('', $response->getAdditionalCalculations());
+ $this->_priceExpression = $table . '.min_price';
+ $this->_additionalPriceExpression = $additional;
+ $this->_catalogPreparePriceSelect = clone $select;
+
+ return $this;
+ }
+
+ /**
+ * Initialize resources
+ *
+ */
+ protected function _construct()
+ {
+ if ($this->isEnabledFlat()) {
+ $this->_init('catalog/product', 'catalog/product_flat');
+ } else {
+ $this->_init('catalog/product');
+ }
+ $this->_initTables();
+ }
+
+ /**
+ * Define product website and category product tables
+ *
+ */
+ protected function _initTables()
+ {
+ $this->_productWebsiteTable = $this->getResource()->getTable('catalog/product_website');
+ $this->_productCategoryTable = $this->getResource()->getTable('catalog/category_product');
+ }
+
+ /**
+ * Standard resource collection initialization
+ *
+ * @inheritDoc
+ */
+ protected function _init($model, $entityModel = null)
+ {
+ if ($this->isEnabledFlat()) {
+ $entityModel = 'catalog/product_flat';
+ }
+
+ return parent::_init($model, $entityModel);
+ }
+
+ /**
+ * Prepare static entity fields
+ *
+ * @inheritDoc
+ */
+ protected function _prepareStaticFields()
+ {
+ if ($this->isEnabledFlat()) {
+ return $this;
+ }
+ return parent::_prepareStaticFields();
+ }
+
+ /**
+ * Initialize collection select
+ * Redeclared for remove entity_type_id condition
+ * in catalog_product_entity we store just products
+ *
+ * @return $this
+ */
+ protected function _initSelect()
+ {
+ if ($this->isEnabledFlat()) {
+ $this->getSelect()
+ ->from([self::MAIN_TABLE_ALIAS => $this->getEntity()->getFlatTableName()], null)
+ ->where('e.status = ?', new Zend_Db_Expr((string) Mage_Catalog_Model_Product_Status::STATUS_ENABLED));
+ $this->addAttributeToSelect(['entity_id', 'type_id', 'attribute_set_id']);
+ if ($this->getFlatHelper()->isAddChildData()) {
+ $this->getSelect()
+ ->where('e.is_child = ?', 0);
+ $this->addAttributeToSelect(['child_id', 'is_child']);
+ }
+ } else {
+ $this->getSelect()->from([self::MAIN_TABLE_ALIAS => $this->getEntity()->getEntityTable()]);
+ }
+ return $this;
+ }
+
+ /**
+ * Add tax class id attribute to select and join price rules data if needed
+ *
+ * @inheritDoc
+ */
+ protected function _beforeLoad()
+ {
+ Mage::dispatchEvent('catalog_product_collection_load_before', ['collection' => $this]);
+
+ return parent::_beforeLoad();
+ }
+
+ /**
+ * Processing collection items after loading
+ * Adding url rewrites, minimal prices, final prices, tax percents
+ *
+ * @return $this
+ */
+ protected function _afterLoad()
+ {
+ if ($this->_addUrlRewrite) {
+ $this->_addUrlRewrite($this->_urlRewriteCategory);
+ }
+
+ if (count($this) > 0) {
+ Mage::dispatchEvent('catalog_product_collection_load_after', ['collection' => $this]);
+ }
+
+ foreach ($this as $product) {
+ if ($product->isRecurring() && $profile = $product->getRecurringProfile()) {
+ $product->setRecurringProfile(Mage::helper('core/unserializeArray')->unserialize($profile));
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Prepare Url Data object
+ *
+ * @return $this
+ * @deprecated after 1.7.0.2
+ */
+ protected function _prepareUrlDataObject()
+ {
+ $objects = [];
+ /** @var Mage_Catalog_Model_Product $item */
+ foreach ($this->_items as $item) {
+ if ($this->getFlag('do_not_use_category_id')) {
+ $item->setDoNotUseCategoryId(true);
+ }
+ if (!$item->isVisibleInSiteVisibility() && $item->getItemStoreId()) {
+ $objects[$item->getEntityId()] = $item->getItemStoreId();
+ }
+ }
+
+ if ($objects && $this->hasFlag('url_data_object')) {
+ $objects = Mage::getResourceSingleton('catalog/url')
+ ->getRewriteByProductStore($objects);
+ foreach ($this->_items as $item) {
+ if (isset($objects[$item->getEntityId()])) {
+ $object = new Varien_Object($objects[$item->getEntityId()]);
+ $item->setUrlDataObject($object);
+ }
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get SQL for get record count
+ *
+ * @param Varien_Db_Select|null $select
+ * @param bool $resetLeftJoins
+ * @return Varien_Db_Select
+ */
+ protected function _getSelectCountSql($select = null, $resetLeftJoins = true)
+ {
+ $this->_renderFilters();
+ $countSelect = (is_null($select)) ?
+ $this->_getClearSelect() :
+ $this->_buildClearSelect($select);
+ // Clear GROUP condition for count method
+ $countSelect->reset(Zend_Db_Select::GROUP);
+ $countSelect->columns('COUNT(DISTINCT e.entity_id)');
+ if ($resetLeftJoins) {
+ $countSelect->resetJoinLeft();
+ }
+ return $countSelect;
+ }
+
+ /**
+ * Prepare statistics data
+ *
+ * @return $this
+ */
+ protected function _prepareStatisticsData()
+ {
+ $select = clone $this->getSelect();
+ $priceExpression = $this->getPriceExpression($select) . ' ' . $this->getAdditionalPriceExpression($select);
+ $sqlEndPart = ') * ' . $this->getCurrencyRate() . ', 2)';
+ $select = $this->_getSelectCountSql($select, false);
+ $select->columns([
+ 'max' => 'ROUND(MAX(' . $priceExpression . $sqlEndPart,
+ 'min' => 'ROUND(MIN(' . $priceExpression . $sqlEndPart,
+ 'std' => $this->getConnection()->getStandardDeviationSql('ROUND((' . $priceExpression . $sqlEndPart),
+ ]);
+ $select->where($this->getPriceExpression($select) . ' IS NOT NULL');
+ $row = $this->getConnection()->fetchRow($select, $this->_bindParams, Zend_Db::FETCH_NUM);
+ $this->_pricesCount = (int) $row[0];
+ $this->_maxPrice = (float) $row[1];
+ $this->_minPrice = (float) $row[2];
+ $this->_priceStandardDeviation = (float) $row[3];
+
+ return $this;
+ }
+
+ /**
+ * Retrieve clear select
+ *
+ * @return Varien_Db_Select
+ */
+ protected function _getClearSelect()
+ {
+ return $this->_buildClearSelect();
+ }
+
+ /**
+ * Build clear select
+ *
+ * @param Varien_Db_Select $select
+ * @return Varien_Db_Select
+ */
+ protected function _buildClearSelect($select = null)
+ {
+ if (is_null($select)) {
+ $select = clone $this->getSelect();
+ }
+ $select->reset(Zend_Db_Select::ORDER);
+ $select->reset(Zend_Db_Select::LIMIT_COUNT);
+ $select->reset(Zend_Db_Select::LIMIT_OFFSET);
+ $select->reset(Zend_Db_Select::COLUMNS);
+
+ return $select;
+ }
+
+ /**
+ * Add URL rewrites to collection
+ *
+ */
+ protected function _addUrlRewrite()
+ {
+ $urlRewrites = null;
+ if ($this->_cacheConf) {
+ if (!($urlRewrites = Mage::app()->loadCache($this->_cacheConf['prefix'] . 'urlrewrite'))) {
+ $urlRewrites = null;
+ } else {
+ $urlRewrites = unserialize($urlRewrites, ['allowed_classes' => false]);
+ }
+ }
+
+ if (!$urlRewrites) {
+ $productIds = [];
+ foreach ($this->getItems() as $item) {
+ $productIds[] = $item->getEntityId();
+ }
+ if (!count($productIds)) {
+ return;
+ }
+
+ $select = $this->_factory->getProductUrlRewriteHelper()
+ ->getTableSelect($productIds, $this->_urlRewriteCategory, Mage::app()->getStore($this->getStoreId())->getId());
+
+ $urlRewrites = [];
+ foreach ($this->getConnection()->fetchAll($select) as $row) {
+ if (!isset($urlRewrites[$row['product_id']])) {
+ $urlRewrites[$row['product_id']] = $row['request_path'];
+ }
+ }
+
+ if ($this->_cacheConf) {
+ Mage::app()->saveCache(
+ serialize($urlRewrites),
+ $this->_cacheConf['prefix'] . 'urlrewrite',
+ array_merge($this->_cacheConf['tags'], [Mage_Catalog_Model_Product_Url::CACHE_TAG]),
+ $this->_cacheLifetime,
+ );
+ }
+ }
+
+ foreach ($this->getItems() as $item) {
+ if (empty($this->_urlRewriteCategory)) {
+ $item->setDoNotUseCategoryId(true);
+ }
+ if (isset($urlRewrites[$item->getEntityId()])) {
+ $item->setData('request_path', $urlRewrites[$item->getEntityId()]);
+ } else {
+ $item->setData('request_path', false);
+ }
+ }
+ }
+
+ /**
+ * Add minimal price to product collection
+ *
+ * @deprecated since 1.3.2.2
+ * @see Mage_Catalog_Model_Resource_Product_Collection::addPriceData
+ *
+ * @return $this
+ */
+ protected function _addMinimalPrice()
+ {
+ return $this;
+ }
+
+ /**
+ * Join prices from price rules to products collection
+ *
+ * @return $this
+ */
+ protected function _joinPriceRules()
+ {
+ if ($this->isEnabledFlat()) {
+ $customerGroup = Mage::getSingleton('customer/session')->getCustomerGroupId();
+ $priceColumn = 'e.display_price_group_' . $customerGroup;
+ $this->getSelect()->columns(['_rule_price' => $priceColumn]);
+
+ return $this;
+ }
+ if (!$this->isModuleEnabled('Mage_CatalogRule', 'catalog')) {
+ return $this;
+ }
+ $wId = Mage::app()->getWebsite()->getId();
+ $gId = Mage::getSingleton('customer/session')->getCustomerGroupId();
+
+ $storeDate = Mage::app()->getLocale()->storeTimeStamp($this->getStoreId());
+ $conditions = 'price_rule.product_id = e.entity_id AND ';
+ $conditions .= "price_rule.rule_date = '" . $this->getResource()->formatDate($storeDate, false) . "' AND ";
+ $conditions .= $this->getConnection()->quoteInto('price_rule.website_id = ? AND', $wId);
+ $conditions .= $this->getConnection()->quoteInto('price_rule.customer_group_id = ?', $gId);
+
+ $this->getSelect()->joinLeft(
+ ['price_rule' => $this->getTable('catalogrule/rule_product_price')],
+ $conditions,
+ ['rule_price' => 'rule_price'],
+ );
+ return $this;
+ }
+
+ /**
+ * Add final price to the product
+ *
+ * @return $this
+ */
+ protected function _addFinalPrice()
+ {
+ foreach ($this->_items as $product) {
+ $basePrice = $product->getPrice();
+ $specialPrice = $product->getSpecialPrice();
+ $specialPriceFrom = $product->getSpecialFromDate();
+ $specialPriceTo = $product->getSpecialToDate();
+ if ($this->isEnabledFlat()) {
+ $rulePrice = null;
+ if ($product->getData('_rule_price') != $basePrice) {
+ $rulePrice = $product->getData('_rule_price');
+ }
+ } else {
+ $rulePrice = $product->getData('_rule_price');
+ }
+
+ $finalPrice = $product->getPriceModel()->calculatePrice(
+ $basePrice,
+ $specialPrice,
+ $specialPriceFrom,
+ $specialPriceTo,
+ $rulePrice,
+ null,
+ null,
+ $product->getId(),
+ );
+
+ $product->setCalculatedFinalPrice($finalPrice);
+ }
+
+ return $this;
+ }
+
+ /**
+ * @deprecated from 1.3.0
+ *
+ */
+ protected function _addTaxPercents()
+ {
+ $classToRate = [];
+ $request = Mage::getSingleton('tax/calculation')->getRateRequest();
+ foreach ($this as &$item) {
+ if ($item->getTaxClassId() === null) {
+ $item->setTaxClassId($item->getMinimalTaxClassId());
+ }
+ if (!isset($classToRate[$item->getTaxClassId()])) {
+ $request->setProductClassId($item->getTaxClassId());
+ $classToRate[$item->getTaxClassId()] = Mage::getSingleton('tax/calculation')->getRate($request);
+ }
+ $item->setTaxPercent($classToRate[$item->getTaxClassId()]);
+ }
+ }
+
+ /**
+ * Prepare limitation filters
+ *
+ * @return $this
+ */
+ protected function _prepareProductLimitationFilters()
+ {
+ if (isset($this->_productLimitationFilters['visibility'])
+ && !isset($this->_productLimitationFilters['store_id'])
+ ) {
+ $this->_productLimitationFilters['store_id'] = $this->getStoreId();
+ }
+ if (isset($this->_productLimitationFilters['category_id'])
+ && !isset($this->_productLimitationFilters['store_id'])
+ ) {
+ $this->_productLimitationFilters['store_id'] = $this->getStoreId();
+ }
+ if (isset($this->_productLimitationFilters['store_id'])
+ && isset($this->_productLimitationFilters['visibility'])
+ && !isset($this->_productLimitationFilters['category_id'])
) {
$this->_productLimitationFilters['category_id'] = Mage::app()
->getStore($this->_productLimitationFilters['store_id'])
@@ -1760,40 +2022,20 @@ protected function _productLimitationPrice($joinLeft = false)
$tableName = ['price_index' => $this->getTable('catalog/product_index_price')];
if ($joinLeft) {
$select->joinLeft($tableName, $joinCond, $colls);
- } else {
- $select->join($tableName, $joinCond, $colls);
- }
- // Set additional field filters
- foreach ($this->_priceDataFieldFilters as $filterData) {
- $select->where(call_user_func_array('sprintf', $filterData));
- }
- } else {
- $fromPart['price_index']['joinCondition'] = $joinCond;
- $select->setPart(Zend_Db_Select::FROM, $fromPart);
- }
- //Clean duplicated fields
- $helper->prepareColumnsList($select);
-
- return $this;
- }
-
- /**
- * Apply front-end price limitation filters to the collection
- *
- * @return $this
- */
- public function applyFrontendPriceLimitations()
- {
- $this->_productLimitationFilters['use_price_index'] = true;
- if (!isset($this->_productLimitationFilters['customer_group_id'])) {
- $customerGroupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
- $this->_productLimitationFilters['customer_group_id'] = $customerGroupId;
- }
- if (!isset($this->_productLimitationFilters['website_id'])) {
- $websiteId = Mage::app()->getStore($this->getStoreId())->getWebsiteId();
- $this->_productLimitationFilters['website_id'] = $websiteId;
+ } else {
+ $select->join($tableName, $joinCond, $colls);
+ }
+ // Set additional field filters
+ foreach ($this->_priceDataFieldFilters as $filterData) {
+ $select->where(call_user_func_array('sprintf', $filterData));
+ }
+ } else {
+ $fromPart['price_index']['joinCondition'] = $joinCond;
+ $select->setPart(Zend_Db_Select::FROM, $fromPart);
}
- $this->_applyProductLimitations();
+ //Clean duplicated fields
+ $helper->prepareColumnsList($select);
+
return $this;
}
@@ -1895,246 +2137,4 @@ protected function _applyZeroStoreProductLimitations()
return $this;
}
-
- /**
- * Add category ids to loaded items
- *
- * @return $this
- */
- public function addCategoryIds()
- {
- if ($this->getFlag('category_ids_added')) {
- return $this;
- }
- $ids = array_keys($this->_items);
- if (empty($ids)) {
- return $this;
- }
-
- $select = $this->getConnection()->select();
-
- $select->from($this->_productCategoryTable, ['product_id', 'category_id']);
- $select->where('product_id IN (?)', $ids);
-
- $data = $this->getConnection()->fetchAll($select);
-
- $categoryIds = [];
- foreach ($data as $info) {
- if (isset($categoryIds[$info['product_id']])) {
- $categoryIds[$info['product_id']][] = $info['category_id'];
- } else {
- $categoryIds[$info['product_id']] = [$info['category_id']];
- }
- }
-
- foreach ($this->getItems() as $item) {
- $productId = $item->getId();
- if (isset($categoryIds[$productId])) {
- $item->setCategoryIds($categoryIds[$productId]);
- } else {
- $item->setCategoryIds([]);
- }
- }
-
- $this->setFlag('category_ids_added', true);
- return $this;
- }
-
- /**
- * Add tier price data to loaded items
- *
- * @return $this
- */
- public function addTierPriceData()
- {
- if ($this->getFlag('tier_price_added')) {
- return $this;
- }
-
- $tierPrices = [];
- $productIds = [];
- foreach ($this->getItems() as $item) {
- $productIds[] = $item->getId();
- $tierPrices[$item->getId()] = [];
- }
- if (!$productIds) {
- return $this;
- }
-
- /** @var Mage_Catalog_Model_Resource_Eav_Attribute $attribute */
- $attribute = $this->getAttribute('tier_price');
- if ($attribute->isScopeGlobal()) {
- $websiteId = 0;
- } elseif ($this->getStoreId()) {
- $websiteId = Mage::app()->getStore($this->getStoreId())->getWebsiteId();
- }
-
- $adapter = $this->getConnection();
- $columns = [
- 'price_id' => 'value_id',
- 'website_id' => 'website_id',
- 'all_groups' => 'all_groups',
- 'cust_group' => 'customer_group_id',
- 'price_qty' => 'qty',
- 'price' => 'value',
- 'product_id' => 'entity_id',
- ];
- $select = $adapter->select()
- ->from($this->getTable('catalog/product_attribute_tier_price'), $columns)
- ->where('entity_id IN(?)', $productIds)
- ->order(['entity_id','qty']);
-
- if ($websiteId == '0') {
- $select->where('website_id = ?', $websiteId);
- } else {
- $select->where('website_id IN(?)', ['0', $websiteId]);
- }
-
- foreach ($adapter->fetchAll($select) as $row) {
- $tierPrices[$row['product_id']][] = [
- 'website_id' => $row['website_id'],
- 'cust_group' => $row['all_groups'] ? Mage_Customer_Model_Group::CUST_GROUP_ALL : $row['cust_group'],
- 'price_qty' => $row['price_qty'],
- 'price' => $row['price'],
- 'website_price' => $row['price'],
-
- ];
- }
-
- /** @var Mage_Catalog_Model_Product_Attribute_Backend_Tierprice $backend */
- $backend = $attribute->getBackend();
-
- foreach ($this->getItems() as $item) {
- $data = $tierPrices[$item->getId()];
- if (!empty($data) && $websiteId) {
- $data = $backend->preparePriceData($data, $item->getTypeId(), $websiteId);
- }
- $item->setData('tier_price', $data);
- }
-
- $this->setFlag('tier_price_added', true);
- return $this;
- }
-
- /**
- * Add field comparison expression
- *
- * @param string $comparisonFormat - expression for sprintf()
- * @param array $fields - list of fields
- * @return $this
- * @throws Exception
- */
- public function addPriceDataFieldFilter($comparisonFormat, $fields)
- {
- if (!preg_match('/^%s( (<|>|=|<=|>=|<>) %s)*$/', $comparisonFormat)) {
- throw new Exception('Invalid comparison format.');
- }
-
- if (!is_array($fields)) {
- $fields = [$fields];
- }
- foreach ($fields as $key => $field) {
- $fields[$key] = $this->_getMappedField($field);
- }
-
- $this->_priceDataFieldFilters[] = array_merge([$comparisonFormat], $fields);
- return $this;
- }
-
- /**
- * Clear collection
- *
- * @inheritDoc
- */
- public function clear()
- {
- foreach ($this->_items as $i => $item) {
- if ($item->hasStockItem()) {
- $item->unsStockItem();
- }
- $item = $this->_items[$i] = null;
- }
-
- foreach ($this->_itemsById as $i => $item) {
- $item = $this->_itemsById[$i] = null;
- }
-
- unset($this->_items, $this->_data, $this->_itemsById);
- $this->_data = [];
- $this->_itemsById = [];
- return parent::clear();
- }
-
- /**
- * Set Order field
- *
- * @param string $attribute
- * @param string $dir
- * @return $this
- */
- public function setOrder($attribute, $dir = 'desc')
- {
- if ($attribute == 'price') {
- $this->addAttributeToSort($attribute, $dir);
- } else {
- parent::setOrder($attribute, $dir);
- }
- return $this;
- }
-
- /**
- * Get products max price
- *
- * @return float
- */
- public function getMaxPrice()
- {
- if (is_null($this->_maxPrice)) {
- $this->_prepareStatisticsData();
- }
-
- return $this->_maxPrice;
- }
-
- /**
- * Get products min price
- *
- * @return float
- */
- public function getMinPrice()
- {
- if (is_null($this->_minPrice)) {
- $this->_prepareStatisticsData();
- }
-
- return $this->_minPrice;
- }
-
- /**
- * Get standard deviation of products price
- *
- * @return float
- */
- public function getPriceStandardDeviation()
- {
- if (is_null($this->_priceStandardDeviation)) {
- $this->_prepareStatisticsData();
- }
-
- return $this->_priceStandardDeviation;
- }
-
- /**
- * Get count of product prices
- *
- * @return int
- */
- public function getPricesCount()
- {
- if (is_null($this->_pricesCount)) {
- $this->_prepareStatisticsData();
- }
-
- return $this->_pricesCount;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Compare/Item.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Compare/Item.php
index fcb84c58246..507a3bb0e0c 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Compare/Item.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Compare/Item.php
@@ -22,11 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Product_Compare_Item extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/compare_item', 'catalog_compare_item_id');
- }
-
/**
* Load object by product
*
@@ -232,4 +227,8 @@ public function clearItems($visitorId = null, $customerId = null)
$this->_getWriteAdapter()->delete($this->getMainTable(), $where);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('catalog/compare_item', 'catalog_compare_item_id');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Compare/Item/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Compare/Item/Collection.php
index b64dea76045..5bacd8829ff 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Compare/Item/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Compare/Item/Collection.php
@@ -43,15 +43,6 @@ class Mage_Catalog_Model_Resource_Product_Compare_Item_Collection extends Mage_C
*/
protected $_comparableAttributes;
- /**
- * Initialize resources
- */
- protected function _construct()
- {
- $this->_init('catalog/product_compare_item', 'catalog/product');
- $this->_initTables();
- }
-
/**
* Set customer filter to collection
*
@@ -141,66 +132,6 @@ public function _addJoinToSelect()
return $this;
}
- /**
- * Retrieve compare products attribute set ids
- *
- * @return array
- */
- protected function _getAttributeSetIds()
- {
- // prepare compare items table conditions
- $compareConds = [
- 'compare.product_id=entity.entity_id',
- ];
- if ($this->getCustomerId()) {
- $compareConds[] = $this->getConnection()
- ->quoteInto('compare.customer_id = ?', $this->getCustomerId());
- } else {
- $compareConds[] = $this->getConnection()
- ->quoteInto('compare.visitor_id = ?', $this->getVisitorId());
- }
-
- // prepare website filter
- $websiteId = (int) Mage::app()->getStore($this->getStoreId())->getWebsiteId();
- $websiteConds = [
- 'website.product_id = entity.entity_id',
- $this->getConnection()->quoteInto('website.website_id = ?', $websiteId),
- ];
-
- // retrieve attribute sets
- $select = $this->getConnection()->select()
- ->distinct(true)
- ->from(
- ['entity' => $this->getEntity()->getEntityTable()],
- 'attribute_set_id',
- )
- ->join(
- ['website' => $this->getTable('catalog/product_website')],
- implode(' AND ', $websiteConds),
- [],
- )
- ->join(
- ['compare' => $this->getTable('catalog/compare_item')],
- implode(' AND ', $compareConds),
- [],
- );
- return $this->getConnection()->fetchCol($select);
- }
-
- /**
- * Retrieve attribute ids by set ids
- *
- * @return array
- */
- protected function _getAttributeIdsBySetIds(array $setIds)
- {
- $select = $this->getConnection()->select()
- ->distinct(true)
- ->from($this->getTable('eav/entity_attribute'), 'attribute_id')
- ->where('attribute_set_id IN(?)', $setIds);
- return $this->getConnection()->fetchCol($select);
- }
-
/**
* Retrieve Merged comparable attributes for compared product items
*
@@ -312,4 +243,73 @@ public function isEnabledFlat()
}
return parent::isEnabledFlat();
}
+
+ /**
+ * Initialize resources
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_compare_item', 'catalog/product');
+ $this->_initTables();
+ }
+
+ /**
+ * Retrieve compare products attribute set ids
+ *
+ * @return array
+ */
+ protected function _getAttributeSetIds()
+ {
+ // prepare compare items table conditions
+ $compareConds = [
+ 'compare.product_id=entity.entity_id',
+ ];
+ if ($this->getCustomerId()) {
+ $compareConds[] = $this->getConnection()
+ ->quoteInto('compare.customer_id = ?', $this->getCustomerId());
+ } else {
+ $compareConds[] = $this->getConnection()
+ ->quoteInto('compare.visitor_id = ?', $this->getVisitorId());
+ }
+
+ // prepare website filter
+ $websiteId = (int) Mage::app()->getStore($this->getStoreId())->getWebsiteId();
+ $websiteConds = [
+ 'website.product_id = entity.entity_id',
+ $this->getConnection()->quoteInto('website.website_id = ?', $websiteId),
+ ];
+
+ // retrieve attribute sets
+ $select = $this->getConnection()->select()
+ ->distinct(true)
+ ->from(
+ ['entity' => $this->getEntity()->getEntityTable()],
+ 'attribute_set_id',
+ )
+ ->join(
+ ['website' => $this->getTable('catalog/product_website')],
+ implode(' AND ', $websiteConds),
+ [],
+ )
+ ->join(
+ ['compare' => $this->getTable('catalog/compare_item')],
+ implode(' AND ', $compareConds),
+ [],
+ );
+ return $this->getConnection()->fetchCol($select);
+ }
+
+ /**
+ * Retrieve attribute ids by set ids
+ *
+ * @return array
+ */
+ protected function _getAttributeIdsBySetIds(array $setIds)
+ {
+ $select = $this->getConnection()->select()
+ ->distinct(true)
+ ->from($this->getTable('eav/entity_attribute'), 'attribute_id')
+ ->where('attribute_set_id IN(?)', $setIds);
+ return $this->getConnection()->fetchCol($select);
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Flat.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Flat.php
index b8152256243..7a637555d4a 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Flat.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Flat.php
@@ -36,16 +36,6 @@ class Mage_Catalog_Model_Resource_Product_Flat extends Mage_Core_Model_Resource_
*/
protected $_isBuilt = [];
- /**
- * Init connection and resource table
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/product_flat', 'entity_id');
- $this->_storeId = (int) Mage::app()->getStore()->getId();
- }
-
/**
* Retrieve store for resource model
*
@@ -241,4 +231,14 @@ public function isBuilt($storeView = null)
}
return $this->_isBuilt[$storeId];
}
+
+ /**
+ * Init connection and resource table
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_flat', 'entity_id');
+ $this->_storeId = (int) Mage::app()->getStore()->getId();
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php
index 81c9ccb168b..e5bda389925 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php
@@ -88,11 +88,6 @@ class Mage_Catalog_Model_Resource_Product_Flat_Indexer extends Mage_Index_Model_
*/
protected $_preparedFlatTables = [];
- protected function _construct()
- {
- $this->_init('catalog/product', 'entity_id');
- }
-
/**
* Rebuild Catalog Product Flat Data
*
@@ -287,111 +282,6 @@ public function getFlatTableName($storeId)
return sprintf('%s_%s', $this->getTable('catalog/product_flat'), $storeId);
}
- /**
- * Retrieve catalog product flat columns array in old format (used before MMDB support)
- *
- * @return array
- */
- protected function _getFlatColumnsOldDefinition()
- {
- $columns = [];
- $columns['entity_id'] = [
- 'type' => 'int(10)',
- 'unsigned' => true,
- 'is_null' => false,
- 'default' => null,
- 'extra' => null,
- ];
- if ($this->getFlatHelper()->isAddChildData()) {
- $columns['child_id'] = [
- 'type' => 'int(10)',
- 'unsigned' => true,
- 'is_null' => true,
- 'default' => null,
- 'extra' => null,
- ];
- $columns['is_child'] = [
- 'type' => 'tinyint(1)',
- 'unsigned' => true,
- 'is_null' => false,
- 'default' => 0,
- 'extra' => null,
- ];
- }
- $columns['attribute_set_id'] = [
- 'type' => 'smallint(5)',
- 'unsigned' => true,
- 'is_null' => false,
- 'default' => 0,
- 'extra' => null,
- ];
- $columns['type_id'] = [
- 'type' => 'varchar(32)',
- 'unsigned' => false,
- 'is_null' => false,
- 'default' => Mage_Catalog_Model_Product_Type::TYPE_SIMPLE,
- 'extra' => null,
- ];
-
- return $columns;
- }
-
- /**
- * Retrieve catalog product flat columns array in DDL format
- *
- * @return array
- */
- protected function _getFlatColumnsDdlDefinition()
- {
- $columns = [];
- $columns['entity_id'] = [
- 'type' => Varien_Db_Ddl_Table::TYPE_INTEGER,
- 'length' => null,
- 'unsigned' => true,
- 'nullable' => false,
- 'default' => false,
- 'primary' => true,
- 'comment' => 'Entity Id',
- ];
- if ($this->getFlatHelper()->isAddChildData()) {
- $columns['child_id'] = [
- 'type' => Varien_Db_Ddl_Table::TYPE_INTEGER,
- 'length' => null,
- 'unsigned' => true,
- 'nullable' => true,
- 'default' => null,
- 'primary' => true,
- 'comment' => 'Child Id',
- ];
- $columns['is_child'] = [
- 'type' => Varien_Db_Ddl_Table::TYPE_SMALLINT,
- 'length' => 1,
- 'unsigned' => true,
- 'nullable' => false,
- 'default' => '0',
- 'comment' => 'Checks If Entity Is Child',
- ];
- }
- $columns['attribute_set_id'] = [
- 'type' => Varien_Db_Ddl_Table::TYPE_SMALLINT,
- 'length' => 5,
- 'unsigned' => true,
- 'nullable' => false,
- 'default' => '0',
- 'comment' => 'Attribute Set Id',
- ];
- $columns['type_id'] = [
- 'type' => Varien_Db_Ddl_Table::TYPE_TEXT,
- 'length' => 32,
- 'unsigned' => false,
- 'nullable' => false,
- 'default' => Mage_Catalog_Model_Product_Type::TYPE_SIMPLE,
- 'comment' => 'Type Id',
- ];
-
- return $columns;
- }
-
/**
* Retrieve catalog product flat table columns array
*
@@ -489,95 +379,6 @@ public function getFlatIndexes()
return $this->_indexes;
}
- /**
- * Compare Flat style with Describe style columns
- * If column a different - return false
- *
- * @param array $column
- * @param array $describe
- * @return bool
- */
- protected function _compareColumnProperties($column, $describe)
- {
- /** @var Mage_Catalog_Model_Resource_Helper_Mysql4 $helper */
- $helper = Mage::getResourceHelper('catalog');
- return $helper->compareIndexColumnProperties($column, $describe);
- }
-
- /**
- * Retrieve column definition fragment
- * @deprecated since 1.5.0.0
- *
- * Example: `field_name` smallint(5) unsigned NOT NULL default '0'
- *
- * @param string $fieldName
- * @param array $fieldProp
- * @return string
- */
- protected function _sqlColunmDefinition($fieldName, $fieldProp)
- {
- $fieldNameQuote = $this->_getWriteAdapter()->quoteIdentifier($fieldName);
-
- /**
- * Process the case when 'is_null' prohibits null value, and 'default' proposed to be null
- * It just means that default value not specified
- */
- if ($fieldProp['is_null'] === false && $fieldProp['default'] === null) {
- $defaultValue = '';
- } else {
- $defaultValue = $fieldProp['default'] === null ? ' DEFAULT NULL' : $this->_getReadAdapter()
- ->quoteInto(' DEFAULT ?', $fieldProp['default']);
- }
-
- return "{$fieldNameQuote} {$fieldProp['type']}"
- . ($fieldProp['unsigned'] ? ' UNSIGNED' : '')
- . ($fieldProp['extra'] ? ' ' . $fieldProp['extra'] : '')
- . ($fieldProp['is_null'] === false ? ' NOT NULL' : '')
- . $defaultValue;
- }
-
- /**
- * Retrieve index definition fragment
- * @deprecated since 1.5.0.0
- *
- * Example: INDEX `IDX_NAME` (`field_id`)
- *
- * @param string $indexName
- * @param array $indexProp
- * @return string
- */
- protected function _sqlIndexDefinition($indexName, $indexProp)
- {
- $fields = $indexProp['fields'];
- if (is_array($fields)) {
- $fieldSql = [];
- foreach ($fields as $field) {
- $fieldSql[] = $this->_getReadAdapter()->quoteIdentifier($field);
- }
- $fieldSql = implode(',', $fieldSql);
- } else {
- $fieldSql = $this->_getReadAdapter()->quoteIdentifier($fields);
- }
-
- $indexNameQuote = $this->_getReadAdapter()->quoteIdentifier($indexName);
- switch (strtolower($indexProp['type'])) {
- case 'primary':
- $condition = 'PRIMARY KEY';
- break;
- case 'unique':
- $condition = 'UNIQUE ' . $indexNameQuote;
- break;
- case 'fulltext':
- $condition = 'FULLTEXT ' . $indexNameQuote;
- break;
- default:
- $condition = 'INDEX ' . $indexNameQuote;
- break;
- }
-
- return sprintf('%s (%s)', $condition, $fieldSql);
- }
-
/**
* Retrieve UNIQUE HASH for a Table foreign key
*
@@ -1335,6 +1136,230 @@ public function deleteFlatTable($storeId)
return $this;
}
+ /**
+ * Transactional rebuild Catalog Product Flat Data
+ *
+ * @return $this
+ */
+ public function reindexAll()
+ {
+ foreach (Mage::app()->getStores() as $storeId => $store) {
+ if (!$store->getIsActive()) {
+ continue;
+ }
+ $this->prepareFlatTable($storeId);
+ $this->beginTransaction();
+ try {
+ $this->rebuild($store);
+ $this->commit();
+ } catch (Exception $e) {
+ $this->rollBack();
+ throw $e;
+ }
+ }
+
+ return $this;
+ }
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product', 'entity_id');
+ }
+
+ /**
+ * Retrieve catalog product flat columns array in old format (used before MMDB support)
+ *
+ * @return array
+ */
+ protected function _getFlatColumnsOldDefinition()
+ {
+ $columns = [];
+ $columns['entity_id'] = [
+ 'type' => 'int(10)',
+ 'unsigned' => true,
+ 'is_null' => false,
+ 'default' => null,
+ 'extra' => null,
+ ];
+ if ($this->getFlatHelper()->isAddChildData()) {
+ $columns['child_id'] = [
+ 'type' => 'int(10)',
+ 'unsigned' => true,
+ 'is_null' => true,
+ 'default' => null,
+ 'extra' => null,
+ ];
+ $columns['is_child'] = [
+ 'type' => 'tinyint(1)',
+ 'unsigned' => true,
+ 'is_null' => false,
+ 'default' => 0,
+ 'extra' => null,
+ ];
+ }
+ $columns['attribute_set_id'] = [
+ 'type' => 'smallint(5)',
+ 'unsigned' => true,
+ 'is_null' => false,
+ 'default' => 0,
+ 'extra' => null,
+ ];
+ $columns['type_id'] = [
+ 'type' => 'varchar(32)',
+ 'unsigned' => false,
+ 'is_null' => false,
+ 'default' => Mage_Catalog_Model_Product_Type::TYPE_SIMPLE,
+ 'extra' => null,
+ ];
+
+ return $columns;
+ }
+
+ /**
+ * Retrieve catalog product flat columns array in DDL format
+ *
+ * @return array
+ */
+ protected function _getFlatColumnsDdlDefinition()
+ {
+ $columns = [];
+ $columns['entity_id'] = [
+ 'type' => Varien_Db_Ddl_Table::TYPE_INTEGER,
+ 'length' => null,
+ 'unsigned' => true,
+ 'nullable' => false,
+ 'default' => false,
+ 'primary' => true,
+ 'comment' => 'Entity Id',
+ ];
+ if ($this->getFlatHelper()->isAddChildData()) {
+ $columns['child_id'] = [
+ 'type' => Varien_Db_Ddl_Table::TYPE_INTEGER,
+ 'length' => null,
+ 'unsigned' => true,
+ 'nullable' => true,
+ 'default' => null,
+ 'primary' => true,
+ 'comment' => 'Child Id',
+ ];
+ $columns['is_child'] = [
+ 'type' => Varien_Db_Ddl_Table::TYPE_SMALLINT,
+ 'length' => 1,
+ 'unsigned' => true,
+ 'nullable' => false,
+ 'default' => '0',
+ 'comment' => 'Checks If Entity Is Child',
+ ];
+ }
+ $columns['attribute_set_id'] = [
+ 'type' => Varien_Db_Ddl_Table::TYPE_SMALLINT,
+ 'length' => 5,
+ 'unsigned' => true,
+ 'nullable' => false,
+ 'default' => '0',
+ 'comment' => 'Attribute Set Id',
+ ];
+ $columns['type_id'] = [
+ 'type' => Varien_Db_Ddl_Table::TYPE_TEXT,
+ 'length' => 32,
+ 'unsigned' => false,
+ 'nullable' => false,
+ 'default' => Mage_Catalog_Model_Product_Type::TYPE_SIMPLE,
+ 'comment' => 'Type Id',
+ ];
+
+ return $columns;
+ }
+
+ /**
+ * Compare Flat style with Describe style columns
+ * If column a different - return false
+ *
+ * @param array $column
+ * @param array $describe
+ * @return bool
+ */
+ protected function _compareColumnProperties($column, $describe)
+ {
+ /** @var Mage_Catalog_Model_Resource_Helper_Mysql4 $helper */
+ $helper = Mage::getResourceHelper('catalog');
+ return $helper->compareIndexColumnProperties($column, $describe);
+ }
+
+ /**
+ * Retrieve column definition fragment
+ * @deprecated since 1.5.0.0
+ *
+ * Example: `field_name` smallint(5) unsigned NOT NULL default '0'
+ *
+ * @param string $fieldName
+ * @param array $fieldProp
+ * @return string
+ */
+ protected function _sqlColunmDefinition($fieldName, $fieldProp)
+ {
+ $fieldNameQuote = $this->_getWriteAdapter()->quoteIdentifier($fieldName);
+
+ /**
+ * Process the case when 'is_null' prohibits null value, and 'default' proposed to be null
+ * It just means that default value not specified
+ */
+ if ($fieldProp['is_null'] === false && $fieldProp['default'] === null) {
+ $defaultValue = '';
+ } else {
+ $defaultValue = $fieldProp['default'] === null ? ' DEFAULT NULL' : $this->_getReadAdapter()
+ ->quoteInto(' DEFAULT ?', $fieldProp['default']);
+ }
+
+ return "{$fieldNameQuote} {$fieldProp['type']}"
+ . ($fieldProp['unsigned'] ? ' UNSIGNED' : '')
+ . ($fieldProp['extra'] ? ' ' . $fieldProp['extra'] : '')
+ . ($fieldProp['is_null'] === false ? ' NOT NULL' : '')
+ . $defaultValue;
+ }
+
+ /**
+ * Retrieve index definition fragment
+ * @deprecated since 1.5.0.0
+ *
+ * Example: INDEX `IDX_NAME` (`field_id`)
+ *
+ * @param string $indexName
+ * @param array $indexProp
+ * @return string
+ */
+ protected function _sqlIndexDefinition($indexName, $indexProp)
+ {
+ $fields = $indexProp['fields'];
+ if (is_array($fields)) {
+ $fieldSql = [];
+ foreach ($fields as $field) {
+ $fieldSql[] = $this->_getReadAdapter()->quoteIdentifier($field);
+ }
+ $fieldSql = implode(',', $fieldSql);
+ } else {
+ $fieldSql = $this->_getReadAdapter()->quoteIdentifier($fields);
+ }
+
+ $indexNameQuote = $this->_getReadAdapter()->quoteIdentifier($indexName);
+ switch (strtolower($indexProp['type'])) {
+ case 'primary':
+ $condition = 'PRIMARY KEY';
+ break;
+ case 'unique':
+ $condition = 'UNIQUE ' . $indexNameQuote;
+ break;
+ case 'fulltext':
+ $condition = 'FULLTEXT ' . $indexNameQuote;
+ break;
+ default:
+ $condition = 'INDEX ' . $indexNameQuote;
+ break;
+ }
+
+ return sprintf('%s (%s)', $condition, $fieldSql);
+ }
+
/**
* Check is flat table for store exists
*
@@ -1390,29 +1415,4 @@ protected function _arrayNextKey(array $array, $key)
}
return false;
}
-
- /**
- * Transactional rebuild Catalog Product Flat Data
- *
- * @return $this
- */
- public function reindexAll()
- {
- foreach (Mage::app()->getStores() as $storeId => $store) {
- if (!$store->getIsActive()) {
- continue;
- }
- $this->prepareFlatTable($storeId);
- $this->beginTransaction();
- try {
- $this->rebuild($store);
- $this->commit();
- } catch (Exception $e) {
- $this->rollBack();
- throw $e;
- }
- }
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Abstract.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Abstract.php
index 191e2765b7a..e031924d61c 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Abstract.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Abstract.php
@@ -22,6 +22,45 @@
*/
abstract class Mage_Catalog_Model_Resource_Product_Indexer_Abstract extends Mage_Index_Model_Resource_Abstract
{
+ /**
+ * Retrieve product relations by children
+ *
+ * @param int|array $childIds
+ * @return array
+ */
+ public function getRelationsByChild($childIds)
+ {
+ $write = $this->_getWriteAdapter();
+ $select = $write->select()
+ ->from($this->getTable('catalog/product_relation'), 'parent_id')
+ ->where('child_id IN(?)', $childIds);
+
+ return $write->fetchCol($select);
+ }
+
+ /**
+ * Retrieve product relations by parents
+ *
+ * @param int|array $parentIds
+ * @return array
+ */
+ public function getRelationsByParent($parentIds)
+ {
+ if (!is_array($parentIds)) {
+ $parentIds = [$parentIds];
+ }
+
+ $result = [];
+ if (!empty($parentIds)) {
+ $write = $this->_getWriteAdapter();
+ $select = $write->select()
+ ->from($this->getTable('catalog/product_relation'), 'child_id')
+ ->where('parent_id IN(?)', $parentIds);
+ $result = $write->fetchCol($select);
+ }
+
+ return $result;
+ }
/**
* Retrieve catalog_product attribute instance by attribute code
*
@@ -153,44 +192,4 @@ protected function _addProductWebsiteJoinToSelect($select, $website, $product)
return $this;
}
-
- /**
- * Retrieve product relations by children
- *
- * @param int|array $childIds
- * @return array
- */
- public function getRelationsByChild($childIds)
- {
- $write = $this->_getWriteAdapter();
- $select = $write->select()
- ->from($this->getTable('catalog/product_relation'), 'parent_id')
- ->where('child_id IN(?)', $childIds);
-
- return $write->fetchCol($select);
- }
-
- /**
- * Retrieve product relations by parents
- *
- * @param int|array $parentIds
- * @return array
- */
- public function getRelationsByParent($parentIds)
- {
- if (!is_array($parentIds)) {
- $parentIds = [$parentIds];
- }
-
- $result = [];
- if (!empty($parentIds)) {
- $write = $this->_getWriteAdapter();
- $select = $write->select()
- ->from($this->getTable('catalog/product_relation'), 'child_id')
- ->where('parent_id IN(?)', $parentIds);
- $result = $write->fetchCol($select);
- }
-
- return $result;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav.php
index 63cee0d0a77..88e873e1d27 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav.php
@@ -29,15 +29,6 @@ class Mage_Catalog_Model_Resource_Product_Indexer_Eav extends Mage_Catalog_Model
*/
protected $_types;
- /**
- * Define main index table
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/product_index_eav', 'entity_id');
- }
-
/**
* Retrieve array of EAV type indexers
*
@@ -185,4 +176,13 @@ public function getIdxTable($table = null)
}
return $this->getTable('catalog/product_eav_indexer_tmp');
}
+
+ /**
+ * Define main index table
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_index_eav', 'entity_id');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Decimal.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Decimal.php
index 49e256c5c04..9ffc864f8ee 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Decimal.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Decimal.php
@@ -22,6 +22,19 @@
*/
class Mage_Catalog_Model_Resource_Product_Indexer_Eav_Decimal extends Mage_Catalog_Model_Resource_Product_Indexer_Eav_Abstract
{
+ /**
+ * Retrieve temporary decimal index table name
+ *
+ * @param string $table
+ * @return string
+ */
+ public function getIdxTable($table = null)
+ {
+ if ($this->useIdxTable()) {
+ return $this->getTable('catalog/product_eav_decimal_indexer_idx');
+ }
+ return $this->getTable('catalog/product_eav_decimal_indexer_tmp');
+ }
protected function _construct()
{
$this->_init('catalog/product_index_eav_decimal', 'entity_id');
@@ -115,18 +128,4 @@ protected function _getIndexableAttributes()
return $adapter->fetchCol($select);
}
-
- /**
- * Retrieve temporary decimal index table name
- *
- * @param string $table
- * @return string
- */
- public function getIdxTable($table = null)
- {
- if ($this->useIdxTable()) {
- return $this->getTable('catalog/product_eav_decimal_indexer_idx');
- }
- return $this->getTable('catalog/product_eav_decimal_indexer_tmp');
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Source.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Source.php
index eeac3506258..2b57a8723c0 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Source.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Source.php
@@ -22,6 +22,19 @@
*/
class Mage_Catalog_Model_Resource_Product_Indexer_Eav_Source extends Mage_Catalog_Model_Resource_Product_Indexer_Eav_Abstract
{
+ /**
+ * Retrieve temporary source index table name
+ *
+ * @param string $table
+ * @return string
+ */
+ public function getIdxTable($table = null)
+ {
+ if ($this->useIdxTable()) {
+ return $this->getTable('catalog/product_eav_indexer_idx');
+ }
+ return $this->getTable('catalog/product_eav_indexer_tmp');
+ }
protected function _construct()
{
$this->_init('catalog/product_index_eav', 'entity_id');
@@ -268,18 +281,4 @@ protected function _saveIndexData(array $data)
$adapter->insertArray($this->getIdxTable(), ['entity_id', 'attribute_id', 'store_id', 'value'], $data);
return $this;
}
-
- /**
- * Retrieve temporary source index table name
- *
- * @param string $table
- * @return string
- */
- public function getIdxTable($table = null)
- {
- if ($this->useIdxTable()) {
- return $this->getTable('catalog/product_eav_indexer_idx');
- }
- return $this->getTable('catalog/product_eav_indexer_tmp');
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Price.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Price.php
index eb6c8599c18..fd0afc3b391 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Price.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Price.php
@@ -36,15 +36,6 @@ class Mage_Catalog_Model_Resource_Product_Indexer_Price extends Mage_Index_Model
*/
protected $_indexers;
- /**
- * Define main index table
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/product_index_price', 'entity_id');
- }
-
/**
* Retrieve parent ids and types by child id
* Return array with key product_id and value as product type id
@@ -98,38 +89,6 @@ public function catalogProductDelete(Mage_Index_Model_Event $event)
return $this;
}
- /**
- * Copy data from temporary index table to main table by defined ids
- *
- * @param array $processIds
- * @return $this
- * @throws Exception
- */
- protected function _copyIndexDataToMainTable($processIds)
- {
- $write = $this->_getWriteAdapter();
- $this->beginTransaction();
- try {
- // remove old index
- $where = $write->quoteInto('entity_id IN(?)', $processIds);
- $write->delete($this->getMainTable(), $where);
-
- // remove additional data from index
- $where = $write->quoteInto('entity_id NOT IN(?)', $processIds);
- $write->delete($this->getIdxTable(), $where);
-
- // insert new index
- $this->insertFromTable($this->getIdxTable(), $this->getMainTable());
-
- $this->commit();
- } catch (Exception $e) {
- $this->rollBack();
- throw $e;
- }
-
- return $this;
- }
-
/**
* Process product save.
* Method is responsible for index support
@@ -306,22 +265,6 @@ public function reindexProductIds($ids)
return $this;
}
- /**
- * Retrieve Price indexer by Product Type
- *
- * @param string $productTypeId
- * @return Mage_Catalog_Model_Resource_Product_Indexer_Price_Interface
- * @throws Mage_Core_Exception
- */
- protected function _getIndexer($productTypeId)
- {
- $types = $this->getTypeIndexers();
- if (!isset($types[$productTypeId])) {
- Mage::throwException(Mage::helper('catalog')->__('Unsupported product type "%s".', $productTypeId));
- }
- return $types[$productTypeId];
- }
-
/**
* Retrieve price indexers per product type
*
@@ -376,6 +319,77 @@ public function reindexAll()
return $this;
}
+ /**
+ * Retrieve temporary index table name
+ *
+ * @param string $table
+ * @return string
+ */
+ public function getIdxTable($table = null)
+ {
+ if ($this->useIdxTable()) {
+ return $this->getTable('catalog/product_price_indexer_idx');
+ }
+ return $this->getTable('catalog/product_price_indexer_tmp');
+ }
+
+ /**
+ * Define main index table
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_index_price', 'entity_id');
+ }
+
+ /**
+ * Copy data from temporary index table to main table by defined ids
+ *
+ * @param array $processIds
+ * @return $this
+ * @throws Exception
+ */
+ protected function _copyIndexDataToMainTable($processIds)
+ {
+ $write = $this->_getWriteAdapter();
+ $this->beginTransaction();
+ try {
+ // remove old index
+ $where = $write->quoteInto('entity_id IN(?)', $processIds);
+ $write->delete($this->getMainTable(), $where);
+
+ // remove additional data from index
+ $where = $write->quoteInto('entity_id NOT IN(?)', $processIds);
+ $write->delete($this->getIdxTable(), $where);
+
+ // insert new index
+ $this->insertFromTable($this->getIdxTable(), $this->getMainTable());
+
+ $this->commit();
+ } catch (Exception $e) {
+ $this->rollBack();
+ throw $e;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Retrieve Price indexer by Product Type
+ *
+ * @param string $productTypeId
+ * @return Mage_Catalog_Model_Resource_Product_Indexer_Price_Interface
+ * @throws Mage_Core_Exception
+ */
+ protected function _getIndexer($productTypeId)
+ {
+ $types = $this->getTypeIndexers();
+ if (!isset($types[$productTypeId])) {
+ Mage::throwException(Mage::helper('catalog')->__('Unsupported product type "%s".', $productTypeId));
+ }
+ return $types[$productTypeId];
+ }
+
/**
* Retrieve table name for product tier price index
*
@@ -595,18 +609,4 @@ protected function _prepareWebsiteDateTable()
return $this;
}
-
- /**
- * Retrieve temporary index table name
- *
- * @param string $table
- * @return string
- */
- public function getIdxTable($table = null)
- {
- if ($this->useIdxTable()) {
- return $this->getTable('catalog/product_price_indexer_idx');
- }
- return $this->getTable('catalog/product_price_indexer_tmp');
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Price/Default.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Price/Default.php
index 6b3b7d7c688..737038444fc 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Price/Default.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Price/Default.php
@@ -37,15 +37,6 @@ class Mage_Catalog_Model_Resource_Product_Indexer_Price_Default extends Mage_Cat
*/
protected $_isComposite = false;
- /**
- * Define main price index table
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/product_index_price', 'entity_id');
- }
-
/**
* Set Product Type code
*
@@ -129,6 +120,34 @@ public function reindexEntity($entityIds)
return $this;
}
+ /**
+ * Register data required by product type process in event object
+ */
+ public function registerEvent(Mage_Index_Model_Event $event) {}
+
+ /**
+ * Retrieve temporary index table name
+ *
+ * @param string $table
+ * @return string
+ */
+ public function getIdxTable($table = null)
+ {
+ if ($this->useIdxTable()) {
+ return $this->getTable('catalog/product_price_indexer_idx');
+ }
+ return $this->getTable('catalog/product_price_indexer_tmp');
+ }
+
+ /**
+ * Define main price index table
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_index_price', 'entity_id');
+ }
+
/**
* Retrieve final price temporary index table name
*
@@ -592,23 +611,4 @@ protected function _getGroupPriceIndexTable()
{
return $this->getTable('catalog/product_index_group_price');
}
-
- /**
- * Register data required by product type process in event object
- */
- public function registerEvent(Mage_Index_Model_Event $event) {}
-
- /**
- * Retrieve temporary index table name
- *
- * @param string $table
- * @return string
- */
- public function getIdxTable($table = null)
- {
- if ($this->useIdxTable()) {
- return $this->getTable('catalog/product_price_indexer_idx');
- }
- return $this->getTable('catalog/product_price_indexer_tmp');
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Link.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Link.php
index b6bf9838e33..e369b3fbdde 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Link.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Link.php
@@ -29,12 +29,6 @@ class Mage_Catalog_Model_Resource_Product_Link extends Mage_Core_Model_Resource_
*/
protected $_attributesTable;
- protected function _construct()
- {
- $this->_init('catalog/product_link', 'link_id');
- $this->_attributesTable = $this->getTable('catalog/product_link_attribute');
- }
-
/**
* Save Product Links process
*
@@ -117,23 +111,6 @@ public function saveProductLinks($product, $data, $typeId)
return $this;
}
- /**
- * Prepare link attribute value by attribute type
- *
- * @param string $type
- * @param mixed $value
- * @return mixed
- */
- protected function _prepareAttributeValue($type, $value)
- {
- if ($type == 'int') {
- $value = (int) $value;
- } elseif ($type == 'decimal') {
- $value = (float) sprintf('%F', $value);
- }
- return $value;
- }
-
/**
* Retrieve product link attributes by link type
*
@@ -263,4 +240,27 @@ public function saveGroupedLinks($product, $data, $typeId)
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product_link', 'link_id');
+ $this->_attributesTable = $this->getTable('catalog/product_link_attribute');
+ }
+
+ /**
+ * Prepare link attribute value by attribute type
+ *
+ * @param string $type
+ * @param mixed $value
+ * @return mixed
+ */
+ protected function _prepareAttributeValue($type, $value)
+ {
+ if ($type == 'int') {
+ $value = (int) $value;
+ } elseif ($type == 'decimal') {
+ $value = (float) sprintf('%F', $value);
+ }
+ return $value;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Link/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Link/Collection.php
index 87047a05eee..d1fb411fd0d 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Link/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Link/Collection.php
@@ -43,11 +43,6 @@ class Mage_Catalog_Model_Resource_Product_Link_Collection extends Mage_Core_Mode
*/
protected $_linkTypeId;
- protected function _construct()
- {
- $this->_init('catalog/product_link');
- }
-
/**
* Declare link model and initialize type attributes join
*
@@ -146,4 +141,9 @@ public function joinAttributes()
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product_link');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Link/Product/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Link/Product/Collection.php
index e8373bff94f..8b0dae1cdf2 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Link/Product/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Link/Product/Collection.php
@@ -183,57 +183,6 @@ public function setGroupBy($groupBy = 'e.entity_id')
return $this;
}
- /**
- * Join linked products when specified link model
- *
- * @inheritDoc
- */
- protected function _beforeLoad()
- {
- if ($this->getLinkModel()) {
- $this->_joinLinks();
- }
- return parent::_beforeLoad();
- }
-
- /**
- * Join linked products and their attributes
- *
- * @return $this
- */
- protected function _joinLinks()
- {
- $select = $this->getSelect();
- $adapter = $select->getAdapter();
-
- $joinCondition = [
- 'links.linked_product_id = e.entity_id',
- $adapter->quoteInto('links.link_type_id = ?', $this->_linkTypeId),
- ];
- $joinType = 'join';
- if ($this->getProduct() && $this->getProduct()->getId()) {
- $productId = $this->getProduct()->getId();
- if ($this->_isStrongMode) {
- $this->getSelect()->where('links.product_id = ?', (int) $productId);
- } else {
- $joinType = 'joinLeft';
- $joinCondition[] = $adapter->quoteInto('links.product_id = ?', $productId);
- }
- $this->addFieldToFilter('entity_id', ['neq' => $productId]);
- } elseif ($this->_isStrongMode) {
- $this->addFieldToFilter('entity_id', ['eq' => -1]);
- }
- if ($this->_hasLinkFilter) {
- $select->$joinType(
- ['links' => $this->getTable('catalog/product_link')],
- implode(' AND ', $joinCondition),
- ['link_id'],
- );
- $this->joinAttributes();
- }
- return $this;
- }
-
/**
* Enable sorting products by its position
*
@@ -266,19 +215,6 @@ public function setAttributeSetIdOrder($dir = self::SORT_ORDER_ASC)
return $this;
}
- /**
- * Get table alias for link model attribute
- *
- * @param string $attributeCode
- * @param string $attributeType
- *
- * @return string
- */
- protected function _getLinkAttributeTableAlias($attributeCode, $attributeType)
- {
- return sprintf('link_attribute_%s_%s', $attributeCode, $attributeType);
- }
-
/**
* Join attributes
*
@@ -359,4 +295,68 @@ public function addLinkModelFieldToFilter($attributeCode, $condition = null)
return $this;
}
+
+ /**
+ * Join linked products when specified link model
+ *
+ * @inheritDoc
+ */
+ protected function _beforeLoad()
+ {
+ if ($this->getLinkModel()) {
+ $this->_joinLinks();
+ }
+ return parent::_beforeLoad();
+ }
+
+ /**
+ * Join linked products and their attributes
+ *
+ * @return $this
+ */
+ protected function _joinLinks()
+ {
+ $select = $this->getSelect();
+ $adapter = $select->getAdapter();
+
+ $joinCondition = [
+ 'links.linked_product_id = e.entity_id',
+ $adapter->quoteInto('links.link_type_id = ?', $this->_linkTypeId),
+ ];
+ $joinType = 'join';
+ if ($this->getProduct() && $this->getProduct()->getId()) {
+ $productId = $this->getProduct()->getId();
+ if ($this->_isStrongMode) {
+ $this->getSelect()->where('links.product_id = ?', (int) $productId);
+ } else {
+ $joinType = 'joinLeft';
+ $joinCondition[] = $adapter->quoteInto('links.product_id = ?', $productId);
+ }
+ $this->addFieldToFilter('entity_id', ['neq' => $productId]);
+ } elseif ($this->_isStrongMode) {
+ $this->addFieldToFilter('entity_id', ['eq' => -1]);
+ }
+ if ($this->_hasLinkFilter) {
+ $select->$joinType(
+ ['links' => $this->getTable('catalog/product_link')],
+ implode(' AND ', $joinCondition),
+ ['link_id'],
+ );
+ $this->joinAttributes();
+ }
+ return $this;
+ }
+
+ /**
+ * Get table alias for link model attribute
+ *
+ * @param string $attributeCode
+ * @param string $attributeType
+ *
+ * @return string
+ */
+ protected function _getLinkAttributeTableAlias($attributeCode, $attributeType)
+ {
+ return sprintf('link_attribute_%s_%s', $attributeCode, $attributeType);
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Option.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Option.php
index ecda7697cea..131a870043e 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Option.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Option.php
@@ -22,6 +22,212 @@
*/
class Mage_Catalog_Model_Resource_Product_Option extends Mage_Core_Model_Resource_Db_Abstract
{
+ /**
+ * Delete prices
+ *
+ * @param int|string $optionId
+ * @return $this
+ */
+ public function deletePrices($optionId)
+ {
+ $this->_getWriteAdapter()->delete(
+ $this->getTable('catalog/product_option_price'),
+ [
+ 'option_id = ?' => $optionId,
+ ],
+ );
+
+ return $this;
+ }
+
+ /**
+ * Delete titles
+ *
+ * @param int|string $optionId
+ * @return $this
+ */
+ public function deleteTitles($optionId)
+ {
+ $this->_getWriteAdapter()->delete(
+ $this->getTable('catalog/product_option_title'),
+ [
+ 'option_id = ?' => $optionId,
+ ],
+ );
+
+ return $this;
+ }
+
+ /**
+ * Duplicate custom options for product
+ *
+ * @param int $oldProductId
+ * @param int $newProductId
+ * @return Mage_Catalog_Model_Product_Option
+ */
+ public function duplicate(Mage_Catalog_Model_Product_Option $object, $oldProductId, $newProductId)
+ {
+ $write = $this->_getWriteAdapter();
+ $read = $this->_getReadAdapter();
+
+ $optionsCond = [];
+ $optionsData = [];
+
+ // read and prepare original product options
+ $select = $read->select()
+ ->from($this->getTable('catalog/product_option'))
+ ->where('product_id = ?', $oldProductId);
+
+ $query = $read->query($select);
+
+ while ($row = $query->fetch()) {
+ $optionsData[$row['option_id']] = $row;
+ $optionsData[$row['option_id']]['product_id'] = $newProductId;
+ unset($optionsData[$row['option_id']]['option_id']);
+ }
+
+ // insert options to duplicated product
+ foreach ($optionsData as $oId => $data) {
+ $write->insert($this->getMainTable(), $data);
+ $optionsCond[$oId] = $write->lastInsertId($this->getMainTable());
+ }
+
+ // copy options prefs
+ foreach ($optionsCond as $oldOptionId => $newOptionId) {
+ // title
+ $table = $this->getTable('catalog/product_option_title');
+
+ $select = $this->_getReadAdapter()->select()
+ ->from($table, [new Zend_Db_Expr($newOptionId), 'store_id', 'title'])
+ ->where('option_id = ?', $oldOptionId);
+
+ $insertSelect = $write->insertFromSelect(
+ $select,
+ $table,
+ ['option_id', 'store_id', 'title'],
+ Varien_Db_Adapter_Interface::INSERT_ON_DUPLICATE,
+ );
+ $write->query($insertSelect);
+
+ // price
+ $table = $this->getTable('catalog/product_option_price');
+
+ $select = $read->select()
+ ->from($table, [new Zend_Db_Expr($newOptionId), 'store_id', 'price', 'price_type'])
+ ->where('option_id = ?', $oldOptionId);
+
+ $insertSelect = $write->insertFromSelect(
+ $select,
+ $table,
+ [
+ 'option_id',
+ 'store_id',
+ 'price',
+ 'price_type',
+ ],
+ Varien_Db_Adapter_Interface::INSERT_ON_DUPLICATE,
+ );
+ $write->query($insertSelect);
+
+ $object->getValueInstance()->duplicate($oldOptionId, $newOptionId);
+ }
+
+ return $object;
+ }
+
+ /**
+ * Retrieve option searchable data
+ *
+ * @param int $productId
+ * @param int $storeId
+ * @return array
+ */
+ public function getSearchableData($productId, $storeId)
+ {
+ $searchData = [];
+
+ $adapter = $this->_getReadAdapter();
+
+ $titleCheckSql = $adapter->getCheckSql(
+ 'option_title_store.title IS NULL',
+ 'option_title_default.title',
+ 'option_title_store.title',
+ );
+
+ // retrieve options title
+
+ $defaultOptionJoin = implode(
+ ' AND ',
+ ['option_title_default.option_id=product_option.option_id',
+ $adapter->quoteInto('option_title_default.store_id = ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID)],
+ );
+
+ $storeOptionJoin = implode(
+ ' AND ',
+ [
+ 'option_title_store.option_id=product_option.option_id',
+ $adapter->quoteInto('option_title_store.store_id = ?', (int) $storeId)],
+ );
+
+ $select = $adapter->select()
+ ->from(['product_option' => $this->getMainTable()], null)
+ ->join(
+ ['option_title_default' => $this->getTable('catalog/product_option_title')],
+ $defaultOptionJoin,
+ [],
+ )
+ ->joinLeft(
+ ['option_title_store' => $this->getTable('catalog/product_option_title')],
+ $storeOptionJoin,
+ ['title' => $titleCheckSql],
+ )
+ ->where('product_option.product_id = ?', $productId);
+
+ if ($titles = $adapter->fetchCol($select)) {
+ $searchData = array_merge($searchData, $titles);
+ }
+
+ //select option type titles
+
+ $defaultOptionJoin = implode(
+ ' AND ',
+ [
+ 'option_title_default.option_type_id=option_type.option_type_id',
+ $adapter->quoteInto('option_title_default.store_id = ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID)],
+ );
+
+ $storeOptionJoin = implode(
+ ' AND ',
+ [
+ 'option_title_store.option_type_id = option_type.option_type_id',
+ $adapter->quoteInto('option_title_store.store_id = ?', (int) $storeId)],
+ );
+
+ $select = $adapter->select()
+ ->from(['product_option' => $this->getMainTable()], null)
+ ->join(
+ ['option_type' => $this->getTable('catalog/product_option_type_value')],
+ 'option_type.option_id=product_option.option_id',
+ [],
+ )
+ ->join(
+ ['option_title_default' => $this->getTable('catalog/product_option_type_title')],
+ $defaultOptionJoin,
+ [],
+ )
+ ->joinLeft(
+ ['option_title_store' => $this->getTable('catalog/product_option_type_title')],
+ $storeOptionJoin,
+ ['title' => $titleCheckSql],
+ )
+ ->where('product_option.product_id = ?', $productId);
+
+ if ($titles = $adapter->fetchCol($select)) {
+ $searchData = array_merge($searchData, $titles);
+ }
+
+ return $searchData;
+ }
protected function _construct()
{
$this->_init('catalog/product_option', 'option_id');
@@ -283,211 +489,4 @@ protected function _saveValueTitles(Mage_Core_Model_Abstract $object)
);
}
}
-
- /**
- * Delete prices
- *
- * @param int|string $optionId
- * @return $this
- */
- public function deletePrices($optionId)
- {
- $this->_getWriteAdapter()->delete(
- $this->getTable('catalog/product_option_price'),
- [
- 'option_id = ?' => $optionId,
- ],
- );
-
- return $this;
- }
-
- /**
- * Delete titles
- *
- * @param int|string $optionId
- * @return $this
- */
- public function deleteTitles($optionId)
- {
- $this->_getWriteAdapter()->delete(
- $this->getTable('catalog/product_option_title'),
- [
- 'option_id = ?' => $optionId,
- ],
- );
-
- return $this;
- }
-
- /**
- * Duplicate custom options for product
- *
- * @param int $oldProductId
- * @param int $newProductId
- * @return Mage_Catalog_Model_Product_Option
- */
- public function duplicate(Mage_Catalog_Model_Product_Option $object, $oldProductId, $newProductId)
- {
- $write = $this->_getWriteAdapter();
- $read = $this->_getReadAdapter();
-
- $optionsCond = [];
- $optionsData = [];
-
- // read and prepare original product options
- $select = $read->select()
- ->from($this->getTable('catalog/product_option'))
- ->where('product_id = ?', $oldProductId);
-
- $query = $read->query($select);
-
- while ($row = $query->fetch()) {
- $optionsData[$row['option_id']] = $row;
- $optionsData[$row['option_id']]['product_id'] = $newProductId;
- unset($optionsData[$row['option_id']]['option_id']);
- }
-
- // insert options to duplicated product
- foreach ($optionsData as $oId => $data) {
- $write->insert($this->getMainTable(), $data);
- $optionsCond[$oId] = $write->lastInsertId($this->getMainTable());
- }
-
- // copy options prefs
- foreach ($optionsCond as $oldOptionId => $newOptionId) {
- // title
- $table = $this->getTable('catalog/product_option_title');
-
- $select = $this->_getReadAdapter()->select()
- ->from($table, [new Zend_Db_Expr($newOptionId), 'store_id', 'title'])
- ->where('option_id = ?', $oldOptionId);
-
- $insertSelect = $write->insertFromSelect(
- $select,
- $table,
- ['option_id', 'store_id', 'title'],
- Varien_Db_Adapter_Interface::INSERT_ON_DUPLICATE,
- );
- $write->query($insertSelect);
-
- // price
- $table = $this->getTable('catalog/product_option_price');
-
- $select = $read->select()
- ->from($table, [new Zend_Db_Expr($newOptionId), 'store_id', 'price', 'price_type'])
- ->where('option_id = ?', $oldOptionId);
-
- $insertSelect = $write->insertFromSelect(
- $select,
- $table,
- [
- 'option_id',
- 'store_id',
- 'price',
- 'price_type',
- ],
- Varien_Db_Adapter_Interface::INSERT_ON_DUPLICATE,
- );
- $write->query($insertSelect);
-
- $object->getValueInstance()->duplicate($oldOptionId, $newOptionId);
- }
-
- return $object;
- }
-
- /**
- * Retrieve option searchable data
- *
- * @param int $productId
- * @param int $storeId
- * @return array
- */
- public function getSearchableData($productId, $storeId)
- {
- $searchData = [];
-
- $adapter = $this->_getReadAdapter();
-
- $titleCheckSql = $adapter->getCheckSql(
- 'option_title_store.title IS NULL',
- 'option_title_default.title',
- 'option_title_store.title',
- );
-
- // retrieve options title
-
- $defaultOptionJoin = implode(
- ' AND ',
- ['option_title_default.option_id=product_option.option_id',
- $adapter->quoteInto('option_title_default.store_id = ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID)],
- );
-
- $storeOptionJoin = implode(
- ' AND ',
- [
- 'option_title_store.option_id=product_option.option_id',
- $adapter->quoteInto('option_title_store.store_id = ?', (int) $storeId)],
- );
-
- $select = $adapter->select()
- ->from(['product_option' => $this->getMainTable()], null)
- ->join(
- ['option_title_default' => $this->getTable('catalog/product_option_title')],
- $defaultOptionJoin,
- [],
- )
- ->joinLeft(
- ['option_title_store' => $this->getTable('catalog/product_option_title')],
- $storeOptionJoin,
- ['title' => $titleCheckSql],
- )
- ->where('product_option.product_id = ?', $productId);
-
- if ($titles = $adapter->fetchCol($select)) {
- $searchData = array_merge($searchData, $titles);
- }
-
- //select option type titles
-
- $defaultOptionJoin = implode(
- ' AND ',
- [
- 'option_title_default.option_type_id=option_type.option_type_id',
- $adapter->quoteInto('option_title_default.store_id = ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID)],
- );
-
- $storeOptionJoin = implode(
- ' AND ',
- [
- 'option_title_store.option_type_id = option_type.option_type_id',
- $adapter->quoteInto('option_title_store.store_id = ?', (int) $storeId)],
- );
-
- $select = $adapter->select()
- ->from(['product_option' => $this->getMainTable()], null)
- ->join(
- ['option_type' => $this->getTable('catalog/product_option_type_value')],
- 'option_type.option_id=product_option.option_id',
- [],
- )
- ->join(
- ['option_title_default' => $this->getTable('catalog/product_option_type_title')],
- $defaultOptionJoin,
- [],
- )
- ->joinLeft(
- ['option_title_store' => $this->getTable('catalog/product_option_type_title')],
- $storeOptionJoin,
- ['title' => $titleCheckSql],
- )
- ->where('product_option.product_id = ?', $productId);
-
- if ($titles = $adapter->fetchCol($select)) {
- $searchData = array_merge($searchData, $titles);
- }
-
- return $searchData;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Collection.php
index c9f6ca0a1a9..25cbef663af 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Collection.php
@@ -24,11 +24,6 @@
*/
class Mage_Catalog_Model_Resource_Product_Option_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product_option');
- }
-
/**
* Adds title, price & price_type attributes to result
*
@@ -219,4 +214,8 @@ public function reset()
{
return $this->_reset();
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product_option');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Value.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Value.php
index 29a647a4b00..60d72f2e552 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Value.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Value.php
@@ -22,6 +22,125 @@
*/
class Mage_Catalog_Model_Resource_Product_Option_Value extends Mage_Core_Model_Resource_Db_Abstract
{
+ /**
+ * Delete values by option id
+ *
+ * @param int|string $optionId
+ * @return $this
+ */
+ public function deleteValue($optionId)
+ {
+ $statement = $this->_getReadAdapter()->select()
+ ->from($this->getTable('catalog/product_option_type_value'))
+ ->where('option_id = ?', $optionId);
+
+ $rowSet = $this->_getReadAdapter()->fetchAll($statement);
+
+ foreach ($rowSet as $optionType) {
+ $this->deleteValues($optionType['option_type_id']);
+ }
+
+ $this->_getWriteAdapter()->delete(
+ $this->getMainTable(),
+ [
+ 'option_id = ?' => $optionId,
+ ],
+ );
+
+ return $this;
+ }
+
+ /**
+ * Delete values by option type
+ *
+ * @param int $optionTypeId
+ */
+ public function deleteValues($optionTypeId)
+ {
+ $condition = [
+ 'option_type_id = ?' => $optionTypeId,
+ ];
+
+ $this->_getWriteAdapter()->delete(
+ $this->getTable('catalog/product_option_type_price'),
+ $condition,
+ );
+
+ $this->_getWriteAdapter()->delete(
+ $this->getTable('catalog/product_option_type_title'),
+ $condition,
+ );
+ }
+
+ /**
+ * Duplicate product options value
+ *
+ * @param int $oldOptionId
+ * @param int $newOptionId
+ * @return Mage_Catalog_Model_Product_Option_Value
+ */
+ public function duplicate(Mage_Catalog_Model_Product_Option_Value $object, $oldOptionId, $newOptionId)
+ {
+ $writeAdapter = $this->_getWriteAdapter();
+ $readAdapter = $this->_getReadAdapter();
+ $select = $readAdapter->select()
+ ->from($this->getMainTable())
+ ->where('option_id = ?', $oldOptionId);
+ $valueData = $readAdapter->fetchAll($select);
+
+ $valueCond = [];
+
+ foreach ($valueData as $data) {
+ $optionTypeId = $data[$this->getIdFieldName()];
+ unset($data[$this->getIdFieldName()]);
+ $data['option_id'] = $newOptionId;
+
+ $writeAdapter->insert($this->getMainTable(), $data);
+ $valueCond[$optionTypeId] = $writeAdapter->lastInsertId($this->getMainTable());
+ }
+
+ unset($valueData);
+
+ foreach ($valueCond as $oldTypeId => $newTypeId) {
+ // price
+ $priceTable = $this->getTable('catalog/product_option_type_price');
+ $columns = [
+ new Zend_Db_Expr($newTypeId),
+ 'store_id', 'price', 'price_type',
+ ];
+
+ $select = $readAdapter->select()
+ ->from($priceTable, [])
+ ->where('option_type_id = ?', $oldTypeId)
+ ->columns($columns);
+ $insertSelect = $writeAdapter->insertFromSelect(
+ $select,
+ $priceTable,
+ ['option_type_id', 'store_id', 'price', 'price_type'],
+ );
+ $writeAdapter->query($insertSelect);
+
+ // title
+ $titleTable = $this->getTable('catalog/product_option_type_title');
+ $columns = [
+ new Zend_Db_Expr($newTypeId),
+ 'store_id', 'title',
+ ];
+
+ $select = $this->_getReadAdapter()->select()
+ ->from($titleTable, [])
+ ->where('option_type_id = ?', $oldTypeId)
+ ->columns($columns);
+ $insertSelect = $writeAdapter->insertFromSelect(
+ $select,
+ $titleTable,
+ ['option_type_id', 'store_id', 'title'],
+ );
+ $writeAdapter->query($insertSelect);
+ }
+
+ return $object;
+ }
protected function _construct()
{
$this->_init('catalog/product_option_type_value', 'option_type_id');
@@ -211,124 +330,4 @@ protected function _saveValueTitles(Mage_Core_Model_Abstract $object)
$this->_getWriteAdapter()->delete($titleTable, $where);
}
}
-
- /**
- * Delete values by option id
- *
- * @param int|string $optionId
- * @return $this
- */
- public function deleteValue($optionId)
- {
- $statement = $this->_getReadAdapter()->select()
- ->from($this->getTable('catalog/product_option_type_value'))
- ->where('option_id = ?', $optionId);
-
- $rowSet = $this->_getReadAdapter()->fetchAll($statement);
-
- foreach ($rowSet as $optionType) {
- $this->deleteValues($optionType['option_type_id']);
- }
-
- $this->_getWriteAdapter()->delete(
- $this->getMainTable(),
- [
- 'option_id = ?' => $optionId,
- ],
- );
-
- return $this;
- }
-
- /**
- * Delete values by option type
- *
- * @param int $optionTypeId
- */
- public function deleteValues($optionTypeId)
- {
- $condition = [
- 'option_type_id = ?' => $optionTypeId,
- ];
-
- $this->_getWriteAdapter()->delete(
- $this->getTable('catalog/product_option_type_price'),
- $condition,
- );
-
- $this->_getWriteAdapter()->delete(
- $this->getTable('catalog/product_option_type_title'),
- $condition,
- );
- }
-
- /**
- * Duplicate product options value
- *
- * @param int $oldOptionId
- * @param int $newOptionId
- * @return Mage_Catalog_Model_Product_Option_Value
- */
- public function duplicate(Mage_Catalog_Model_Product_Option_Value $object, $oldOptionId, $newOptionId)
- {
- $writeAdapter = $this->_getWriteAdapter();
- $readAdapter = $this->_getReadAdapter();
- $select = $readAdapter->select()
- ->from($this->getMainTable())
- ->where('option_id = ?', $oldOptionId);
- $valueData = $readAdapter->fetchAll($select);
-
- $valueCond = [];
-
- foreach ($valueData as $data) {
- $optionTypeId = $data[$this->getIdFieldName()];
- unset($data[$this->getIdFieldName()]);
- $data['option_id'] = $newOptionId;
-
- $writeAdapter->insert($this->getMainTable(), $data);
- $valueCond[$optionTypeId] = $writeAdapter->lastInsertId($this->getMainTable());
- }
-
- unset($valueData);
-
- foreach ($valueCond as $oldTypeId => $newTypeId) {
- // price
- $priceTable = $this->getTable('catalog/product_option_type_price');
- $columns = [
- new Zend_Db_Expr($newTypeId),
- 'store_id', 'price', 'price_type',
- ];
-
- $select = $readAdapter->select()
- ->from($priceTable, [])
- ->where('option_type_id = ?', $oldTypeId)
- ->columns($columns);
- $insertSelect = $writeAdapter->insertFromSelect(
- $select,
- $priceTable,
- ['option_type_id', 'store_id', 'price', 'price_type'],
- );
- $writeAdapter->query($insertSelect);
-
- // title
- $titleTable = $this->getTable('catalog/product_option_type_title');
- $columns = [
- new Zend_Db_Expr($newTypeId),
- 'store_id', 'title',
- ];
-
- $select = $this->_getReadAdapter()->select()
- ->from($titleTable, [])
- ->where('option_type_id = ?', $oldTypeId)
- ->columns($columns);
- $insertSelect = $writeAdapter->insertFromSelect(
- $select,
- $titleTable,
- ['option_type_id', 'store_id', 'title'],
- );
- $writeAdapter->query($insertSelect);
- }
-
- return $object;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Value/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Value/Collection.php
index 2a863f806e0..8a528dd0929 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Value/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Value/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Product_Option_Value_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product_option_value');
- }
-
/**
* Add price, title to result
*
@@ -223,4 +218,8 @@ public function addOptionToFilter($option)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product_option_value');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Relation.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Relation.php
index 9dd7d046a42..250715eff10 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Relation.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Relation.php
@@ -22,11 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Product_Relation extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product_relation', 'parent_id');
- }
-
/**
* Save (rebuild) product relations
*
@@ -65,4 +60,8 @@ public function processRelations($parentId, $childIds)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product_relation', 'parent_id');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Status.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Status.php
index 045174cdbfa..47a561c0ca3 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Status.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Status.php
@@ -29,11 +29,6 @@ class Mage_Catalog_Model_Resource_Product_Status extends Mage_Core_Model_Resourc
*/
protected $_productAttributes = [];
- protected function _construct()
- {
- $this->_init('catalog/product_enabled_index', 'product_id');
- }
-
/**
* Retrieve product attribute (public method for status model)
*
@@ -45,21 +40,6 @@ public function getProductAttribute($attributeCode)
return $this->_getProductAttribute($attributeCode);
}
- /**
- * Retrieve product attribute
- *
- * @param string|int|Mage_Core_Model_Config_Element $attribute
- * @return Mage_Eav_Model_Entity_Attribute_Abstract
- */
- protected function _getProductAttribute($attribute)
- {
- if (empty($this->_productAttributes[$attribute])) {
- $this->_productAttributes[$attribute] =
- Mage::getSingleton('catalog/product')->getResource()->getAttribute($attribute);
- }
- return $this->_productAttributes[$attribute];
- }
-
/**
* Refresh enabled index cache
*
@@ -194,4 +174,24 @@ public function getProductStatus($productIds, $storeId = null)
return $statuses;
}
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product_enabled_index', 'product_id');
+ }
+
+ /**
+ * Retrieve product attribute
+ *
+ * @param string|int|Mage_Core_Model_Config_Element $attribute
+ * @return Mage_Eav_Model_Entity_Attribute_Abstract
+ */
+ protected function _getProductAttribute($attribute)
+ {
+ if (empty($this->_productAttributes[$attribute])) {
+ $this->_productAttributes[$attribute] =
+ Mage::getSingleton('catalog/product')->getResource()->getAttribute($attribute);
+ }
+ return $this->_productAttributes[$attribute];
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php
index bbfc2fd3e2e..ff21ee40e89 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php
@@ -22,15 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Product_Type_Configurable extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Init resource
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/product_super_link', 'link_id');
- }
-
/**
* Save configurable product relations
*
@@ -214,4 +205,12 @@ public function getConfigurableOptions($product, $attributes)
}
return $attributesOptionsData;
}
+ /**
+ * Init resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_super_link', 'link_id');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute.php
index 7f3278706ee..bd8d1c0bb90 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute.php
@@ -36,17 +36,6 @@ class Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute extends Ma
*/
protected $_priceTable;
- /**
- * Inititalize connection and define tables
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/product_super_attribute', 'product_super_attribute_id');
- $this->_labelTable = $this->getTable('catalog/product_super_attribute_label');
- $this->_priceTable = $this->getTable('catalog/product_super_attribute_pricing');
- }
-
/**
* Retrieve Catalog Helper
*
@@ -288,4 +277,15 @@ public function getUsedAttributes($setId)
return $adapter->fetchCol($select, $bind);
}
+
+ /**
+ * Inititalize connection and define tables
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product_super_attribute', 'product_super_attribute_id');
+ $this->_labelTable = $this->getTable('catalog/product_super_attribute_label');
+ $this->_priceTable = $this->getTable('catalog/product_super_attribute_pricing');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php
index a6ee64c24b7..6cb52a4cd69 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php
@@ -45,13 +45,6 @@ class Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute_Collection
*/
protected $_product;
- protected function _construct()
- {
- $this->_init('catalog/product_type_configurable_attribute');
- $this->_labelTable = $this->getTable('catalog/product_super_attribute_label');
- $this->_priceTable = $this->getTable('catalog/product_super_attribute_pricing');
- }
-
/**
* Retrieve catalog helper
*
@@ -96,6 +89,36 @@ public function getStoreId()
return (int) $this->_product->getStoreId();
}
+ /**
+ * Add Associated Product Filters (From Product Type Instance)
+ *
+ * @return $this
+ */
+ public function _addAssociatedProductFilters()
+ {
+ /** @var Mage_Catalog_Model_Product_Type_Configurable $productType */
+ $productType = $this->getProduct()->getTypeInstance(true);
+ $productType->getUsedProducts($this->getColumnValues('attribute_id'), $this->getProduct()); //Filter associated products
+ return $this;
+ }
+
+ /**
+ * Retrieve product instance
+ *
+ * @return Mage_Catalog_Model_Product
+ */
+ public function getProduct()
+ {
+ return $this->_product;
+ }
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product_type_configurable_attribute');
+ $this->_labelTable = $this->getTable('catalog/product_super_attribute_label');
+ $this->_priceTable = $this->getTable('catalog/product_super_attribute_pricing');
+ }
+
/**
* After load collection process
*
@@ -134,19 +157,6 @@ protected function _addProductAttributes()
return $this;
}
- /**
- * Add Associated Product Filters (From Product Type Instance)
- *
- * @return $this
- */
- public function _addAssociatedProductFilters()
- {
- /** @var Mage_Catalog_Model_Product_Type_Configurable $productType */
- $productType = $this->getProduct()->getTypeInstance(true);
- $productType->getUsedProducts($this->getColumnValues('attribute_id'), $this->getProduct()); //Filter associated products
- return $this;
- }
-
/**
* Load attribute labels
*
@@ -302,14 +312,4 @@ protected function _loadPrices()
}
return $this;
}
-
- /**
- * Retrieve product instance
- *
- * @return Mage_Catalog_Model_Product
- */
- public function getProduct()
- {
- return $this->_product;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Product/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Product/Collection.php
index 538d280ec74..8445920593f 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Product/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Product/Collection.php
@@ -29,6 +29,29 @@ class Mage_Catalog_Model_Resource_Product_Type_Configurable_Product_Collection e
*/
protected $_linkTable;
+ /**
+ * Set Product filter to result
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @return $this
+ */
+ public function setProductFilter($product)
+ {
+ $this->getSelect()->where('link_table.parent_id = ?', (int) $product->getId());
+ return $this;
+ }
+
+ /**
+ * Retrieve is flat enabled flag
+ * Return alvays false if magento run admin
+ *
+ * @return bool
+ */
+ public function isEnabledFlat()
+ {
+ return false;
+ }
+
/**
* Assign link table name
*/
@@ -53,27 +76,4 @@ protected function _initSelect()
return $this;
}
-
- /**
- * Set Product filter to result
- *
- * @param Mage_Catalog_Model_Product $product
- * @return $this
- */
- public function setProductFilter($product)
- {
- $this->getSelect()->where('link_table.parent_id = ?', (int) $product->getId());
- return $this;
- }
-
- /**
- * Retrieve is flat enabled flag
- * Return alvays false if magento run admin
- *
- * @return bool
- */
- public function isEnabledFlat()
- {
- return false;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Website.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Website.php
index ed7283bef32..3cf21695fd5 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Website.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Website.php
@@ -22,21 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Product_Website extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product_website', 'product_id');
- }
-
- /**
- * Get catalog product resource model
- *
- * @return Mage_Catalog_Model_Resource_Product
- */
- protected function _getProductResource()
- {
- return Mage::getResourceSingleton('catalog/product');
- }
-
/**
* Removes products from websites
*
@@ -141,4 +126,18 @@ public function getWebsites($productIds)
return $result;
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product_website', 'product_id');
+ }
+
+ /**
+ * Get catalog product resource model
+ *
+ * @return Mage_Catalog_Model_Resource_Product
+ */
+ protected function _getProductResource()
+ {
+ return Mage::getResourceSingleton('catalog/product');
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Setup.php b/app/code/core/Mage/Catalog/Model/Resource/Setup.php
index 561badaf330..777c57f2014 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Setup.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Setup.php
@@ -22,40 +22,6 @@
*/
class Mage_Catalog_Model_Resource_Setup extends Mage_Eav_Model_Entity_Setup
{
- /**
- * Prepare catalog attribute values to save
- *
- * @param array $attr
- * @return array
- */
- protected function _prepareValues($attr)
- {
- $data = parent::_prepareValues($attr);
- return array_merge($data, [
- 'frontend_input_renderer' => $this->_getValue($attr, 'input_renderer'),
- 'is_global' => $this->_getValue(
- $attr,
- 'global',
- Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
- ),
- 'is_visible' => $this->_getValue($attr, 'visible', 1),
- 'is_searchable' => $this->_getValue($attr, 'searchable', 0),
- 'is_filterable' => $this->_getValue($attr, 'filterable', 0),
- 'is_comparable' => $this->_getValue($attr, 'comparable', 0),
- 'is_visible_on_front' => $this->_getValue($attr, 'visible_on_front', 0),
- 'is_wysiwyg_enabled' => $this->_getValue($attr, 'wysiwyg_enabled', 0),
- 'is_html_allowed_on_front' => $this->_getValue($attr, 'is_html_allowed_on_front', 0),
- 'is_visible_in_advanced_search' => $this->_getValue($attr, 'visible_in_advanced_search', 0),
- 'is_filterable_in_search' => $this->_getValue($attr, 'filterable_in_search', 0),
- 'used_in_product_listing' => $this->_getValue($attr, 'used_in_product_listing', 0),
- 'used_for_sort_by' => $this->_getValue($attr, 'used_for_sort_by', 0),
- 'apply_to' => $this->_getValue($attr, 'apply_to'),
- 'position' => $this->_getValue($attr, 'position', 0),
- 'is_configurable' => $this->_getValue($attr, 'is_configurable', 1),
- 'is_used_for_promo_rules' => $this->_getValue($attr, 'used_for_promo_rules', 0),
- ]);
- }
-
/**
* Default entities and attributes
*
@@ -870,6 +836,64 @@ public function convertOldTreeToNew()
return $this;
}
+ /**
+ * Creates level values for categories and saves them
+ *
+ * @deprecated since 1.5.0.0
+ * @return $this
+ */
+ public function rebuildCategoryLevels()
+ {
+ $adapter = $this->getConnection();
+ $select = $adapter->select()
+ ->from($this->getTable('catalog/category'));
+
+ $categories = $adapter->fetchAll($select);
+
+ foreach ($categories as $category) {
+ $level = count(explode('/', $category['path'])) - 1;
+ $adapter->update(
+ $this->getTable('catalog/category'),
+ ['level' => $level],
+ ['entity_id = ?' => $category['entity_id']],
+ );
+ }
+ return $this;
+ }
+ /**
+ * Prepare catalog attribute values to save
+ *
+ * @param array $attr
+ * @return array
+ */
+ protected function _prepareValues($attr)
+ {
+ $data = parent::_prepareValues($attr);
+ return array_merge($data, [
+ 'frontend_input_renderer' => $this->_getValue($attr, 'input_renderer'),
+ 'is_global' => $this->_getValue(
+ $attr,
+ 'global',
+ Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
+ ),
+ 'is_visible' => $this->_getValue($attr, 'visible', 1),
+ 'is_searchable' => $this->_getValue($attr, 'searchable', 0),
+ 'is_filterable' => $this->_getValue($attr, 'filterable', 0),
+ 'is_comparable' => $this->_getValue($attr, 'comparable', 0),
+ 'is_visible_on_front' => $this->_getValue($attr, 'visible_on_front', 0),
+ 'is_wysiwyg_enabled' => $this->_getValue($attr, 'wysiwyg_enabled', 0),
+ 'is_html_allowed_on_front' => $this->_getValue($attr, 'is_html_allowed_on_front', 0),
+ 'is_visible_in_advanced_search' => $this->_getValue($attr, 'visible_in_advanced_search', 0),
+ 'is_filterable_in_search' => $this->_getValue($attr, 'filterable_in_search', 0),
+ 'used_in_product_listing' => $this->_getValue($attr, 'used_in_product_listing', 0),
+ 'used_for_sort_by' => $this->_getValue($attr, 'used_for_sort_by', 0),
+ 'apply_to' => $this->_getValue($attr, 'apply_to'),
+ 'position' => $this->_getValue($attr, 'position', 0),
+ 'is_configurable' => $this->_getValue($attr, 'is_configurable', 1),
+ 'is_used_for_promo_rules' => $this->_getValue($attr, 'used_for_promo_rules', 0),
+ ]);
+ }
+
/**
* Returns category entity row by category id
*
@@ -906,29 +930,4 @@ protected function _getCategoryPath($category, $path = [])
return $path;
}
-
- /**
- * Creates level values for categories and saves them
- *
- * @deprecated since 1.5.0.0
- * @return $this
- */
- public function rebuildCategoryLevels()
- {
- $adapter = $this->getConnection();
- $select = $adapter->select()
- ->from($this->getTable('catalog/category'));
-
- $categories = $adapter->fetchAll($select);
-
- foreach ($categories as $category) {
- $level = count(explode('/', $category['path'])) - 1;
- $adapter->update(
- $this->getTable('catalog/category'),
- ['level' => $level],
- ['entity_id = ?' => $category['entity_id']],
- );
- }
- return $this;
- }
}
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Url.php b/app/code/core/Mage/Catalog/Model/Resource/Url.php
index a8edc75995f..93d8cab81d5 100644
--- a/app/code/core/Mage/Catalog/Model/Resource/Url.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Url.php
@@ -57,15 +57,6 @@ class Mage_Catalog_Model_Resource_Url extends Mage_Core_Model_Resource_Db_Abstra
*/
protected $_rootChildrenIds = [];
- /**
- * Load core Url rewrite model
- *
- */
- protected function _construct()
- {
- $this->_init('core/url_rewrite', 'url_rewrite_id');
- }
-
/**
* Retrieve stores array or store model
*
@@ -403,87 +394,6 @@ public function saveCategoryAttribute(Varien_Object $category, $attributeCode)
return $this;
}
- /**
- * Retrieve category attributes
- *
- * @param string $attributeCode
- * @param int|array $categoryIds
- * @param int $storeId
- * @return array
- */
- protected function _getCategoryAttribute($attributeCode, $categoryIds, $storeId)
- {
- $adapter = $this->_getWriteAdapter();
- if (!isset($this->_categoryAttributes[$attributeCode])) {
- $attribute = $this->getCategoryModel()->getResource()->getAttribute($attributeCode);
-
- $this->_categoryAttributes[$attributeCode] = [
- 'entity_type_id' => $attribute->getEntityTypeId(),
- 'attribute_id' => $attribute->getId(),
- 'table' => $attribute->getBackend()->getTable(),
- 'is_global' => $attribute->getIsGlobal(),
- 'is_static' => $attribute->isStatic(),
- ];
- unset($attribute);
- }
-
- if (!is_array($categoryIds)) {
- $categoryIds = [$categoryIds];
- }
-
- $attributeTable = $this->_categoryAttributes[$attributeCode]['table'];
- $select = $adapter->select();
- $bind = [];
- if ($this->_categoryAttributes[$attributeCode]['is_static']) {
- $select
- ->from(
- $this->getTable('catalog/category'),
- ['value' => $attributeCode, 'entity_id' => 'entity_id'],
- )
- ->where('entity_id IN(?)', $categoryIds);
- } elseif ($this->_categoryAttributes[$attributeCode]['is_global'] || $storeId == 0) {
- $select
- ->from($attributeTable, ['entity_id', 'value'])
- ->where('attribute_id = :attribute_id')
- ->where('store_id = ?', 0)
- ->where('entity_id IN(?)', $categoryIds);
- $bind['attribute_id'] = $this->_categoryAttributes[$attributeCode]['attribute_id'];
- } else {
- $valueExpr = $adapter->getCheckSql('t2.value_id > 0', 't2.value', 't1.value');
- $select
- ->from(
- ['t1' => $attributeTable],
- ['entity_id', 'value' => $valueExpr],
- )
- ->joinLeft(
- ['t2' => $attributeTable],
- 't1.entity_id = t2.entity_id AND t1.attribute_id = t2.attribute_id AND t2.store_id = :store_id',
- [],
- )
- ->where('t1.store_id = ?', 0)
- ->where('t1.attribute_id = :attribute_id')
- ->where('t1.entity_id IN(?)', $categoryIds);
-
- $bind['attribute_id'] = $this->_categoryAttributes[$attributeCode]['attribute_id'];
- $bind['store_id'] = $storeId;
- }
-
- $rowSet = $adapter->fetchAll($select, $bind);
-
- $attributes = [];
- foreach ($rowSet as $row) {
- $attributes[$row['entity_id']] = $row['value'];
- }
- unset($rowSet);
- foreach ($categoryIds as $categoryId) {
- if (!isset($attributes[$categoryId])) {
- $attributes[$categoryId] = null;
- }
- }
-
- return $attributes;
- }
-
/**
* Save product attribute
*
@@ -625,153 +535,6 @@ public function _getProductAttribute($attributeCode, $productIds, $storeId)
return $attributes;
}
- /**
- * Prepare category parentId
- *
- * @return $this
- */
- protected function _prepareCategoryParentId(Varien_Object $category)
- {
- if ($category->getPath() != $category->getId()) {
- $split = explode('/', $category->getPath());
- $category->setParentId($split[(count($split) - 2)]);
- } else {
- $category->setParentId(0);
- }
- return $this;
- }
-
- /**
- * Prepare stores root categories
- *
- * @param Mage_Core_Model_Store[] $stores
- * @return Mage_Core_Model_Store[]
- */
- protected function _prepareStoreRootCategories($stores)
- {
- $rootCategoryIds = [];
- foreach ($stores as $store) {
- $rootCategoryId = $store->getRootCategoryId();
- $rootCategoryIds[$rootCategoryId] = $rootCategoryId;
- }
- if ($rootCategoryIds) {
- $categories = $this->_getCategories($rootCategoryIds);
- }
- foreach ($stores as $store) {
- $rootCategoryId = $store->getRootCategoryId();
- if (isset($categories[$rootCategoryId])) {
- $store->setRootCategoryPath($categories[$rootCategoryId]->getPath());
- $store->setRootCategory($categories[$rootCategoryId]);
- } else {
- unset($stores[$store->getId()]);
- }
- }
- return $stores;
- }
-
- /**
- * Retrieve categories objects
- * Either $categoryIds or $path (with ending slash) must be specified
- *
- * @param int|array|null $categoryIds
- * @param int $storeId
- * @param string $path
- * @return array
- */
- protected function _getCategories($categoryIds, $storeId = null, $path = null)
- {
- $isActiveAttribute = Mage::getSingleton('eav/config')
- ->getAttribute(Mage_Catalog_Model_Category::ENTITY, 'is_active');
- $categories = [];
- $adapter = $this->_getReadAdapter();
-
- if (!is_array($categoryIds)) {
- $categoryIds = [$categoryIds];
- }
- $isActiveExpr = $adapter->getCheckSql('c.value_id > 0', 'c.value', 'd.value');
- $select = $adapter->select()
- ->from(['main_table' => $this->getTable('catalog/category')], [
- 'main_table.entity_id',
- 'main_table.parent_id',
- 'main_table.level',
- 'is_active' => $isActiveExpr,
- 'main_table.path']);
-
- // Prepare variables for checking whether categories belong to store
- if ($path === null) {
- $select->where('main_table.entity_id IN(?)', $categoryIds);
- } else {
- // Ensure that path ends with '/', otherwise we can get wrong results - e.g. $path = '1/2' will get '1/20'
- if (substr($path, -1) !== '/') {
- $path .= '/';
- }
-
- $select
- ->where('main_table.path LIKE ?', $path . '%')
- ->order('main_table.path');
- }
- $table = $this->getTable(['catalog/category', 'int']);
- $select->joinLeft(
- ['d' => $table],
- 'd.attribute_id = :attribute_id AND d.store_id = 0 AND d.entity_id = main_table.entity_id',
- [],
- )
- ->joinLeft(
- ['c' => $table],
- 'c.attribute_id = :attribute_id AND c.store_id = :store_id AND c.entity_id = main_table.entity_id',
- [],
- );
-
- if ($storeId !== null) {
- $rootCategoryPath = $this->getStores($storeId)->getRootCategoryPath();
- $rootCategoryPathLength = strlen($rootCategoryPath);
- }
- $bind = [
- 'attribute_id' => (int) $isActiveAttribute->getId(),
- 'store_id' => (int) $storeId,
- ];
-
- $rowSet = $adapter->fetchAll($select, $bind);
- foreach ($rowSet as $row) {
- if ($storeId !== null) {
- // Check the category to be either store's root or its descendant
- // First - check that category's start is the same as root category
- if (substr($row['path'], 0, $rootCategoryPathLength) != $rootCategoryPath) {
- continue;
- }
- // Second - check non-root category - that it's really a descendant, not a simple string match
- if ((strlen($row['path']) > $rootCategoryPathLength)
- && ($row['path'][$rootCategoryPathLength] !== '/')
- ) {
- continue;
- }
- }
-
- $category = new Varien_Object($row);
- $category->setIdFieldName('entity_id');
- $category->setStoreId($storeId);
- $this->_prepareCategoryParentId($category);
-
- $categories[$category->getId()] = $category;
- }
- unset($rowSet);
-
- if ($storeId !== null && $categories) {
- foreach (['name', 'url_key', 'url_path'] as $attributeCode) {
- $attributes = $this->_getCategoryAttribute(
- $attributeCode,
- array_keys($categories),
- $category->getStoreId(),
- );
- foreach ($attributes as $categoryId => $attributeValue) {
- $categories[$categoryId]->setData($attributeCode, $attributeValue);
- }
- }
- }
-
- return $categories;
- }
-
/**
* Retrieve category data object
*
@@ -917,89 +680,13 @@ public function getProductIdsByCategory($category)
}
/**
- * Retrieve Product data objects
+ * Retrieve Product data object
*
- * @param int|array|null $productIds
+ * @param int $productId
* @param int $storeId
- * @param int $entityId
- * @param int $lastEntityId
- * @return array
+ * @return Varien_Object|false
*/
- protected function _getProducts($productIds, $storeId, $entityId, &$lastEntityId)
- {
- $products = [];
- $websiteId = Mage::app()->getStore($storeId)->getWebsiteId();
- $adapter = $this->_getReadAdapter();
- if ($productIds !== null) {
- if (!is_array($productIds)) {
- $productIds = [$productIds];
- }
- }
- $bind = [
- 'website_id' => (int) $websiteId,
- 'entity_id' => (int) $entityId,
- ];
- $select = $adapter->select()
- ->useStraightJoin(true)
- ->from(['e' => $this->getTable('catalog/product')], ['entity_id'])
- ->join(
- ['w' => $this->getTable('catalog/product_website')],
- 'e.entity_id = w.product_id AND w.website_id = :website_id',
- [],
- )
- ->where('e.entity_id > :entity_id')
- ->order('e.entity_id')
- ->limit($this->_productLimit);
- if ($productIds !== null) {
- $select->where('e.entity_id IN(?)', $productIds);
- }
-
- $rowSet = $adapter->fetchAll($select, $bind);
- foreach ($rowSet as $row) {
- $product = new Varien_Object($row);
- $product->setIdFieldName('entity_id');
- $product->setCategoryIds([]);
- $product->setStoreId($storeId);
- $products[$product->getId()] = $product;
- $lastEntityId = $product->getId();
- }
-
- unset($rowSet);
-
- if ($products) {
- $select = $adapter->select()
- ->from(
- $this->getTable('catalog/category_product'),
- ['product_id', 'category_id'],
- )
- ->where('product_id IN(?)', array_keys($products));
- $categories = $adapter->fetchAll($select);
- foreach ($categories as $category) {
- $productId = $category['product_id'];
- $categoryIds = $products[$productId]->getCategoryIds();
- $categoryIds[] = $category['category_id'];
- $products[$productId]->setCategoryIds($categoryIds);
- }
-
- foreach (['name', 'url_key', 'url_path'] as $attributeCode) {
- $attributes = $this->_getProductAttribute($attributeCode, array_keys($products), $storeId);
- foreach ($attributes as $productId => $attributeValue) {
- $products[$productId]->setData($attributeCode, $attributeValue);
- }
- }
- }
-
- return $products;
- }
-
- /**
- * Retrieve Product data object
- *
- * @param int $productId
- * @param int $storeId
- * @return Varien_Object|false
- */
- public function getProduct($productId, $storeId)
+ public function getProduct($productId, $storeId)
{
$entityId = 0;
$products = $this->_getProducts($productId, $storeId, 0, $entityId);
@@ -1353,4 +1040,317 @@ public function deleteRewriteRecord($requestPath, $storeId, $rp = false)
}
$this->_getWriteAdapter()->delete($this->getMainTable(), $conditions);
}
+
+ /**
+ * Load core Url rewrite model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('core/url_rewrite', 'url_rewrite_id');
+ }
+
+ /**
+ * Retrieve category attributes
+ *
+ * @param string $attributeCode
+ * @param int|array $categoryIds
+ * @param int $storeId
+ * @return array
+ */
+ protected function _getCategoryAttribute($attributeCode, $categoryIds, $storeId)
+ {
+ $adapter = $this->_getWriteAdapter();
+ if (!isset($this->_categoryAttributes[$attributeCode])) {
+ $attribute = $this->getCategoryModel()->getResource()->getAttribute($attributeCode);
+
+ $this->_categoryAttributes[$attributeCode] = [
+ 'entity_type_id' => $attribute->getEntityTypeId(),
+ 'attribute_id' => $attribute->getId(),
+ 'table' => $attribute->getBackend()->getTable(),
+ 'is_global' => $attribute->getIsGlobal(),
+ 'is_static' => $attribute->isStatic(),
+ ];
+ unset($attribute);
+ }
+
+ if (!is_array($categoryIds)) {
+ $categoryIds = [$categoryIds];
+ }
+
+ $attributeTable = $this->_categoryAttributes[$attributeCode]['table'];
+ $select = $adapter->select();
+ $bind = [];
+ if ($this->_categoryAttributes[$attributeCode]['is_static']) {
+ $select
+ ->from(
+ $this->getTable('catalog/category'),
+ ['value' => $attributeCode, 'entity_id' => 'entity_id'],
+ )
+ ->where('entity_id IN(?)', $categoryIds);
+ } elseif ($this->_categoryAttributes[$attributeCode]['is_global'] || $storeId == 0) {
+ $select
+ ->from($attributeTable, ['entity_id', 'value'])
+ ->where('attribute_id = :attribute_id')
+ ->where('store_id = ?', 0)
+ ->where('entity_id IN(?)', $categoryIds);
+ $bind['attribute_id'] = $this->_categoryAttributes[$attributeCode]['attribute_id'];
+ } else {
+ $valueExpr = $adapter->getCheckSql('t2.value_id > 0', 't2.value', 't1.value');
+ $select
+ ->from(
+ ['t1' => $attributeTable],
+ ['entity_id', 'value' => $valueExpr],
+ )
+ ->joinLeft(
+ ['t2' => $attributeTable],
+ 't1.entity_id = t2.entity_id AND t1.attribute_id = t2.attribute_id AND t2.store_id = :store_id',
+ [],
+ )
+ ->where('t1.store_id = ?', 0)
+ ->where('t1.attribute_id = :attribute_id')
+ ->where('t1.entity_id IN(?)', $categoryIds);
+
+ $bind['attribute_id'] = $this->_categoryAttributes[$attributeCode]['attribute_id'];
+ $bind['store_id'] = $storeId;
+ }
+
+ $rowSet = $adapter->fetchAll($select, $bind);
+
+ $attributes = [];
+ foreach ($rowSet as $row) {
+ $attributes[$row['entity_id']] = $row['value'];
+ }
+ unset($rowSet);
+ foreach ($categoryIds as $categoryId) {
+ if (!isset($attributes[$categoryId])) {
+ $attributes[$categoryId] = null;
+ }
+ }
+
+ return $attributes;
+ }
+
+ /**
+ * Prepare category parentId
+ *
+ * @return $this
+ */
+ protected function _prepareCategoryParentId(Varien_Object $category)
+ {
+ if ($category->getPath() != $category->getId()) {
+ $split = explode('/', $category->getPath());
+ $category->setParentId($split[(count($split) - 2)]);
+ } else {
+ $category->setParentId(0);
+ }
+ return $this;
+ }
+
+ /**
+ * Prepare stores root categories
+ *
+ * @param Mage_Core_Model_Store[] $stores
+ * @return Mage_Core_Model_Store[]
+ */
+ protected function _prepareStoreRootCategories($stores)
+ {
+ $rootCategoryIds = [];
+ foreach ($stores as $store) {
+ $rootCategoryId = $store->getRootCategoryId();
+ $rootCategoryIds[$rootCategoryId] = $rootCategoryId;
+ }
+ if ($rootCategoryIds) {
+ $categories = $this->_getCategories($rootCategoryIds);
+ }
+ foreach ($stores as $store) {
+ $rootCategoryId = $store->getRootCategoryId();
+ if (isset($categories[$rootCategoryId])) {
+ $store->setRootCategoryPath($categories[$rootCategoryId]->getPath());
+ $store->setRootCategory($categories[$rootCategoryId]);
+ } else {
+ unset($stores[$store->getId()]);
+ }
+ }
+ return $stores;
+ }
+
+ /**
+ * Retrieve categories objects
+ * Either $categoryIds or $path (with ending slash) must be specified
+ *
+ * @param int|array|null $categoryIds
+ * @param int $storeId
+ * @param string $path
+ * @return array
+ */
+ protected function _getCategories($categoryIds, $storeId = null, $path = null)
+ {
+ $isActiveAttribute = Mage::getSingleton('eav/config')
+ ->getAttribute(Mage_Catalog_Model_Category::ENTITY, 'is_active');
+ $categories = [];
+ $adapter = $this->_getReadAdapter();
+
+ if (!is_array($categoryIds)) {
+ $categoryIds = [$categoryIds];
+ }
+ $isActiveExpr = $adapter->getCheckSql('c.value_id > 0', 'c.value', 'd.value');
+ $select = $adapter->select()
+ ->from(['main_table' => $this->getTable('catalog/category')], [
+ 'main_table.entity_id',
+ 'main_table.parent_id',
+ 'main_table.level',
+ 'is_active' => $isActiveExpr,
+ 'main_table.path']);
+
+ // Prepare variables for checking whether categories belong to store
+ if ($path === null) {
+ $select->where('main_table.entity_id IN(?)', $categoryIds);
+ } else {
+ // Ensure that path ends with '/', otherwise we can get wrong results - e.g. $path = '1/2' will get '1/20'
+ if (substr($path, -1) !== '/') {
+ $path .= '/';
+ }
+
+ $select
+ ->where('main_table.path LIKE ?', $path . '%')
+ ->order('main_table.path');
+ }
+ $table = $this->getTable(['catalog/category', 'int']);
+ $select->joinLeft(
+ ['d' => $table],
+ 'd.attribute_id = :attribute_id AND d.store_id = 0 AND d.entity_id = main_table.entity_id',
+ [],
+ )
+ ->joinLeft(
+ ['c' => $table],
+ 'c.attribute_id = :attribute_id AND c.store_id = :store_id AND c.entity_id = main_table.entity_id',
+ [],
+ );
+
+ if ($storeId !== null) {
+ $rootCategoryPath = $this->getStores($storeId)->getRootCategoryPath();
+ $rootCategoryPathLength = strlen($rootCategoryPath);
+ }
+ $bind = [
+ 'attribute_id' => (int) $isActiveAttribute->getId(),
+ 'store_id' => (int) $storeId,
+ ];
+
+ $rowSet = $adapter->fetchAll($select, $bind);
+ foreach ($rowSet as $row) {
+ if ($storeId !== null) {
+ // Check the category to be either store's root or its descendant
+ // First - check that category's start is the same as root category
+ if (substr($row['path'], 0, $rootCategoryPathLength) != $rootCategoryPath) {
+ continue;
+ }
+ // Second - check non-root category - that it's really a descendant, not a simple string match
+ if ((strlen($row['path']) > $rootCategoryPathLength)
+ && ($row['path'][$rootCategoryPathLength] !== '/')
+ ) {
+ continue;
+ }
+ }
+
+ $category = new Varien_Object($row);
+ $category->setIdFieldName('entity_id');
+ $category->setStoreId($storeId);
+ $this->_prepareCategoryParentId($category);
+
+ $categories[$category->getId()] = $category;
+ }
+ unset($rowSet);
+
+ if ($storeId !== null && $categories) {
+ foreach (['name', 'url_key', 'url_path'] as $attributeCode) {
+ $attributes = $this->_getCategoryAttribute(
+ $attributeCode,
+ array_keys($categories),
+ $category->getStoreId(),
+ );
+ foreach ($attributes as $categoryId => $attributeValue) {
+ $categories[$categoryId]->setData($attributeCode, $attributeValue);
+ }
+ }
+ }
+
+ return $categories;
+ }
+
+ /**
+ * Retrieve Product data objects
+ *
+ * @param int|array|null $productIds
+ * @param int $storeId
+ * @param int $entityId
+ * @param int $lastEntityId
+ * @return array
+ */
+ protected function _getProducts($productIds, $storeId, $entityId, &$lastEntityId)
+ {
+ $products = [];
+ $websiteId = Mage::app()->getStore($storeId)->getWebsiteId();
+ $adapter = $this->_getReadAdapter();
+ if ($productIds !== null) {
+ if (!is_array($productIds)) {
+ $productIds = [$productIds];
+ }
+ }
+ $bind = [
+ 'website_id' => (int) $websiteId,
+ 'entity_id' => (int) $entityId,
+ ];
+ $select = $adapter->select()
+ ->useStraightJoin(true)
+ ->from(['e' => $this->getTable('catalog/product')], ['entity_id'])
+ ->join(
+ ['w' => $this->getTable('catalog/product_website')],
+ 'e.entity_id = w.product_id AND w.website_id = :website_id',
+ [],
+ )
+ ->where('e.entity_id > :entity_id')
+ ->order('e.entity_id')
+ ->limit($this->_productLimit);
+ if ($productIds !== null) {
+ $select->where('e.entity_id IN(?)', $productIds);
+ }
+
+ $rowSet = $adapter->fetchAll($select, $bind);
+ foreach ($rowSet as $row) {
+ $product = new Varien_Object($row);
+ $product->setIdFieldName('entity_id');
+ $product->setCategoryIds([]);
+ $product->setStoreId($storeId);
+ $products[$product->getId()] = $product;
+ $lastEntityId = $product->getId();
+ }
+
+ unset($rowSet);
+
+ if ($products) {
+ $select = $adapter->select()
+ ->from(
+ $this->getTable('catalog/category_product'),
+ ['product_id', 'category_id'],
+ )
+ ->where('product_id IN(?)', array_keys($products));
+ $categories = $adapter->fetchAll($select);
+ foreach ($categories as $category) {
+ $productId = $category['product_id'];
+ $categoryIds = $products[$productId]->getCategoryIds();
+ $categoryIds[] = $category['category_id'];
+ $products[$productId]->setCategoryIds($categoryIds);
+ }
+
+ foreach (['name', 'url_key', 'url_path'] as $attributeCode) {
+ $attributes = $this->_getProductAttribute($attributeCode, array_keys($products), $storeId);
+ foreach ($attributes as $productId => $attributeValue) {
+ $products[$productId]->setData($attributeCode, $attributeValue);
+ }
+ }
+ }
+
+ return $products;
+ }
}
diff --git a/app/code/core/Mage/Catalog/Model/Url.php b/app/code/core/Mage/Catalog/Model/Url.php
index de75e84540c..438c88d7e75 100644
--- a/app/code/core/Mage/Catalog/Model/Url.php
+++ b/app/code/core/Mage/Catalog/Model/Url.php
@@ -158,38 +158,6 @@ public function getUrlRewrite()
return $this->_urlRewrite;
}
- /**
- * Adds url_path property for non-root category - to ensure that url path is not empty.
- *
- * Sometimes attribute 'url_path' can be empty, because url_path hasn't been generated yet,
- * in this case category is loaded with empty url_path and we should generate it manually.
- *
- * @param Varien_Object|Mage_Catalog_Model_Category $category
- */
- protected function _addCategoryUrlPath($category)
- {
- if (!($category instanceof Varien_Object) || $category->getUrlPath()) {
- return;
- }
-
- // This routine is not intended to be used with root categories,
- // but handle 'em gracefully - ensure them to have empty path.
- if ($category->getLevel() <= 1) {
- $category->setUrlPath('');
- return;
- }
-
- if (self::$_categoryForUrlPath === null) {
- self::$_categoryForUrlPath = Mage::getModel('catalog/category');
- }
-
- // Generate url_path
- $urlPath = self::$_categoryForUrlPath
- ->setData($category->getData())
- ->getUrlPath();
- $category->setUrlPath($urlPath);
- }
-
/**
* Retrieve stores array or store model
*
@@ -305,167 +273,6 @@ public function refreshRewrites($storeId = null)
return $this;
}
- /**
- * Refresh category rewrite
- *
- * @param string $parentPath
- * @param bool $refreshProducts
- * @return $this
- */
- protected function _refreshCategoryRewrites(Varien_Object $category, $parentPath = null, $refreshProducts = true)
- {
- if ($category->getId() != $this->getStores($category->getStoreId())->getRootCategoryId()) {
- $locale = Mage::getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $category->getStoreId());
- $urlKey = $category->getUrlKey() == '' ? $category->getName() : $category->getUrlKey();
- $urlKey = $this->getCategoryModel()->setLocale($locale)->formatUrlKey($urlKey);
-
- $idPath = $this->generatePath('id', null, $category);
- $targetPath = $this->generatePath('target', null, $category);
- $requestPath = $this->getCategoryRequestPath($category, $parentPath);
-
- $rewriteData = [
- 'store_id' => $category->getStoreId(),
- 'category_id' => $category->getId(),
- 'product_id' => null,
- 'id_path' => $idPath,
- 'request_path' => $requestPath,
- 'target_path' => $targetPath,
- 'is_system' => 1,
- ];
-
- $this->getResource()->saveRewrite($rewriteData, $this->_rewrite);
-
- if ($this->getShouldSaveRewritesHistory($category->getStoreId())) {
- $this->_saveRewriteHistory($rewriteData, $this->_rewrite);
- }
-
- if ($category->getUrlKey() != $urlKey) {
- $category->setUrlKey($urlKey);
- $this->getResource()->saveCategoryAttribute($category, 'url_key');
- }
- if ($category->getUrlPath() != $requestPath) {
- $category->setUrlPath($requestPath);
- $this->getResource()->saveCategoryAttribute($category, 'url_path');
- }
- } else {
- if ($category->getUrlPath() != '') {
- $category->setUrlPath('');
- $this->getResource()->saveCategoryAttribute($category, 'url_path');
- }
- }
-
- if ($refreshProducts) {
- $this->_refreshCategoryProductRewrites($category);
- }
-
- foreach ($category->getChilds() as $child) {
- $this->_refreshCategoryRewrites($child, $category->getUrlPath() . '/', $refreshProducts);
- }
-
- return $this;
- }
-
- /**
- * Refresh product rewrite
- *
- * @return $this
- * @throws Mage_Core_Exception
- */
- protected function _refreshProductRewrite(Varien_Object $product, Varien_Object $category)
- {
- if ($category->getId() == $category->getPath()) {
- return $this;
- }
-
- $locale = Mage::getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $product->getStoreId());
- $urlKey = $product->getUrlKey() == '' ? $product->getName() : $product->getUrlKey();
- $urlKey = $this->getProductModel()->setLocale($locale)->formatUrlKey($urlKey);
-
- $idPath = $this->generatePath('id', $product, $category);
- $targetPath = $this->generatePath('target', $product, $category);
- $requestPath = $this->getProductRequestPath($product, $category);
-
- $categoryId = null;
- $updateKeys = true;
- if ($category->getLevel() > 1) {
- $categoryId = $category->getId();
- $updateKeys = false;
- }
-
- $rewriteData = [
- 'store_id' => $category->getStoreId(),
- 'category_id' => $categoryId,
- 'product_id' => $product->getId(),
- 'id_path' => $idPath,
- 'request_path' => $requestPath,
- 'target_path' => $targetPath,
- 'is_system' => 1,
- ];
-
- $this->getResource()->saveRewrite($rewriteData, $this->_rewrite);
-
- if ($this->getShouldSaveRewritesHistory($category->getStoreId())) {
- $this->_saveRewriteHistory($rewriteData, $this->_rewrite);
- }
-
- if ($updateKeys && $product->getUrlKey() != $urlKey) {
- $product->setUrlKey($urlKey);
- $this->getResource()->saveProductAttribute($product, 'url_key');
- }
- if ($updateKeys && $product->getUrlPath() != $requestPath) {
- $product->setUrlPath($requestPath);
- $this->getResource()->saveProductAttribute($product, 'url_path');
- }
-
- return $this;
- }
-
- /**
- * Refresh products for category
- *
- * @return $this
- */
- protected function _refreshCategoryProductRewrites(Varien_Object $category)
- {
- $originalRewrites = $this->_rewrites;
- $process = true;
- $lastEntityId = 0;
- $firstIteration = true;
- while ($process == true) {
- $products = $this->getResource()->getProductsByCategory($category, $lastEntityId);
- if (!$products) {
- if ($firstIteration) {
- $this->getResource()->deleteCategoryProductStoreRewrites(
- $category->getId(),
- [],
- $category->getStoreId(),
- );
- }
- $process = false;
- break;
- }
-
- // Prepare rewrites for generation
- $rootCategory = $this->getStoreRootCategory($category->getStoreId());
- $categoryIds = [$category->getId(), $rootCategory->getId()];
- $this->_rewrites = $this->getResource()->prepareRewrites(
- $category->getStoreId(),
- $categoryIds,
- array_keys($products),
- );
-
- foreach ($products as $product) {
- // Product always must have rewrite in root category
- $this->_refreshProductRewrite($product, $rootCategory);
- $this->_refreshProductRewrite($product, $category);
- }
- $firstIteration = false;
- unset($products);
- }
- $this->_rewrites = $originalRewrites;
- return $this;
- }
-
/**
* Refresh category and children rewrites
* Called when reindexing all rewrites and as a reaction on category change that affects rewrites
@@ -791,25 +598,6 @@ public function getCategoryRequestPath($category, $parentPath)
return $this->getUnusedPathByUrlKey($storeId, $fullPath, $this->generatePath('id', null, $category), $urlKey);
}
- /**
- * Check if current generated request path is one of the old paths
- *
- * @param string $requestPath
- * @param string $idPath
- * @param int $storeId
- * @return bool
- */
- protected function _deleteOldTargetPath($requestPath, $idPath, $storeId)
- {
- $finalOldTargetPath = $this->getResource()->findFinalTargetPath($requestPath, $storeId);
- if ($finalOldTargetPath && $finalOldTargetPath == $idPath) {
- $this->getResource()->deleteRewriteRecord($requestPath, $storeId, true);
- return true;
- }
-
- return false;
- }
-
/**
* Get unique product request path
*
@@ -1012,28 +800,6 @@ public function generateUniqueIdPath()
return str_replace('0.', '', str_replace(' ', '_', microtime()));
}
- /**
- * Create Custom URL Rewrite for old product/category URL after url_key changed
- * It will perform permanent redirect from old URL to new URL
- *
- * @param array $rewriteData New rewrite data
- * @param Varien_Object $rewrite Rewrite model
- * @return $this
- */
- protected function _saveRewriteHistory($rewriteData, $rewrite)
- {
- if ($rewrite instanceof Varien_Object && $rewrite->getId()) {
- $rewriteData['target_path'] = $rewriteData['request_path'];
- $rewriteData['request_path'] = $rewrite->getRequestPath();
- $rewriteData['id_path'] = $this->generateUniqueIdPath();
- $rewriteData['is_system'] = 0;
- $rewriteData['options'] = 'RP'; // Redirect = Permanent
- $this->getResource()->saveRewriteHistory($rewriteData);
- }
-
- return $this;
- }
-
/**
* Format Key for URL
*
@@ -1093,4 +859,238 @@ public function setLocale(?string $locale)
$this->locale = $locale;
return $this;
}
+
+ /**
+ * Adds url_path property for non-root category - to ensure that url path is not empty.
+ *
+ * Sometimes attribute 'url_path' can be empty, because url_path hasn't been generated yet,
+ * in this case category is loaded with empty url_path and we should generate it manually.
+ *
+ * @param Varien_Object|Mage_Catalog_Model_Category $category
+ */
+ protected function _addCategoryUrlPath($category)
+ {
+ if (!($category instanceof Varien_Object) || $category->getUrlPath()) {
+ return;
+ }
+
+ // This routine is not intended to be used with root categories,
+ // but handle 'em gracefully - ensure them to have empty path.
+ if ($category->getLevel() <= 1) {
+ $category->setUrlPath('');
+ return;
+ }
+
+ if (self::$_categoryForUrlPath === null) {
+ self::$_categoryForUrlPath = Mage::getModel('catalog/category');
+ }
+
+ // Generate url_path
+ $urlPath = self::$_categoryForUrlPath
+ ->setData($category->getData())
+ ->getUrlPath();
+ $category->setUrlPath($urlPath);
+ }
+
+ /**
+ * Refresh category rewrite
+ *
+ * @param string $parentPath
+ * @param bool $refreshProducts
+ * @return $this
+ */
+ protected function _refreshCategoryRewrites(Varien_Object $category, $parentPath = null, $refreshProducts = true)
+ {
+ if ($category->getId() != $this->getStores($category->getStoreId())->getRootCategoryId()) {
+ $locale = Mage::getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $category->getStoreId());
+ $urlKey = $category->getUrlKey() == '' ? $category->getName() : $category->getUrlKey();
+ $urlKey = $this->getCategoryModel()->setLocale($locale)->formatUrlKey($urlKey);
+
+ $idPath = $this->generatePath('id', null, $category);
+ $targetPath = $this->generatePath('target', null, $category);
+ $requestPath = $this->getCategoryRequestPath($category, $parentPath);
+
+ $rewriteData = [
+ 'store_id' => $category->getStoreId(),
+ 'category_id' => $category->getId(),
+ 'product_id' => null,
+ 'id_path' => $idPath,
+ 'request_path' => $requestPath,
+ 'target_path' => $targetPath,
+ 'is_system' => 1,
+ ];
+
+ $this->getResource()->saveRewrite($rewriteData, $this->_rewrite);
+
+ if ($this->getShouldSaveRewritesHistory($category->getStoreId())) {
+ $this->_saveRewriteHistory($rewriteData, $this->_rewrite);
+ }
+
+ if ($category->getUrlKey() != $urlKey) {
+ $category->setUrlKey($urlKey);
+ $this->getResource()->saveCategoryAttribute($category, 'url_key');
+ }
+ if ($category->getUrlPath() != $requestPath) {
+ $category->setUrlPath($requestPath);
+ $this->getResource()->saveCategoryAttribute($category, 'url_path');
+ }
+ } else {
+ if ($category->getUrlPath() != '') {
+ $category->setUrlPath('');
+ $this->getResource()->saveCategoryAttribute($category, 'url_path');
+ }
+ }
+
+ if ($refreshProducts) {
+ $this->_refreshCategoryProductRewrites($category);
+ }
+
+ foreach ($category->getChilds() as $child) {
+ $this->_refreshCategoryRewrites($child, $category->getUrlPath() . '/', $refreshProducts);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Refresh product rewrite
+ *
+ * @return $this
+ * @throws Mage_Core_Exception
+ */
+ protected function _refreshProductRewrite(Varien_Object $product, Varien_Object $category)
+ {
+ if ($category->getId() == $category->getPath()) {
+ return $this;
+ }
+
+ $locale = Mage::getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $product->getStoreId());
+ $urlKey = $product->getUrlKey() == '' ? $product->getName() : $product->getUrlKey();
+ $urlKey = $this->getProductModel()->setLocale($locale)->formatUrlKey($urlKey);
+
+ $idPath = $this->generatePath('id', $product, $category);
+ $targetPath = $this->generatePath('target', $product, $category);
+ $requestPath = $this->getProductRequestPath($product, $category);
+
+ $categoryId = null;
+ $updateKeys = true;
+ if ($category->getLevel() > 1) {
+ $categoryId = $category->getId();
+ $updateKeys = false;
+ }
+
+ $rewriteData = [
+ 'store_id' => $category->getStoreId(),
+ 'category_id' => $categoryId,
+ 'product_id' => $product->getId(),
+ 'id_path' => $idPath,
+ 'request_path' => $requestPath,
+ 'target_path' => $targetPath,
+ 'is_system' => 1,
+ ];
+
+ $this->getResource()->saveRewrite($rewriteData, $this->_rewrite);
+
+ if ($this->getShouldSaveRewritesHistory($category->getStoreId())) {
+ $this->_saveRewriteHistory($rewriteData, $this->_rewrite);
+ }
+
+ if ($updateKeys && $product->getUrlKey() != $urlKey) {
+ $product->setUrlKey($urlKey);
+ $this->getResource()->saveProductAttribute($product, 'url_key');
+ }
+ if ($updateKeys && $product->getUrlPath() != $requestPath) {
+ $product->setUrlPath($requestPath);
+ $this->getResource()->saveProductAttribute($product, 'url_path');
+ }
+
+ return $this;
+ }
+
+ /**
+ * Refresh products for category
+ *
+ * @return $this
+ */
+ protected function _refreshCategoryProductRewrites(Varien_Object $category)
+ {
+ $originalRewrites = $this->_rewrites;
+ $process = true;
+ $lastEntityId = 0;
+ $firstIteration = true;
+ while ($process == true) {
+ $products = $this->getResource()->getProductsByCategory($category, $lastEntityId);
+ if (!$products) {
+ if ($firstIteration) {
+ $this->getResource()->deleteCategoryProductStoreRewrites(
+ $category->getId(),
+ [],
+ $category->getStoreId(),
+ );
+ }
+ $process = false;
+ break;
+ }
+
+ // Prepare rewrites for generation
+ $rootCategory = $this->getStoreRootCategory($category->getStoreId());
+ $categoryIds = [$category->getId(), $rootCategory->getId()];
+ $this->_rewrites = $this->getResource()->prepareRewrites(
+ $category->getStoreId(),
+ $categoryIds,
+ array_keys($products),
+ );
+
+ foreach ($products as $product) {
+ // Product always must have rewrite in root category
+ $this->_refreshProductRewrite($product, $rootCategory);
+ $this->_refreshProductRewrite($product, $category);
+ }
+ $firstIteration = false;
+ unset($products);
+ }
+ $this->_rewrites = $originalRewrites;
+ return $this;
+ }
+
+ /**
+ * Check if current generated request path is one of the old paths
+ *
+ * @param string $requestPath
+ * @param string $idPath
+ * @param int $storeId
+ * @return bool
+ */
+ protected function _deleteOldTargetPath($requestPath, $idPath, $storeId)
+ {
+ $finalOldTargetPath = $this->getResource()->findFinalTargetPath($requestPath, $storeId);
+ if ($finalOldTargetPath && $finalOldTargetPath == $idPath) {
+ $this->getResource()->deleteRewriteRecord($requestPath, $storeId, true);
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Create Custom URL Rewrite for old product/category URL after url_key changed
+ * It will perform permanent redirect from old URL to new URL
+ *
+ * @param array $rewriteData New rewrite data
+ * @param Varien_Object $rewrite Rewrite model
+ * @return $this
+ */
+ protected function _saveRewriteHistory($rewriteData, $rewrite)
+ {
+ if ($rewrite instanceof Varien_Object && $rewrite->getId()) {
+ $rewriteData['target_path'] = $rewriteData['request_path'];
+ $rewriteData['request_path'] = $rewrite->getRequestPath();
+ $rewriteData['id_path'] = $this->generateUniqueIdPath();
+ $rewriteData['is_system'] = 0;
+ $rewriteData['options'] = 'RP'; // Redirect = Permanent
+ $this->getResource()->saveRewriteHistory($rewriteData);
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Catalog/controllers/CategoryController.php b/app/code/core/Mage/Catalog/controllers/CategoryController.php
index f0352af3316..efc427052ef 100644
--- a/app/code/core/Mage/Catalog/controllers/CategoryController.php
+++ b/app/code/core/Mage/Catalog/controllers/CategoryController.php
@@ -22,6 +22,64 @@
*/
class Mage_Catalog_CategoryController extends Mage_Core_Controller_Front_Action
{
+ /**
+ * Category view action
+ * @throws Mage_Core_Exception
+ */
+ public function viewAction()
+ {
+ if ($category = $this->_initCategory()) {
+ $design = Mage::getSingleton('catalog/design');
+ $settings = $design->getDesignSettings($category);
+
+ // apply custom design
+ if ($settings->getCustomDesign()) {
+ $design->applyCustomDesign($settings->getCustomDesign());
+ }
+
+ Mage::getSingleton('catalog/session')->setLastViewedCategoryId($category->getId());
+
+ $update = $this->getLayout()->getUpdate();
+ $update->addHandle('default');
+
+ if (!$category->hasChildren()) {
+ $update->addHandle('catalog_category_layered_nochildren');
+ }
+
+ $this->addActionLayoutHandles();
+ $update->addHandle($category->getLayoutUpdateHandle());
+ $update->addHandle('CATEGORY_' . $category->getId());
+ $this->loadLayoutUpdates();
+
+ // apply custom layout update once layout is loaded
+ if ($layoutUpdates = $settings->getLayoutUpdates()) {
+ if (is_array($layoutUpdates)) {
+ foreach ($layoutUpdates as $layoutUpdate) {
+ $update->addUpdate($layoutUpdate);
+ }
+ }
+ }
+
+ $this->generateLayoutXml()->generateLayoutBlocks();
+ // apply custom layout (page) template once the blocks are generated
+ if ($settings->getPageLayout()) {
+ $this->getLayout()->helper('page/layout')->applyTemplate($settings->getPageLayout());
+ }
+
+ /** @var Mage_Page_Block_Html $root */
+ $root = $this->getLayout()->getBlock('root');
+ if ($root) {
+ $root->addBodyClass('categorypath-' . $category->getUrlPath())
+ ->addBodyClass('category-' . $category->getUrlKey());
+ }
+
+ $this->_initLayoutMessages('catalog/session');
+ $this->_initLayoutMessages('checkout/session');
+ $this->renderLayout();
+ } elseif (!$this->getResponse()->isRedirect()) {
+ $this->_forward('noRoute');
+ }
+ }
/**
* Initialize requested category object
*
@@ -110,63 +168,4 @@ protected function _applyCustomDesignSettings($category, $update)
return $this;
}
-
- /**
- * Category view action
- * @throws Mage_Core_Exception
- */
- public function viewAction()
- {
- if ($category = $this->_initCategory()) {
- $design = Mage::getSingleton('catalog/design');
- $settings = $design->getDesignSettings($category);
-
- // apply custom design
- if ($settings->getCustomDesign()) {
- $design->applyCustomDesign($settings->getCustomDesign());
- }
-
- Mage::getSingleton('catalog/session')->setLastViewedCategoryId($category->getId());
-
- $update = $this->getLayout()->getUpdate();
- $update->addHandle('default');
-
- if (!$category->hasChildren()) {
- $update->addHandle('catalog_category_layered_nochildren');
- }
-
- $this->addActionLayoutHandles();
- $update->addHandle($category->getLayoutUpdateHandle());
- $update->addHandle('CATEGORY_' . $category->getId());
- $this->loadLayoutUpdates();
-
- // apply custom layout update once layout is loaded
- if ($layoutUpdates = $settings->getLayoutUpdates()) {
- if (is_array($layoutUpdates)) {
- foreach ($layoutUpdates as $layoutUpdate) {
- $update->addUpdate($layoutUpdate);
- }
- }
- }
-
- $this->generateLayoutXml()->generateLayoutBlocks();
- // apply custom layout (page) template once the blocks are generated
- if ($settings->getPageLayout()) {
- $this->getLayout()->helper('page/layout')->applyTemplate($settings->getPageLayout());
- }
-
- /** @var Mage_Page_Block_Html $root */
- $root = $this->getLayout()->getBlock('root');
- if ($root) {
- $root->addBodyClass('categorypath-' . $category->getUrlPath())
- ->addBodyClass('category-' . $category->getUrlKey());
- }
-
- $this->_initLayoutMessages('catalog/session');
- $this->_initLayoutMessages('checkout/session');
- $this->renderLayout();
- } elseif (!$this->getResponse()->isRedirect()) {
- $this->_forward('noRoute');
- }
- }
}
diff --git a/app/code/core/Mage/Catalog/controllers/ProductController.php b/app/code/core/Mage/Catalog/controllers/ProductController.php
index 30e0291a975..723972d1527 100644
--- a/app/code/core/Mage/Catalog/controllers/ProductController.php
+++ b/app/code/core/Mage/Catalog/controllers/ProductController.php
@@ -30,76 +30,6 @@ class Mage_Catalog_ProductController extends Mage_Core_Controller_Front_Action
*/
protected $_designProductSettingsApplied = [];
- /**
- * Initialize requested product object
- *
- * @return Mage_Catalog_Model_Product
- */
- protected function _initProduct()
- {
- $categoryId = (int) $this->getRequest()->getParam('category', false);
- $productId = (int) $this->getRequest()->getParam('id');
-
- $params = new Varien_Object();
- $params->setCategoryId($categoryId);
-
- return Mage::helper('catalog/product')->initProduct($productId, $this, $params);
- }
-
- /**
- * Initialize product view layout
- *
- * @param Mage_Catalog_Model_Product $product
- * @return Mage_Catalog_ProductController
- */
- protected function _initProductLayout($product)
- {
- Mage::helper('catalog/product_view')->initProductLayout($product, $this);
- return $this;
- }
-
- /**
- * Recursively apply custom design settings to product if it's container
- * category custom_use_for_products option is set to 1.
- * If not or product shows not in category - applies product's internal settings
- *
- * @deprecated after 1.4.2.0-beta1, functionality moved to Mage_Catalog_Model_Design
- * @param Mage_Catalog_Model_Category|Mage_Catalog_Model_Product $object
- * @param Mage_Core_Model_Layout_Update $update
- */
- protected function _applyCustomDesignSettings($object, $update)
- {
- if ($object instanceof Mage_Catalog_Model_Category) {
- // lookup the proper category recursively
- if ($object->getCustomUseParentSettings()) {
- $parentCategory = $object->getParentCategory();
- if ($parentCategory && $parentCategory->getId() && $parentCategory->getLevel() > 1) {
- $this->_applyCustomDesignSettings($parentCategory, $update);
- }
- return;
- }
-
- // don't apply to the product
- if (!$object->getCustomApplyToProducts()) {
- return;
- }
- }
-
- if ($this->_designProductSettingsApplied) {
- return;
- }
-
- $date = $object->getCustomDesignDate();
- if (array_key_exists('from', $date) && array_key_exists('to', $date)
- && Mage::app()->getLocale()->isStoreDateInInterval(null, $date['from'], $date['to'])
- ) {
- if ($object->getPageLayout()) {
- $this->_designProductSettingsApplied['layout'] = $object->getPageLayout();
- }
- $this->_designProductSettingsApplied['update'] = $object->getCustomLayoutUpdate();
- }
- }
-
/**
* Product view action
*
@@ -169,4 +99,74 @@ public function imageAction()
*/
$this->_forward('noRoute');
}
+
+ /**
+ * Initialize requested product object
+ *
+ * @return Mage_Catalog_Model_Product
+ */
+ protected function _initProduct()
+ {
+ $categoryId = (int) $this->getRequest()->getParam('category', false);
+ $productId = (int) $this->getRequest()->getParam('id');
+
+ $params = new Varien_Object();
+ $params->setCategoryId($categoryId);
+
+ return Mage::helper('catalog/product')->initProduct($productId, $this, $params);
+ }
+
+ /**
+ * Initialize product view layout
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @return Mage_Catalog_ProductController
+ */
+ protected function _initProductLayout($product)
+ {
+ Mage::helper('catalog/product_view')->initProductLayout($product, $this);
+ return $this;
+ }
+
+ /**
+ * Recursively apply custom design settings to product if it's container
+ * category custom_use_for_products option is set to 1.
+ * If not or product shows not in category - applies product's internal settings
+ *
+ * @deprecated after 1.4.2.0-beta1, functionality moved to Mage_Catalog_Model_Design
+ * @param Mage_Catalog_Model_Category|Mage_Catalog_Model_Product $object
+ * @param Mage_Core_Model_Layout_Update $update
+ */
+ protected function _applyCustomDesignSettings($object, $update)
+ {
+ if ($object instanceof Mage_Catalog_Model_Category) {
+ // lookup the proper category recursively
+ if ($object->getCustomUseParentSettings()) {
+ $parentCategory = $object->getParentCategory();
+ if ($parentCategory && $parentCategory->getId() && $parentCategory->getLevel() > 1) {
+ $this->_applyCustomDesignSettings($parentCategory, $update);
+ }
+ return;
+ }
+
+ // don't apply to the product
+ if (!$object->getCustomApplyToProducts()) {
+ return;
+ }
+ }
+
+ if ($this->_designProductSettingsApplied) {
+ return;
+ }
+
+ $date = $object->getCustomDesignDate();
+ if (array_key_exists('from', $date) && array_key_exists('to', $date)
+ && Mage::app()->getLocale()->isStoreDateInInterval(null, $date['from'], $date['to'])
+ ) {
+ if ($object->getPageLayout()) {
+ $this->_designProductSettingsApplied['layout'] = $object->getPageLayout();
+ }
+ $this->_designProductSettingsApplied['update'] = $object->getCustomLayoutUpdate();
+ }
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Aggregation.php b/app/code/core/Mage/CatalogIndex/Model/Aggregation.php
index 2e96301cf16..64456dddeb8 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Aggregation.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Aggregation.php
@@ -35,19 +35,6 @@ class Mage_CatalogIndex_Model_Aggregation extends Mage_Core_Model_Abstract
{
public const CACHE_FLAG_NAME = 'layered_navigation';
- protected function _construct()
- {
- $this->_init('catalogindex/aggregation');
- }
-
- /**
- * @return array|bool
- */
- protected function _isEnabled()
- {
- return Mage::app()->useCache(self::CACHE_FLAG_NAME);
- }
-
/**
* Get aggregated data by data key and store
*
@@ -129,6 +116,19 @@ public function clearProductData($productIds)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/aggregation');
+ }
+
+ /**
+ * @return array|bool
+ */
+ protected function _isEnabled()
+ {
+ return Mage::app()->useCache(self::CACHE_FLAG_NAME);
+ }
+
/**
* Prepare data key
*
diff --git a/app/code/core/Mage/CatalogIndex/Model/Attribute.php b/app/code/core/Mage/CatalogIndex/Model/Attribute.php
index 085620bc2d6..3e13960fee1 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Attribute.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Attribute.php
@@ -32,12 +32,6 @@
*/
class Mage_CatalogIndex_Model_Attribute extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('catalogindex/attribute');
- $this->_getResource()->setStoreId(Mage::app()->getStore()->getId());
- }
-
/**
* @param Mage_Eav_Model_Entity_Attribute $attribute
* @param string $filter
@@ -81,4 +75,9 @@ public function applyFilterToCollection($collection, $attribute, $value)
$this->_getResource()->applyFilterToCollection($collection, $attribute, $value);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/attribute');
+ $this->_getResource()->setStoreId(Mage::app()->getStore()->getId());
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Catalog/Index/Flag.php b/app/code/core/Mage/CatalogIndex/Model/Catalog/Index/Flag.php
index c17a813e29d..034305908f7 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Catalog/Index/Flag.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Catalog/Index/Flag.php
@@ -20,10 +20,9 @@
*/
class Mage_CatalogIndex_Model_Catalog_Index_Flag extends Mage_Core_Model_Flag
{
- protected $_flagCode = 'catalogindex';
-
public const STATE_QUEUED = 1;
public const STATE_RUNNING = 2;
+ protected $_flagCode = 'catalogindex';
/**
* @return Mage_Core_Model_Flag
diff --git a/app/code/core/Mage/CatalogIndex/Model/Data/Abstract.php b/app/code/core/Mage/CatalogIndex/Model/Data/Abstract.php
index 5b02a2c0aa6..31c2a28db9a 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Data/Abstract.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Data/Abstract.php
@@ -27,6 +27,8 @@
*/
class Mage_CatalogIndex_Model_Data_Abstract extends Mage_Core_Model_Abstract
{
+ public const LINK_GET_CHILDREN = 1;
+ public const LINK_GET_PARENTS = 1;
/**
* Product Type instance
*
@@ -52,18 +54,6 @@ class Mage_CatalogIndex_Model_Data_Abstract extends Mage_Core_Model_Abstract
*/
protected $_haveParents = true;
- public const LINK_GET_CHILDREN = 1;
- public const LINK_GET_PARENTS = 1;
-
- /**
- * Initialize abstract resource model
- *
- */
- protected function _construct()
- {
- $this->_init('catalogindex/data_abstract');
- }
-
/**
* Return all children ids
*
@@ -104,37 +94,6 @@ public function getParentProductIds($store, $childIds)
return $this->fetchLinkInformation($store, $this->_getLinkSettings(), self::LINK_GET_PARENTS, $childIds);
}
- /**
- * Returns an array of product children/parents
- *
- * @param Mage_Core_Model_Store $store
- * @param array $settings
- * @param int $type
- * @param int|array $suppliedId
- * @return array
- */
- protected function fetchLinkInformation($store, $settings, $type, $suppliedId)
- {
- switch ($type) {
- case self::LINK_GET_CHILDREN:
- $whereField = $settings['parent_field'];
- $idField = $settings['child_field'];
- break;
-
- case self::LINK_GET_PARENTS:
- $idField = $settings['parent_field'];
- $whereField = $settings['child_field'];
- break;
- }
-
- $additional = [];
- if (isset($settings['additional']) && is_array($settings['additional'])) {
- $additional = $settings['additional'];
- }
-
- return $this->getResource()->fetchLinkInformation($store->getId(), $settings['table'], $idField, $whereField, $suppliedId, $additional);
- }
-
/**
* Fetch final price for product
*
@@ -252,16 +211,6 @@ public function getTypeCode()
Mage::throwException('Define custom data retreiver with getTypeCode function');
}
- /**
- * Get child link table and field settings
- *
- * @return mixed
- */
- protected function _getLinkSettings()
- {
- return false;
- }
-
/**
* Returns if type supports children of the specified type
*
@@ -291,4 +240,54 @@ public function getTypeInstance()
}
return $this->_typeInstance;
}
+
+ /**
+ * Initialize abstract resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalogindex/data_abstract');
+ }
+
+ /**
+ * Returns an array of product children/parents
+ *
+ * @param Mage_Core_Model_Store $store
+ * @param array $settings
+ * @param int $type
+ * @param int|array $suppliedId
+ * @return array
+ */
+ protected function fetchLinkInformation($store, $settings, $type, $suppliedId)
+ {
+ switch ($type) {
+ case self::LINK_GET_CHILDREN:
+ $whereField = $settings['parent_field'];
+ $idField = $settings['child_field'];
+ break;
+
+ case self::LINK_GET_PARENTS:
+ $idField = $settings['parent_field'];
+ $whereField = $settings['child_field'];
+ break;
+ }
+
+ $additional = [];
+ if (isset($settings['additional']) && is_array($settings['additional'])) {
+ $additional = $settings['additional'];
+ }
+
+ return $this->getResource()->fetchLinkInformation($store->getId(), $settings['table'], $idField, $whereField, $suppliedId, $additional);
+ }
+
+ /**
+ * Get child link table and field settings
+ *
+ * @return mixed
+ */
+ protected function _getLinkSettings()
+ {
+ return false;
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Data/Configurable.php b/app/code/core/Mage/CatalogIndex/Model/Data/Configurable.php
index 6fe27869bca..51e122d1b25 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Data/Configurable.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Data/Configurable.php
@@ -40,11 +40,6 @@ class Mage_CatalogIndex_Model_Data_Configurable extends Mage_CatalogIndex_Model_
*/
protected $_haveParents = false;
- protected function _construct()
- {
- $this->_init('catalogindex/data_configurable');
- }
-
/**
* Retrieve product type code
*
@@ -55,6 +50,11 @@ public function getTypeCode()
return Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE;
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/data_configurable');
+ }
+
/**
* Get child link table and field settings
*
diff --git a/app/code/core/Mage/CatalogIndex/Model/Data/Grouped.php b/app/code/core/Mage/CatalogIndex/Model/Data/Grouped.php
index 5686b7919da..222f2a36f4c 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Data/Grouped.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Data/Grouped.php
@@ -29,11 +29,6 @@ class Mage_CatalogIndex_Model_Data_Grouped extends Mage_CatalogIndex_Model_Data_
*/
protected $_haveParents = false;
- protected function _construct()
- {
- $this->_init('catalogindex/data_grouped');
- }
-
/**
* Fetch final price for product
*
@@ -57,6 +52,11 @@ public function getTypeCode()
return Mage_Catalog_Model_Product_Type::TYPE_GROUPED;
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/data_grouped');
+ }
+
/**
* Get child link table and field settings
*
diff --git a/app/code/core/Mage/CatalogIndex/Model/Indexer.php b/app/code/core/Mage/CatalogIndex/Model/Indexer.php
index 4b766abedfc..000e14a9e86 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Indexer.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Indexer.php
@@ -77,96 +77,6 @@ class Mage_CatalogIndex_Model_Indexer extends Mage_Core_Model_Abstract
*/
protected $_productTypePriority = null;
- /**
- * Initialize all indexers and resource model
- *
- */
- protected function _construct()
- {
- $this->_loadIndexers();
- $this->_init('catalogindex/indexer');
- }
-
- /**
- * Create instances of all index types
- *
- * @return $this
- */
- protected function _loadIndexers()
- {
- foreach ($this->_getRegisteredIndexers() as $name => $class) {
- $this->_indexers[$name] = Mage::getSingleton($class);
- }
- return $this;
- }
-
- /**
- * Get all registered in configuration indexers
- *
- * @return array
- */
- protected function _getRegisteredIndexers()
- {
- $result = [];
- $indexerRegistry = Mage::getConfig()->getNode('global/catalogindex/indexer');
-
- foreach ($indexerRegistry->children() as $node) {
- $result[$node->getName()] = (string) $node->class;
- }
- return $result;
- }
-
- /**
- * Get array of attribute codes required for indexing
- * Each indexer type provide his own set of attributes
- *
- * @return array
- */
- protected function _getIndexableAttributeCodes()
- {
- $result = [];
- foreach ($this->_indexers as $indexer) {
- $codes = $indexer->getIndexableAttributeCodes();
-
- if (is_array($codes)) {
- $result = array_merge($result, $codes);
- }
- }
- return $result;
- }
-
- /**
- * Retrieve store collection
- *
- * @return array
- */
- protected function _getStores()
- {
- $stores = $this->getData('_stores');
- if (is_null($stores)) {
- $stores = Mage::app()->getStores();
- $this->setData('_stores', $stores);
- }
- return $stores;
- }
-
- /**
- * Retrieve store collection
- *
- * @return Mage_Core_Model_Resource_Website_Collection
- */
- protected function _getWebsites()
- {
- $websites = $this->getData('_websites');
- if (is_null($websites)) {
- /** @var Mage_Core_Model_Resource_Website_Collection $websites */
- $websites = Mage::getModel('core/website')->getCollection()->load();
-
- $this->setData('_websites', $websites);
- }
- return $websites;
- }
-
/**
* Remove index data for specifuc product
*
@@ -338,69 +248,6 @@ public function plainReindex($products = null, $attributes = null, $stores = nul
return $this;
}
- /**
- * After plain reindex process
- *
- * @param Mage_Core_Model_Store|array|int|Mage_Core_Model_Website $store
- * @param int|array|Mage_Catalog_Model_Product_Condition_Interface|Mage_Catalog_Model_Product $products
- * @return $this
- */
- protected function _afterPlainReindex($store, $products = null)
- {
- Mage::dispatchEvent('catalogindex_plain_reindex_after', [
- 'products' => $products,
- ]);
-
- /**
- * Catalog Product Flat price update
- */
- /** @var Mage_Catalog_Helper_Product_Flat $productFlatHelper */
- $productFlatHelper = Mage::helper('catalog/product_flat');
- if ($productFlatHelper->isAvailable() && $productFlatHelper->isBuilt()) {
- if ($store instanceof Mage_Core_Model_Website) {
- foreach ($store->getStores() as $storeObject) {
- $this->_afterPlainReindex($storeObject->getId(), $products);
- }
- return $this;
- } elseif ($store instanceof Mage_Core_Model_Store) {
- $store = $store->getId();
- } elseif (is_array($store)) { // array of stores
- foreach ($store as $storeObject) {
- $this->_afterPlainReindex($storeObject->getId(), $products);
- }
- return $this;
- }
-
- $this->updateCatalogProductFlat($store, $products);
- }
-
- return $this;
- }
-
- /**
- * Return collection with product and store filters
- *
- * @param Mage_Core_Model_Store $store
- * @param mixed $products
- * @return Mage_Catalog_Model_Resource_Product_Collection
- */
- protected function _getProductCollection($store, $products)
- {
- $collection = Mage::getModel('catalog/product')
- ->getCollection()
- ->setStoreId($store)
- ->addStoreFilter($store);
- if ($products instanceof Mage_Catalog_Model_Product) {
- $collection->addIdFilter($products->getId());
- } elseif (is_array($products) || is_numeric($products)) {
- $collection->addIdFilter($products);
- } elseif ($products instanceof Mage_Catalog_Model_Product_Condition_Interface) {
- $products->applyToCollection($collection);
- }
-
- return $collection;
- }
-
/**
* Walk Product Collection for Relation Parent products
*
@@ -449,67 +296,6 @@ public function _walkCollectionRelation($collection, $store, $attributes = [], $
return $this;
}
- /**
- * Run indexing process for product collection
- *
- * @param Mage_Catalog_Model_Resource_Product_Collection $collection
- * @param mixed $store
- * @param array $attributes
- * @param array $prices
- * @return Mage_CatalogIndex_Model_Indexer
- */
- protected function _walkCollection($collection, $store, $attributes = [], $prices = [])
- {
- $productCount = $collection->getSize();
- if (!$productCount) {
- return $this;
- }
-
- for ($i = 0; $i < $productCount / self::STEP_SIZE; $i++) {
- $this->_getResource()->beginTransaction();
- try {
- $deleteKill = false;
-
- $stepData = $collection->getAllIds(self::STEP_SIZE, $i * self::STEP_SIZE);
-
- /**
- * Reindex EAV attributes if required
- */
- if (count($attributes)) {
- $this->_getResource()->reindexAttributes($stepData, $attributes, $store);
- }
-
- /**
- * Reindex prices if required
- */
- if (count($prices)) {
- $this->_getResource()->reindexPrices($stepData, $prices, $store);
- $this->_getResource()->reindexTiers($stepData, $store);
- $this->_getResource()->reindexMinimalPrices($stepData, $store);
- $this->_getResource()->reindexFinalPrices($stepData, $store);
- }
-
- Mage::getResourceSingleton('catalog/product')->refreshEnabledIndex($store, $stepData);
-
- $kill = Mage::getModel('catalogindex/catalog_index_kill_flag')->loadSelf();
- if ($kill->checkIsThisProcess()) {
- $this->_getResource()->rollBack();
- $deleteKill = true;
- } else {
- $this->_getResource()->commit();
- }
- } catch (Exception $e) {
- $this->_getResource()->rollBack();
- throw $e;
- }
-
- if ($deleteKill && isset($kill)) {
- $kill->delete();
- }
- }
- return $this;
- }
-
/**
* Retrieve Data retriever
*
@@ -536,41 +322,6 @@ public function queueIndexing()
return $this;
}
- /**
- * Get product types list by type priority
- * type priority is important in index process
- * example: before indexing complex (configurable, grouped etc.) products
- * we have to index all simple products
- *
- * @return array
- */
- protected function _getPriorifiedProductTypes()
- {
- if (is_null($this->_productTypePriority)) {
- $this->_productTypePriority = [];
- $config = Mage::getConfig()->getNode('global/catalog/product/type');
-
- foreach ($config->children() as $type) {
- $typeName = $type->getName();
- $typePriority = (string) $type->index_priority;
- $this->_productTypePriority[$typePriority] = $typeName;
- }
- ksort($this->_productTypePriority);
- }
- return $this->_productTypePriority;
- }
-
- /**
- * Retrieve Base to Specified Currency Rate
- *
- * @param string $code
- * @return double
- */
- protected function _getBaseToSpecifiedCurrencyRate($code)
- {
- return Mage::app()->getStore()->getBaseCurrency()->getRate($code);
- }
-
/**
* Build Entity price filter
*
@@ -741,73 +492,322 @@ public function buildEntityFilter($attributes, $values, &$filteredAttributes, $p
}
/**
- * Retrieve SELECT object
+ * Prepare Catalog Product Flat Columns
*
- * @return Varien_Db_Select
+ * @return $this
*/
- protected function _getSelect()
+ public function prepareCatalogProductFlatColumns(Varien_Object $object)
{
- return $this->_getResource()->getReadConnection()->select();
+ $this->_getResource()->prepareCatalogProductFlatColumns($object);
+
+ return $this;
}
/**
- * Add indexable attributes to product collection select
+ * Prepare Catalog Product Flat Indexes
*
- * @deprecated
- * @param Mage_Catalog_Model_Resource_Product_Collection $collection
- * @return Mage_CatalogIndex_Model_Indexer
+ * @return $this
*/
- protected function _addFilterableAttributesToCollection($collection)
+ public function prepareCatalogProductFlatIndexes(Varien_Object $object)
{
- $attributeCodes = $this->_getIndexableAttributeCodes();
- foreach ($attributeCodes as $code) {
- $collection->addAttributeToSelect($code);
- }
+ $this->_getResource()->prepareCatalogProductFlatIndexes($object);
return $this;
}
/**
- * Prepare Catalog Product Flat Columns
+ * Update price process for catalog product flat
*
+ * @param Mage_Core_Model_Store|int $store
+ * @param Mage_Catalog_Model_Product|int|array|null $products
+ * @param string $resourceTable
* @return $this
*/
- public function prepareCatalogProductFlatColumns(Varien_Object $object)
+ public function updateCatalogProductFlat($store, $products = null, $resourceTable = null)
{
- $this->_getResource()->prepareCatalogProductFlatColumns($object);
+ if ($store instanceof Mage_Core_Model_Store) {
+ $store = $store->getId();
+ }
+ if ($products instanceof Mage_Catalog_Model_Product) {
+ $products = $products->getId();
+ }
+ $this->_getResource()->updateCatalogProductFlat($store, $products, $resourceTable);
return $this;
}
/**
- * Prepare Catalog Product Flat Indexes
+ * Initialize all indexers and resource model
*
- * @return $this
*/
- public function prepareCatalogProductFlatIndexes(Varien_Object $object)
+ protected function _construct()
{
- $this->_getResource()->prepareCatalogProductFlatIndexes($object);
+ $this->_loadIndexers();
+ $this->_init('catalogindex/indexer');
+ }
+ /**
+ * Create instances of all index types
+ *
+ * @return $this
+ */
+ protected function _loadIndexers()
+ {
+ foreach ($this->_getRegisteredIndexers() as $name => $class) {
+ $this->_indexers[$name] = Mage::getSingleton($class);
+ }
return $this;
}
/**
- * Update price process for catalog product flat
+ * Get all registered in configuration indexers
*
- * @param Mage_Core_Model_Store|int $store
- * @param Mage_Catalog_Model_Product|int|array|null $products
- * @param string $resourceTable
+ * @return array
+ */
+ protected function _getRegisteredIndexers()
+ {
+ $result = [];
+ $indexerRegistry = Mage::getConfig()->getNode('global/catalogindex/indexer');
+
+ foreach ($indexerRegistry->children() as $node) {
+ $result[$node->getName()] = (string) $node->class;
+ }
+ return $result;
+ }
+
+ /**
+ * Get array of attribute codes required for indexing
+ * Each indexer type provide his own set of attributes
+ *
+ * @return array
+ */
+ protected function _getIndexableAttributeCodes()
+ {
+ $result = [];
+ foreach ($this->_indexers as $indexer) {
+ $codes = $indexer->getIndexableAttributeCodes();
+
+ if (is_array($codes)) {
+ $result = array_merge($result, $codes);
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * Retrieve store collection
+ *
+ * @return array
+ */
+ protected function _getStores()
+ {
+ $stores = $this->getData('_stores');
+ if (is_null($stores)) {
+ $stores = Mage::app()->getStores();
+ $this->setData('_stores', $stores);
+ }
+ return $stores;
+ }
+
+ /**
+ * Retrieve store collection
+ *
+ * @return Mage_Core_Model_Resource_Website_Collection
+ */
+ protected function _getWebsites()
+ {
+ $websites = $this->getData('_websites');
+ if (is_null($websites)) {
+ /** @var Mage_Core_Model_Resource_Website_Collection $websites */
+ $websites = Mage::getModel('core/website')->getCollection()->load();
+
+ $this->setData('_websites', $websites);
+ }
+ return $websites;
+ }
+
+ /**
+ * After plain reindex process
+ *
+ * @param Mage_Core_Model_Store|array|int|Mage_Core_Model_Website $store
+ * @param int|array|Mage_Catalog_Model_Product_Condition_Interface|Mage_Catalog_Model_Product $products
* @return $this
*/
- public function updateCatalogProductFlat($store, $products = null, $resourceTable = null)
+ protected function _afterPlainReindex($store, $products = null)
{
- if ($store instanceof Mage_Core_Model_Store) {
- $store = $store->getId();
+ Mage::dispatchEvent('catalogindex_plain_reindex_after', [
+ 'products' => $products,
+ ]);
+
+ /**
+ * Catalog Product Flat price update
+ */
+ /** @var Mage_Catalog_Helper_Product_Flat $productFlatHelper */
+ $productFlatHelper = Mage::helper('catalog/product_flat');
+ if ($productFlatHelper->isAvailable() && $productFlatHelper->isBuilt()) {
+ if ($store instanceof Mage_Core_Model_Website) {
+ foreach ($store->getStores() as $storeObject) {
+ $this->_afterPlainReindex($storeObject->getId(), $products);
+ }
+ return $this;
+ } elseif ($store instanceof Mage_Core_Model_Store) {
+ $store = $store->getId();
+ } elseif (is_array($store)) { // array of stores
+ foreach ($store as $storeObject) {
+ $this->_afterPlainReindex($storeObject->getId(), $products);
+ }
+ return $this;
+ }
+
+ $this->updateCatalogProductFlat($store, $products);
}
+
+ return $this;
+ }
+
+ /**
+ * Return collection with product and store filters
+ *
+ * @param Mage_Core_Model_Store $store
+ * @param mixed $products
+ * @return Mage_Catalog_Model_Resource_Product_Collection
+ */
+ protected function _getProductCollection($store, $products)
+ {
+ $collection = Mage::getModel('catalog/product')
+ ->getCollection()
+ ->setStoreId($store)
+ ->addStoreFilter($store);
if ($products instanceof Mage_Catalog_Model_Product) {
- $products = $products->getId();
+ $collection->addIdFilter($products->getId());
+ } elseif (is_array($products) || is_numeric($products)) {
+ $collection->addIdFilter($products);
+ } elseif ($products instanceof Mage_Catalog_Model_Product_Condition_Interface) {
+ $products->applyToCollection($collection);
+ }
+
+ return $collection;
+ }
+
+ /**
+ * Run indexing process for product collection
+ *
+ * @param Mage_Catalog_Model_Resource_Product_Collection $collection
+ * @param mixed $store
+ * @param array $attributes
+ * @param array $prices
+ * @return Mage_CatalogIndex_Model_Indexer
+ */
+ protected function _walkCollection($collection, $store, $attributes = [], $prices = [])
+ {
+ $productCount = $collection->getSize();
+ if (!$productCount) {
+ return $this;
+ }
+
+ for ($i = 0; $i < $productCount / self::STEP_SIZE; $i++) {
+ $this->_getResource()->beginTransaction();
+ try {
+ $deleteKill = false;
+
+ $stepData = $collection->getAllIds(self::STEP_SIZE, $i * self::STEP_SIZE);
+
+ /**
+ * Reindex EAV attributes if required
+ */
+ if (count($attributes)) {
+ $this->_getResource()->reindexAttributes($stepData, $attributes, $store);
+ }
+
+ /**
+ * Reindex prices if required
+ */
+ if (count($prices)) {
+ $this->_getResource()->reindexPrices($stepData, $prices, $store);
+ $this->_getResource()->reindexTiers($stepData, $store);
+ $this->_getResource()->reindexMinimalPrices($stepData, $store);
+ $this->_getResource()->reindexFinalPrices($stepData, $store);
+ }
+
+ Mage::getResourceSingleton('catalog/product')->refreshEnabledIndex($store, $stepData);
+
+ $kill = Mage::getModel('catalogindex/catalog_index_kill_flag')->loadSelf();
+ if ($kill->checkIsThisProcess()) {
+ $this->_getResource()->rollBack();
+ $deleteKill = true;
+ } else {
+ $this->_getResource()->commit();
+ }
+ } catch (Exception $e) {
+ $this->_getResource()->rollBack();
+ throw $e;
+ }
+
+ if ($deleteKill && isset($kill)) {
+ $kill->delete();
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Get product types list by type priority
+ * type priority is important in index process
+ * example: before indexing complex (configurable, grouped etc.) products
+ * we have to index all simple products
+ *
+ * @return array
+ */
+ protected function _getPriorifiedProductTypes()
+ {
+ if (is_null($this->_productTypePriority)) {
+ $this->_productTypePriority = [];
+ $config = Mage::getConfig()->getNode('global/catalog/product/type');
+
+ foreach ($config->children() as $type) {
+ $typeName = $type->getName();
+ $typePriority = (string) $type->index_priority;
+ $this->_productTypePriority[$typePriority] = $typeName;
+ }
+ ksort($this->_productTypePriority);
+ }
+ return $this->_productTypePriority;
+ }
+
+ /**
+ * Retrieve Base to Specified Currency Rate
+ *
+ * @param string $code
+ * @return double
+ */
+ protected function _getBaseToSpecifiedCurrencyRate($code)
+ {
+ return Mage::app()->getStore()->getBaseCurrency()->getRate($code);
+ }
+
+ /**
+ * Retrieve SELECT object
+ *
+ * @return Varien_Db_Select
+ */
+ protected function _getSelect()
+ {
+ return $this->_getResource()->getReadConnection()->select();
+ }
+
+ /**
+ * Add indexable attributes to product collection select
+ *
+ * @deprecated
+ * @param Mage_Catalog_Model_Resource_Product_Collection $collection
+ * @return Mage_CatalogIndex_Model_Indexer
+ */
+ protected function _addFilterableAttributesToCollection($collection)
+ {
+ $attributeCodes = $this->_getIndexableAttributeCodes();
+ foreach ($attributeCodes as $code) {
+ $collection->addAttributeToSelect($code);
}
- $this->_getResource()->updateCatalogProductFlat($store, $products, $resourceTable);
return $this;
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Indexer/Abstract.php b/app/code/core/Mage/CatalogIndex/Model/Indexer/Abstract.php
index 5666bb8ec60..96232c7b2ab 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Indexer/Abstract.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Indexer/Abstract.php
@@ -114,67 +114,67 @@ public function saveIndices(array $data, $storeId, $productId)
/**
* @return bool
*/
- protected function _isObjectIndexable(Mage_Catalog_Model_Product $object)
+ public function isAttributeIndexable(Mage_Eav_Model_Entity_Attribute_Abstract $attribute)
{
- if ($object->getStatus() != Mage_Catalog_Model_Product_Status::STATUS_ENABLED) {
- return false;
- }
-
- if ($object->getVisibility() != Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG &&
- $object->getVisibility() != Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH
- ) {
- return false;
- }
-
- return true;
+ return $this->_isAttributeIndexable($attribute);
}
/**
- * @return bool
+ * @return array
*/
- public function isAttributeIndexable(Mage_Eav_Model_Entity_Attribute_Abstract $attribute)
+ public function getIndexableAttributeCodes()
{
- return $this->_isAttributeIndexable($attribute);
+ return $this->_getResource()->loadAttributeCodesByCondition($this->_getIndexableAttributeConditions());
}
/**
- * @return bool
+ * @param int $productId
+ * @param int $storeId
*/
- protected function _isAttributeIndexable(Mage_Eav_Model_Entity_Attribute_Abstract $attribute)
+ public function cleanup($productId, $storeId = null)
{
- return true;
+ $this->_getResource()->cleanup($productId, $storeId);
}
/**
- * @return array
+ * @return bool
*/
- public function getIndexableAttributeCodes()
+ public function isAttributeIdUsed()
{
- return $this->_getResource()->loadAttributeCodesByCondition($this->_getIndexableAttributeConditions());
+ return true;
}
/**
- * @return array
+ * @return bool
*/
- protected function _getIndexableAttributeConditions()
+ protected function _isObjectIndexable(Mage_Catalog_Model_Product $object)
{
- return [];
+ if ($object->getStatus() != Mage_Catalog_Model_Product_Status::STATUS_ENABLED) {
+ return false;
+ }
+
+ if ($object->getVisibility() != Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG &&
+ $object->getVisibility() != Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH
+ ) {
+ return false;
+ }
+
+ return true;
}
/**
- * @param int $productId
- * @param int $storeId
+ * @return bool
*/
- public function cleanup($productId, $storeId = null)
+ protected function _isAttributeIndexable(Mage_Eav_Model_Entity_Attribute_Abstract $attribute)
{
- $this->_getResource()->cleanup($productId, $storeId);
+ return true;
}
/**
- * @return bool
+ * @return array
*/
- public function isAttributeIdUsed()
+ protected function _getIndexableAttributeConditions()
{
- return true;
+ return [];
}
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Indexer/Eav.php b/app/code/core/Mage/CatalogIndex/Model/Indexer/Eav.php
index b43f683d0de..cbe7ea368e3 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Indexer/Eav.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Indexer/Eav.php
@@ -32,12 +32,6 @@
*/
class Mage_CatalogIndex_Model_Indexer_Eav extends Mage_CatalogIndex_Model_Indexer_Abstract
{
- protected function _construct()
- {
- $this->_init('catalogindex/indexer_eav');
- parent::_construct();
- }
-
/**
* @return array
*/
@@ -65,6 +59,11 @@ public function createIndexData(Mage_Catalog_Model_Product $object, ?Mage_Eav_Mo
//return $this->_spreadDataForStores($object, $attribute, $data);
return $data;
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/indexer_eav');
+ parent::_construct();
+ }
/**
* @return bool
diff --git a/app/code/core/Mage/CatalogIndex/Model/Indexer/Minimalprice.php b/app/code/core/Mage/CatalogIndex/Model/Indexer/Minimalprice.php
index bf92246bce6..cdc64187a2a 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Indexer/Minimalprice.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Indexer/Minimalprice.php
@@ -49,15 +49,6 @@ class Mage_CatalogIndex_Model_Indexer_Minimalprice extends Mage_CatalogIndex_Mod
protected $_runOnce = true;
protected $_processChildren = false;
- protected function _construct()
- {
- $this->_init('catalogindex/indexer_minimalprice');
- $this->_currencyModel = Mage::getModel('directory/currency');
- $this->_customerGroups = Mage::getModel('customer/group')->getCollection();
-
- parent::_construct();
- }
-
/**
* @return Mage_Eav_Model_Entity_Attribute_Abstract|mixed
* @throws Mage_Core_Exception
@@ -142,6 +133,15 @@ public function isAttributeIdUsed()
return false;
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/indexer_minimalprice');
+ $this->_currencyModel = Mage::getModel('directory/currency');
+ $this->_customerGroups = Mage::getModel('customer/group')->getCollection();
+
+ parent::_construct();
+ }
+
/**
* @return bool
*/
diff --git a/app/code/core/Mage/CatalogIndex/Model/Indexer/Price.php b/app/code/core/Mage/CatalogIndex/Model/Indexer/Price.php
index 8211cebcfb9..65534a7bde0 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Indexer/Price.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Indexer/Price.php
@@ -45,12 +45,6 @@ class Mage_CatalogIndex_Model_Indexer_Price extends Mage_CatalogIndex_Model_Inde
protected $_customerGroups = [];
protected $_processChildrenForConfigurable = false;
- protected function _construct()
- {
- $this->_init('catalogindex/indexer_price');
- $this->_customerGroups = Mage::getModel('customer/group')->getCollection();
- }
-
/**
* @return array
*/
@@ -79,6 +73,12 @@ public function createIndexData(Mage_Catalog_Model_Product $object, ?Mage_Eav_Mo
return $data;
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/indexer_price');
+ $this->_customerGroups = Mage::getModel('customer/group')->getCollection();
+ }
+
/**
* @return bool
*/
diff --git a/app/code/core/Mage/CatalogIndex/Model/Indexer/Tierprice.php b/app/code/core/Mage/CatalogIndex/Model/Indexer/Tierprice.php
index dad08037ced..353d2f135fe 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Indexer/Tierprice.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Indexer/Tierprice.php
@@ -55,15 +55,6 @@ class Mage_CatalogIndex_Model_Indexer_Tierprice extends Mage_CatalogIndex_Model_
protected $_processChildren = false;
- protected function _construct()
- {
- $this->_init('catalogindex/indexer_price');
- $this->_currencyModel = Mage::getModel('directory/currency');
- $this->_customerGroups = Mage::getModel('customer/group')->getCollection();
-
- parent::_construct();
- }
-
/**
* @return array
*/
@@ -103,6 +94,15 @@ public function createIndexData(Mage_Catalog_Model_Product $object, ?Mage_Eav_Mo
return $result;
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/indexer_price');
+ $this->_currencyModel = Mage::getModel('directory/currency');
+ $this->_customerGroups = Mage::getModel('customer/group')->getCollection();
+
+ parent::_construct();
+ }
+
/**
* @return bool
*/
diff --git a/app/code/core/Mage/CatalogIndex/Model/Observer.php b/app/code/core/Mage/CatalogIndex/Model/Observer.php
index 067e11b5346..a79859af6d8 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Observer.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Observer.php
@@ -25,28 +25,6 @@ class Mage_CatalogIndex_Model_Observer extends Mage_Core_Model_Abstract
protected $_parentProductIds = [];
protected $_productIdsMassupdate = [];
- protected function _construct() {}
-
- /**
- * Get indexer object
- *
- * @return Mage_CatalogIndex_Model_Indexer
- */
- protected function _getIndexer()
- {
- return Mage::getSingleton('catalogindex/indexer');
- }
-
- /**
- * Get aggregation object
- *
- * @return Mage_CatalogIndex_Model_Aggregation
- */
- protected function _getAggregator()
- {
- return Mage::getSingleton('catalogindex/aggregation');
- }
-
/**
* Reindex all catalog data
*
@@ -377,4 +355,26 @@ public function catalogProductFlatUpdateProduct(Varien_Event_Observer $observer)
return $this;
}
+
+ protected function _construct() {}
+
+ /**
+ * Get indexer object
+ *
+ * @return Mage_CatalogIndex_Model_Indexer
+ */
+ protected function _getIndexer()
+ {
+ return Mage::getSingleton('catalogindex/indexer');
+ }
+
+ /**
+ * Get aggregation object
+ *
+ * @return Mage_CatalogIndex_Model_Aggregation
+ */
+ protected function _getAggregator()
+ {
+ return Mage::getSingleton('catalogindex/aggregation');
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Price.php b/app/code/core/Mage/CatalogIndex/Model/Price.php
index 60e47268a66..da38c83cad7 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Price.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Price.php
@@ -42,14 +42,6 @@
*/
class Mage_CatalogIndex_Model_Price extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('catalogindex/price');
- $this->_getResource()->setStoreId(Mage::app()->getStore()->getId());
- $this->_getResource()->setRate(Mage::app()->getStore()->getCurrentCurrencyRate());
- $this->_getResource()->setCustomerGroupId(Mage::getSingleton('customer/session')->getCustomerGroupId());
- }
-
/**
* @param Mage_Eav_Model_Entity_Attribute $attribute
* @param Zend_Db_Select $entityIdsFilter
@@ -107,4 +99,11 @@ public function addMinimalPrices(Mage_Catalog_Model_Resource_Product_Collection
}
}
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/price');
+ $this->_getResource()->setStoreId(Mage::app()->getStore()->getId());
+ $this->_getResource()->setRate(Mage::app()->getStore()->getCurrentCurrencyRate());
+ $this->_getResource()->setCustomerGroupId(Mage::getSingleton('customer/session')->getCustomerGroupId());
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Resource/Abstract.php b/app/code/core/Mage/CatalogIndex/Model/Resource/Abstract.php
index 36989a02f0d..a13a564d6b7 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Resource/Abstract.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Resource/Abstract.php
@@ -26,12 +26,6 @@ class Mage_CatalogIndex_Model_Resource_Abstract extends Mage_Core_Model_Resource
protected $_websiteId = null;
- /**
- * Initialize model
- *
- */
- protected function _construct() {}
-
/**
* storeId setter
*
@@ -65,4 +59,10 @@ public function getWebsiteId()
}
return $this->_websiteId;
}
+
+ /**
+ * Initialize model
+ *
+ */
+ protected function _construct() {}
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Resource/Aggregation.php b/app/code/core/Mage/CatalogIndex/Model/Resource/Aggregation.php
index 1c2b3015185..0520d496660 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Resource/Aggregation.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Resource/Aggregation.php
@@ -36,17 +36,6 @@ class Mage_CatalogIndex_Model_Resource_Aggregation extends Mage_Core_Model_Resou
*/
protected $_toTagTable;
- /**
- * Initialize resource tables
- *
- */
- protected function _construct()
- {
- $this->_init('catalogindex/aggregation', 'aggregation_id');
- $this->_tagTable = $this->getTable('catalogindex/aggregation_tag');
- $this->_toTagTable = $this->getTable('catalogindex/aggregation_to_tag');
- }
-
/**
* Get aggregated cache data by data key and store
*
@@ -149,6 +138,38 @@ public function clearCacheData($tags, $storeId)
return $this;
}
+ /**
+ * ProductCategoryPaths getter
+ *
+ * @param array $productIds
+ * @return array
+ */
+ public function getProductCategoryPaths($productIds)
+ {
+ $select = $this->_getReadAdapter()->select()
+ ->from(['cat' => $this->getTable('catalog/category')], 'path')
+ ->joinInner(
+ ['cat_prod' => $this->getTable('catalog/category_product')],
+ $this->_getReadAdapter()->quoteInto(
+ 'cat.entity_id=cat_prod.category_id AND cat_prod.product_id IN (?)',
+ $productIds,
+ ),
+ [],
+ );
+ return $this->_getReadAdapter()->fetchCol($select);
+ }
+
+ /**
+ * Initialize resource tables
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalogindex/aggregation', 'aggregation_id');
+ $this->_tagTable = $this->getTable('catalogindex/aggregation_tag');
+ $this->_toTagTable = $this->getTable('catalogindex/aggregation_to_tag');
+ }
+
/**
* Save related tags for aggreagation data
*
@@ -223,25 +244,4 @@ protected function _addTags($tags)
}
return $this;
}
-
- /**
- * ProductCategoryPaths getter
- *
- * @param array $productIds
- * @return array
- */
- public function getProductCategoryPaths($productIds)
- {
- $select = $this->_getReadAdapter()->select()
- ->from(['cat' => $this->getTable('catalog/category')], 'path')
- ->joinInner(
- ['cat_prod' => $this->getTable('catalog/category_product')],
- $this->_getReadAdapter()->quoteInto(
- 'cat.entity_id=cat_prod.category_id AND cat_prod.product_id IN (?)',
- $productIds,
- ),
- [],
- );
- return $this->_getReadAdapter()->fetchCol($select);
- }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Resource/Attribute.php b/app/code/core/Mage/CatalogIndex/Model/Resource/Attribute.php
index 242b30f4264..b8df0635d5a 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Resource/Attribute.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Resource/Attribute.php
@@ -22,11 +22,6 @@
*/
class Mage_CatalogIndex_Model_Resource_Attribute extends Mage_CatalogIndex_Model_Resource_Abstract
{
- protected function _construct()
- {
- $this->_init('catalogindex/eav', 'index_id');
- }
-
/**
* @param Mage_Eav_Model_Entity_Attribute $attribute
* @param string $filter
@@ -101,4 +96,8 @@ public function applyFilterToCollection($collection, $attribute, $value)
->where($alias . '.value = ?', $value);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/eav', 'index_id');
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Resource/Data/Abstract.php b/app/code/core/Mage/CatalogIndex/Model/Resource/Data/Abstract.php
index bdcc7950276..6f41d5889ae 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Resource/Data/Abstract.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Resource/Data/Abstract.php
@@ -36,37 +36,6 @@ class Mage_CatalogIndex_Model_Resource_Data_Abstract extends Mage_Core_Model_Res
*/
protected $_linkSelect = null;
- /**
- * Set link select
- *
- * @param Zend_Db_Select $select
- * @return $this
- */
- protected function _setLinkSelect($select)
- {
- $this->_linkSelect = $select;
- return $this;
- }
-
- /**
- * Get link select
- *
- * @return Zend_Db_Select $select
- */
- protected function _getLinkSelect()
- {
- return $this->_linkSelect;
- }
-
- /**
- * Init resource
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/product', 'entity_id');
- }
-
/**
* Retrieve specified attribute data for specified products from specified store
*
@@ -158,18 +127,6 @@ public function fetchLinkInformation($store, $table, $idField, $whereField, $id,
return $this->_getWriteAdapter()->fetchCol($this->_getLinkSelect());
}
- /**
- * Prepare select statement before 'fetchLinkInformation' function result fetch
- *
- * @param int $store
- * @param string $table
- * @param string $idField
- * @param string $whereField
- * @param int $id
- * @param array $additionalWheres
- */
- protected function _prepareLinkFetchSelect($store, $table, $idField, $whereField, $id, $additionalWheres = []) {}
-
/**
* Return minimal prices for specified products
*
@@ -226,6 +183,49 @@ public function getTierPrices($products, $website)
return $this->_getReadAdapter()->fetchAll($select);
}
+ /**
+ * Set link select
+ *
+ * @param Zend_Db_Select $select
+ * @return $this
+ */
+ protected function _setLinkSelect($select)
+ {
+ $this->_linkSelect = $select;
+ return $this;
+ }
+
+ /**
+ * Get link select
+ *
+ * @return Zend_Db_Select $select
+ */
+ protected function _getLinkSelect()
+ {
+ return $this->_linkSelect;
+ }
+
+ /**
+ * Init resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product', 'entity_id');
+ }
+
+ /**
+ * Prepare select statement before 'fetchLinkInformation' function result fetch
+ *
+ * @param int $store
+ * @param string $table
+ * @param string $idField
+ * @param string $whereField
+ * @param int $id
+ * @param array $additionalWheres
+ */
+ protected function _prepareLinkFetchSelect($store, $table, $idField, $whereField, $id, $additionalWheres = []) {}
+
/**
* Add attribute filter to select
*
diff --git a/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer.php b/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer.php
index 261c2167bb8..c7f7dfc87cf 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer.php
@@ -37,24 +37,6 @@ class Mage_CatalogIndex_Model_Resource_Indexer extends Mage_Core_Model_Resource_
*/
protected $_attributeCache = [];
- protected function _construct()
- {
- $this->_init('catalog/product', 'entity_id');
- }
-
- /**
- * @param int $id
- * @return Mage_Eav_Model_Entity_Attribute
- */
- protected function _loadAttribute($id)
- {
- if (!isset($this->_attributeCache[$id])) {
- $this->_attributeCache[$id] = Mage::getModel('eav/entity_attribute')->load($id);
- }
-
- return $this->_attributeCache[$id];
- }
-
/**
* Delete index data by specific conditions
*
@@ -161,16 +143,6 @@ public function clear(
}
}
- /**
- * Get tables which are used for index related with price
- *
- * @return array
- */
- protected function _getPriceTables()
- {
- return ['catalogindex/price', 'catalogindex/minimal_price'];
- }
-
/**
* Reindex data for tier prices
*
@@ -510,56 +482,6 @@ public function getProductData($products, $attributeIds, $store)
return $result;
}
- /**
- * Prepare base information for data insert
- *
- * @param string $table
- * @param array $fields
- * @return $this
- */
- protected function _beginInsert($table, $fields)
- {
- $this->_tableFields[$table] = $fields;
- return $this;
- }
-
- /**
- * Put data into table
- *
- * @param string $table
- * @param bool $forced
- * @return $this
- */
- protected function _commitInsert($table, $forced = true)
- {
- if (isset($this->_insertData[$table]) && count($this->_insertData[$table]) && ($forced || count($this->_insertData[$table]) >= 100)) {
- $query = 'REPLACE INTO ' . $this->getTable($table) . ' (' . implode(', ', $this->_tableFields[$table]) . ') VALUES ';
- $separator = '';
- foreach ($this->_insertData[$table] as $row) {
- $rowString = $this->_getWriteAdapter()->quoteInto('(?)', $row);
- $query .= $separator . $rowString;
- $separator = ', ';
- }
- $this->_getWriteAdapter()->query($query);
- $this->_insertData[$table] = [];
- }
- return $this;
- }
-
- /**
- * Insert data to table
- *
- * @param string $table
- * @param array $data
- * @return $this
- */
- protected function _insert($table, $data)
- {
- $this->_insertData[$table][] = $data;
- $this->_commitInsert($table, false);
- return $this;
- }
-
/**
* Add price columns for catalog product flat table
*
@@ -684,4 +606,82 @@ public function updateCatalogProductFlat($storeId, $productIds = null, $tableNam
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('catalog/product', 'entity_id');
+ }
+
+ /**
+ * @param int $id
+ * @return Mage_Eav_Model_Entity_Attribute
+ */
+ protected function _loadAttribute($id)
+ {
+ if (!isset($this->_attributeCache[$id])) {
+ $this->_attributeCache[$id] = Mage::getModel('eav/entity_attribute')->load($id);
+ }
+
+ return $this->_attributeCache[$id];
+ }
+
+ /**
+ * Get tables which are used for index related with price
+ *
+ * @return array
+ */
+ protected function _getPriceTables()
+ {
+ return ['catalogindex/price', 'catalogindex/minimal_price'];
+ }
+
+ /**
+ * Prepare base information for data insert
+ *
+ * @param string $table
+ * @param array $fields
+ * @return $this
+ */
+ protected function _beginInsert($table, $fields)
+ {
+ $this->_tableFields[$table] = $fields;
+ return $this;
+ }
+
+ /**
+ * Put data into table
+ *
+ * @param string $table
+ * @param bool $forced
+ * @return $this
+ */
+ protected function _commitInsert($table, $forced = true)
+ {
+ if (isset($this->_insertData[$table]) && count($this->_insertData[$table]) && ($forced || count($this->_insertData[$table]) >= 100)) {
+ $query = 'REPLACE INTO ' . $this->getTable($table) . ' (' . implode(', ', $this->_tableFields[$table]) . ') VALUES ';
+ $separator = '';
+ foreach ($this->_insertData[$table] as $row) {
+ $rowString = $this->_getWriteAdapter()->quoteInto('(?)', $row);
+ $query .= $separator . $rowString;
+ $separator = ', ';
+ }
+ $this->_getWriteAdapter()->query($query);
+ $this->_insertData[$table] = [];
+ }
+ return $this;
+ }
+
+ /**
+ * Insert data to table
+ *
+ * @param string $table
+ * @param array $data
+ * @return $this
+ */
+ protected function _insert($table, $data)
+ {
+ $this->_insertData[$table][] = $data;
+ $this->_commitInsert($table, false);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer/Abstract.php b/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer/Abstract.php
index 7f220922d7a..db585a8d287 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer/Abstract.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer/Abstract.php
@@ -37,12 +37,6 @@ class Mage_CatalogIndex_Model_Resource_Indexer_Abstract extends Mage_Core_Model_
*/
protected $_storeIdFieldName;
- /**
- * should be defined because abstract
- *
- */
- protected function _construct() {}
-
/**
* @param array $data
* @param int $storeId
@@ -63,29 +57,6 @@ public function saveIndices(array $data, $storeId, $productId)
$this->_executeReplace($data, $storeId, $productId);
}
- /**
- * @param array $data
- * @param int $storeId
- * @param int $productId
- * @return $this
- */
- protected function _executeReplace($data, $storeId, $productId)
- {
- $this->beginTransaction();
- try {
- foreach ($data as $row) {
- $row[$this->_entityIdFieldName] = $productId;
- $this->_getWriteAdapter()->insert($this->getMainTable(), $row);
- }
- $this->commit();
- } catch (Exception $e) {
- $this->rollBack();
- throw $e;
- }
-
- return $this;
- }
-
/**
* @param int $productId
* @param int $storeId
@@ -145,4 +116,33 @@ public function loadAttributeCodesByCondition($conditions)
}
return $this->_getReadAdapter()->fetchCol($select);
}
+
+ /**
+ * should be defined because abstract
+ *
+ */
+ protected function _construct() {}
+
+ /**
+ * @param array $data
+ * @param int $storeId
+ * @param int $productId
+ * @return $this
+ */
+ protected function _executeReplace($data, $storeId, $productId)
+ {
+ $this->beginTransaction();
+ try {
+ foreach ($data as $row) {
+ $row[$this->_entityIdFieldName] = $productId;
+ $this->_getWriteAdapter()->insert($this->getMainTable(), $row);
+ }
+ $this->commit();
+ } catch (Exception $e) {
+ $this->rollBack();
+ throw $e;
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer/Minimalprice.php b/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer/Minimalprice.php
index d76be55171a..660f870eaf2 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer/Minimalprice.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Resource/Indexer/Minimalprice.php
@@ -22,14 +22,6 @@
*/
class Mage_CatalogIndex_Model_Resource_Indexer_Minimalprice extends Mage_CatalogIndex_Model_Resource_Indexer_Abstract
{
- protected function _construct()
- {
- $this->_init('catalogindex/minimal_price', 'index_id');
-
- $this->_entityIdFieldName = 'entity_id';
- $this->_storeIdFieldName = 'store_id';
- }
-
/**
* @param array $conditions
* @return string
@@ -66,4 +58,11 @@ public function cleanup($productId, $storeId = null, $attributeId = null)
$conditions = implode(' AND ', $conditions);
$this->_getWriteAdapter()->delete($this->getMainTable(), $conditions);
}
+ protected function _construct()
+ {
+ $this->_init('catalogindex/minimal_price', 'index_id');
+
+ $this->_entityIdFieldName = 'entity_id';
+ $this->_storeIdFieldName = 'store_id';
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Resource/Price.php b/app/code/core/Mage/CatalogIndex/Model/Resource/Price.php
index 9ab46bfe49e..00000279df9 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Resource/Price.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Resource/Price.php
@@ -37,11 +37,6 @@ class Mage_CatalogIndex_Model_Resource_Price extends Mage_CatalogIndex_Model_Res
*/
protected $_taxRates = null;
- protected function _construct()
- {
- $this->_init('catalogindex/price', 'index_id');
- }
-
/**
* @param float $rate
*/
@@ -265,4 +260,9 @@ public function getMinimalPrices($ids)
->where('price_table.customer_group_id = ?', $this->getCustomerGroupId());
return $this->_getReadAdapter()->fetchAll($select);
}
+
+ protected function _construct()
+ {
+ $this->_init('catalogindex/price', 'index_id');
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Resource/Retreiver.php b/app/code/core/Mage/CatalogIndex/Model/Resource/Retreiver.php
index 6877e7dbfd4..de174285f3c 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Resource/Retreiver.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Resource/Retreiver.php
@@ -22,11 +22,6 @@
*/
class Mage_CatalogIndex_Model_Resource_Retreiver extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product', 'entity_id');
- }
-
/**
* Return id-type pairs
*
@@ -40,4 +35,8 @@ public function getProductTypes($ids)
->where('main_table.entity_id in (?)', $ids);
return $this->_getReadAdapter()->fetchAll($select);
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product', 'entity_id');
+ }
}
diff --git a/app/code/core/Mage/CatalogIndex/Model/Retreiver.php b/app/code/core/Mage/CatalogIndex/Model/Retreiver.php
index 59f39b71a5b..d7cc7ee6b9a 100644
--- a/app/code/core/Mage/CatalogIndex/Model/Retreiver.php
+++ b/app/code/core/Mage/CatalogIndex/Model/Retreiver.php
@@ -61,22 +61,6 @@ class Mage_CatalogIndex_Model_Retreiver extends Mage_Core_Model_Abstract
*/
protected $_retreivers = [];
- /**
- * Retriever factory init, load retriever settings
- *
- */
- protected function _construct()
- {
- $config = Mage::getConfig()->getNode('global/catalog/product/type')->asArray();
- foreach ($config as $type => $data) {
- if (isset($data['index_data_retreiver'])) {
- $this->_retreivers[$type] = $data['index_data_retreiver'];
- }
- }
-
- $this->_init('catalogindex/retreiver');
- }
-
/**
* Returns data retriever model by specified product type
*
@@ -121,4 +105,20 @@ public function assignProductTypes($products)
}
return $result;
}
+
+ /**
+ * Retriever factory init, load retriever settings
+ *
+ */
+ protected function _construct()
+ {
+ $config = Mage::getConfig()->getNode('global/catalog/product/type')->asArray();
+ foreach ($config as $type => $data) {
+ if (isset($data['index_data_retreiver'])) {
+ $this->_retreivers[$type] = $data['index_data_retreiver'];
+ }
+ }
+
+ $this->_init('catalogindex/retreiver');
+ }
}
diff --git a/app/code/core/Mage/CatalogInventory/Block/Adminhtml/Form/Field/Customergroup.php b/app/code/core/Mage/CatalogInventory/Block/Adminhtml/Form/Field/Customergroup.php
index f6069a66459..c57c87fd4a7 100644
--- a/app/code/core/Mage/CatalogInventory/Block/Adminhtml/Form/Field/Customergroup.php
+++ b/app/code/core/Mage/CatalogInventory/Block/Adminhtml/Form/Field/Customergroup.php
@@ -22,41 +22,18 @@
*/
class Mage_CatalogInventory_Block_Adminhtml_Form_Field_Customergroup extends Mage_Core_Block_Html_Select
{
- /**
- * Customer groups cache
- *
- * @var array|null
- */
- private $_customerGroups;
-
/**
* Flag whether to add group all option or no
*
* @var bool
*/
protected $_addGroupAllOption = true;
-
/**
- * Retrieve allowed customer groups
+ * Customer groups cache
*
- * @param int $groupId return name by customer group id
- * @return array|string
+ * @var array|null
*/
- protected function _getCustomerGroups($groupId = null)
- {
- if (is_null($this->_customerGroups)) {
- $this->_customerGroups = [];
- $collection = Mage::getModel('customer/group')->getCollection();
- foreach ($collection as $item) {
- /** @var Mage_Customer_Model_Group $item */
- $this->_customerGroups[$item->getId()] = $item->getCustomerGroupCode();
- }
- }
- if (!is_null($groupId)) {
- return $this->_customerGroups[$groupId] ?? null;
- }
- return $this->_customerGroups;
- }
+ private $_customerGroups;
/**
* @param string $value
@@ -84,4 +61,26 @@ public function _toHtml()
}
return parent::_toHtml();
}
+
+ /**
+ * Retrieve allowed customer groups
+ *
+ * @param int $groupId return name by customer group id
+ * @return array|string
+ */
+ protected function _getCustomerGroups($groupId = null)
+ {
+ if (is_null($this->_customerGroups)) {
+ $this->_customerGroups = [];
+ $collection = Mage::getModel('customer/group')->getCollection();
+ foreach ($collection as $item) {
+ /** @var Mage_Customer_Model_Group $item */
+ $this->_customerGroups[$item->getId()] = $item->getCustomerGroupCode();
+ }
+ }
+ if (!is_null($groupId)) {
+ return $this->_customerGroups[$groupId] ?? null;
+ }
+ return $this->_customerGroups;
+ }
}
diff --git a/app/code/core/Mage/CatalogInventory/Block/Qtyincrements.php b/app/code/core/Mage/CatalogInventory/Block/Qtyincrements.php
index 6d56e0b81f3..5a4e4264a3c 100644
--- a/app/code/core/Mage/CatalogInventory/Block/Qtyincrements.php
+++ b/app/code/core/Mage/CatalogInventory/Block/Qtyincrements.php
@@ -29,16 +29,6 @@ class Mage_CatalogInventory_Block_Qtyincrements extends Mage_Core_Block_Template
*/
protected $_qtyIncrements;
- /**
- * Retrieve current product object
- *
- * @return Mage_Catalog_Model_Product
- */
- protected function _getProduct()
- {
- return Mage::registry('current_product');
- }
-
/**
* Retrieve current product name
*
@@ -74,4 +64,14 @@ public function getCacheTags()
{
return array_merge(parent::getCacheTags(), $this->_getProduct()->getCacheIdTags());
}
+
+ /**
+ * Retrieve current product object
+ *
+ * @return Mage_Catalog_Model_Product
+ */
+ protected function _getProduct()
+ {
+ return Mage::registry('current_product');
+ }
}
diff --git a/app/code/core/Mage/CatalogInventory/Block/Stockqty/Abstract.php b/app/code/core/Mage/CatalogInventory/Block/Stockqty/Abstract.php
index e25a259c4c0..33f63cd02a7 100644
--- a/app/code/core/Mage/CatalogInventory/Block/Stockqty/Abstract.php
+++ b/app/code/core/Mage/CatalogInventory/Block/Stockqty/Abstract.php
@@ -24,16 +24,6 @@ abstract class Mage_CatalogInventory_Block_Stockqty_Abstract extends Mage_Core_B
{
public const XML_PATH_STOCK_THRESHOLD_QTY = 'cataloginventory/options/stock_threshold_qty';
- /**
- * Retrieve current product object
- *
- * @return Mage_Catalog_Model_Product
- */
- protected function _getProduct()
- {
- return Mage::registry('current_product');
- }
-
/**
* Retrieve current product stock qty
*
@@ -84,4 +74,14 @@ public function isMsgVisible()
{
return ($this->getStockQty() > 0 && $this->getStockQty() <= $this->getThresholdQty());
}
+
+ /**
+ * Retrieve current product object
+ *
+ * @return Mage_Catalog_Model_Product
+ */
+ protected function _getProduct()
+ {
+ return Mage::registry('current_product');
+ }
}
diff --git a/app/code/core/Mage/CatalogInventory/Block/Stockqty/Composite.php b/app/code/core/Mage/CatalogInventory/Block/Stockqty/Composite.php
index 4f09d61970b..9d655816bf4 100644
--- a/app/code/core/Mage/CatalogInventory/Block/Stockqty/Composite.php
+++ b/app/code/core/Mage/CatalogInventory/Block/Stockqty/Composite.php
@@ -29,13 +29,6 @@ abstract class Mage_CatalogInventory_Block_Stockqty_Composite extends Mage_Catal
*/
private $_childProducts;
- /**
- * Retrieve child products
- *
- * @return array
- */
- abstract protected function _getChildProducts();
-
/**
* Retrieve child products (using cache)
*
@@ -69,4 +62,11 @@ public function getDetailsPlaceholderId()
{
return $this->getPlaceholderId() . '-details';
}
+
+ /**
+ * Retrieve child products
+ *
+ * @return array
+ */
+ abstract protected function _getChildProducts();
}
diff --git a/app/code/core/Mage/CatalogInventory/Block/Stockqty/Default.php b/app/code/core/Mage/CatalogInventory/Block/Stockqty/Default.php
index c16bc3df1b7..54b51691508 100644
--- a/app/code/core/Mage/CatalogInventory/Block/Stockqty/Default.php
+++ b/app/code/core/Mage/CatalogInventory/Block/Stockqty/Default.php
@@ -22,6 +22,15 @@
*/
class Mage_CatalogInventory_Block_Stockqty_Default extends Mage_CatalogInventory_Block_Stockqty_Abstract
{
+ /**
+ * Retrieve block cache tags
+ *
+ * @return array
+ */
+ public function getCacheTags()
+ {
+ return array_merge(parent::getCacheTags(), $this->_getProduct()->getCacheIdTags());
+ }
/**
* Render block HTML
*
@@ -34,14 +43,4 @@ protected function _toHtml()
}
return parent::_toHtml();
}
-
- /**
- * Retrieve block cache tags
- *
- * @return array
- */
- public function getCacheTags()
- {
- return array_merge(parent::getCacheTags(), $this->_getProduct()->getCacheIdTags());
- }
}
diff --git a/app/code/core/Mage/CatalogInventory/Helper/Minsaleqty.php b/app/code/core/Mage/CatalogInventory/Helper/Minsaleqty.php
index a2368800d95..6547e5397d4 100644
--- a/app/code/core/Mage/CatalogInventory/Helper/Minsaleqty.php
+++ b/app/code/core/Mage/CatalogInventory/Helper/Minsaleqty.php
@@ -24,6 +24,61 @@ class Mage_CatalogInventory_Helper_Minsaleqty
{
protected $_moduleName = 'Mage_CatalogInventory';
+ /**
+ * Retrieve min_sale_qty value from config
+ *
+ * @param int $customerGroupId
+ * @param mixed $store
+ * @return float|null
+ */
+ public function getConfigValue($customerGroupId, $store = null)
+ {
+ $value = Mage::getStoreConfig(Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MIN_SALE_QTY, $store);
+ $value = $this->_unserializeValue($value);
+ if ($this->_isEncodedArrayFieldValue($value)) {
+ $value = $this->_decodeArrayFieldValue($value);
+ }
+ $result = null;
+ foreach ($value as $groupId => $qty) {
+ if ($groupId == $customerGroupId) {
+ $result = $qty;
+ break;
+ } elseif ($groupId == Mage_Customer_Model_Group::CUST_GROUP_ALL) {
+ $result = $qty;
+ }
+ }
+ return $this->_fixQty($result);
+ }
+
+ /**
+ * Make value readable by Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract
+ *
+ * @param mixed $value
+ * @return array
+ */
+ public function makeArrayFieldValue($value)
+ {
+ $value = $this->_unserializeValue($value);
+ if (!$this->_isEncodedArrayFieldValue($value)) {
+ $value = $this->_encodeArrayFieldValue($value);
+ }
+ return $value;
+ }
+
+ /**
+ * Make value ready for store
+ *
+ * @param mixed $value
+ * @return string
+ */
+ public function makeStorableArrayFieldValue($value)
+ {
+ if ($this->_isEncodedArrayFieldValue($value)) {
+ $value = $this->_decodeArrayFieldValue($value);
+ }
+ return $this->_serializeValue($value);
+ }
+
/**
* Retrieve fixed qty value
*
@@ -142,59 +197,4 @@ protected function _decodeArrayFieldValue(array $value)
}
return $result;
}
-
- /**
- * Retrieve min_sale_qty value from config
- *
- * @param int $customerGroupId
- * @param mixed $store
- * @return float|null
- */
- public function getConfigValue($customerGroupId, $store = null)
- {
- $value = Mage::getStoreConfig(Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MIN_SALE_QTY, $store);
- $value = $this->_unserializeValue($value);
- if ($this->_isEncodedArrayFieldValue($value)) {
- $value = $this->_decodeArrayFieldValue($value);
- }
- $result = null;
- foreach ($value as $groupId => $qty) {
- if ($groupId == $customerGroupId) {
- $result = $qty;
- break;
- } elseif ($groupId == Mage_Customer_Model_Group::CUST_GROUP_ALL) {
- $result = $qty;
- }
- }
- return $this->_fixQty($result);
- }
-
- /**
- * Make value readable by Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract
- *
- * @param mixed $value
- * @return array
- */
- public function makeArrayFieldValue($value)
- {
- $value = $this->_unserializeValue($value);
- if (!$this->_isEncodedArrayFieldValue($value)) {
- $value = $this->_encodeArrayFieldValue($value);
- }
- return $value;
- }
-
- /**
- * Make value ready for store
- *
- * @param mixed $value
- * @return string
- */
- public function makeStorableArrayFieldValue($value)
- {
- if ($this->_isEncodedArrayFieldValue($value)) {
- $value = $this->_decodeArrayFieldValue($value);
- }
- return $this->_serializeValue($value);
- }
}
diff --git a/app/code/core/Mage/CatalogInventory/Model/Indexer/Stock.php b/app/code/core/Mage/CatalogInventory/Model/Indexer/Stock.php
index 31c9368f5c8..c101a7c23a1 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Indexer/Stock.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Indexer/Stock.php
@@ -76,11 +76,6 @@ class Mage_CatalogInventory_Model_Indexer_Stock extends Mage_Index_Model_Indexer
Mage_CatalogInventory_Helper_Data::XML_PATH_SHOW_OUT_OF_STOCK,
];
- protected function _construct()
- {
- $this->_init('cataloginventory/indexer_stock');
- }
-
/**
* Retrieve Indexer name
*
@@ -147,6 +142,11 @@ public function matchEvent(Mage_Index_Model_Event $event)
return $result;
}
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/indexer_stock');
+ }
+
/**
* Register data required by process in event object
*/
diff --git a/app/code/core/Mage/CatalogInventory/Model/Observer.php b/app/code/core/Mage/CatalogInventory/Model/Observer.php
index 44f00f632f5..e7eccf19cef 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Observer.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Observer.php
@@ -190,112 +190,6 @@ public function copyInventoryData($observer)
return $this;
}
- /**
- * Prepare stock item data for save
- *
- * @param Mage_CatalogInventory_Model_Stock_Item $item
- * @param Mage_Catalog_Model_Product $product
- * @return $this
- */
- protected function _prepareItemForSave($item, $product)
- {
- $item->addData($product->getStockData())
- ->setProduct($product)
- ->setProductId($product->getId())
- ->setStockId($item->getStockId());
- if (!is_null($product->getData('stock_data/min_qty'))
- && is_null($product->getData('stock_data/use_config_min_qty'))
- ) {
- $item->setData('use_config_min_qty', false);
- }
- if (!is_null($product->getData('stock_data/min_sale_qty'))
- && is_null($product->getData('stock_data/use_config_min_sale_qty'))
- ) {
- $item->setData('use_config_min_sale_qty', false);
- }
- if (!is_null($product->getData('stock_data/max_sale_qty'))
- && is_null($product->getData('stock_data/use_config_max_sale_qty'))
- ) {
- $item->setData('use_config_max_sale_qty', false);
- }
- if (!is_null($product->getData('stock_data/backorders'))
- && is_null($product->getData('stock_data/use_config_backorders'))
- ) {
- $item->setData('use_config_backorders', false);
- }
- if (!is_null($product->getData('stock_data/notify_stock_qty'))
- && is_null($product->getData('stock_data/use_config_notify_stock_qty'))
- ) {
- $item->setData('use_config_notify_stock_qty', false);
- }
- $originalQty = $product->getData('stock_data/original_inventory_qty');
- if (is_numeric($originalQty)) {
- $item->setQtyCorrection($item->getQty() - $originalQty);
- }
- if (!is_null($product->getData('stock_data/enable_qty_increments'))
- && is_null($product->getData('stock_data/use_config_enable_qty_inc'))
- ) {
- $item->setData('use_config_enable_qty_inc', false);
- }
- if (!is_null($product->getData('stock_data/qty_increments'))
- && is_null($product->getData('stock_data/use_config_qty_increments'))
- ) {
- $item->setData('use_config_qty_increments', false);
- }
- return $this;
- }
-
- /**
- * Removes error statuses from quote and item, set by this observer
- *
- * @param Mage_Sales_Model_Quote_Item $item
- * @param int $code
- * @return $this
- */
- protected function _removeErrorsFromQuoteAndItem($item, $code)
- {
- if ($item->getHasError()) {
- $params = [
- 'origin' => 'cataloginventory',
- 'code' => $code,
- ];
- $item->removeErrorInfosByParams($params);
- }
-
- $quote = $item->getQuote();
- $quoteItems = $quote->getItemsCollection();
- $canRemoveErrorFromQuote = true;
-
- /** @var Mage_Sales_Model_Quote_Item $quoteItem */
- foreach ($quoteItems as $quoteItemId => $quoteItem) {
- if ($quoteItemId == $item->getItemId()) {
- continue;
- }
-
- $errorInfos = $quoteItem->getErrorInfos();
- foreach ($errorInfos as $errorInfo) {
- if ($errorInfo['code'] == $code) {
- $canRemoveErrorFromQuote = false;
- break;
- }
- }
-
- if (!$canRemoveErrorFromQuote) {
- break;
- }
- }
-
- if ($quote->getHasError() && $canRemoveErrorFromQuote) {
- $params = [
- 'origin' => 'cataloginventory',
- 'code' => $code,
- ];
- $quote->removeErrorInfosByParams(null, $params);
- }
-
- return $this;
- }
-
/**
* Check product inventory data when quote item quantity declaring
*
@@ -559,49 +453,6 @@ public function checkQuoteItemQty($observer)
return $this;
}
- /**
- * Get product qty includes information from all quote items
- * Need be used only in sungleton mode
- *
- * @param int $productId
- * @param float $itemQty
- * @return float|mixed
- * @deprecated after 1.4.2.0-rc1
- */
- protected function _getProductQtyForCheck($productId, $itemQty)
- {
- $qty = $itemQty;
- if (isset($this->_checkedProductsQty[$productId])) {
- $qty += $this->_checkedProductsQty[$productId];
- }
- $this->_checkedProductsQty[$productId] = $qty;
- return $qty;
- }
-
- /**
- * Get product qty includes information from all quote items
- * Need be used only in sungleton mode
- *
- * @param int $productId
- * @param int $quoteItemId
- * @param float $itemQty
- * @return int
- */
- protected function _getQuoteItemQtyForCheck($productId, $quoteItemId, $itemQty)
- {
- $qty = $itemQty;
- if (isset($this->_checkedQuoteItems[$productId]['qty']) &&
- !in_array($quoteItemId, $this->_checkedQuoteItems[$productId]['items'])
- ) {
- $qty += $this->_checkedQuoteItems[$productId]['qty'];
- }
-
- $this->_checkedQuoteItems[$productId]['qty'] = $qty;
- $this->_checkedQuoteItems[$productId]['items'][] = $quoteItemId;
-
- return $qty;
- }
-
/**
* Subtract qtys of quote item products after multishipping checkout
*
@@ -662,71 +513,6 @@ public function revertQuoteInventory($observer)
$quote->setInventoryProcessed(false);
}
- /**
- * Adds stock item qty to $items (creates new entry or increments existing one)
- * $items is array with following structure:
- * array(
- * $productId => array(
- * 'qty' => $qty,
- * 'item' => $stockItems|null
- * )
- * )
- *
- * @param Mage_Sales_Model_Quote_Item $quoteItem
- * @param array $items
- */
- protected function _addItemToQtyArray($quoteItem, &$items)
- {
- $productId = $quoteItem->getProductId();
- if (!$productId) {
- return;
- }
- if (isset($items[$productId])) {
- $items[$productId]['qty'] += $quoteItem->getTotalQty();
- } else {
- $stockItem = null;
- if ($quoteItem->getProduct()) {
- $stockItem = $quoteItem->getProduct()->getStockItem();
- }
- $items[$productId] = [
- 'item' => $stockItem,
- 'qty' => $quoteItem->getTotalQty(),
- ];
- }
- }
-
- /**
- * Prepare array with information about used product qty and product stock item
- * result is:
- * array(
- * $productId => array(
- * 'qty' => $qty,
- * 'item' => $stockItems|null
- * )
- * )
- * @param array $relatedItems
- * @return array
- */
- protected function _getProductsQty($relatedItems)
- {
- $items = [];
- foreach ($relatedItems as $item) {
- $productId = $item->getProductId();
- if (!$productId) {
- continue;
- }
- $children = $item->getChildrenItems();
- if ($children) {
- foreach ($children as $childItem) {
- $this->_addItemToQtyArray($childItem, $items);
- }
- } else {
- $this->_addItemToQtyArray($item, $items);
- }
- }
- return $items;
- }
-
/**
* Refresh stock index for specific stock items after successful order placement
*
@@ -1056,4 +842,218 @@ public function displayProductStatusInfo($observer)
$info->setDisplayStatus(Mage::helper('cataloginventory')->isDisplayProductStockStatus());
return $this;
}
+
+ /**
+ * Prepare stock item data for save
+ *
+ * @param Mage_CatalogInventory_Model_Stock_Item $item
+ * @param Mage_Catalog_Model_Product $product
+ * @return $this
+ */
+ protected function _prepareItemForSave($item, $product)
+ {
+ $item->addData($product->getStockData())
+ ->setProduct($product)
+ ->setProductId($product->getId())
+ ->setStockId($item->getStockId());
+ if (!is_null($product->getData('stock_data/min_qty'))
+ && is_null($product->getData('stock_data/use_config_min_qty'))
+ ) {
+ $item->setData('use_config_min_qty', false);
+ }
+ if (!is_null($product->getData('stock_data/min_sale_qty'))
+ && is_null($product->getData('stock_data/use_config_min_sale_qty'))
+ ) {
+ $item->setData('use_config_min_sale_qty', false);
+ }
+ if (!is_null($product->getData('stock_data/max_sale_qty'))
+ && is_null($product->getData('stock_data/use_config_max_sale_qty'))
+ ) {
+ $item->setData('use_config_max_sale_qty', false);
+ }
+ if (!is_null($product->getData('stock_data/backorders'))
+ && is_null($product->getData('stock_data/use_config_backorders'))
+ ) {
+ $item->setData('use_config_backorders', false);
+ }
+ if (!is_null($product->getData('stock_data/notify_stock_qty'))
+ && is_null($product->getData('stock_data/use_config_notify_stock_qty'))
+ ) {
+ $item->setData('use_config_notify_stock_qty', false);
+ }
+ $originalQty = $product->getData('stock_data/original_inventory_qty');
+ if (is_numeric($originalQty)) {
+ $item->setQtyCorrection($item->getQty() - $originalQty);
+ }
+ if (!is_null($product->getData('stock_data/enable_qty_increments'))
+ && is_null($product->getData('stock_data/use_config_enable_qty_inc'))
+ ) {
+ $item->setData('use_config_enable_qty_inc', false);
+ }
+ if (!is_null($product->getData('stock_data/qty_increments'))
+ && is_null($product->getData('stock_data/use_config_qty_increments'))
+ ) {
+ $item->setData('use_config_qty_increments', false);
+ }
+ return $this;
+ }
+
+ /**
+ * Removes error statuses from quote and item, set by this observer
+ *
+ * @param Mage_Sales_Model_Quote_Item $item
+ * @param int $code
+ * @return $this
+ */
+ protected function _removeErrorsFromQuoteAndItem($item, $code)
+ {
+ if ($item->getHasError()) {
+ $params = [
+ 'origin' => 'cataloginventory',
+ 'code' => $code,
+ ];
+ $item->removeErrorInfosByParams($params);
+ }
+
+ $quote = $item->getQuote();
+ $quoteItems = $quote->getItemsCollection();
+ $canRemoveErrorFromQuote = true;
+
+ /** @var Mage_Sales_Model_Quote_Item $quoteItem */
+ foreach ($quoteItems as $quoteItemId => $quoteItem) {
+ if ($quoteItemId == $item->getItemId()) {
+ continue;
+ }
+
+ $errorInfos = $quoteItem->getErrorInfos();
+ foreach ($errorInfos as $errorInfo) {
+ if ($errorInfo['code'] == $code) {
+ $canRemoveErrorFromQuote = false;
+ break;
+ }
+ }
+
+ if (!$canRemoveErrorFromQuote) {
+ break;
+ }
+ }
+
+ if ($quote->getHasError() && $canRemoveErrorFromQuote) {
+ $params = [
+ 'origin' => 'cataloginventory',
+ 'code' => $code,
+ ];
+ $quote->removeErrorInfosByParams(null, $params);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get product qty includes information from all quote items
+ * Need be used only in sungleton mode
+ *
+ * @param int $productId
+ * @param float $itemQty
+ * @return float|mixed
+ * @deprecated after 1.4.2.0-rc1
+ */
+ protected function _getProductQtyForCheck($productId, $itemQty)
+ {
+ $qty = $itemQty;
+ if (isset($this->_checkedProductsQty[$productId])) {
+ $qty += $this->_checkedProductsQty[$productId];
+ }
+ $this->_checkedProductsQty[$productId] = $qty;
+ return $qty;
+ }
+
+ /**
+ * Get product qty includes information from all quote items
+ * Need be used only in sungleton mode
+ *
+ * @param int $productId
+ * @param int $quoteItemId
+ * @param float $itemQty
+ * @return int
+ */
+ protected function _getQuoteItemQtyForCheck($productId, $quoteItemId, $itemQty)
+ {
+ $qty = $itemQty;
+ if (isset($this->_checkedQuoteItems[$productId]['qty']) &&
+ !in_array($quoteItemId, $this->_checkedQuoteItems[$productId]['items'])
+ ) {
+ $qty += $this->_checkedQuoteItems[$productId]['qty'];
+ }
+
+ $this->_checkedQuoteItems[$productId]['qty'] = $qty;
+ $this->_checkedQuoteItems[$productId]['items'][] = $quoteItemId;
+
+ return $qty;
+ }
+
+ /**
+ * Adds stock item qty to $items (creates new entry or increments existing one)
+ * $items is array with following structure:
+ * array(
+ * $productId => array(
+ * 'qty' => $qty,
+ * 'item' => $stockItems|null
+ * )
+ * )
+ *
+ * @param Mage_Sales_Model_Quote_Item $quoteItem
+ * @param array $items
+ */
+ protected function _addItemToQtyArray($quoteItem, &$items)
+ {
+ $productId = $quoteItem->getProductId();
+ if (!$productId) {
+ return;
+ }
+ if (isset($items[$productId])) {
+ $items[$productId]['qty'] += $quoteItem->getTotalQty();
+ } else {
+ $stockItem = null;
+ if ($quoteItem->getProduct()) {
+ $stockItem = $quoteItem->getProduct()->getStockItem();
+ }
+ $items[$productId] = [
+ 'item' => $stockItem,
+ 'qty' => $quoteItem->getTotalQty(),
+ ];
+ }
+ }
+
+ /**
+ * Prepare array with information about used product qty and product stock item
+ * result is:
+ * array(
+ * $productId => array(
+ * 'qty' => $qty,
+ * 'item' => $stockItems|null
+ * )
+ * )
+ * @param array $relatedItems
+ * @return array
+ */
+ protected function _getProductsQty($relatedItems)
+ {
+ $items = [];
+ foreach ($relatedItems as $item) {
+ $productId = $item->getProductId();
+ if (!$productId) {
+ continue;
+ }
+ $children = $item->getChildrenItems();
+ if ($children) {
+ foreach ($children as $childItem) {
+ $this->_addItemToQtyArray($childItem, $items);
+ }
+ } else {
+ $this->_addItemToQtyArray($item, $items);
+ }
+ }
+ return $items;
+ }
}
diff --git a/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock.php b/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock.php
index da69d84bcff..295ad3d731b 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock.php
@@ -37,11 +37,6 @@ class Mage_CatalogInventory_Model_Resource_Indexer_Stock extends Mage_Catalog_Mo
*/
protected $_defaultIndexer = 'cataloginventory/indexer_stock_default';
- protected function _construct()
- {
- $this->_init('cataloginventory/stock_status', 'product_id');
- }
-
/**
* Process stock item save action
*
@@ -236,6 +231,46 @@ public function reindexAll()
return $this;
}
+ /**
+ * Retrieve parent ids and types by child id
+ * Return array with key product_id and value as product type id
+ *
+ * @param int $childId
+ * @return array
+ */
+ public function getProductParentsByChild($childId)
+ {
+ $write = $this->_getWriteAdapter();
+ $select = $write->select()
+ ->from(['l' => $this->getTable('catalog/product_relation')], ['parent_id'])
+ ->join(
+ ['e' => $this->getTable('catalog/product')],
+ 'l.parent_id=e.entity_id',
+ ['e.type_id'],
+ )
+ ->where('l.child_id = :child_id');
+ return $write->fetchPairs($select, [':child_id' => $childId]);
+ }
+
+ /**
+ * Retrieve temporary index table name
+ *
+ * @param string $table
+ * @return string
+ */
+ public function getIdxTable($table = null)
+ {
+ if ($this->useIdxTable()) {
+ return $this->getTable('cataloginventory/stock_status_indexer_idx');
+ }
+ return $this->getTable('cataloginventory/stock_status_indexer_tmp');
+ }
+
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/stock_status', 'product_id');
+ }
+
/**
* Retrieve Stock Indexer Models per Product Type
*
@@ -273,39 +308,4 @@ protected function _getIndexer($productTypeId)
}
return $types[$productTypeId];
}
-
- /**
- * Retrieve parent ids and types by child id
- * Return array with key product_id and value as product type id
- *
- * @param int $childId
- * @return array
- */
- public function getProductParentsByChild($childId)
- {
- $write = $this->_getWriteAdapter();
- $select = $write->select()
- ->from(['l' => $this->getTable('catalog/product_relation')], ['parent_id'])
- ->join(
- ['e' => $this->getTable('catalog/product')],
- 'l.parent_id=e.entity_id',
- ['e.type_id'],
- )
- ->where('l.child_id = :child_id');
- return $write->fetchPairs($select, [':child_id' => $childId]);
- }
-
- /**
- * Retrieve temporary index table name
- *
- * @param string $table
- * @return string
- */
- public function getIdxTable($table = null)
- {
- if ($this->useIdxTable()) {
- return $this->getTable('cataloginventory/stock_status_indexer_idx');
- }
- return $this->getTable('cataloginventory/stock_status_indexer_tmp');
- }
}
diff --git a/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock/Default.php b/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock/Default.php
index e8d408e33be..15686a83857 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock/Default.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock/Default.php
@@ -36,11 +36,6 @@ class Mage_CatalogInventory_Model_Resource_Indexer_Stock_Default extends Mage_Ca
*/
protected $_isComposite = false;
- protected function _construct()
- {
- $this->_init('cataloginventory/stock_status', 'product_id');
- }
-
/**
* Reindex all stock status data for default logic product type
*
@@ -121,6 +116,25 @@ public function getIsComposite()
return $this->_isComposite;
}
+ /**
+ * Retrieve temporary index table name
+ *
+ * @param string $table
+ * @return string
+ */
+ public function getIdxTable($table = null)
+ {
+ if ($this->useIdxTable()) {
+ return $this->getTable('cataloginventory/stock_status_indexer_idx');
+ }
+ return $this->getTable('cataloginventory/stock_status_indexer_tmp');
+ }
+
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/stock_status', 'product_id');
+ }
+
/**
* Retrieve is Global Manage Stock enabled
*
@@ -257,18 +271,4 @@ protected function _updateIndexTable($data)
return $this;
}
-
- /**
- * Retrieve temporary index table name
- *
- * @param string $table
- * @return string
- */
- public function getIdxTable($table = null)
- {
- if ($this->useIdxTable()) {
- return $this->getTable('cataloginventory/stock_status_indexer_idx');
- }
- return $this->getTable('cataloginventory/stock_status_indexer_tmp');
- }
}
diff --git a/app/code/core/Mage/CatalogInventory/Model/Resource/Stock.php b/app/code/core/Mage/CatalogInventory/Model/Resource/Stock.php
index f9ebb4c7cf3..968aa7c32c1 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Resource/Stock.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Resource/Stock.php
@@ -71,11 +71,6 @@ class Mage_CatalogInventory_Model_Resource_Stock extends Mage_Core_Model_Resourc
*/
protected $_stock;
- protected function _construct()
- {
- $this->_init('cataloginventory/stock', 'stock_id');
- }
-
/**
* Lock product items
*
@@ -206,30 +201,6 @@ public function setInStockFilterToCollection($collection)
return $this;
}
- /**
- * Load some inventory configuration settings
- *
- */
- protected function _initConfig()
- {
- if (!$this->_isConfig) {
- $configMap = [
- '_isConfigManageStock' => Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MANAGE_STOCK,
- '_isConfigBackorders' => Mage_CatalogInventory_Model_Stock_Item::XML_PATH_BACKORDERS,
- '_configMinQty' => Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MIN_QTY,
- '_configNotifyStockQty' => Mage_CatalogInventory_Model_Stock_Item::XML_PATH_NOTIFY_STOCK_QTY,
- ];
-
- foreach ($configMap as $field => $const) {
- $this->$field = Mage::getStoreConfig($const);
- }
-
- $this->_isConfig = true;
- $this->_stock = Mage::getModel('cataloginventory/stock');
- $this->_configTypeIds = array_keys(Mage::helper('cataloginventory')->getIsQtyTypeIds(true));
- }
- }
-
/**
* Set items out of stock basing on their quantities and config settings
*
@@ -378,4 +349,33 @@ public function addLowStockFilter(Mage_Catalog_Model_Resource_Product_Collection
);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/stock', 'stock_id');
+ }
+
+ /**
+ * Load some inventory configuration settings
+ *
+ */
+ protected function _initConfig()
+ {
+ if (!$this->_isConfig) {
+ $configMap = [
+ '_isConfigManageStock' => Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MANAGE_STOCK,
+ '_isConfigBackorders' => Mage_CatalogInventory_Model_Stock_Item::XML_PATH_BACKORDERS,
+ '_configMinQty' => Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MIN_QTY,
+ '_configNotifyStockQty' => Mage_CatalogInventory_Model_Stock_Item::XML_PATH_NOTIFY_STOCK_QTY,
+ ];
+
+ foreach ($configMap as $field => $const) {
+ $this->$field = Mage::getStoreConfig($const);
+ }
+
+ $this->_isConfig = true;
+ $this->_stock = Mage::getModel('cataloginventory/stock');
+ $this->_configTypeIds = array_keys(Mage::helper('cataloginventory')->getIsQtyTypeIds(true));
+ }
+ }
}
diff --git a/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Item.php b/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Item.php
index b85a6871888..bd779670022 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Item.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Item.php
@@ -22,11 +22,6 @@
*/
class Mage_CatalogInventory_Model_Resource_Stock_Item extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('cataloginventory/stock_item', 'item_id');
- }
-
/**
* Loading stock item data by product
*
@@ -45,24 +40,6 @@ public function loadByProductId(Mage_CatalogInventory_Model_Stock_Item $item, $p
return $this;
}
- /**
- * Retrieve select object and join it to product entity table to get type ids
- *
- * @param string $field
- * @param mixed $value
- * @param Mage_CatalogInventory_Model_Stock_Item $object
- * @return Varien_Db_Select
- */
- protected function _getLoadSelect($field, $value, $object)
- {
- return parent::_getLoadSelect($field, $value, $object)
- ->join(
- ['p' => $this->getTable('catalog/product')],
- 'product_id=p.entity_id',
- ['type_id'],
- );
- }
-
/**
* Add join for catalog in stock field to product collection
*
@@ -88,6 +65,28 @@ public function addCatalogInventoryToProductCollection($productCollection)
);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/stock_item', 'item_id');
+ }
+
+ /**
+ * Retrieve select object and join it to product entity table to get type ids
+ *
+ * @param string $field
+ * @param mixed $value
+ * @param Mage_CatalogInventory_Model_Stock_Item $object
+ * @return Varien_Db_Select
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ return parent::_getLoadSelect($field, $value, $object)
+ ->join(
+ ['p' => $this->getTable('catalog/product')],
+ 'product_id=p.entity_id',
+ ['type_id'],
+ );
+ }
/**
* Use qty correction for qty column update
diff --git a/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Item/Collection.php b/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Item/Collection.php
index efac70bdcc1..fb7d2c42d8b 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Item/Collection.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Item/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_CatalogInventory_Model_Resource_Stock_Item_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('cataloginventory/stock_item');
- }
-
/**
* Add stock filter to collection
*
@@ -129,6 +124,10 @@ public function addQtyFilter($comparsionMethod, $qty)
return $this->addFieldToFilter('main_table.qty', [$methods[$comparsionMethod] => $qty]);
}
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/stock_item');
+ }
/**
* @inheritDoc
diff --git a/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Status.php b/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Status.php
index effdaa03ca8..0de88ff0f83 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Status.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Resource/Stock/Status.php
@@ -22,11 +22,6 @@
*/
class Mage_CatalogInventory_Model_Resource_Stock_Status extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('cataloginventory/stock_status', 'product_id');
- }
-
/**
* Save Product Status per website
*
@@ -250,4 +245,8 @@ public function addIsInStockFilterToCollection($collection)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/stock_status', 'product_id');
+ }
}
diff --git a/app/code/core/Mage/CatalogInventory/Model/Stock.php b/app/code/core/Mage/CatalogInventory/Model/Stock.php
index 6b268886f67..0e4019a466d 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Stock.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Stock.php
@@ -40,11 +40,6 @@ class Mage_CatalogInventory_Model_Stock extends Mage_Core_Model_Abstract
public const DEFAULT_STOCK_ID = 1;
- protected function _construct()
- {
- $this->_init('cataloginventory/stock');
- }
-
/**
* Retrieve stock identifier
*
@@ -92,29 +87,6 @@ public function getItemCollection()
->addStockFilter($this->getId());
}
- /**
- * Prepare array($productId=>$qty) based on array($productId => array('qty'=>$qty, 'item'=>$stockItem))
- *
- * @param array $items
- * @return array
- */
- protected function _prepareProductQtys($items)
- {
- $qtys = [];
- foreach ($items as $productId => $item) {
- if (empty($item['item'])) {
- $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
- } else {
- $stockItem = $item['item'];
- }
- $canSubtractQty = $stockItem->getId() && $stockItem->canSubtractQty();
- if ($canSubtractQty && Mage::helper('cataloginventory')->isQty($stockItem->getTypeId())) {
- $qtys[$productId] = $item['qty'];
- }
- }
- return $qtys;
- }
-
/**
* Subtract product qtys from stock.
* Return array of items that require full save
@@ -230,4 +202,32 @@ public function addInStockFilterToCollection($collection)
$this->getResource()->setInStockFilterToCollection($collection);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/stock');
+ }
+
+ /**
+ * Prepare array($productId=>$qty) based on array($productId => array('qty'=>$qty, 'item'=>$stockItem))
+ *
+ * @param array $items
+ * @return array
+ */
+ protected function _prepareProductQtys($items)
+ {
+ $qtys = [];
+ foreach ($items as $productId => $item) {
+ if (empty($item['item'])) {
+ $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
+ } else {
+ $stockItem = $item['item'];
+ }
+ $canSubtractQty = $stockItem->getId() && $stockItem->canSubtractQty();
+ if ($canSubtractQty && Mage::helper('cataloginventory')->isQty($stockItem->getTypeId())) {
+ $qtys[$productId] = $item['qty'];
+ }
+ }
+ return $qtys;
+ }
}
diff --git a/app/code/core/Mage/CatalogInventory/Model/Stock/Item.php b/app/code/core/Mage/CatalogInventory/Model/Stock/Item.php
index faa35607cfd..781268d2169 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Stock/Item.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Stock/Item.php
@@ -102,11 +102,6 @@ class Mage_CatalogInventory_Model_Stock_Item extends Mage_Core_Model_Abstract
public const ENTITY = 'cataloginventory_stock_item';
- /**
- * @var array
- */
- private $_minSaleQtyCache = [];
-
/**
* @var float|false
*/
@@ -149,25 +144,10 @@ class Mage_CatalogInventory_Model_Stock_Item extends Mage_Core_Model_Abstract
*/
protected $_processIndexEvents = true;
- protected function _construct()
- {
- $this->_init('cataloginventory/stock_item');
- }
-
/**
- * Init mapping array of short fields to
- * its full names
- *
- * @return void
+ * @var array
*/
- protected function _initOldFieldsMap()
- {
- // pre 1.6 fields names, old => new
- $this->_oldFieldsMap = [
- 'stock_status_changed_automatically' => 'stock_status_changed_auto',
- 'use_config_enable_qty_increments' => 'use_config_enable_qty_inc',
- ];
- }
+ private $_minSaleQtyCache = [];
/**
* Retrieve stock identifier
@@ -718,70 +698,6 @@ public function addCatalogInventoryToProductCollection($productCollection)
return $this;
}
- /**
- * Add error to Quote Item
- *
- * @param string $itemError
- * @param string $quoteError
- * @param string $errorIndex
- * @return $this
- */
- protected function _addQuoteItemError(
- Mage_Sales_Model_Quote_Item $item,
- $itemError,
- $quoteError,
- $errorIndex = 'error'
- ) {
- $item->setHasError(true);
- $item->setMessage($itemError);
- $item->setQuoteMessage($quoteError);
- $item->setQuoteMessageIndex($errorIndex);
- return $this;
- }
-
- /**
- * Before save prepare process
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- // see if quantity is defined for this item type
- $typeId = $this->getTypeId();
- if ($productTypeId = $this->getProductTypeId()) {
- $typeId = $productTypeId;
- }
-
- $isQty = Mage::helper('cataloginventory')->isQty($typeId);
-
- if ($isQty) {
- if (!$this->verifyStock()) {
- $this->setIsInStock(false)
- ->setStockStatusChangedAutomaticallyFlag(true);
- }
-
- // if qty is below notify qty, update the low stock date to today date otherwise set null
- $this->setLowStockDate(null);
- if ($this->verifyNotification()) {
- $this->setLowStockDate(Mage::app()->getLocale()->date(null, null, null, false)
- ->toString(Varien_Date::DATETIME_INTERNAL_FORMAT));
- }
-
- $this->setStockStatusChangedAutomatically(0);
- if ($this->hasStockStatusChangedAutomaticallyFlag()) {
- $this->setStockStatusChangedAutomatically((int) $this->getStockStatusChangedAutomaticallyFlag());
- }
- } else {
- $this->setQty(0);
- }
-
- if (!$this->hasData('stock_id')) {
- $this->setStockId($this->getStockId());
- }
-
- return $this;
- }
-
/**
* Chceck if item should be in stock or out of stock based on $qty param of existing item qty
*
@@ -939,4 +855,88 @@ public function afterCommitCallback()
}
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/stock_item');
+ }
+
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return void
+ */
+ protected function _initOldFieldsMap()
+ {
+ // pre 1.6 fields names, old => new
+ $this->_oldFieldsMap = [
+ 'stock_status_changed_automatically' => 'stock_status_changed_auto',
+ 'use_config_enable_qty_increments' => 'use_config_enable_qty_inc',
+ ];
+ }
+
+ /**
+ * Add error to Quote Item
+ *
+ * @param string $itemError
+ * @param string $quoteError
+ * @param string $errorIndex
+ * @return $this
+ */
+ protected function _addQuoteItemError(
+ Mage_Sales_Model_Quote_Item $item,
+ $itemError,
+ $quoteError,
+ $errorIndex = 'error'
+ ) {
+ $item->setHasError(true);
+ $item->setMessage($itemError);
+ $item->setQuoteMessage($quoteError);
+ $item->setQuoteMessageIndex($errorIndex);
+ return $this;
+ }
+
+ /**
+ * Before save prepare process
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ // see if quantity is defined for this item type
+ $typeId = $this->getTypeId();
+ if ($productTypeId = $this->getProductTypeId()) {
+ $typeId = $productTypeId;
+ }
+
+ $isQty = Mage::helper('cataloginventory')->isQty($typeId);
+
+ if ($isQty) {
+ if (!$this->verifyStock()) {
+ $this->setIsInStock(false)
+ ->setStockStatusChangedAutomaticallyFlag(true);
+ }
+
+ // if qty is below notify qty, update the low stock date to today date otherwise set null
+ $this->setLowStockDate(null);
+ if ($this->verifyNotification()) {
+ $this->setLowStockDate(Mage::app()->getLocale()->date(null, null, null, false)
+ ->toString(Varien_Date::DATETIME_INTERNAL_FORMAT));
+ }
+
+ $this->setStockStatusChangedAutomatically(0);
+ if ($this->hasStockStatusChangedAutomaticallyFlag()) {
+ $this->setStockStatusChangedAutomatically((int) $this->getStockStatusChangedAutomaticallyFlag());
+ }
+ } else {
+ $this->setQty(0);
+ }
+
+ if (!$this->hasData('stock_id')) {
+ $this->setStockId($this->getStockId());
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/CatalogInventory/Model/Stock/Status.php b/app/code/core/Mage/CatalogInventory/Model/Stock/Status.php
index c14509f1adf..9edb54223c9 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Stock/Status.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Stock/Status.php
@@ -52,15 +52,6 @@ class Mage_CatalogInventory_Model_Stock_Status extends Mage_Core_Model_Abstract
*/
protected $_websites;
- /**
- * Init resource model
- *
- */
- protected function _construct()
- {
- $this->_init('cataloginventory/stock_status');
- }
-
/**
* Retrieve Product Type Instances
* as key - type code, value - instance model
@@ -250,123 +241,6 @@ public function updateStatus($productId, $productType = null, $websiteId = null)
return $this;
}
- /**
- * Process children stock status
- *
- * @param int $productId
- * @param string $productType
- * @param int|float $qty
- * @param int $status
- * @param int $stockId
- * @param int $websiteId
- *
- * @return $this
- */
- protected function _processChildren(
- $productId,
- $productType,
- $qty = 0,
- $status = self::STATUS_IN_STOCK,
- $stockId = 1,
- $websiteId = null
- ) {
- if ($status == self::STATUS_OUT_OF_STOCK) {
- $this->saveProductStatus($productId, $status, $qty, $stockId, $websiteId);
- return $this;
- }
-
- $statuses = [];
- $websites = $this->getWebsites($websiteId);
-
- foreach (array_keys($websites) as $websiteId) {
- $statuses[$websiteId] = $status;
- }
-
- if (!$typeInstance = $this->getProductTypeInstance($productType)) {
- return $this;
- }
-
- $requiredChildrenIds = $typeInstance->getChildrenIds($productId, true);
- if ($requiredChildrenIds) {
- $childrenIds = [];
- foreach ($requiredChildrenIds as $groupedChildrenIds) {
- $childrenIds = array_merge($childrenIds, $groupedChildrenIds);
- }
- $childrenWebsites = Mage::getSingleton('catalog/product_website')
- ->getWebsites($childrenIds);
- foreach ($websites as $websiteId => $storeId) {
- $childrenStatus = $this->getProductStatusModel()
- ->getProductStatus($childrenIds, $storeId);
- $childrenStock = $this->getProductStatus($childrenIds, $websiteId, $stockId);
-
- $websiteStatus = $statuses[$websiteId];
- foreach ($requiredChildrenIds as $groupedChildrenIds) {
- $optionStatus = false;
- foreach ($groupedChildrenIds as $childId) {
- if (isset($childrenStatus[$childId])
- && isset($childrenWebsites[$childId])
- && in_array($websiteId, $childrenWebsites[$childId])
- && $childrenStatus[$childId] == $this->getProductStatusEnabled()
- && isset($childrenStock[$childId])
- && $childrenStock[$childId] == self::STATUS_IN_STOCK
- ) {
- $optionStatus = true;
- }
- }
- $websiteStatus = $websiteStatus && $optionStatus;
- }
- $statuses[$websiteId] = (int) $websiteStatus;
- }
- }
-
- foreach ($statuses as $websiteId => $websiteStatus) {
- $this->saveProductStatus($productId, $websiteStatus, $qty, $stockId, $websiteId);
- }
-
- return $this;
- }
-
- /**
- * Process Parents by child
- *
- * @param int $productId
- * @param int $stockId
- * @param int $websiteId
- * @return $this
- */
- protected function _processParents($productId, $stockId = 1, $websiteId = null)
- {
- $parentIds = [];
- foreach ($this->getProductTypeInstances() as $typeInstance) {
- /** @var Mage_Catalog_Model_Product_Type_Abstract $typeInstance */
- $parentIds = array_merge($parentIds, $typeInstance->getParentIdsByChild($productId));
- }
-
- if (!$parentIds) {
- return $this;
- }
-
- $productTypes = $this->getProductsType($parentIds);
- $item = $this->getStockItemModel();
-
- foreach ($parentIds as $parentId) {
- $parentType = $productTypes[$parentId] ?? null;
- $item->setData(['stock_id' => $stockId])
- ->setOrigData()
- ->loadByProduct($parentId);
- $status = self::STATUS_IN_STOCK;
- $qty = 0;
- if ($item->getId()) {
- $status = $item->getIsInStock();
- $qty = $item->getQty();
- }
-
- $this->_processChildren($parentId, $parentType, $qty, $status, $item->getStockId(), $websiteId);
- }
-
- return $this;
- }
-
/**
* Save product status per website
* if website is null, saved for all websites
@@ -517,4 +391,130 @@ public function addIsInStockFilterToCollection($collection)
$this->_getResource()->addIsInStockFilterToCollection($collection);
return $this;
}
+
+ /**
+ * Init resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('cataloginventory/stock_status');
+ }
+
+ /**
+ * Process children stock status
+ *
+ * @param int $productId
+ * @param string $productType
+ * @param int|float $qty
+ * @param int $status
+ * @param int $stockId
+ * @param int $websiteId
+ *
+ * @return $this
+ */
+ protected function _processChildren(
+ $productId,
+ $productType,
+ $qty = 0,
+ $status = self::STATUS_IN_STOCK,
+ $stockId = 1,
+ $websiteId = null
+ ) {
+ if ($status == self::STATUS_OUT_OF_STOCK) {
+ $this->saveProductStatus($productId, $status, $qty, $stockId, $websiteId);
+ return $this;
+ }
+
+ $statuses = [];
+ $websites = $this->getWebsites($websiteId);
+
+ foreach (array_keys($websites) as $websiteId) {
+ $statuses[$websiteId] = $status;
+ }
+
+ if (!$typeInstance = $this->getProductTypeInstance($productType)) {
+ return $this;
+ }
+
+ $requiredChildrenIds = $typeInstance->getChildrenIds($productId, true);
+ if ($requiredChildrenIds) {
+ $childrenIds = [];
+ foreach ($requiredChildrenIds as $groupedChildrenIds) {
+ $childrenIds = array_merge($childrenIds, $groupedChildrenIds);
+ }
+ $childrenWebsites = Mage::getSingleton('catalog/product_website')
+ ->getWebsites($childrenIds);
+ foreach ($websites as $websiteId => $storeId) {
+ $childrenStatus = $this->getProductStatusModel()
+ ->getProductStatus($childrenIds, $storeId);
+ $childrenStock = $this->getProductStatus($childrenIds, $websiteId, $stockId);
+
+ $websiteStatus = $statuses[$websiteId];
+ foreach ($requiredChildrenIds as $groupedChildrenIds) {
+ $optionStatus = false;
+ foreach ($groupedChildrenIds as $childId) {
+ if (isset($childrenStatus[$childId])
+ && isset($childrenWebsites[$childId])
+ && in_array($websiteId, $childrenWebsites[$childId])
+ && $childrenStatus[$childId] == $this->getProductStatusEnabled()
+ && isset($childrenStock[$childId])
+ && $childrenStock[$childId] == self::STATUS_IN_STOCK
+ ) {
+ $optionStatus = true;
+ }
+ }
+ $websiteStatus = $websiteStatus && $optionStatus;
+ }
+ $statuses[$websiteId] = (int) $websiteStatus;
+ }
+ }
+
+ foreach ($statuses as $websiteId => $websiteStatus) {
+ $this->saveProductStatus($productId, $websiteStatus, $qty, $stockId, $websiteId);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Process Parents by child
+ *
+ * @param int $productId
+ * @param int $stockId
+ * @param int $websiteId
+ * @return $this
+ */
+ protected function _processParents($productId, $stockId = 1, $websiteId = null)
+ {
+ $parentIds = [];
+ foreach ($this->getProductTypeInstances() as $typeInstance) {
+ /** @var Mage_Catalog_Model_Product_Type_Abstract $typeInstance */
+ $parentIds = array_merge($parentIds, $typeInstance->getParentIdsByChild($productId));
+ }
+
+ if (!$parentIds) {
+ return $this;
+ }
+
+ $productTypes = $this->getProductsType($parentIds);
+ $item = $this->getStockItemModel();
+
+ foreach ($parentIds as $parentId) {
+ $parentType = $productTypes[$parentId] ?? null;
+ $item->setData(['stock_id' => $stockId])
+ ->setOrigData()
+ ->loadByProduct($parentId);
+ $status = self::STATUS_IN_STOCK;
+ $qty = 0;
+ if ($item->getId()) {
+ $status = $item->getIsInStock();
+ $qty = $item->getQty();
+ }
+
+ $this->_processChildren($parentId, $parentType, $qty, $status, $item->getStockId(), $websiteId);
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/CatalogRule/Model/Action/Index/Refresh.php b/app/code/core/Mage/CatalogRule/Model/Action/Index/Refresh.php
index 7df431dc22c..7e018fde204 100644
--- a/app/code/core/Mage/CatalogRule/Model/Action/Index/Refresh.php
+++ b/app/code/core/Mage/CatalogRule/Model/Action/Index/Refresh.php
@@ -66,6 +66,27 @@ public function __construct(array $args)
$this->_app = !empty($args['app']) ? $args['app'] : Mage::app();
}
+ /**
+ * Run reindex
+ */
+ public function execute()
+ {
+ $this->_app->dispatchEvent('catalogrule_before_apply', ['resource' => $this->_resource]);
+
+ /** @var Mage_Core_Model_Date $coreDate */
+ $coreDate = $this->_factory->getModel('core/date');
+ $timestamp = $coreDate->gmtTimestamp();
+
+ foreach ($this->_app->getWebsites(false) as $website) {
+ if ($website->getDefaultStore()) {
+ $this->_reindex($website, $timestamp);
+ }
+ }
+
+ $this->_prepareGroupWebsite($timestamp);
+ $this->_prepareAffectedProduct();
+ }
+
/**
* Set connection
*/
@@ -90,27 +111,6 @@ protected function _setResource(Mage_Core_Model_Resource_Db_Abstract $resource)
$this->_resource = $resource;
}
- /**
- * Run reindex
- */
- public function execute()
- {
- $this->_app->dispatchEvent('catalogrule_before_apply', ['resource' => $this->_resource]);
-
- /** @var Mage_Core_Model_Date $coreDate */
- $coreDate = $this->_factory->getModel('core/date');
- $timestamp = $coreDate->gmtTimestamp();
-
- foreach ($this->_app->getWebsites(false) as $website) {
- if ($website->getDefaultStore()) {
- $this->_reindex($website, $timestamp);
- }
- }
-
- $this->_prepareGroupWebsite($timestamp);
- $this->_prepareAffectedProduct();
- }
-
/**
* Return temporary table name
*
diff --git a/app/code/core/Mage/CatalogRule/Model/Observer.php b/app/code/core/Mage/CatalogRule/Model/Observer.php
index 30a1889ed23..b35a3c59350 100644
--- a/app/code/core/Mage/CatalogRule/Model/Observer.php
+++ b/app/code/core/Mage/CatalogRule/Model/Observer.php
@@ -298,64 +298,6 @@ public function prepareCatalogProductPriceIndexTable(Varien_Event_Observer $obse
return $this;
}
- /**
- * Check rules that contains affected attribute
- * If rules were found they will be set to inactive and notice will be add to admin session
- *
- * @param string $attributeCode
- *
- * @return $this
- */
- protected function _checkCatalogRulesAvailability($attributeCode)
- {
- /** @var Mage_CatalogRule_Model_Resource_Rule_Collection $collection */
- $collection = Mage::getResourceModel('catalogrule/rule_collection')
- ->addAttributeInConditionFilter($attributeCode);
-
- $disabledRulesCount = 0;
- foreach ($collection as $rule) {
- /** @var Mage_CatalogRule_Model_Rule $rule */
- $rule->setIsActive(0);
- /** @var $rule->getConditions() Mage_CatalogRule_Model_Rule_Condition_Combine */
- $this->_removeAttributeFromConditions($rule->getConditions(), $attributeCode);
- $rule->save();
-
- $disabledRulesCount++;
- }
-
- if ($disabledRulesCount) {
- Mage::getModel('catalogrule/rule')->applyAll();
- Mage::getSingleton('adminhtml/session')->addWarning(
- Mage::helper('catalogrule')->__('%d Catalog Price Rules based on "%s" attribute have been disabled.', $disabledRulesCount, $attributeCode),
- );
- }
-
- return $this;
- }
-
- /**
- * Remove catalog attribute condition by attribute code from rule conditions
- *
- * @param Mage_CatalogRule_Model_Rule_Condition_Combine $combine
- *
- * @param string $attributeCode
- */
- protected function _removeAttributeFromConditions($combine, $attributeCode)
- {
- $conditions = $combine->getConditions();
- foreach ($conditions as $conditionId => $condition) {
- if ($condition instanceof Mage_CatalogRule_Model_Rule_Condition_Combine) {
- $this->_removeAttributeFromConditions($condition, $attributeCode);
- }
- if ($condition instanceof Mage_Rule_Model_Condition_Product_Abstract) {
- if ($condition->getAttribute() == $attributeCode) {
- unset($conditions[$conditionId]);
- }
- }
- }
- $combine->setConditions($conditions);
- }
-
/**
* After save attribute if it is not used for promo rules already check rules for containing this attribute
*
@@ -471,6 +413,64 @@ public function runCatalogProductPriceReindex(Varien_Event_Observer $observer)
}
}
+ /**
+ * Check rules that contains affected attribute
+ * If rules were found they will be set to inactive and notice will be add to admin session
+ *
+ * @param string $attributeCode
+ *
+ * @return $this
+ */
+ protected function _checkCatalogRulesAvailability($attributeCode)
+ {
+ /** @var Mage_CatalogRule_Model_Resource_Rule_Collection $collection */
+ $collection = Mage::getResourceModel('catalogrule/rule_collection')
+ ->addAttributeInConditionFilter($attributeCode);
+
+ $disabledRulesCount = 0;
+ foreach ($collection as $rule) {
+ /** @var Mage_CatalogRule_Model_Rule $rule */
+ $rule->setIsActive(0);
+ /** @var $rule->getConditions() Mage_CatalogRule_Model_Rule_Condition_Combine */
+ $this->_removeAttributeFromConditions($rule->getConditions(), $attributeCode);
+ $rule->save();
+
+ $disabledRulesCount++;
+ }
+
+ if ($disabledRulesCount) {
+ Mage::getModel('catalogrule/rule')->applyAll();
+ Mage::getSingleton('adminhtml/session')->addWarning(
+ Mage::helper('catalogrule')->__('%d Catalog Price Rules based on "%s" attribute have been disabled.', $disabledRulesCount, $attributeCode),
+ );
+ }
+
+ return $this;
+ }
+
+ /**
+ * Remove catalog attribute condition by attribute code from rule conditions
+ *
+ * @param Mage_CatalogRule_Model_Rule_Condition_Combine $combine
+ *
+ * @param string $attributeCode
+ */
+ protected function _removeAttributeFromConditions($combine, $attributeCode)
+ {
+ $conditions = $combine->getConditions();
+ foreach ($conditions as $conditionId => $condition) {
+ if ($condition instanceof Mage_CatalogRule_Model_Rule_Condition_Combine) {
+ $this->_removeAttributeFromConditions($condition, $attributeCode);
+ }
+ if ($condition instanceof Mage_Rule_Model_Condition_Product_Abstract) {
+ if ($condition->getAttribute() == $attributeCode) {
+ unset($conditions[$conditionId]);
+ }
+ }
+ }
+ $combine->setConditions($conditions);
+ }
+
/**
* Generate key for rule prices
*
diff --git a/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php b/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php
index c486b8ab2a2..0a9161db778 100644
--- a/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php
+++ b/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php
@@ -77,57 +77,6 @@ public function __construct(array $args = [])
parent::__construct();
}
- /**
- * Initialize main table and table id field
- */
- protected function _construct()
- {
- $this->_init('catalogrule/rule', 'rule_id');
- }
-
- /**
- * Add customer group ids and website ids to rule data after load
- *
- *
- * @inheritDoc
- */
- protected function _afterLoad(Mage_Core_Model_Abstract $object)
- {
- $object->setData('customer_group_ids', (array) $this->getCustomerGroupIds($object->getId()));
- $object->setData('website_ids', (array) $this->getWebsiteIds($object->getId()));
-
- return parent::_afterLoad($object);
- }
-
- /**
- * Bind catalog rule to customer group(s) and website(s).
- * Update products which are matched for rule.
- *
- *
- * @return $this
- */
- protected function _afterSave(Mage_Core_Model_Abstract $object)
- {
- if ($object->hasWebsiteIds()) {
- $websiteIds = $object->getWebsiteIds();
- if (!is_array($websiteIds)) {
- $websiteIds = explode(',', (string) $websiteIds);
- }
- $this->bindRuleToEntity($object->getId(), $websiteIds, 'website');
- }
-
- if ($object->hasCustomerGroupIds()) {
- $customerGroupIds = $object->getCustomerGroupIds();
- if (!is_array($customerGroupIds)) {
- $customerGroupIds = explode(',', (string) $customerGroupIds);
- }
- $this->bindRuleToEntity($object->getId(), $customerGroupIds, 'customer_group');
- }
-
- parent::_afterSave($object);
- return $this;
- }
-
/**
* Deletes records in catalogrule/product_data by rule ID and product IDs
*
@@ -423,6 +372,235 @@ public function deleteOldData($date, $productId = null)
return $this;
}
+ /**
+ * Generate catalog price rules prices for specified date range
+ * If from date is not defined - will be used previous day by UTC
+ * If to date is not defined - will be used next day by UTC
+ *
+ * @param int|Mage_Catalog_Model_Product $product
+ *
+ * @throws Exception
+ * @return $this
+ */
+ public function applyAllRules($product = null)
+ {
+ $this->_reindexCatalogRule($product);
+ return $this;
+ }
+
+ /**
+ * Generate catalog price rules prices for specified date range
+ * If from date is not defined - will be used previous day by UTC
+ * If to date is not defined - will be used next day by UTC
+ *
+ * @param int|string|null $fromDate
+ * @param int|string|null $toDate
+ * @param int $productId
+ *
+ * @deprecated after 1.7.0.2 use method applyAllRules
+ *
+ * @return $this
+ */
+ public function applyAllRulesForDateRange($fromDate = null, $toDate = null, $productId = null)
+ {
+ return $this->applyAllRules($productId);
+ }
+
+ /**
+ * Get catalog rules product price for specific date, website and
+ * customer group
+ *
+ * @param int|string $date
+ * @param int $wId
+ * @param int $gId
+ * @param int $pId
+ *
+ * @return float|bool
+ */
+ public function getRulePrice($date, $wId, $gId, $pId)
+ {
+ $data = $this->getRulePrices($date, $wId, $gId, [$pId]);
+ return $data[$pId] ?? false;
+ }
+
+ /**
+ * Retrieve product prices by catalog rule for specific date, website and customer group
+ * Collect data with product Id => price pairs
+ *
+ * @param int|string $date
+ * @param int $websiteId
+ * @param int $customerGroupId
+ * @param array $productIds
+ *
+ * @return array
+ */
+ public function getRulePrices($date, $websiteId, $customerGroupId, $productIds)
+ {
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from($this->getTable('catalogrule/rule_product_price'), ['product_id', 'rule_price'])
+ ->where('rule_date = ?', $this->formatDate($date, false))
+ ->where('website_id = ?', $websiteId)
+ ->where('customer_group_id = ?', $customerGroupId)
+ ->where('product_id IN(?)', $productIds);
+ return $adapter->fetchPairs($select);
+ }
+
+ /**
+ * Get active rule data based on few filters
+ *
+ * @param int|string $date
+ * @param int $websiteId
+ * @param int $customerGroupId
+ * @param int $productId
+ * @return array
+ */
+ public function getRulesFromProduct($date, $websiteId, $customerGroupId, $productId)
+ {
+ $adapter = $this->_getReadAdapter();
+ if (is_string($date)) {
+ $date = strtotime($date);
+ }
+ $select = $adapter->select()
+ ->from($this->getTable('catalogrule/rule_product'))
+ ->where('website_id = ?', $websiteId)
+ ->where('customer_group_id = ?', $customerGroupId)
+ ->where('product_id = ?', $productId)
+ ->where('from_time = 0 or from_time < ?', $date)
+ ->where('to_time = 0 or to_time > ?', $date)
+ ->order('sort_order');
+
+ return $adapter->fetchAll($select);
+ }
+
+ /**
+ * Retrieve product price data for all customer groups
+ *
+ * @param int|string $date
+ * @param int $wId
+ * @param int $pId
+ *
+ * @return array
+ */
+ public function getRulesForProduct($date, $wId, $pId)
+ {
+ $read = $this->_getReadAdapter();
+ $select = $read->select()
+ ->from($this->getTable('catalogrule/rule_product_price'), '*')
+ ->where('rule_date=?', $this->formatDate($date, false))
+ ->where('website_id=?', $wId)
+ ->where('product_id=?', $pId);
+
+ return $read->fetchAll($select);
+ }
+
+ /**
+ * Apply catalog rule to product
+ *
+ * @param Mage_CatalogRule_Model_Rule $rule
+ * @param Mage_Catalog_Model_Product $product
+ * @param array $websiteIds
+ *
+ * @throws Exception
+ * @return $this
+ */
+ public function applyToProduct($rule, $product, $websiteIds)
+ {
+ if (!$rule->getIsActive()) {
+ return $this;
+ }
+
+ $ruleId = $rule->getId();
+ $productId = $product->getId();
+
+ $write = $this->_getWriteAdapter();
+ $write->beginTransaction();
+ try {
+ if ($this->_isProductMatchedRule($ruleId, $product)) {
+ $this->cleanProductData($ruleId, [$productId]);
+ }
+ if ($this->validateProduct($rule, $product, $websiteIds)) {
+ $this->insertRuleData($rule, $websiteIds, [
+ $productId => array_combine(array_values($websiteIds), array_values($websiteIds))]);
+ } else {
+ $write->delete($this->getTable('catalogrule/rule_product_price'), [
+ $write->quoteInto('product_id = ?', $productId),
+ ]);
+ }
+
+ $write->commit();
+ } catch (Exception $e) {
+ $write->rollBack();
+ throw $e;
+ }
+ return $this;
+ }
+
+ /**
+ * Get ids of matched rules for specific product
+ *
+ * @param int $productId
+ * @return array
+ */
+ public function getProductRuleIds($productId)
+ {
+ $read = $this->_getReadAdapter();
+ $select = $read->select()->from($this->getTable('catalogrule/rule_product'), 'rule_id');
+ $select->where('product_id = ?', $productId);
+ return array_flip($read->fetchCol($select));
+ }
+
+ /**
+ * Initialize main table and table id field
+ */
+ protected function _construct()
+ {
+ $this->_init('catalogrule/rule', 'rule_id');
+ }
+
+ /**
+ * Add customer group ids and website ids to rule data after load
+ *
+ *
+ * @inheritDoc
+ */
+ protected function _afterLoad(Mage_Core_Model_Abstract $object)
+ {
+ $object->setData('customer_group_ids', (array) $this->getCustomerGroupIds($object->getId()));
+ $object->setData('website_ids', (array) $this->getWebsiteIds($object->getId()));
+
+ return parent::_afterLoad($object);
+ }
+
+ /**
+ * Bind catalog rule to customer group(s) and website(s).
+ * Update products which are matched for rule.
+ *
+ *
+ * @return $this
+ */
+ protected function _afterSave(Mage_Core_Model_Abstract $object)
+ {
+ if ($object->hasWebsiteIds()) {
+ $websiteIds = $object->getWebsiteIds();
+ if (!is_array($websiteIds)) {
+ $websiteIds = explode(',', (string) $websiteIds);
+ }
+ $this->bindRuleToEntity($object->getId(), $websiteIds, 'website');
+ }
+
+ if ($object->hasCustomerGroupIds()) {
+ $customerGroupIds = $object->getCustomerGroupIds();
+ if (!is_array($customerGroupIds)) {
+ $customerGroupIds = explode(',', (string) $customerGroupIds);
+ }
+ $this->bindRuleToEntity($object->getId(), $customerGroupIds, 'customer_group');
+ }
+
+ parent::_afterSave($object);
+ return $this;
+ }
+
/**
* Get DB resource statement for processing query result
*
@@ -519,40 +697,6 @@ protected function _getRuleProductsStmt($fromDate, $toDate, $productId = null, $
return $read->query($select);
}
- /**
- * Generate catalog price rules prices for specified date range
- * If from date is not defined - will be used previous day by UTC
- * If to date is not defined - will be used next day by UTC
- *
- * @param int|Mage_Catalog_Model_Product $product
- *
- * @throws Exception
- * @return $this
- */
- public function applyAllRules($product = null)
- {
- $this->_reindexCatalogRule($product);
- return $this;
- }
-
- /**
- * Generate catalog price rules prices for specified date range
- * If from date is not defined - will be used previous day by UTC
- * If to date is not defined - will be used next day by UTC
- *
- * @param int|string|null $fromDate
- * @param int|string|null $toDate
- * @param int $productId
- *
- * @deprecated after 1.7.0.2 use method applyAllRules
- *
- * @return $this
- */
- public function applyAllRulesForDateRange($fromDate = null, $toDate = null, $productId = null)
- {
- return $this->applyAllRules($productId);
- }
-
/**
* Run reindex
*
@@ -642,150 +786,6 @@ protected function _saveRuleProductPrices($arrData)
return $this;
}
- /**
- * Get catalog rules product price for specific date, website and
- * customer group
- *
- * @param int|string $date
- * @param int $wId
- * @param int $gId
- * @param int $pId
- *
- * @return float|bool
- */
- public function getRulePrice($date, $wId, $gId, $pId)
- {
- $data = $this->getRulePrices($date, $wId, $gId, [$pId]);
- return $data[$pId] ?? false;
- }
-
- /**
- * Retrieve product prices by catalog rule for specific date, website and customer group
- * Collect data with product Id => price pairs
- *
- * @param int|string $date
- * @param int $websiteId
- * @param int $customerGroupId
- * @param array $productIds
- *
- * @return array
- */
- public function getRulePrices($date, $websiteId, $customerGroupId, $productIds)
- {
- $adapter = $this->_getReadAdapter();
- $select = $adapter->select()
- ->from($this->getTable('catalogrule/rule_product_price'), ['product_id', 'rule_price'])
- ->where('rule_date = ?', $this->formatDate($date, false))
- ->where('website_id = ?', $websiteId)
- ->where('customer_group_id = ?', $customerGroupId)
- ->where('product_id IN(?)', $productIds);
- return $adapter->fetchPairs($select);
- }
-
- /**
- * Get active rule data based on few filters
- *
- * @param int|string $date
- * @param int $websiteId
- * @param int $customerGroupId
- * @param int $productId
- * @return array
- */
- public function getRulesFromProduct($date, $websiteId, $customerGroupId, $productId)
- {
- $adapter = $this->_getReadAdapter();
- if (is_string($date)) {
- $date = strtotime($date);
- }
- $select = $adapter->select()
- ->from($this->getTable('catalogrule/rule_product'))
- ->where('website_id = ?', $websiteId)
- ->where('customer_group_id = ?', $customerGroupId)
- ->where('product_id = ?', $productId)
- ->where('from_time = 0 or from_time < ?', $date)
- ->where('to_time = 0 or to_time > ?', $date)
- ->order('sort_order');
-
- return $adapter->fetchAll($select);
- }
-
- /**
- * Retrieve product price data for all customer groups
- *
- * @param int|string $date
- * @param int $wId
- * @param int $pId
- *
- * @return array
- */
- public function getRulesForProduct($date, $wId, $pId)
- {
- $read = $this->_getReadAdapter();
- $select = $read->select()
- ->from($this->getTable('catalogrule/rule_product_price'), '*')
- ->where('rule_date=?', $this->formatDate($date, false))
- ->where('website_id=?', $wId)
- ->where('product_id=?', $pId);
-
- return $read->fetchAll($select);
- }
-
- /**
- * Apply catalog rule to product
- *
- * @param Mage_CatalogRule_Model_Rule $rule
- * @param Mage_Catalog_Model_Product $product
- * @param array $websiteIds
- *
- * @throws Exception
- * @return $this
- */
- public function applyToProduct($rule, $product, $websiteIds)
- {
- if (!$rule->getIsActive()) {
- return $this;
- }
-
- $ruleId = $rule->getId();
- $productId = $product->getId();
-
- $write = $this->_getWriteAdapter();
- $write->beginTransaction();
- try {
- if ($this->_isProductMatchedRule($ruleId, $product)) {
- $this->cleanProductData($ruleId, [$productId]);
- }
- if ($this->validateProduct($rule, $product, $websiteIds)) {
- $this->insertRuleData($rule, $websiteIds, [
- $productId => array_combine(array_values($websiteIds), array_values($websiteIds))]);
- } else {
- $write->delete($this->getTable('catalogrule/rule_product_price'), [
- $write->quoteInto('product_id = ?', $productId),
- ]);
- }
-
- $write->commit();
- } catch (Exception $e) {
- $write->rollBack();
- throw $e;
- }
- return $this;
- }
-
- /**
- * Get ids of matched rules for specific product
- *
- * @param int $productId
- * @return array
- */
- public function getProductRuleIds($productId)
- {
- $read = $this->_getReadAdapter();
- $select = $read->select()->from($this->getTable('catalogrule/rule_product'), 'rule_id');
- $select->where('product_id = ?', $productId);
- return array_flip($read->fetchCol($select));
- }
-
/**
* Is product has been matched the rule
*
diff --git a/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Collection.php b/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Collection.php
index 1b659fe4353..278a9c7ef5e 100644
--- a/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Collection.php
+++ b/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Collection.php
@@ -33,14 +33,6 @@ class Mage_CatalogRule_Model_Resource_Rule_Collection extends Mage_Rule_Model_Re
],
];
- /**
- * Set resource model
- */
- protected function _construct()
- {
- $this->_init('catalogrule/rule');
- }
-
/**
* Find product attribute in conditions or actions
*
@@ -54,4 +46,12 @@ public function addAttributeInConditionFilter($attributeCode)
return $this;
}
+
+ /**
+ * Set resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('catalogrule/rule');
+ }
}
diff --git a/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Product/Price.php b/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Product/Price.php
index 453724cf2d2..f42bd345526 100644
--- a/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Product/Price.php
+++ b/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Product/Price.php
@@ -22,11 +22,6 @@
*/
class Mage_CatalogRule_Model_Resource_Rule_Product_Price extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('catalogrule/rule_product_price', 'rule_product_price_id');
- }
-
/**
* Apply price rule price to price index table
*
@@ -78,4 +73,8 @@ public function applyPriceRuleToIndexTable(
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('catalogrule/rule_product_price', 'rule_product_price_id');
+ }
}
diff --git a/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Product/Price/Collection.php b/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Product/Price/Collection.php
index 89796eba4ba..62d02d32479 100644
--- a/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Product/Price/Collection.php
+++ b/app/code/core/Mage/CatalogRule/Model/Resource/Rule/Product/Price/Collection.php
@@ -20,12 +20,6 @@
*/
class Mage_CatalogRule_Model_Resource_Rule_Product_Price_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- parent::_construct();
- $this->_init('catalogrule/rule_product_price');
- }
-
/**
* @return array
*/
@@ -40,4 +34,9 @@ public function getProductIds()
$idsSelect->distinct(true);
return $this->getConnection()->fetchCol($idsSelect);
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('catalogrule/rule_product_price');
+ }
}
diff --git a/app/code/core/Mage/CatalogRule/Model/Rule.php b/app/code/core/Mage/CatalogRule/Model/Rule.php
index 7cae8e9606e..8670c731e50 100644
--- a/app/code/core/Mage/CatalogRule/Model/Rule.php
+++ b/app/code/core/Mage/CatalogRule/Model/Rule.php
@@ -136,16 +136,6 @@ public function __construct(array $args = [])
parent::__construct();
}
- /**
- * Init resource model and id field
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_init('catalogrule/rule');
- $this->setIdFieldName('rule_id');
- }
-
/**
* Getter for rule conditions collection
*
@@ -254,22 +244,6 @@ public function callbackValidateProduct($args)
$this->_productIds[$product->getId()] = $results;
}
- /**
- * Prepare website to default assigned store map
- *
- * @return array
- */
- protected function _getWebsitesMap()
- {
- $map = [];
- foreach ($this->_app->getWebsites(true) as $website) {
- if ($website->getDefaultStore()) {
- $map[$website->getId()] = $website->getDefaultStore()->getId();
- }
- }
- return $map;
- }
-
/**
* Apply rule to product
*
@@ -422,21 +396,6 @@ public function getProductsFilter()
return $this->_productsFilter;
}
- /**
- * Invalidate related cache types
- *
- * @return $this
- */
- protected function _invalidateCache()
- {
- $types = $this->_config->getNode(self::XML_NODE_RELATED_CACHE);
- if ($types) {
- $types = $types->asArray();
- $this->_app->getCacheInstance()->invalidateType(array_keys($types));
- }
- return $this;
- }
-
/**
* @deprecated after 1.11.2.0
*
@@ -482,4 +441,45 @@ public function loadProductRules(Mage_Catalog_Model_Product $product)
}
return $this;
}
+
+ /**
+ * Init resource model and id field
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('catalogrule/rule');
+ $this->setIdFieldName('rule_id');
+ }
+
+ /**
+ * Prepare website to default assigned store map
+ *
+ * @return array
+ */
+ protected function _getWebsitesMap()
+ {
+ $map = [];
+ foreach ($this->_app->getWebsites(true) as $website) {
+ if ($website->getDefaultStore()) {
+ $map[$website->getId()] = $website->getDefaultStore()->getId();
+ }
+ }
+ return $map;
+ }
+
+ /**
+ * Invalidate related cache types
+ *
+ * @return $this
+ */
+ protected function _invalidateCache()
+ {
+ $types = $this->_config->getNode(self::XML_NODE_RELATED_CACHE);
+ if ($types) {
+ $types = $types->asArray();
+ $this->_app->getCacheInstance()->invalidateType(array_keys($types));
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/CatalogRule/Model/Rule/Product/Price.php b/app/code/core/Mage/CatalogRule/Model/Rule/Product/Price.php
index b3479586172..7f7c0547c55 100644
--- a/app/code/core/Mage/CatalogRule/Model/Rule/Product/Price.php
+++ b/app/code/core/Mage/CatalogRule/Model/Rule/Product/Price.php
@@ -39,11 +39,6 @@
*/
class Mage_CatalogRule_Model_Rule_Product_Price extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('catalogrule/rule_product_price');
- }
-
/**
* Apply price rule price to price index table
*
@@ -76,4 +71,8 @@ public function applyPriceRuleToIndexTable(
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('catalogrule/rule_product_price');
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Block/Advanced/Form.php b/app/code/core/Mage/CatalogSearch/Block/Advanced/Form.php
index 6b07cf28913..2e5b009a8fb 100644
--- a/app/code/core/Mage/CatalogSearch/Block/Advanced/Form.php
+++ b/app/code/core/Mage/CatalogSearch/Block/Advanced/Form.php
@@ -231,32 +231,6 @@ public function getAttributeYesNoElement($attribute)
->getHtml();
}
- /**
- * @return Mage_Core_Block_Abstract|Mage_Core_Block_Html_Select
- */
- protected function _getSelectBlock()
- {
- $block = $this->getData('_select_block');
- if (is_null($block)) {
- $block = $this->getLayout()->createBlock('core/html_select');
- $this->setData('_select_block', $block);
- }
- return $block;
- }
-
- /**
- * @return Mage_Core_Block_Abstract|Mage_Core_Block_Html_Date
- */
- protected function _getDateBlock()
- {
- $block = $this->getData('_date_block');
- if (is_null($block)) {
- $block = $this->getLayout()->createBlock('core/html_date');
- $this->setData('_date_block', $block);
- }
- return $block;
- }
-
/**
* Retrieve advanced search model object
*
@@ -299,4 +273,30 @@ public function getDateInput($attribute, $part = 'from')
->setClass('input-text')
->getHtml();
}
+
+ /**
+ * @return Mage_Core_Block_Abstract|Mage_Core_Block_Html_Select
+ */
+ protected function _getSelectBlock()
+ {
+ $block = $this->getData('_select_block');
+ if (is_null($block)) {
+ $block = $this->getLayout()->createBlock('core/html_select');
+ $this->setData('_select_block', $block);
+ }
+ return $block;
+ }
+
+ /**
+ * @return Mage_Core_Block_Abstract|Mage_Core_Block_Html_Date
+ */
+ protected function _getDateBlock()
+ {
+ $block = $this->getData('_date_block');
+ if (is_null($block)) {
+ $block = $this->getLayout()->createBlock('core/html_date');
+ $this->setData('_date_block', $block);
+ }
+ return $block;
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Block/Advanced/Result.php b/app/code/core/Mage/CatalogSearch/Block/Advanced/Result.php
index 024bd4259fe..7572760df21 100644
--- a/app/code/core/Mage/CatalogSearch/Block/Advanced/Result.php
+++ b/app/code/core/Mage/CatalogSearch/Block/Advanced/Result.php
@@ -24,28 +24,6 @@
*/
class Mage_CatalogSearch_Block_Advanced_Result extends Mage_Core_Block_Template
{
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Breadcrumbs $breadcrumbs */
- $breadcrumbs = $this->getLayout()->getBlock('breadcrumbs');
- if ($breadcrumbs) {
- $breadcrumbs->addCrumb('home', [
- 'label' => Mage::helper('catalogsearch')->__('Home'),
- 'title' => Mage::helper('catalogsearch')->__('Go to Home Page'),
- 'link' => Mage::getBaseUrl(),
- ])->addCrumb('search', [
- 'label' => Mage::helper('catalogsearch')->__('Catalog Advanced Search'),
- 'link' => $this->getUrl('*/*/'),
- ])->addCrumb('search_result', [
- 'label' => Mage::helper('catalogsearch')->__('Results'),
- ]);
- }
- return parent::_prepareLayout();
- }
-
public function setListOrders()
{
$category = Mage::getSingleton('catalog/layer')
@@ -76,14 +54,6 @@ public function setListCollection()
->setCollection($this->_getProductCollection());
}
- /**
- * @return Mage_CatalogSearch_Model_Resource_Advanced_Collection
- */
- protected function _getProductCollection()
- {
- return $this->getSearchModel()->getProductCollection();
- }
-
/**
* @return Mage_CatalogSearch_Model_Advanced|Mage_Core_Model_Abstract
*/
@@ -135,4 +105,33 @@ public function getSearchCriterias()
return ['left' => $left, 'right' => $right];
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Breadcrumbs $breadcrumbs */
+ $breadcrumbs = $this->getLayout()->getBlock('breadcrumbs');
+ if ($breadcrumbs) {
+ $breadcrumbs->addCrumb('home', [
+ 'label' => Mage::helper('catalogsearch')->__('Home'),
+ 'title' => Mage::helper('catalogsearch')->__('Go to Home Page'),
+ 'link' => Mage::getBaseUrl(),
+ ])->addCrumb('search', [
+ 'label' => Mage::helper('catalogsearch')->__('Catalog Advanced Search'),
+ 'link' => $this->getUrl('*/*/'),
+ ])->addCrumb('search_result', [
+ 'label' => Mage::helper('catalogsearch')->__('Results'),
+ ]);
+ }
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * @return Mage_CatalogSearch_Model_Resource_Advanced_Collection
+ */
+ protected function _getProductCollection()
+ {
+ return $this->getSearchModel()->getProductCollection();
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Block/Autocomplete.php b/app/code/core/Mage/CatalogSearch/Block/Autocomplete.php
index 4696ea371f6..f01c5b21f84 100644
--- a/app/code/core/Mage/CatalogSearch/Block/Autocomplete.php
+++ b/app/code/core/Mage/CatalogSearch/Block/Autocomplete.php
@@ -27,6 +27,36 @@ class Mage_CatalogSearch_Block_Autocomplete extends Mage_Core_Block_Abstract
*/
protected $_suggestData;
+ /**
+ * @return array
+ */
+ public function getSuggestData()
+ {
+ if (!$this->_suggestData) {
+ /** @var Mage_CatalogSearch_Helper_Data $helper */
+ $helper = $this->helper('catalogsearch');
+ $collection = $helper->getSuggestCollection();
+ $query = $helper->getQueryText();
+ $counter = 0;
+ $data = [];
+ foreach ($collection as $item) {
+ $_data = [
+ 'title' => $item->getQueryText(),
+ 'row_class' => (++$counter) % 2 ? 'odd' : 'even',
+ 'num_of_results' => $item->getNumResults(),
+ ];
+
+ if ($item->getQueryText() == $query) {
+ array_unshift($data, $_data);
+ } else {
+ $data[] = $_data;
+ }
+ }
+ $this->_suggestData = $data;
+ }
+ return $this->_suggestData;
+ }
+
/**
* @return string
* @throws Mage_Core_Model_Store_Exception
@@ -68,34 +98,4 @@ protected function _toHtml()
return $html . '';
}
-
- /**
- * @return array
- */
- public function getSuggestData()
- {
- if (!$this->_suggestData) {
- /** @var Mage_CatalogSearch_Helper_Data $helper */
- $helper = $this->helper('catalogsearch');
- $collection = $helper->getSuggestCollection();
- $query = $helper->getQueryText();
- $counter = 0;
- $data = [];
- foreach ($collection as $item) {
- $_data = [
- 'title' => $item->getQueryText(),
- 'row_class' => (++$counter) % 2 ? 'odd' : 'even',
- 'num_of_results' => $item->getNumResults(),
- ];
-
- if ($item->getQueryText() == $query) {
- array_unshift($data, $_data);
- } else {
- $data[] = $_data;
- }
- }
- $this->_suggestData = $data;
- }
- return $this->_suggestData;
- }
}
diff --git a/app/code/core/Mage/CatalogSearch/Block/Layer.php b/app/code/core/Mage/CatalogSearch/Block/Layer.php
index 08a010bdd65..7be539660c1 100644
--- a/app/code/core/Mage/CatalogSearch/Block/Layer.php
+++ b/app/code/core/Mage/CatalogSearch/Block/Layer.php
@@ -22,37 +22,6 @@
*/
class Mage_CatalogSearch_Block_Layer extends Mage_Catalog_Block_Layer_View
{
- /**
- * Internal constructor
- */
- protected function _construct()
- {
- parent::_construct();
- Mage::register('current_layer', $this->getLayer(), true);
- }
-
- /**
- * Get attribute filter block name
- *
- * @deprecated after 1.4.1.0
- *
- * @return string
- */
- protected function _getAttributeFilterBlockName()
- {
- return 'catalogsearch/layer_filter_attribute';
- }
-
- /**
- * Initialize blocks names
- */
- protected function _initBlocks()
- {
- parent::_initBlocks();
-
- $this->_attributeFilterBlockName = 'catalogsearch/layer_filter_attribute';
- }
-
/**
* Get layer object
*
@@ -84,4 +53,34 @@ public function canShowBlock()
}
return false;
}
+ /**
+ * Internal constructor
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ Mage::register('current_layer', $this->getLayer(), true);
+ }
+
+ /**
+ * Get attribute filter block name
+ *
+ * @deprecated after 1.4.1.0
+ *
+ * @return string
+ */
+ protected function _getAttributeFilterBlockName()
+ {
+ return 'catalogsearch/layer_filter_attribute';
+ }
+
+ /**
+ * Initialize blocks names
+ */
+ protected function _initBlocks()
+ {
+ parent::_initBlocks();
+
+ $this->_attributeFilterBlockName = 'catalogsearch/layer_filter_attribute';
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Block/Result.php b/app/code/core/Mage/CatalogSearch/Block/Result.php
index d136e2fb5dd..744635a490a 100644
--- a/app/code/core/Mage/CatalogSearch/Block/Result.php
+++ b/app/code/core/Mage/CatalogSearch/Block/Result.php
@@ -32,51 +32,6 @@ class Mage_CatalogSearch_Block_Result extends Mage_Core_Block_Template
*/
protected $_productCollection;
- /**
- * Retrieve query model object
- *
- * @return Mage_CatalogSearch_Model_Query
- */
- protected function _getQuery()
- {
- /** @var Mage_CatalogSearch_Helper_Data $helper */
- $helper = $this->helper('catalogsearch');
- return $helper->getQuery();
- }
-
- /**
- * Prepare layout
- *
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_CatalogSearch_Helper_Data $helper */
- $helper = $this->helper('catalogsearch');
-
- // add Home breadcrumb
- /** @var Mage_Page_Block_Html_Breadcrumbs $breadcrumbs */
- $breadcrumbs = $this->getLayout()->getBlock('breadcrumbs');
- if ($breadcrumbs) {
- $title = $this->__("Search results for: '%s'", $helper->getQueryText());
-
- $breadcrumbs->addCrumb('home', [
- 'label' => $this->__('Home'),
- 'title' => $this->__('Go to Home Page'),
- 'link' => Mage::getBaseUrl(),
- ])->addCrumb('search', [
- 'label' => $title,
- 'title' => $title,
- ]);
- }
-
- // modify page title
- $title = $this->__("Search results for: '%s'", $helper->getEscapedQueryText());
- $this->getLayout()->getBlock('head')->setTitle($title);
-
- return parent::_prepareLayout();
- }
-
/**
* Retrieve additional blocks html
*
@@ -155,20 +110,6 @@ public function getProductListHtml()
return $this->getChildHtml('search_result_list');
}
- /**
- * Retrieve loaded category collection
- *
- * @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection|Mage_Eav_Model_Entity_Collection_Abstract
- */
- protected function _getProductCollection()
- {
- if (is_null($this->_productCollection)) {
- $this->_productCollection = $this->getListBlock()->getLoadedProductCollection();
- }
-
- return $this->_productCollection;
- }
-
/**
* Retrieve search result count
*
@@ -209,4 +150,63 @@ public function getNoteMessages()
{
return Mage::helper('catalogsearch')->getNoteMessages();
}
+
+ /**
+ * Retrieve query model object
+ *
+ * @return Mage_CatalogSearch_Model_Query
+ */
+ protected function _getQuery()
+ {
+ /** @var Mage_CatalogSearch_Helper_Data $helper */
+ $helper = $this->helper('catalogsearch');
+ return $helper->getQuery();
+ }
+
+ /**
+ * Prepare layout
+ *
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_CatalogSearch_Helper_Data $helper */
+ $helper = $this->helper('catalogsearch');
+
+ // add Home breadcrumb
+ /** @var Mage_Page_Block_Html_Breadcrumbs $breadcrumbs */
+ $breadcrumbs = $this->getLayout()->getBlock('breadcrumbs');
+ if ($breadcrumbs) {
+ $title = $this->__("Search results for: '%s'", $helper->getQueryText());
+
+ $breadcrumbs->addCrumb('home', [
+ 'label' => $this->__('Home'),
+ 'title' => $this->__('Go to Home Page'),
+ 'link' => Mage::getBaseUrl(),
+ ])->addCrumb('search', [
+ 'label' => $title,
+ 'title' => $title,
+ ]);
+ }
+
+ // modify page title
+ $title = $this->__("Search results for: '%s'", $helper->getEscapedQueryText());
+ $this->getLayout()->getBlock('head')->setTitle($title);
+
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Retrieve loaded category collection
+ *
+ * @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection|Mage_Eav_Model_Entity_Collection_Abstract
+ */
+ protected function _getProductCollection()
+ {
+ if (is_null($this->_productCollection)) {
+ $this->_productCollection = $this->getListBlock()->getLoadedProductCollection();
+ }
+
+ return $this->_productCollection;
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Block/Term.php b/app/code/core/Mage/CatalogSearch/Block/Term.php
index 268690d4cd0..1c29a3ae384 100644
--- a/app/code/core/Mage/CatalogSearch/Block/Term.php
+++ b/app/code/core/Mage/CatalogSearch/Block/Term.php
@@ -29,6 +29,46 @@ class Mage_CatalogSearch_Block_Term extends Mage_Core_Block_Template
protected $_minPopularity;
protected $_maxPopularity;
+ /**
+ * @return array
+ */
+ public function getTerms()
+ {
+ $this->_loadTerms();
+ return $this->_terms;
+ }
+
+ /**
+ * @param Varien_Object $obj
+ * @return string
+ */
+ public function getSearchUrl($obj)
+ {
+ $url = Mage::getModel('core/url');
+ /*
+ * url encoding will be done in Url.php http_build_query
+ * so no need to explicitly called urlencode for the text
+ */
+ $url->setQueryParam('q', $obj->getName());
+ return $url->getUrl('catalogsearch/result');
+ }
+
+ /**
+ * @return int
+ */
+ public function getMaxPopularity()
+ {
+ return $this->_maxPopularity;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMinPopularity()
+ {
+ return $this->_minPopularity;
+ }
+
/**
* Load terms and try to sort it by names
*
@@ -71,44 +111,4 @@ protected function _loadTerms()
}
return $this;
}
-
- /**
- * @return array
- */
- public function getTerms()
- {
- $this->_loadTerms();
- return $this->_terms;
- }
-
- /**
- * @param Varien_Object $obj
- * @return string
- */
- public function getSearchUrl($obj)
- {
- $url = Mage::getModel('core/url');
- /*
- * url encoding will be done in Url.php http_build_query
- * so no need to explicitly called urlencode for the text
- */
- $url->setQueryParam('q', $obj->getName());
- return $url->getUrl('catalogsearch/result');
- }
-
- /**
- * @return int
- */
- public function getMaxPopularity()
- {
- return $this->_maxPopularity;
- }
-
- /**
- * @return int
- */
- public function getMinPopularity()
- {
- return $this->_minPopularity;
- }
}
diff --git a/app/code/core/Mage/CatalogSearch/Helper/Data.php b/app/code/core/Mage/CatalogSearch/Helper/Data.php
index 311782b2abf..d6a94c27ad0 100644
--- a/app/code/core/Mage/CatalogSearch/Helper/Data.php
+++ b/app/code/core/Mage/CatalogSearch/Helper/Data.php
@@ -180,16 +180,6 @@ public function getSuggestUrl()
]);
}
- /**
- * Get App
- *
- * @return Mage_Core_Model_App
- */
- protected function _getApp()
- {
- return Mage::app();
- }
-
/**
* Retrieve search term url
*
@@ -354,4 +344,14 @@ public function getEngine()
return $this->_engine;
}
+
+ /**
+ * Get App
+ *
+ * @return Mage_Core_Model_App
+ */
+ protected function _getApp()
+ {
+ return Mage::app();
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Advanced.php b/app/code/core/Mage/CatalogSearch/Model/Advanced.php
index 5abc78f7967..cbd1362881a 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Advanced.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Advanced.php
@@ -63,38 +63,6 @@ class Mage_CatalogSearch_Model_Advanced extends Mage_Core_Model_Abstract
*/
protected $_productCollection;
- protected function _construct()
- {
- $this->_getEngine();
- $this->_init('catalogsearch/advanced');
- }
-
- /**
- * @return Mage_CatalogSearch_Model_Resource_Fulltext_Engine|object
- */
- protected function _getEngine()
- {
- if ($this->_engine == null) {
- $this->_engine = Mage::helper('catalogsearch')->getEngine();
- }
-
- return $this->_engine;
- }
-
- /**
- * Retrieve resource instance wrapper
- *
- * @inheritDoc
- */
- protected function _getResource()
- {
- $resourceName = $this->_engine->getResourceName();
- if ($resourceName) {
- $this->_resourceName = $resourceName;
- }
- return parent::_getResource();
- }
-
/**
* Retrieve array of attributes used in advanced search
*
@@ -120,20 +88,6 @@ public function getAttributes()
return $attributes;
}
- /**
- * Prepare search condition for attribute
- *
- * @deprecated after 1.4.1.0 - use Mage_CatalogSearch_Model_Resource_Advanced->_prepareCondition()
- *
- * @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute
- * @param string|array $value
- * @return mixed
- */
- protected function _prepareCondition($attribute, $value)
- {
- return $this->_getResource()->prepareCondition($attribute, $value, $this->getProductCollection());
- }
-
/**
* Add advanced search filters to product collection
*
@@ -216,6 +170,103 @@ public function addFilters($values)
return $this;
}
+ /**
+ * Returns prepared search criteria in text
+ *
+ * @return array
+ */
+ public function getSearchCriterias()
+ {
+ return $this->_searchCriterias;
+ }
+
+ /**
+ * Retrieve advanced search product collection
+ *
+ * @return Mage_CatalogSearch_Model_Resource_Advanced_Collection
+ */
+ public function getProductCollection()
+ {
+ if (is_null($this->_productCollection)) {
+ $collection = $this->_engine->getAdvancedResultCollection();
+ $this->prepareProductCollection($collection);
+ if (!$collection) {
+ return $collection;
+ }
+ $this->_productCollection = $collection;
+ }
+
+ return $this->_productCollection;
+ }
+
+ /**
+ * Prepare product collection
+ *
+ * @param Mage_CatalogSearch_Model_Resource_Advanced_Collection $collection
+ * @return $this
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ public function prepareProductCollection($collection)
+ {
+ $collection->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
+ ->setStore(Mage::app()->getStore())
+ ->addMinimalPrice()
+ ->addTaxPercents()
+ ->addStoreFilter()
+ ->addAttributeToFilter('status', [
+ 'in' => Mage::getSingleton('catalog/product_status')->getVisibleStatusIds(),
+ ]);
+ Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($collection);
+
+ return $this;
+ }
+
+ protected function _construct()
+ {
+ $this->_getEngine();
+ $this->_init('catalogsearch/advanced');
+ }
+
+ /**
+ * @return Mage_CatalogSearch_Model_Resource_Fulltext_Engine|object
+ */
+ protected function _getEngine()
+ {
+ if ($this->_engine == null) {
+ $this->_engine = Mage::helper('catalogsearch')->getEngine();
+ }
+
+ return $this->_engine;
+ }
+
+ /**
+ * Retrieve resource instance wrapper
+ *
+ * @inheritDoc
+ */
+ protected function _getResource()
+ {
+ $resourceName = $this->_engine->getResourceName();
+ if ($resourceName) {
+ $this->_resourceName = $resourceName;
+ }
+ return parent::_getResource();
+ }
+
+ /**
+ * Prepare search condition for attribute
+ *
+ * @deprecated after 1.4.1.0 - use Mage_CatalogSearch_Model_Resource_Advanced->_prepareCondition()
+ *
+ * @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute
+ * @param string|array $value
+ * @return mixed
+ */
+ protected function _prepareCondition($attribute, $value)
+ {
+ return $this->_getResource()->prepareCondition($attribute, $value, $this->getProductCollection());
+ }
+
/**
* Add data about search criteria to object state
*
@@ -282,55 +333,4 @@ protected function _addSearchCriteria($attribute, $value)
$this->_searchCriterias[] = ['name' => $name, 'value' => $value];
return $this;
}
-
- /**
- * Returns prepared search criteria in text
- *
- * @return array
- */
- public function getSearchCriterias()
- {
- return $this->_searchCriterias;
- }
-
- /**
- * Retrieve advanced search product collection
- *
- * @return Mage_CatalogSearch_Model_Resource_Advanced_Collection
- */
- public function getProductCollection()
- {
- if (is_null($this->_productCollection)) {
- $collection = $this->_engine->getAdvancedResultCollection();
- $this->prepareProductCollection($collection);
- if (!$collection) {
- return $collection;
- }
- $this->_productCollection = $collection;
- }
-
- return $this->_productCollection;
- }
-
- /**
- * Prepare product collection
- *
- * @param Mage_CatalogSearch_Model_Resource_Advanced_Collection $collection
- * @return $this
- * @throws Mage_Core_Model_Store_Exception
- */
- public function prepareProductCollection($collection)
- {
- $collection->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
- ->setStore(Mage::app()->getStore())
- ->addMinimalPrice()
- ->addTaxPercents()
- ->addStoreFilter()
- ->addAttributeToFilter('status', [
- 'in' => Mage::getSingleton('catalog/product_status')->getVisibleStatusIds(),
- ]);
- Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($collection);
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Fulltext.php b/app/code/core/Mage/CatalogSearch/Model/Fulltext.php
index 008e0a5bb38..4db797e0b07 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Fulltext.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Fulltext.php
@@ -47,11 +47,6 @@ class Mage_CatalogSearch_Model_Fulltext extends Mage_Core_Model_Abstract
*/
protected $_allowTableChanges = true;
- protected function _construct()
- {
- $this->_init('catalogsearch/fulltext');
- }
-
/**
* Regenerate all Stores index
*
@@ -171,4 +166,9 @@ public function updateCategoryIndex($productIds, $categoryIds)
$this->getResource()->updateCategoryIndex($productIds, $categoryIds);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('catalogsearch/fulltext');
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Fulltext/Observer.php b/app/code/core/Mage/CatalogSearch/Model/Fulltext/Observer.php
index d156cbb66ce..df2da5a50ac 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Fulltext/Observer.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Fulltext/Observer.php
@@ -22,16 +22,6 @@
*/
class Mage_CatalogSearch_Model_Fulltext_Observer
{
- /**
- * Retrieve fulltext (indexer) model
- *
- * @return Mage_CatalogSearch_Model_Fulltext
- */
- protected function _getFulltextModel()
- {
- return Mage::getSingleton('catalogsearch/fulltext');
- }
-
/**
* Update product index when product data updated
*
@@ -173,4 +163,13 @@ public function cleanStoreIndex(Varien_Event_Observer $observer)
return $this;
}
+ /**
+ * Retrieve fulltext (indexer) model
+ *
+ * @return Mage_CatalogSearch_Model_Fulltext
+ */
+ protected function _getFulltextModel()
+ {
+ return Mage::getSingleton('catalogsearch/fulltext');
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Indexer/Fulltext.php b/app/code/core/Mage/CatalogSearch/Model/Indexer/Fulltext.php
index e4ebc88ce5a..fe48f5032d6 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Indexer/Fulltext.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Indexer/Fulltext.php
@@ -34,16 +34,6 @@ class Mage_CatalogSearch_Model_Indexer_Fulltext extends Mage_Index_Model_Indexer
*/
protected $_searchableAttributes = null;
- /**
- * Retrieve resource instance
- *
- * @return Mage_CatalogSearch_Model_Resource_Indexer_Fulltext
- */
- protected function _getResource()
- {
- return Mage::getResourceSingleton('catalogsearch/indexer_fulltext');
- }
-
/**
* Indexer must be match entities
*
@@ -86,16 +76,6 @@ protected function _getResource()
Mage_CatalogSearch_Model_Fulltext::XML_PATH_CATALOG_SEARCH_TYPE,
];
- /**
- * Retrieve Fulltext Search instance
- *
- * @return Mage_CatalogSearch_Model_Fulltext
- */
- protected function _getIndexer()
- {
- return Mage::getSingleton('catalogsearch/fulltext');
- }
-
/**
* Retrieve Indexer name
*
@@ -180,6 +160,43 @@ public function matchEvent(Mage_Index_Model_Event $event)
return $result;
}
+ /**
+ * Rebuild all index data
+ *
+ */
+ public function reindexAll()
+ {
+ $resourceModel = $this->_getIndexer()->getResource();
+ $resourceModel->beginTransaction();
+ try {
+ $this->_getIndexer()->rebuildIndex();
+ $resourceModel->commit();
+ } catch (Exception $e) {
+ $resourceModel->rollBack();
+ throw $e;
+ }
+ }
+
+ /**
+ * Retrieve resource instance
+ *
+ * @return Mage_CatalogSearch_Model_Resource_Indexer_Fulltext
+ */
+ protected function _getResource()
+ {
+ return Mage::getResourceSingleton('catalogsearch/indexer_fulltext');
+ }
+
+ /**
+ * Retrieve Fulltext Search instance
+ *
+ * @return Mage_CatalogSearch_Model_Fulltext
+ */
+ protected function _getIndexer()
+ {
+ return Mage::getSingleton('catalogsearch/fulltext');
+ }
+
/**
* Register data required by process in event object
*/
@@ -424,21 +441,4 @@ protected function _processEvent(Mage_Index_Model_Event $event)
->updateCategoryIndex($productIds, $categoryIds);
}
}
-
- /**
- * Rebuild all index data
- *
- */
- public function reindexAll()
- {
- $resourceModel = $this->_getIndexer()->getResource();
- $resourceModel->beginTransaction();
- try {
- $this->_getIndexer()->rebuildIndex();
- $resourceModel->commit();
- } catch (Exception $e) {
- $resourceModel->rollBack();
- throw $e;
- }
- }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Query.php b/app/code/core/Mage/CatalogSearch/Model/Query.php
index 71a4375f8f6..e6033487fb7 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Query.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Query.php
@@ -48,27 +48,17 @@
*/
class Mage_CatalogSearch_Model_Query extends Mage_Core_Model_Abstract
{
- protected $_eventPrefix = 'catalogsearch_query';
-
- /**
- * @var string
- */
- protected $_eventObject = 'catalogsearch_query';
-
public const CACHE_TAG = 'SEARCH_QUERY';
public const XML_PATH_MIN_QUERY_LENGTH = 'catalog/search/min_query_length';
public const XML_PATH_MAX_QUERY_LENGTH = 'catalog/search/max_query_length';
public const XML_PATH_MAX_QUERY_WORDS = 'catalog/search/max_query_words';
public const XML_PATH_AJAX_SUGGESTION_COUNT = 'catalog/search/show_autocomplete_results_count';
+ protected $_eventPrefix = 'catalogsearch_query';
/**
- * Init resource model
- *
+ * @var string
*/
- protected function _construct()
- {
- $this->_init('catalogsearch/query');
- }
+ protected $_eventObject = 'catalogsearch_query';
/**
* Retrieve search collection
@@ -241,4 +231,13 @@ public function getMaxQueryWords()
{
return Mage::getStoreConfig(self::XML_PATH_MAX_QUERY_WORDS, $this->getStoreId());
}
+
+ /**
+ * Init resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalogsearch/query');
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Resource/Advanced.php b/app/code/core/Mage/CatalogSearch/Model/Resource/Advanced.php
index cd5946ba578..79e6ea3655f 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Resource/Advanced.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Resource/Advanced.php
@@ -22,37 +22,6 @@
*/
class Mage_CatalogSearch_Model_Resource_Advanced extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product', 'entity_id');
- }
-
- /**
- * Prepare response object and dispatch prepare price event
- * Return response object
- *
- * @param Varien_Db_Select $select
- * @return Varien_Object
- */
- protected function _dispatchPreparePriceEvent($select)
- {
- // prepare response object for event
- $response = new Varien_Object();
- $response->setAdditionalCalculations([]);
-
- // prepare event arguments
- $eventArgs = [
- 'select' => $select,
- 'table' => 'price_index',
- 'store_id' => Mage::app()->getStore()->getId(),
- 'response_object' => $response,
- ];
-
- Mage::dispatchEvent('catalog_prepare_price_select', $eventArgs);
-
- return $response;
- }
-
/**
* Prepare search condition for attribute
*
@@ -182,4 +151,34 @@ public function addIndexableAttributeModifiedFilter($collection, $attribute, $va
return true;
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product', 'entity_id');
+ }
+
+ /**
+ * Prepare response object and dispatch prepare price event
+ * Return response object
+ *
+ * @param Varien_Db_Select $select
+ * @return Varien_Object
+ */
+ protected function _dispatchPreparePriceEvent($select)
+ {
+ // prepare response object for event
+ $response = new Varien_Object();
+ $response->setAdditionalCalculations([]);
+
+ // prepare event arguments
+ $eventArgs = [
+ 'select' => $select,
+ 'table' => 'price_index',
+ 'store_id' => Mage::app()->getStore()->getId(),
+ 'response_object' => $response,
+ ];
+
+ Mage::dispatchEvent('catalog_prepare_price_select', $eventArgs);
+
+ return $response;
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext.php b/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext.php
index 51e433d58ab..a153270f879 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext.php
@@ -70,16 +70,6 @@ class Mage_CatalogSearch_Model_Resource_Fulltext extends Mage_Core_Model_Resourc
*/
protected $_foundData = [];
- /**
- * Init resource model
- *
- */
- protected function _construct()
- {
- $this->_init('catalogsearch/fulltext', 'product_id');
- $this->_engine = Mage::helper('catalogsearch')->getEngine();
- }
-
/**
* Return options separator
*
@@ -111,6 +101,163 @@ public function rebuildIndex($storeId = null, $productIds = null)
return $this;
}
+ /**
+ * Reset search results
+ *
+ * @return $this
+ */
+ public function resetSearchResults()
+ {
+ Mage::dispatchEvent('catalogsearch_reset_search_result');
+ return $this;
+ }
+
+ /**
+ * Delete search index data for store
+ *
+ * @param int $storeId Store View Id
+ * @param int $productId Product Entity Id
+ * @return $this
+ */
+ public function cleanIndex($storeId = null, $productId = null)
+ {
+ if ($this->_engine) {
+ $this->_engine->cleanIndex($storeId, $productId);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Prepare results for query
+ *
+ * @param Mage_CatalogSearch_Model_Fulltext $object
+ * @param string $queryText
+ * @param Mage_CatalogSearch_Model_Query $query
+ * @return $this
+ */
+ public function prepareResult($object, $queryText, $query)
+ {
+ /** @var Mage_CatalogSearch_Model_Resource_Helper_Mysql4 $searchHelper */
+ $searchHelper = Mage::getResourceHelper('catalogsearch');
+
+ $adapter = $this->_getWriteAdapter();
+ $searchType = $object->getSearchType($query->getStoreId());
+
+ $preparedTerms = $searchHelper->prepareTerms($queryText, $query->getMaxQueryWords());
+
+ $bind = [];
+ $like = [];
+ $likeCond = '';
+ if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE
+ || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE
+ ) {
+ $helper = Mage::getResourceHelper('core');
+ $words = Mage::helper('core/string')->splitWords($queryText, true, $query->getMaxQueryWords());
+ foreach ($words as $word) {
+ $like[] = $helper->getCILike('s.data_index', $word, ['position' => 'any']);
+ }
+
+ if ($like) {
+ $separator = Mage::getStoreConfig(Mage_CatalogSearch_Model_Fulltext::XML_PATH_CATALOG_SEARCH_SEPARATOR);
+ $likeCond = '(' . implode(' ' . $separator . ' ', $like) . ')';
+ }
+ }
+
+ $mainTableAlias = 's';
+ $fields = ['product_id'];
+
+ $select = $adapter->select()
+ ->from([$mainTableAlias => $this->getMainTable()], $fields)
+ ->joinInner(
+ ['e' => $this->getTable('catalog/product')],
+ 'e.entity_id = s.product_id',
+ [],
+ )
+ ->where($mainTableAlias . '.store_id = ?', (int) $query->getStoreId());
+
+ $where = '';
+ if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_FULLTEXT
+ || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE
+ ) {
+ $bind[':query'] = implode(' ', $preparedTerms[0]);
+ $where = $searchHelper->chooseFulltext($this->getMainTable(), $mainTableAlias, $select);
+ }
+ if ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
+ $where .= ($where ? ' OR ' : '') . $likeCond;
+ } elseif ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE) {
+ $select->columns(['relevance' => new Zend_Db_Expr('0')]);
+ $where = $likeCond;
+ }
+
+ if ($where != '') {
+ $select->where($where);
+ }
+
+ $this->_foundData = $adapter->fetchPairs($select, $bind);
+
+ return $this;
+ }
+
+ /**
+ * Retrieve found data
+ *
+ * @return array
+ */
+ public function getFoundData()
+ {
+ return $this->_foundData;
+ }
+
+ /**
+ * Retrieve EAV Config Singleton
+ *
+ * @return Mage_Eav_Model_Config
+ */
+ public function getEavConfig()
+ {
+ return Mage::getSingleton('eav/config');
+ }
+
+ // Deprecated methods
+
+ /**
+ * Set whether table changes are allowed
+ *
+ * @deprecated after 1.6.1.0
+ * @param bool $value
+ * @return $this
+ */
+ public function setAllowTableChanges($value = true)
+ {
+ $this->_allowTableChanges = $value;
+ return $this;
+ }
+
+ /**
+ * Update category products indexes
+ *
+ * @deprecated after 1.6.2.0
+ *
+ * @param array $productIds
+ * @param array $categoryIds
+ * @return $this
+ */
+ public function updateCategoryIndex($productIds, $categoryIds)
+ {
+ return $this;
+ }
+
+ /**
+ * Init resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalogsearch/fulltext', 'product_id');
+ $this->_engine = Mage::helper('catalogsearch')->getEngine();
+ }
+
/**
* Regenerate search index for specific store
*
@@ -284,124 +431,6 @@ protected function _getSearchableProducts(
return $writeAdapter->fetchAll($select);
}
- /**
- * Reset search results
- *
- * @return $this
- */
- public function resetSearchResults()
- {
- Mage::dispatchEvent('catalogsearch_reset_search_result');
- return $this;
- }
-
- /**
- * Delete search index data for store
- *
- * @param int $storeId Store View Id
- * @param int $productId Product Entity Id
- * @return $this
- */
- public function cleanIndex($storeId = null, $productId = null)
- {
- if ($this->_engine) {
- $this->_engine->cleanIndex($storeId, $productId);
- }
-
- return $this;
- }
-
- /**
- * Prepare results for query
- *
- * @param Mage_CatalogSearch_Model_Fulltext $object
- * @param string $queryText
- * @param Mage_CatalogSearch_Model_Query $query
- * @return $this
- */
- public function prepareResult($object, $queryText, $query)
- {
- /** @var Mage_CatalogSearch_Model_Resource_Helper_Mysql4 $searchHelper */
- $searchHelper = Mage::getResourceHelper('catalogsearch');
-
- $adapter = $this->_getWriteAdapter();
- $searchType = $object->getSearchType($query->getStoreId());
-
- $preparedTerms = $searchHelper->prepareTerms($queryText, $query->getMaxQueryWords());
-
- $bind = [];
- $like = [];
- $likeCond = '';
- if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE
- || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE
- ) {
- $helper = Mage::getResourceHelper('core');
- $words = Mage::helper('core/string')->splitWords($queryText, true, $query->getMaxQueryWords());
- foreach ($words as $word) {
- $like[] = $helper->getCILike('s.data_index', $word, ['position' => 'any']);
- }
-
- if ($like) {
- $separator = Mage::getStoreConfig(Mage_CatalogSearch_Model_Fulltext::XML_PATH_CATALOG_SEARCH_SEPARATOR);
- $likeCond = '(' . implode(' ' . $separator . ' ', $like) . ')';
- }
- }
-
- $mainTableAlias = 's';
- $fields = ['product_id'];
-
- $select = $adapter->select()
- ->from([$mainTableAlias => $this->getMainTable()], $fields)
- ->joinInner(
- ['e' => $this->getTable('catalog/product')],
- 'e.entity_id = s.product_id',
- [],
- )
- ->where($mainTableAlias . '.store_id = ?', (int) $query->getStoreId());
-
- $where = '';
- if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_FULLTEXT
- || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE
- ) {
- $bind[':query'] = implode(' ', $preparedTerms[0]);
- $where = $searchHelper->chooseFulltext($this->getMainTable(), $mainTableAlias, $select);
- }
- if ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
- $where .= ($where ? ' OR ' : '') . $likeCond;
- } elseif ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE) {
- $select->columns(['relevance' => new Zend_Db_Expr('0')]);
- $where = $likeCond;
- }
-
- if ($where != '') {
- $select->where($where);
- }
-
- $this->_foundData = $adapter->fetchPairs($select, $bind);
-
- return $this;
- }
-
- /**
- * Retrieve found data
- *
- * @return array
- */
- public function getFoundData()
- {
- return $this->_foundData;
- }
-
- /**
- * Retrieve EAV Config Singleton
- *
- * @return Mage_Eav_Model_Config
- */
- public function getEavConfig()
- {
- return Mage::getSingleton('eav/config');
- }
-
/**
* Retrieve searchable attributes
*
@@ -823,33 +852,4 @@ protected function _getStoreDate($storeId, $date = null)
return null;
}
-
- // Deprecated methods
-
- /**
- * Set whether table changes are allowed
- *
- * @deprecated after 1.6.1.0
- * @param bool $value
- * @return $this
- */
- public function setAllowTableChanges($value = true)
- {
- $this->_allowTableChanges = $value;
- return $this;
- }
-
- /**
- * Update category products indexes
- *
- * @deprecated after 1.6.2.0
- *
- * @param array $productIds
- * @param array $categoryIds
- * @return $this
- */
- public function updateCategoryIndex($productIds, $categoryIds)
- {
- return $this;
- }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Collection.php b/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Collection.php
index 85ff963043e..1c3f4985eee 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Collection.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Collection.php
@@ -55,16 +55,6 @@ class Mage_CatalogSearch_Model_Resource_Fulltext_Collection extends Mage_Catalog
*/
protected $_isSearchFiltersApplied = false;
- /**
- * Retrieve query model object
- *
- * @return Mage_CatalogSearch_Model_Query
- */
- protected function _getQuery()
- {
- return Mage::helper('catalogsearch')->getQuery();
- }
-
/**
* Add search query filter
*
@@ -77,31 +67,88 @@ public function addSearchFilter($query)
}
/**
- * Before load handler
+ * Get collection size
*
- * @return Mage_Catalog_Model_Resource_Product_Collection
+ * @return int
*/
- protected function _beforeLoad()
+ public function getSize()
{
if (!$this->_isSearchFiltersApplied) {
$this->_applySearchFilters();
}
- return parent::_beforeLoad();
+ return parent::getSize();
}
/**
- * Get collection size
+ * Get found products ids
*
- * @return int
+ * @return array
*/
- public function getSize()
+ public function getFoundIds()
+ {
+ if (is_null($this->_foundData)) {
+ /** @var Mage_CatalogSearch_Model_Fulltext $preparedResult */
+ $preparedResult = Mage::getSingleton('catalogsearch/fulltext');
+ $preparedResult->prepareResult();
+ $this->_foundData = $preparedResult->getResource()->getFoundData();
+ }
+ if (isset($this->_orders[self::RELEVANCE_ORDER_NAME])) {
+ $this->_resortFoundDataByRelevance();
+ }
+ return array_keys($this->_foundData);
+ }
+
+ /**
+ * Set Order field
+ *
+ * @param string $attribute
+ * @param string $dir
+ * @return $this
+ */
+ public function setOrder($attribute, $dir = 'desc')
+ {
+ if ($attribute == 'relevance') {
+ $this->_relevanceSortOrder = ($dir == 'asc') ? SORT_ASC : SORT_DESC;
+ $this->addOrder(self::RELEVANCE_ORDER_NAME);
+ } else {
+ parent::setOrder($attribute, $dir);
+ }
+ return $this;
+ }
+
+ /**
+ * Stub method for compatibility with other search engines
+ *
+ * @return $this
+ */
+ public function setGeneralDefaultQuery()
+ {
+ return $this;
+ }
+
+ /**
+ * Retrieve query model object
+ *
+ * @return Mage_CatalogSearch_Model_Query
+ */
+ protected function _getQuery()
+ {
+ return Mage::helper('catalogsearch')->getQuery();
+ }
+
+ /**
+ * Before load handler
+ *
+ * @return Mage_Catalog_Model_Resource_Product_Collection
+ */
+ protected function _beforeLoad()
{
if (!$this->_isSearchFiltersApplied) {
$this->_applySearchFilters();
}
- return parent::getSize();
+ return parent::_beforeLoad();
}
/**
@@ -122,25 +169,6 @@ protected function _applySearchFilters()
return $this;
}
- /**
- * Get found products ids
- *
- * @return array
- */
- public function getFoundIds()
- {
- if (is_null($this->_foundData)) {
- /** @var Mage_CatalogSearch_Model_Fulltext $preparedResult */
- $preparedResult = Mage::getSingleton('catalogsearch/fulltext');
- $preparedResult->prepareResult();
- $this->_foundData = $preparedResult->getResource()->getFoundData();
- }
- if (isset($this->_orders[self::RELEVANCE_ORDER_NAME])) {
- $this->_resortFoundDataByRelevance();
- }
- return array_keys($this->_foundData);
- }
-
/**
* Resort found data by relevance
*
@@ -166,24 +194,6 @@ protected function _resortFoundDataByRelevance()
return $this;
}
- /**
- * Set Order field
- *
- * @param string $attribute
- * @param string $dir
- * @return $this
- */
- public function setOrder($attribute, $dir = 'desc')
- {
- if ($attribute == 'relevance') {
- $this->_relevanceSortOrder = ($dir == 'asc') ? SORT_ASC : SORT_DESC;
- $this->addOrder(self::RELEVANCE_ORDER_NAME);
- } else {
- parent::setOrder($attribute, $dir);
- }
- return $this;
- }
-
/**
* Add sorting by relevance to select
*
@@ -211,16 +221,6 @@ protected function _addRelevanceSorting()
return $this;
}
- /**
- * Stub method for compatibility with other search engines
- *
- * @return $this
- */
- public function setGeneralDefaultQuery()
- {
- return $this;
- }
-
/**
* Render sql select orders
*
diff --git a/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Engine.php b/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Engine.php
index 3a4736b6d88..84bfdb840ae 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Engine.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Engine.php
@@ -22,15 +22,6 @@
*/
class Mage_CatalogSearch_Model_Resource_Fulltext_Engine extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Init resource model
- *
- */
- protected function _construct()
- {
- $this->_init('catalogsearch/fulltext', 'product_id');
- }
-
/**
* Add entity data to fulltext search table
*
@@ -184,4 +175,12 @@ public function test()
{
return true;
}
+ /**
+ * Init resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalogsearch/fulltext', 'product_id');
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Resource/Indexer/Fulltext.php b/app/code/core/Mage/CatalogSearch/Model/Resource/Indexer/Fulltext.php
index 8007f3cee8a..919cd96f43c 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Resource/Indexer/Fulltext.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Resource/Indexer/Fulltext.php
@@ -22,11 +22,6 @@
*/
class Mage_CatalogSearch_Model_Resource_Indexer_Fulltext extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('catalogsearch/fulltext', 'product_id');
- }
-
/**
* Retrieve product relations by children
*
@@ -42,4 +37,8 @@ public function getRelationsByChild($childIds)
return $write->fetchCol($select);
}
+ protected function _construct()
+ {
+ $this->_init('catalogsearch/fulltext', 'product_id');
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Resource/Query.php b/app/code/core/Mage/CatalogSearch/Model/Resource/Query.php
index b82df9f3e6d..11d9415eb4c 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Resource/Query.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Resource/Query.php
@@ -22,15 +22,6 @@
*/
class Mage_CatalogSearch_Model_Resource_Query extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Init resource data
- *
- */
- protected function _construct()
- {
- $this->_init('catalogsearch/search_query', 'query_id');
- }
-
/**
* Custom load model by search query string
*
@@ -110,4 +101,12 @@ public function _beforeSave(Mage_Core_Model_Abstract $object)
$object->setUpdatedAt($this->formatDate(Mage::getModel('core/date')->gmtTimestamp()));
return $this;
}
+ /**
+ * Init resource data
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalogsearch/search_query', 'query_id');
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/Model/Resource/Query/Collection.php b/app/code/core/Mage/CatalogSearch/Model/Resource/Query/Collection.php
index f75dbb72a99..a08da677c89 100644
--- a/app/code/core/Mage/CatalogSearch/Model/Resource/Query/Collection.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Resource/Query/Collection.php
@@ -29,15 +29,6 @@ class Mage_CatalogSearch_Model_Resource_Query_Collection extends Mage_Core_Model
*/
protected $_storeId;
- /**
- * Init model for collection
- *
- */
- protected function _construct()
- {
- $this->_init('catalogsearch/query');
- }
-
/**
* Set Store ID for filter
*
@@ -150,4 +141,13 @@ public function addStoreFilter($storeIds)
$this->getSelect()->where('main_table.store_id IN (?)', $storeIds);
return $this;
}
+
+ /**
+ * Init model for collection
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalogsearch/query');
+ }
}
diff --git a/app/code/core/Mage/CatalogSearch/controllers/ResultController.php b/app/code/core/Mage/CatalogSearch/controllers/ResultController.php
index 4bc98018f51..3b5a34a481d 100644
--- a/app/code/core/Mage/CatalogSearch/controllers/ResultController.php
+++ b/app/code/core/Mage/CatalogSearch/controllers/ResultController.php
@@ -22,15 +22,6 @@
*/
class Mage_CatalogSearch_ResultController extends Mage_Core_Controller_Front_Action
{
- /**
- * Retrieve catalog session
- *
- * @return Mage_Catalog_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('catalog/session');
- }
/**
* Display search result
*/
@@ -76,4 +67,13 @@ public function indexAction()
$this->_redirectReferer();
}
}
+ /**
+ * Retrieve catalog session
+ *
+ * @return Mage_Catalog_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('catalog/session');
+ }
}
diff --git a/app/code/core/Mage/Centinel/Block/Logo.php b/app/code/core/Mage/Centinel/Block/Logo.php
index 3ceb21962e8..3b4104297ab 100644
--- a/app/code/core/Mage/Centinel/Block/Logo.php
+++ b/app/code/core/Mage/Centinel/Block/Logo.php
@@ -22,12 +22,6 @@
*/
class Mage_Centinel_Block_Logo extends Mage_Core_Block_Template
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('centinel/logo.phtml');
- }
-
/**
* Return code of payment method
*
@@ -37,4 +31,9 @@ public function getCode()
{
return $this->getMethod()->getCode();
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('centinel/logo.phtml');
+ }
}
diff --git a/app/code/core/Mage/Centinel/Helper/Data.php b/app/code/core/Mage/Centinel/Helper/Data.php
index 4168576f200..a9f16753414 100644
--- a/app/code/core/Mage/Centinel/Helper/Data.php
+++ b/app/code/core/Mage/Centinel/Helper/Data.php
@@ -70,6 +70,45 @@ public function getCmpiValue($fieldName, $value)
return '';
}
+ /**
+ * Return centinel block for payment form with logos
+ *
+ * @param Mage_Payment_Model_Method_Abstract $method
+ * @return Mage_Centinel_Block_Logo|Mage_Core_Block_Abstract|false
+ */
+ public function getMethodFormBlock($method)
+ {
+ $blockType = 'centinel/logo';
+ if ($this->getLayout()) {
+ $block = $this->getLayout()->createBlock($blockType);
+ } else {
+ $className = Mage::getConfig()->getBlockClassName($blockType);
+ $block = new $className();
+ }
+ $block->setMethod($method);
+ return $block;
+ }
+
+ /**
+ * Return url of page about visa verification
+ *
+ * @return string
+ */
+ public function getVisaLearnMorePageUrl()
+ {
+ return 'https://usa.visa.com/personal/security/vbv/index.html?ep=v_sym_verifiedbyvisa';
+ }
+
+ /**
+ * Return url of page about mastercard verification
+ *
+ * @return string
+ */
+ public function getMastercardLearnMorePageUrl()
+ {
+ return 'http://www.mastercardbusiness.com/mcbiz/index.jsp?template=/orphans&content=securecodepopup';
+ }
+
/**
* Return text value for cmpi eci flag field
*
@@ -131,43 +170,4 @@ private function _getCmpiParesValue($value)
return $value;
}
}
-
- /**
- * Return centinel block for payment form with logos
- *
- * @param Mage_Payment_Model_Method_Abstract $method
- * @return Mage_Centinel_Block_Logo|Mage_Core_Block_Abstract|false
- */
- public function getMethodFormBlock($method)
- {
- $blockType = 'centinel/logo';
- if ($this->getLayout()) {
- $block = $this->getLayout()->createBlock($blockType);
- } else {
- $className = Mage::getConfig()->getBlockClassName($blockType);
- $block = new $className();
- }
- $block->setMethod($method);
- return $block;
- }
-
- /**
- * Return url of page about visa verification
- *
- * @return string
- */
- public function getVisaLearnMorePageUrl()
- {
- return 'https://usa.visa.com/personal/security/vbv/index.html?ep=v_sym_verifiedbyvisa';
- }
-
- /**
- * Return url of page about mastercard verification
- *
- * @return string
- */
- public function getMastercardLearnMorePageUrl()
- {
- return 'http://www.mastercardbusiness.com/mcbiz/index.jsp?template=/orphans&content=securecodepopup';
- }
}
diff --git a/app/code/core/Mage/Centinel/Model/Api.php b/app/code/core/Mage/Centinel/Model/Api.php
index b2b14a0b450..780f9ecee11 100644
--- a/app/code/core/Mage/Centinel/Model/Api.php
+++ b/app/code/core/Mage/Centinel/Model/Api.php
@@ -65,6 +65,69 @@ class Mage_Centinel_Model_Api extends Varien_Object
*/
protected $_clientInstance = null;
+ /**
+ * Call centinel api lookup method
+ *
+ * @return $this
+ */
+ public function callLookup($data)
+ {
+ $result = new Varien_Object();
+
+ $month = strlen($data->getCardExpMonth()) == 1 ? '0' . $data->getCardExpMonth() : $data->getCardExpMonth();
+ $currencyCode = $data->getCurrencyCode();
+ $currencyNumber = self::$_iso4217Currencies[$currencyCode] ?? '';
+ if (!$currencyNumber) {
+ return $result->setErrorNo(1)->setErrorDesc(
+ Mage::helper('payment')->__('Unsupported currency code: %s.', $currencyCode),
+ );
+ }
+
+ $clientResponse = $this->_call('cmpi_lookup', [
+ 'Amount' => round($data->getAmount() * 100),
+ 'CurrencyCode' => $currencyNumber,
+ 'CardNumber' => $data->getCardNumber(),
+ 'CardExpMonth' => $month,
+ 'CardExpYear' => $data->getCardExpYear(),
+ 'OrderNumber' => $data->getOrderNumber(),
+ ]);
+
+ $result->setErrorNo($clientResponse->getValue('ErrorNo'));
+ $result->setErrorDesc($clientResponse->getValue('ErrorDesc'));
+ $result->setTransactionId($clientResponse->getValue('TransactionId'));
+ $result->setEnrolled($clientResponse->getValue('Enrolled'));
+ $result->setAcsUrl($clientResponse->getValue('ACSUrl'));
+ $result->setPayload($clientResponse->getValue('Payload'));
+ $result->setEciFlag($clientResponse->getValue('EciFlag'));
+
+ return $result;
+ }
+
+ /**
+ * Call centinel api authentication method
+ *
+ * @return Varien_Object
+ */
+ public function callAuthentication($data)
+ {
+ $result = new Varien_Object();
+
+ $clientResponse = $this->_call('cmpi_authenticate', [
+ 'TransactionId' => $data->getTransactionId(),
+ 'PAResPayload' => $data->getPaResPayload(),
+ ]);
+
+ $result->setErrorNo($clientResponse->getValue('ErrorNo'));
+ $result->setErrorDesc($clientResponse->getValue('ErrorDesc'));
+ $result->setPaResStatus($clientResponse->getValue('PAResStatus'));
+ $result->setSignatureVerification($clientResponse->getValue('SignatureVerification'));
+ $result->setCavv($clientResponse->getValue('Cavv'));
+ $result->setEciFlag($clientResponse->getValue('EciFlag'));
+ $result->setXid($clientResponse->getValue('Xid'));
+
+ return $result;
+ }
+
/**
* Return Centinel thin client object
*
@@ -175,69 +238,6 @@ protected function _getApiEndpointUrl()
return $url;
}
- /**
- * Call centinel api lookup method
- *
- * @return $this
- */
- public function callLookup($data)
- {
- $result = new Varien_Object();
-
- $month = strlen($data->getCardExpMonth()) == 1 ? '0' . $data->getCardExpMonth() : $data->getCardExpMonth();
- $currencyCode = $data->getCurrencyCode();
- $currencyNumber = self::$_iso4217Currencies[$currencyCode] ?? '';
- if (!$currencyNumber) {
- return $result->setErrorNo(1)->setErrorDesc(
- Mage::helper('payment')->__('Unsupported currency code: %s.', $currencyCode),
- );
- }
-
- $clientResponse = $this->_call('cmpi_lookup', [
- 'Amount' => round($data->getAmount() * 100),
- 'CurrencyCode' => $currencyNumber,
- 'CardNumber' => $data->getCardNumber(),
- 'CardExpMonth' => $month,
- 'CardExpYear' => $data->getCardExpYear(),
- 'OrderNumber' => $data->getOrderNumber(),
- ]);
-
- $result->setErrorNo($clientResponse->getValue('ErrorNo'));
- $result->setErrorDesc($clientResponse->getValue('ErrorDesc'));
- $result->setTransactionId($clientResponse->getValue('TransactionId'));
- $result->setEnrolled($clientResponse->getValue('Enrolled'));
- $result->setAcsUrl($clientResponse->getValue('ACSUrl'));
- $result->setPayload($clientResponse->getValue('Payload'));
- $result->setEciFlag($clientResponse->getValue('EciFlag'));
-
- return $result;
- }
-
- /**
- * Call centinel api authentication method
- *
- * @return Varien_Object
- */
- public function callAuthentication($data)
- {
- $result = new Varien_Object();
-
- $clientResponse = $this->_call('cmpi_authenticate', [
- 'TransactionId' => $data->getTransactionId(),
- 'PAResPayload' => $data->getPaResPayload(),
- ]);
-
- $result->setErrorNo($clientResponse->getValue('ErrorNo'));
- $result->setErrorDesc($clientResponse->getValue('ErrorDesc'));
- $result->setPaResStatus($clientResponse->getValue('PAResStatus'));
- $result->setSignatureVerification($clientResponse->getValue('SignatureVerification'));
- $result->setCavv($clientResponse->getValue('Cavv'));
- $result->setEciFlag($clientResponse->getValue('EciFlag'));
- $result->setXid($clientResponse->getValue('Xid'));
-
- return $result;
- }
-
/**
* Log debug data to file
*
diff --git a/app/code/core/Mage/Centinel/Model/Config.php b/app/code/core/Mage/Centinel/Model/Config.php
index c646ed5b40b..da81d4e0ed3 100644
--- a/app/code/core/Mage/Centinel/Model/Config.php
+++ b/app/code/core/Mage/Centinel/Model/Config.php
@@ -119,23 +119,23 @@ public function getIsTestMode()
}
/**
- * Return value of node of centinel config section
+ * Define if debugging is enabled
*
- * @param string $key
* @return string
*/
- private function _getServiceConfigValue($key)
+ public function getDebugFlag()
{
- return Mage::getStoreConfig($this->_serviceConfigPath . '/' . $key, $this->getStore());
+ return $this->_getServiceConfigValue('debug');
}
/**
- * Define if debugging is enabled
+ * Return value of node of centinel config section
*
+ * @param string $key
* @return string
*/
- public function getDebugFlag()
+ private function _getServiceConfigValue($key)
{
- return $this->_getServiceConfigValue('debug');
+ return Mage::getStoreConfig($this->_serviceConfigPath . '/' . $key, $this->getStore());
}
}
diff --git a/app/code/core/Mage/Centinel/Model/Service.php b/app/code/core/Mage/Centinel/Model/Service.php
index f430081e68a..15ec77ffb32 100644
--- a/app/code/core/Mage/Centinel/Model/Service.php
+++ b/app/code/core/Mage/Centinel/Model/Service.php
@@ -59,152 +59,6 @@ class Mage_Centinel_Model_Service extends Varien_Object
*/
protected $_validationState;
- /**
- * Return validation session object
- *
- * @return Mage_Centinel_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('centinel/session');
- }
-
- /**
- * Return value from section of centinel config
- *
- * @return Mage_Centinel_Model_Config
- */
- protected function _getConfig()
- {
- $config = Mage::getSingleton('centinel/config');
- return $config->setStore($this->getStore());
- }
-
- /**
- * Generate checksum from all passed parameters
- *
- * @param string $cardType
- * @param string $cardNumber
- * @param string $cardExpMonth
- * @param string $cardExpYear
- * @param double $amount
- * @param string $currencyCode
- * @return string
- */
- protected function _generateChecksum($paymentMethodCode, $cardType, $cardNumber, $cardExpMonth, $cardExpYear, $amount, $currencyCode)
- {
- return md5(implode('_', func_get_args()));
- }
-
- /**
- * Unified validation/authentication URL getter
- *
- * @param string $suffix
- * @param bool $current
- * @return string
- */
- private function _getUrl($suffix, $current = false)
- {
- $params = [
- '_secure' => true,
- '_current' => $current,
- 'form_key' => Mage::getSingleton('core/session')->getFormKey(),
- 'isIframe' => true,
- ];
- if (Mage::app()->getStore()->isAdmin()) {
- return Mage::getSingleton('adminhtml/url')->getUrl('*/centinel_index/' . $suffix, $params);
- } else {
- return Mage::getUrl('centinel/index/' . $suffix, $params);
- }
- }
-
- /**
- * Return validation api model
- *
- * @return Mage_Centinel_Model_Api
- */
- protected function _getApi()
- {
- if ($this->_api !== null) {
- return $this->_api;
- }
-
- $this->_api = Mage::getSingleton('centinel/api');
- $config = $this->_getConfig();
- $this->_api
- ->setProcessorId($config->getProcessorId())
- ->setMerchantId($config->getMerchantId())
- ->setTransactionPwd($config->getTransactionPwd())
- ->setIsTestMode($config->getIsTestMode())
- ->setDebugFlag($config->getDebugFlag())
- ->setApiEndpointUrl($this->getCustomApiEndpointUrl());
- return $this->_api;
- }
-
- /**
- * Create and return validation state model for card type
- *
- * @param string $cardType
- * @return Mage_Centinel_Model_StateAbstract|false
- */
- protected function _getValidationStateModel($cardType)
- {
- if ($modelClass = $this->_getConfig()->getStateModelClass($cardType)) {
- /** @var Mage_Centinel_Model_StateAbstract $model */
- $model = Mage::getModel($modelClass);
- return $model;
- }
- return false;
- }
-
- /**
- * Return validation state model
- *
- * @param string $cardType
- * @return Mage_Centinel_Model_StateAbstract|false
- */
- protected function _getValidationState($cardType = null)
- {
- $type = $cardType ? $cardType : $this->_getSession()->getData('card_type');
- if (!$this->_validationState && $type) {
- $model = $this->_getValidationStateModel($type);
- if (!$model) {
- return false;
- }
- $model->setDataStorage($this->_getSession());
- $this->_validationState = $model;
- }
- return $this->_validationState;
- }
-
- /**
- * Drop validation state model
- *
- */
- protected function _resetValidationState()
- {
- $this->_getSession()->setData([]);
- $this->_validationState = false;
- }
-
- /**
- * Drop old and init new validation state model
- *
- * @param string $cardType
- * @param string $dataChecksum
- * @return Mage_Centinel_Model_StateAbstract
- */
- protected function _initValidationState($cardType, $dataChecksum)
- {
- $this->_resetValidationState();
- $state = $this->_getValidationStateModel($cardType);
- $state->setDataStorage($this->_getSession())
- ->setCardType($cardType)
- ->setChecksum($dataChecksum)
- ->setIsModeStrict($this->getIsModeStrict());
- return $this->_getValidationState();
- }
-
/**
* Process lookup validation and init new validation state model
*
@@ -387,4 +241,150 @@ public function exportCmpiData($to, $map = false)
}
return $to;
}
+
+ /**
+ * Return validation session object
+ *
+ * @return Mage_Centinel_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('centinel/session');
+ }
+
+ /**
+ * Return value from section of centinel config
+ *
+ * @return Mage_Centinel_Model_Config
+ */
+ protected function _getConfig()
+ {
+ $config = Mage::getSingleton('centinel/config');
+ return $config->setStore($this->getStore());
+ }
+
+ /**
+ * Generate checksum from all passed parameters
+ *
+ * @param string $cardType
+ * @param string $cardNumber
+ * @param string $cardExpMonth
+ * @param string $cardExpYear
+ * @param double $amount
+ * @param string $currencyCode
+ * @return string
+ */
+ protected function _generateChecksum($paymentMethodCode, $cardType, $cardNumber, $cardExpMonth, $cardExpYear, $amount, $currencyCode)
+ {
+ return md5(implode('_', func_get_args()));
+ }
+
+ /**
+ * Return validation api model
+ *
+ * @return Mage_Centinel_Model_Api
+ */
+ protected function _getApi()
+ {
+ if ($this->_api !== null) {
+ return $this->_api;
+ }
+
+ $this->_api = Mage::getSingleton('centinel/api');
+ $config = $this->_getConfig();
+ $this->_api
+ ->setProcessorId($config->getProcessorId())
+ ->setMerchantId($config->getMerchantId())
+ ->setTransactionPwd($config->getTransactionPwd())
+ ->setIsTestMode($config->getIsTestMode())
+ ->setDebugFlag($config->getDebugFlag())
+ ->setApiEndpointUrl($this->getCustomApiEndpointUrl());
+ return $this->_api;
+ }
+
+ /**
+ * Create and return validation state model for card type
+ *
+ * @param string $cardType
+ * @return Mage_Centinel_Model_StateAbstract|false
+ */
+ protected function _getValidationStateModel($cardType)
+ {
+ if ($modelClass = $this->_getConfig()->getStateModelClass($cardType)) {
+ /** @var Mage_Centinel_Model_StateAbstract $model */
+ $model = Mage::getModel($modelClass);
+ return $model;
+ }
+ return false;
+ }
+
+ /**
+ * Return validation state model
+ *
+ * @param string $cardType
+ * @return Mage_Centinel_Model_StateAbstract|false
+ */
+ protected function _getValidationState($cardType = null)
+ {
+ $type = $cardType ? $cardType : $this->_getSession()->getData('card_type');
+ if (!$this->_validationState && $type) {
+ $model = $this->_getValidationStateModel($type);
+ if (!$model) {
+ return false;
+ }
+ $model->setDataStorage($this->_getSession());
+ $this->_validationState = $model;
+ }
+ return $this->_validationState;
+ }
+
+ /**
+ * Drop validation state model
+ *
+ */
+ protected function _resetValidationState()
+ {
+ $this->_getSession()->setData([]);
+ $this->_validationState = false;
+ }
+
+ /**
+ * Drop old and init new validation state model
+ *
+ * @param string $cardType
+ * @param string $dataChecksum
+ * @return Mage_Centinel_Model_StateAbstract
+ */
+ protected function _initValidationState($cardType, $dataChecksum)
+ {
+ $this->_resetValidationState();
+ $state = $this->_getValidationStateModel($cardType);
+ $state->setDataStorage($this->_getSession())
+ ->setCardType($cardType)
+ ->setChecksum($dataChecksum)
+ ->setIsModeStrict($this->getIsModeStrict());
+ return $this->_getValidationState();
+ }
+
+ /**
+ * Unified validation/authentication URL getter
+ *
+ * @param string $suffix
+ * @param bool $current
+ * @return string
+ */
+ private function _getUrl($suffix, $current = false)
+ {
+ $params = [
+ '_secure' => true,
+ '_current' => $current,
+ 'form_key' => Mage::getSingleton('core/session')->getFormKey(),
+ 'isIframe' => true,
+ ];
+ if (Mage::app()->getStore()->isAdmin()) {
+ return Mage::getSingleton('adminhtml/url')->getUrl('*/centinel_index/' . $suffix, $params);
+ } else {
+ return Mage::getUrl('centinel/index/' . $suffix, $params);
+ }
+ }
}
diff --git a/app/code/core/Mage/Centinel/Model/StateAbstract.php b/app/code/core/Mage/Centinel/Model/StateAbstract.php
index 552bbe3c53e..ea1b64a59ea 100644
--- a/app/code/core/Mage/Centinel/Model/StateAbstract.php
+++ b/app/code/core/Mage/Centinel/Model/StateAbstract.php
@@ -132,31 +132,31 @@ final public function isLookupSuccessful()
}
/**
- * Analyse lookup`s results. If lookup is strict successful return true
+ * Analyse lookup`s results. If it has require params for authenticate, return true
*
* @return bool
*/
- abstract protected function _isLookupStrictSuccessful();
+ abstract public function isAuthenticateAllowed();
/**
- * Analyse lookup`s results. If lookup is soft successful return true
+ * Analyse authenticate`s results. If authenticate is successful return true and false if it failure
+ * Result depends from flag self::getIsModeStrict()
*
* @return bool
*/
- abstract protected function _isLookupSoftSuccessful();
+ abstract public function isAuthenticateSuccessful();
/**
- * Analyse lookup`s results. If it has require params for authenticate, return true
+ * Analyse lookup`s results. If lookup is strict successful return true
*
* @return bool
*/
- abstract public function isAuthenticateAllowed();
+ abstract protected function _isLookupStrictSuccessful();
/**
- * Analyse authenticate`s results. If authenticate is successful return true and false if it failure
- * Result depends from flag self::getIsModeStrict()
+ * Analyse lookup`s results. If lookup is soft successful return true
*
* @return bool
*/
- abstract public function isAuthenticateSuccessful();
+ abstract protected function _isLookupSoftSuccessful();
}
diff --git a/app/code/core/Mage/Checkout/Block/Cart/Crosssell.php b/app/code/core/Mage/Checkout/Block/Cart/Crosssell.php
index 0d776407638..2392b53254d 100644
--- a/app/code/core/Mage/Checkout/Block/Cart/Crosssell.php
+++ b/app/code/core/Mage/Checkout/Block/Cart/Crosssell.php
@@ -86,6 +86,16 @@ public function getItemCount()
return count($this->getItems());
}
+ /**
+ * Get quote instance
+ *
+ * @return Mage_Sales_Model_Quote
+ */
+ public function getQuote()
+ {
+ return Mage::getSingleton('checkout/session')->getQuote();
+ }
+
/**
* Get ids of products that are in cart
*
@@ -138,16 +148,6 @@ protected function _getLastAddedProductId()
return Mage::getSingleton('checkout/session')->getLastAddedProductId(true);
}
- /**
- * Get quote instance
- *
- * @return Mage_Sales_Model_Quote
- */
- public function getQuote()
- {
- return Mage::getSingleton('checkout/session')->getQuote();
- }
-
/**
* Get crosssell products collection
*
diff --git a/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer.php b/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer.php
index 9d3dbf5a0ce..77fb2563977 100644
--- a/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer.php
+++ b/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer.php
@@ -462,6 +462,32 @@ public function setIgnoreProductUrl($ignore = true)
return $this;
}
+ /**
+ * Retrieve block cache tags
+ *
+ * @return array
+ */
+ public function getCacheTags()
+ {
+ $tags = $this->getProduct()->getCacheIdTags();
+ $tags = is_array($tags) ? $tags : [];
+
+ return array_merge(parent::getCacheTags(), $tags);
+ }
+
+ /**
+ * Returns true if user is going through checkout process now.
+ *
+ * @return bool
+ * @throws Exception
+ */
+ public function isOnCheckoutPage()
+ {
+ $module = $this->getRequest()->getModuleName();
+ $controller = $this->getRequest()->getControllerName();
+ return $module === 'checkout' && ($controller === 'onepage' || $controller === 'multishipping');
+ }
+
/**
* Common code to be called by product renders of gift registry to create a block, which is be used to
* generate html for mrsp price
@@ -491,30 +517,4 @@ protected function _getPriceContent($product)
->setProduct($product)
->toHtml();
}
-
- /**
- * Retrieve block cache tags
- *
- * @return array
- */
- public function getCacheTags()
- {
- $tags = $this->getProduct()->getCacheIdTags();
- $tags = is_array($tags) ? $tags : [];
-
- return array_merge(parent::getCacheTags(), $tags);
- }
-
- /**
- * Returns true if user is going through checkout process now.
- *
- * @return bool
- * @throws Exception
- */
- public function isOnCheckoutPage()
- {
- $module = $this->getRequest()->getModuleName();
- $controller = $this->getRequest()->getControllerName();
- return $module === 'checkout' && ($controller === 'onepage' || $controller === 'multishipping');
- }
}
diff --git a/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer/Grouped.php b/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer/Grouped.php
index a50bc105998..2d446887025 100644
--- a/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer/Grouped.php
+++ b/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer/Grouped.php
@@ -61,6 +61,16 @@ public function getProductThumbnail()
return $helper->init($product, 'thumbnail');
}
+ /**
+ * Retrieve block cache tags
+ *
+ * @return array
+ */
+ public function getCacheTags()
+ {
+ return array_merge(parent::getCacheTags(), $this->getGroupedProduct()->getCacheIdTags());
+ }
+
/**
* Prepare item html
*
@@ -78,14 +88,4 @@ protected function _toHtml()
$renderer->overrideProductThumbnail(null);
return $rendererHtml;
}
-
- /**
- * Retrieve block cache tags
- *
- * @return array
- */
- public function getCacheTags()
- {
- return array_merge(parent::getCacheTags(), $this->getGroupedProduct()->getCacheIdTags());
- }
}
diff --git a/app/code/core/Mage/Checkout/Block/Cart/Sidebar.php b/app/code/core/Mage/Checkout/Block/Cart/Sidebar.php
index 79e83ef8c3c..ba09c25063e 100644
--- a/app/code/core/Mage/Checkout/Block/Cart/Sidebar.php
+++ b/app/code/core/Mage/Checkout/Block/Cart/Sidebar.php
@@ -112,17 +112,6 @@ public function getSubtotalInclTax()
return $this->getSubtotal(false);
}
- /**
- * Get shipping tax amount
- *
- * @return float
- */
- protected function _getShippingTaxAmount()
- {
- $quote = $this->getCustomQuote() ?: $this->getQuote();
- return $quote->getShippingAddress()->getShippingTaxAmount();
- }
-
/**
* Get incl/excl tax label
*
@@ -210,20 +199,6 @@ public function getCacheKeyInfo()
return $cacheKeyInfo;
}
- /**
- * Serialize renders
- *
- * @return string
- */
- protected function _serializeRenders()
- {
- $result = [];
- foreach ($this->_itemRenders as $type => $renderer) {
- $result[] = implode('|', [$type, $renderer['block'], $renderer['template']]);
- }
- return implode('|', $result);
- }
-
/**
* Deserialize renders from string
*
@@ -272,6 +247,31 @@ public function getCacheTags()
);
}
+ /**
+ * Get shipping tax amount
+ *
+ * @return float
+ */
+ protected function _getShippingTaxAmount()
+ {
+ $quote = $this->getCustomQuote() ?: $this->getQuote();
+ return $quote->getShippingAddress()->getShippingTaxAmount();
+ }
+
+ /**
+ * Serialize renders
+ *
+ * @return string
+ */
+ protected function _serializeRenders()
+ {
+ $result = [];
+ foreach ($this->_itemRenders as $type => $renderer) {
+ $result[] = implode('|', [$type, $renderer['block'], $renderer['template']]);
+ }
+ return implode('|', $result);
+ }
+
/**
* Processing block html after rendering
*
diff --git a/app/code/core/Mage/Checkout/Block/Cart/Totals.php b/app/code/core/Mage/Checkout/Block/Cart/Totals.php
index 9e7eaa269da..69d62382767 100644
--- a/app/code/core/Mage/Checkout/Block/Cart/Totals.php
+++ b/app/code/core/Mage/Checkout/Block/Cart/Totals.php
@@ -45,30 +45,6 @@ public function setTotals($value)
return $this;
}
- /**
- * @param string $code
- * @return false|Mage_Core_Block_Abstract|string
- */
- protected function _getTotalRenderer($code)
- {
- $blockName = $code . '_total_renderer';
- $block = $this->getLayout()->getBlock($blockName);
- if (!$block) {
- $block = $this->_defaultRenderer;
- $config = Mage::getConfig()->getNode("global/sales/quote/totals/{$code}/renderer");
- if ($config) {
- $block = (string) $config;
- }
-
- $block = $this->getLayout()->createBlock($block, $blockName);
- }
- /**
- * Transfer totals to renderer
- */
- $block->setTotals($this->getTotals());
- return $block;
- }
-
/**
* @param Mage_Sales_Model_Quote_Address_Total $total
* @param string|null $area
@@ -152,4 +128,28 @@ public function getQuote()
}
return $this->_quote;
}
+
+ /**
+ * @param string $code
+ * @return false|Mage_Core_Block_Abstract|string
+ */
+ protected function _getTotalRenderer($code)
+ {
+ $blockName = $code . '_total_renderer';
+ $block = $this->getLayout()->getBlock($blockName);
+ if (!$block) {
+ $block = $this->_defaultRenderer;
+ $config = Mage::getConfig()->getNode("global/sales/quote/totals/{$code}/renderer");
+ if ($config) {
+ $block = (string) $config;
+ }
+
+ $block = $this->getLayout()->createBlock($block, $blockName);
+ }
+ /**
+ * Transfer totals to renderer
+ */
+ $block->setTotals($this->getTotals());
+ return $block;
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Multishipping/Address/Select.php b/app/code/core/Mage/Checkout/Block/Multishipping/Address/Select.php
index 84d7f2f9068..c141a26f00d 100644
--- a/app/code/core/Mage/Checkout/Block/Multishipping/Address/Select.php
+++ b/app/code/core/Mage/Checkout/Block/Multishipping/Address/Select.php
@@ -22,25 +22,6 @@
*/
class Mage_Checkout_Block_Multishipping_Address_Select extends Mage_Checkout_Block_Multishipping_Abstract
{
- /**
- * @return Mage_Checkout_Block_Multishipping_Abstract
- */
- protected function _prepareLayout()
- {
- if ($headBlock = $this->getLayout()->getBlock('head')) {
- $headBlock->setTitle(Mage::helper('checkout')->__('Change Billing Address') . ' - ' . $headBlock->getDefaultTitle());
- }
- return parent::_prepareLayout();
- }
-
- /**
- * @return Mage_Checkout_Model_Type_Multishipping|Mage_Core_Model_Abstract
- */
- protected function _getCheckout()
- {
- return Mage::getSingleton('checkout/type_multishipping');
- }
-
/**
* @return Mage_Customer_Model_Address[]|mixed
*/
@@ -105,4 +86,22 @@ public function getBackUrl()
{
return $this->getUrl('*/multishipping/billing');
}
+ /**
+ * @return Mage_Checkout_Block_Multishipping_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ if ($headBlock = $this->getLayout()->getBlock('head')) {
+ $headBlock->setTitle(Mage::helper('checkout')->__('Change Billing Address') . ' - ' . $headBlock->getDefaultTitle());
+ }
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * @return Mage_Checkout_Model_Type_Multishipping|Mage_Core_Model_Abstract
+ */
+ protected function _getCheckout()
+ {
+ return Mage::getSingleton('checkout/type_multishipping');
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Multishipping/Addresses.php b/app/code/core/Mage/Checkout/Block/Multishipping/Addresses.php
index 5eaadbaf6fd..a0fed38b035 100644
--- a/app/code/core/Mage/Checkout/Block/Multishipping/Addresses.php
+++ b/app/code/core/Mage/Checkout/Block/Multishipping/Addresses.php
@@ -32,17 +32,6 @@ public function getCheckout()
return Mage::getSingleton('checkout/type_multishipping');
}
- /**
- * @return Mage_Sales_Block_Items_Abstract
- */
- protected function _prepareLayout()
- {
- if ($headBlock = $this->getLayout()->getBlock('head')) {
- $headBlock->setTitle(Mage::helper('checkout')->__('Ship to Multiple Addresses') . ' - ' . $headBlock->getDefaultTitle());
- }
- return parent::_prepareLayout();
- }
-
/**
* @return array
* @throws Exception
@@ -152,4 +141,15 @@ public function isContinueDisabled()
{
return !$this->getCheckout()->validateMinimumAmount();
}
+
+ /**
+ * @return Mage_Sales_Block_Items_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ if ($headBlock = $this->getLayout()->getBlock('head')) {
+ $headBlock->setTitle(Mage::helper('checkout')->__('Ship to Multiple Addresses') . ' - ' . $headBlock->getDefaultTitle());
+ }
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Multishipping/Billing.php b/app/code/core/Mage/Checkout/Block/Multishipping/Billing.php
index 154a31b8be7..c689ba2823d 100644
--- a/app/code/core/Mage/Checkout/Block/Multishipping/Billing.php
+++ b/app/code/core/Mage/Checkout/Block/Multishipping/Billing.php
@@ -22,31 +22,6 @@
*/
class Mage_Checkout_Block_Multishipping_Billing extends Mage_Payment_Block_Form_Container
{
- /**
- * Prepare children blocks
- */
- protected function _prepareLayout()
- {
- if ($headBlock = $this->getLayout()->getBlock('head')) {
- $headBlock->setTitle(
- Mage::helper('checkout')->__('Billing Information - %s', $headBlock->getDefaultTitle()),
- );
- }
-
- return parent::_prepareLayout();
- }
-
- /**
- * Check payment method model
- *
- * @param Mage_Payment_Model_Method_Abstract|null $method
- * @return bool
- */
- protected function _canUseMethod($method)
- {
- return $method && $method->canUseForMultishipping() && parent::_canUseMethod($method);
- }
-
/**
* Retrieve code of current payment method
*
@@ -125,4 +100,28 @@ public function getBackUrl()
{
return $this->getUrl('*/*/backtoshipping');
}
+ /**
+ * Prepare children blocks
+ */
+ protected function _prepareLayout()
+ {
+ if ($headBlock = $this->getLayout()->getBlock('head')) {
+ $headBlock->setTitle(
+ Mage::helper('checkout')->__('Billing Information - %s', $headBlock->getDefaultTitle()),
+ );
+ }
+
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Check payment method model
+ *
+ * @param Mage_Payment_Model_Method_Abstract|null $method
+ * @return bool
+ */
+ protected function _canUseMethod($method)
+ {
+ return $method && $method->canUseForMultishipping() && parent::_canUseMethod($method);
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Multishipping/Overview.php b/app/code/core/Mage/Checkout/Block/Multishipping/Overview.php
index aeb3483d0ba..2fed42ceae6 100644
--- a/app/code/core/Mage/Checkout/Block/Multishipping/Overview.php
+++ b/app/code/core/Mage/Checkout/Block/Multishipping/Overview.php
@@ -22,19 +22,6 @@
*/
class Mage_Checkout_Block_Multishipping_Overview extends Mage_Sales_Block_Items_Abstract
{
- /**
- * Initialize default item renderer for row-level items output
- */
- protected function _construct()
- {
- parent::_construct();
- $this->addItemRender(
- $this->_getRowItemType('default'),
- 'checkout/cart_item_renderer',
- 'checkout/multishipping/overview/item.phtml',
- );
- }
-
/**
* Get multishipping checkout model
*
@@ -45,19 +32,6 @@ public function getCheckout()
return Mage::getSingleton('checkout/type_multishipping');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- if ($headBlock = $this->getLayout()->getBlock('head')) {
- $headBlock->setTitle(
- $this->__('Review Order - %s', $headBlock->getDefaultTitle()),
- );
- }
- return parent::_prepareLayout();
- }
-
/**
* @return Mage_Sales_Model_Quote_Address
*/
@@ -350,6 +324,31 @@ public function _getRowItemRenderer($type)
$type = isset($this->_itemRenders[$type]) ? $type : $this->_getRowItemType('default');
return parent::getItemRenderer($type);
}
+ /**
+ * Initialize default item renderer for row-level items output
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->addItemRender(
+ $this->_getRowItemType('default'),
+ 'checkout/cart_item_renderer',
+ 'checkout/multishipping/overview/item.phtml',
+ );
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ if ($headBlock = $this->getLayout()->getBlock('head')) {
+ $headBlock->setTitle(
+ $this->__('Review Order - %s', $headBlock->getDefaultTitle()),
+ );
+ }
+ return parent::_prepareLayout();
+ }
/**
* Wrap row renderers into namespace by adding 'row_' suffix
diff --git a/app/code/core/Mage/Checkout/Block/Multishipping/Shipping.php b/app/code/core/Mage/Checkout/Block/Multishipping/Shipping.php
index 7c4565f398e..f4f97903cc2 100644
--- a/app/code/core/Mage/Checkout/Block/Multishipping/Shipping.php
+++ b/app/code/core/Mage/Checkout/Block/Multishipping/Shipping.php
@@ -32,17 +32,6 @@ public function getCheckout()
return Mage::getSingleton('checkout/type_multishipping');
}
- /**
- * @return Mage_Sales_Block_Items_Abstract
- */
- protected function _prepareLayout()
- {
- if ($headBlock = $this->getLayout()->getBlock('head')) {
- $headBlock->setTitle(Mage::helper('checkout')->__('Shipping Methods') . ' - ' . $headBlock->getDefaultTitle());
- }
- return parent::_prepareLayout();
- }
-
/**
* @return array
*/
@@ -159,4 +148,15 @@ public function getShippingPrice($address, $price, $flag)
$helper = $this->helper('tax');
return $address->getQuote()->getStore()->convertPrice($helper->getShippingPrice($price, $flag, $address), true);
}
+
+ /**
+ * @return Mage_Sales_Block_Items_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ if ($headBlock = $this->getLayout()->getBlock('head')) {
+ $headBlock->setTitle(Mage::helper('checkout')->__('Shipping Methods') . ' - ' . $headBlock->getDefaultTitle());
+ }
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Onepage/Abstract.php b/app/code/core/Mage/Checkout/Block/Onepage/Abstract.php
index af5ce7a7be2..bd6391bb6ee 100644
--- a/app/code/core/Mage/Checkout/Block/Onepage/Abstract.php
+++ b/app/code/core/Mage/Checkout/Block/Onepage/Abstract.php
@@ -213,22 +213,22 @@ public function getCountryOptions()
}
/**
- * Get checkout steps codes
+ * Retrieve is allow and show block
*
- * @return array
+ * @return bool
*/
- protected function _getStepCodes()
+ public function isShow()
{
- return ['login', 'billing', 'shipping', 'shipping_method', 'payment', 'review'];
+ return true;
}
/**
- * Retrieve is allow and show block
+ * Get checkout steps codes
*
- * @return bool
+ * @return array
*/
- public function isShow()
+ protected function _getStepCodes()
{
- return true;
+ return ['login', 'billing', 'shipping', 'shipping_method', 'payment', 'review'];
}
}
diff --git a/app/code/core/Mage/Checkout/Block/Onepage/Billing.php b/app/code/core/Mage/Checkout/Block/Onepage/Billing.php
index 48c7add2dca..ecd19354d69 100644
--- a/app/code/core/Mage/Checkout/Block/Onepage/Billing.php
+++ b/app/code/core/Mage/Checkout/Block/Onepage/Billing.php
@@ -36,23 +36,6 @@ class Mage_Checkout_Block_Onepage_Billing extends Mage_Checkout_Block_Onepage_Ab
*/
protected $_taxvat;
- /**
- * Initialize billing address step
- *
- */
- protected function _construct()
- {
- $this->getCheckout()->setStepData('billing', [
- 'label' => Mage::helper('checkout')->__('Billing Information'),
- 'is_show' => $this->isShow(),
- ]);
-
- if ($this->isCustomerLoggedIn()) {
- $this->getCheckout()->setStepData('billing', 'allow', true);
- }
- parent::_construct();
- }
-
/**
* @return bool
*/
@@ -170,20 +153,6 @@ public function canShip()
public function getSaveUrl() {}
- /**
- * Get Customer Taxvat Widget block
- *
- * @return Mage_Customer_Block_Widget_Taxvat
- */
- protected function _getTaxvat()
- {
- if (!$this->_taxvat) {
- $this->_taxvat = $this->getLayout()->createBlock('customer/widget_taxvat');
- }
-
- return $this->_taxvat;
- }
-
/**
* Check whether taxvat is enabled
*
@@ -205,4 +174,35 @@ public function getTaxvatHtml()
->setFieldNameFormat('billing[%s]')
->toHtml();
}
+
+ /**
+ * Initialize billing address step
+ *
+ */
+ protected function _construct()
+ {
+ $this->getCheckout()->setStepData('billing', [
+ 'label' => Mage::helper('checkout')->__('Billing Information'),
+ 'is_show' => $this->isShow(),
+ ]);
+
+ if ($this->isCustomerLoggedIn()) {
+ $this->getCheckout()->setStepData('billing', 'allow', true);
+ }
+ parent::_construct();
+ }
+
+ /**
+ * Get Customer Taxvat Widget block
+ *
+ * @return Mage_Customer_Block_Widget_Taxvat
+ */
+ protected function _getTaxvat()
+ {
+ if (!$this->_taxvat) {
+ $this->_taxvat = $this->getLayout()->createBlock('customer/widget_taxvat');
+ }
+
+ return $this->_taxvat;
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Onepage/Login.php b/app/code/core/Mage/Checkout/Block/Onepage/Login.php
index c59638632b8..03628152257 100644
--- a/app/code/core/Mage/Checkout/Block/Onepage/Login.php
+++ b/app/code/core/Mage/Checkout/Block/Onepage/Login.php
@@ -22,14 +22,6 @@
*/
class Mage_Checkout_Block_Onepage_Login extends Mage_Checkout_Block_Onepage_Abstract
{
- protected function _construct()
- {
- if (!$this->isCustomerLoggedIn()) {
- $this->getCheckout()->setStepData('login', ['label' => Mage::helper('checkout')->__('Checkout Method'), 'allow' => true]);
- }
- parent::_construct();
- }
-
/**
* @return Mage_Core_Model_Message_Collection
*/
@@ -87,4 +79,11 @@ public function getUsername()
{
return Mage::getSingleton('customer/session')->getUsername(true);
}
+ protected function _construct()
+ {
+ if (!$this->isCustomerLoggedIn()) {
+ $this->getCheckout()->setStepData('login', ['label' => Mage::helper('checkout')->__('Checkout Method'), 'allow' => true]);
+ }
+ parent::_construct();
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Onepage/Payment.php b/app/code/core/Mage/Checkout/Block/Onepage/Payment.php
index ca3272aea2c..f2d3ae0680f 100644
--- a/app/code/core/Mage/Checkout/Block/Onepage/Payment.php
+++ b/app/code/core/Mage/Checkout/Block/Onepage/Payment.php
@@ -22,15 +22,6 @@
*/
class Mage_Checkout_Block_Onepage_Payment extends Mage_Checkout_Block_Onepage_Abstract
{
- protected function _construct()
- {
- $this->getCheckout()->setStepData('payment', [
- 'label' => $this->__('Payment Information'),
- 'is_show' => $this->isShow(),
- ]);
- parent::_construct();
- }
-
/**
* Getter
*
@@ -40,4 +31,12 @@ public function getQuoteBaseGrandTotal()
{
return (float) $this->getQuote()->getBaseGrandTotal();
}
+ protected function _construct()
+ {
+ $this->getCheckout()->setStepData('payment', [
+ 'label' => $this->__('Payment Information'),
+ 'is_show' => $this->isShow(),
+ ]);
+ parent::_construct();
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Onepage/Payment/Methods.php b/app/code/core/Mage/Checkout/Block/Onepage/Payment/Methods.php
index 2c13cfa2850..fe2e2930337 100644
--- a/app/code/core/Mage/Checkout/Block/Onepage/Payment/Methods.php
+++ b/app/code/core/Mage/Checkout/Block/Onepage/Payment/Methods.php
@@ -30,17 +30,6 @@ public function getQuote()
return Mage::getSingleton('checkout/session')->getQuote();
}
- /**
- * Check payment method model
- *
- * @param Mage_Payment_Model_Method_Abstract|null $method
- * @return bool
- */
- protected function _canUseMethod($method)
- {
- return $method && $method->canUseCheckout() && parent::_canUseMethod($method);
- }
-
/**
* Retrieve code of current payment method
*
@@ -88,4 +77,15 @@ public function getMethodLabelAfterHtml(Mage_Payment_Model_Method_Abstract $meth
}
return '';
}
+
+ /**
+ * Check payment method model
+ *
+ * @param Mage_Payment_Model_Method_Abstract|null $method
+ * @return bool
+ */
+ protected function _canUseMethod($method)
+ {
+ return $method && $method->canUseCheckout() && parent::_canUseMethod($method);
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Onepage/Shipping.php b/app/code/core/Mage/Checkout/Block/Onepage/Shipping.php
index 264ef595ad6..b2f8a4db57d 100644
--- a/app/code/core/Mage/Checkout/Block/Onepage/Shipping.php
+++ b/app/code/core/Mage/Checkout/Block/Onepage/Shipping.php
@@ -29,19 +29,6 @@ class Mage_Checkout_Block_Onepage_Shipping extends Mage_Checkout_Block_Onepage_A
*/
protected $_address = null;
- /**
- * Initialize shipping address step
- */
- protected function _construct()
- {
- $this->getCheckout()->setStepData('shipping', [
- 'label' => Mage::helper('checkout')->__('Shipping Information'),
- 'is_show' => $this->isShow(),
- ]);
-
- parent::_construct();
- }
-
/**
* Return checkout method
*
@@ -75,4 +62,17 @@ public function isShow()
{
return !$this->getQuote()->isVirtual();
}
+
+ /**
+ * Initialize shipping address step
+ */
+ protected function _construct()
+ {
+ $this->getCheckout()->setStepData('shipping', [
+ 'label' => Mage::helper('checkout')->__('Shipping Information'),
+ 'is_show' => $this->isShow(),
+ ]);
+
+ parent::_construct();
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Onepage/Shipping/Method.php b/app/code/core/Mage/Checkout/Block/Onepage/Shipping/Method.php
index 3769d2be55f..d4d56bab4c9 100644
--- a/app/code/core/Mage/Checkout/Block/Onepage/Shipping/Method.php
+++ b/app/code/core/Mage/Checkout/Block/Onepage/Shipping/Method.php
@@ -22,15 +22,6 @@
*/
class Mage_Checkout_Block_Onepage_Shipping_Method extends Mage_Checkout_Block_Onepage_Abstract
{
- protected function _construct()
- {
- $this->getCheckout()->setStepData('shipping_method', [
- 'label' => Mage::helper('checkout')->__('Shipping Method'),
- 'is_show' => $this->isShow(),
- ]);
- parent::_construct();
- }
-
/**
* Retrieve is allow and show block
*
@@ -40,4 +31,12 @@ public function isShow()
{
return !$this->getQuote()->isVirtual();
}
+ protected function _construct()
+ {
+ $this->getCheckout()->setStepData('shipping_method', [
+ 'label' => Mage::helper('checkout')->__('Shipping Method'),
+ 'is_show' => $this->isShow(),
+ ]);
+ parent::_construct();
+ }
}
diff --git a/app/code/core/Mage/Checkout/Block/Total/Default.php b/app/code/core/Mage/Checkout/Block/Total/Default.php
index 4e34127a47c..f6986596ec4 100644
--- a/app/code/core/Mage/Checkout/Block/Total/Default.php
+++ b/app/code/core/Mage/Checkout/Block/Total/Default.php
@@ -31,12 +31,6 @@ class Mage_Checkout_Block_Total_Default extends Mage_Checkout_Block_Cart_Totals
*/
protected $_store;
- protected function _construct()
- {
- $this->setTemplate($this->_template);
- $this->_store = Mage::app()->getStore();
- }
-
/**
* Get style assigned to total object
*
@@ -67,4 +61,10 @@ public function getStore()
{
return $this->_store;
}
+
+ protected function _construct()
+ {
+ $this->setTemplate($this->_template);
+ $this->_store = Mage::app()->getStore();
+ }
}
diff --git a/app/code/core/Mage/Checkout/Helper/Cart.php b/app/code/core/Mage/Checkout/Helper/Cart.php
index 1598aacc540..29c59958aeb 100644
--- a/app/code/core/Mage/Checkout/Helper/Cart.php
+++ b/app/code/core/Mage/Checkout/Helper/Cart.php
@@ -56,17 +56,6 @@ public function getAddUrl($product, $additional = [])
return $this->getAddUrlCustom($product, $additional);
}
- /**
- * Return helper instance
- *
- * @param string $helperName
- * @return Mage_Core_Helper_Abstract
- */
- protected function _getHelperInstance($helperName)
- {
- return Mage::helper($helperName);
- }
-
/**
* Retrieve url for remove product from cart
*
@@ -186,4 +175,15 @@ public function getAddUrlCustom($product, $additional = [], $addFormKey = true)
return $this->_getUrl('checkout/cart/add', $routeParams);
}
+
+ /**
+ * Return helper instance
+ *
+ * @param string $helperName
+ * @return Mage_Core_Helper_Abstract
+ */
+ protected function _getHelperInstance($helperName)
+ {
+ return Mage::helper($helperName);
+ }
}
diff --git a/app/code/core/Mage/Checkout/Helper/Data.php b/app/code/core/Mage/Checkout/Helper/Data.php
index 90d90e94924..8740da5d1d2 100644
--- a/app/code/core/Mage/Checkout/Helper/Data.php
+++ b/app/code/core/Mage/Checkout/Helper/Data.php
@@ -133,16 +133,6 @@ public function getSubtotalInclTax($item)
return $item->getRowTotal() + $tax;
}
- /**
- * Returns the helper for weee
- *
- * @return Mage_Weee_Helper_Data
- */
- protected function _getWeeeHelper()
- {
- return Mage::helper('weee');
- }
-
/**
* Get the base price of the item including tax , excluding weee
*
@@ -258,20 +248,6 @@ public function sendPaymentFailedEmail($checkout, $message, $checkoutType = 'one
return $this;
}
- /**
- * @param string $configPath
- * @param int $storeId
- * @return array|false
- */
- protected function _getEmails($configPath, $storeId)
- {
- $data = Mage::getStoreConfig($configPath, $storeId);
- if (!empty($data)) {
- return explode(',', $data);
- }
- return false;
- }
-
/**
* Check if multishipping checkout is available.
* There should be a valid quote in checkout session. If not, only the config value will be returned.
@@ -343,4 +319,28 @@ public function isCustomerMustBeLogged()
{
return Mage::getStoreConfigFlag(self::XML_PATH_CUSTOMER_MUST_BE_LOGGED);
}
+
+ /**
+ * Returns the helper for weee
+ *
+ * @return Mage_Weee_Helper_Data
+ */
+ protected function _getWeeeHelper()
+ {
+ return Mage::helper('weee');
+ }
+
+ /**
+ * @param string $configPath
+ * @param int $storeId
+ * @return array|false
+ */
+ protected function _getEmails($configPath, $storeId)
+ {
+ $data = Mage::getStoreConfig($configPath, $storeId);
+ if (!empty($data)) {
+ return explode(',', $data);
+ }
+ return false;
+ }
}
diff --git a/app/code/core/Mage/Checkout/Model/Api/Resource/Customer.php b/app/code/core/Mage/Checkout/Model/Api/Resource/Customer.php
index fcba96a74ef..a41cd79364d 100644
--- a/app/code/core/Mage/Checkout/Model/Api/Resource/Customer.php
+++ b/app/code/core/Mage/Checkout/Model/Api/Resource/Customer.php
@@ -35,6 +35,45 @@ class Mage_Checkout_Model_Api_Resource_Customer extends Mage_Checkout_Model_Api_
public const MODE_REGISTER = Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER;
public const MODE_GUEST = Mage_Checkout_Model_Type_Onepage::METHOD_GUEST;
+ /**
+ * @return bool
+ */
+ public function prepareCustomerForQuote(Mage_Sales_Model_Quote $quote)
+ {
+ $isNewCustomer = false;
+ switch ($quote->getCheckoutMethod()) {
+ case self::MODE_GUEST:
+ $this->_prepareGuestQuote($quote);
+ break;
+ case self::MODE_REGISTER:
+ $this->_prepareNewCustomerQuote($quote);
+ $isNewCustomer = true;
+ break;
+ default:
+ $this->_prepareCustomerQuote($quote);
+ break;
+ }
+
+ return $isNewCustomer;
+ }
+
+ /**
+ * Involve new customer to system
+ *
+ * @return $this
+ */
+ public function involveNewCustomer(Mage_Sales_Model_Quote $quote)
+ {
+ $customer = $quote->getCustomer();
+ if ($customer->isConfirmationRequired()) {
+ $customer->sendNewAccountEmail('confirmation');
+ } else {
+ $customer->sendNewAccountEmail();
+ }
+
+ return $this;
+ }
+
/**
* @param int $customerId
* @return Mage_Customer_Model_Customer
@@ -72,28 +111,6 @@ protected function _getCustomerAddress($addressId)
return $address;
}
- /**
- * @return bool
- */
- public function prepareCustomerForQuote(Mage_Sales_Model_Quote $quote)
- {
- $isNewCustomer = false;
- switch ($quote->getCheckoutMethod()) {
- case self::MODE_GUEST:
- $this->_prepareGuestQuote($quote);
- break;
- case self::MODE_REGISTER:
- $this->_prepareNewCustomerQuote($quote);
- $isNewCustomer = true;
- break;
- default:
- $this->_prepareCustomerQuote($quote);
- break;
- }
-
- return $isNewCustomer;
- }
-
/**
* Prepare quote for guest checkout order submit
*
@@ -179,21 +196,4 @@ protected function _prepareCustomerQuote(Mage_Sales_Model_Quote $quote)
return $this;
}
-
- /**
- * Involve new customer to system
- *
- * @return $this
- */
- public function involveNewCustomer(Mage_Sales_Model_Quote $quote)
- {
- $customer = $quote->getCustomer();
- if ($customer->isConfirmationRequired()) {
- $customer->sendNewAccountEmail('confirmation');
- } else {
- $customer->sendNewAccountEmail();
- }
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Checkout/Model/Cart.php b/app/code/core/Mage/Checkout/Model/Cart.php
index 2cab9d82441..c16e0145c22 100644
--- a/app/code/core/Mage/Checkout/Model/Cart.php
+++ b/app/code/core/Mage/Checkout/Model/Cart.php
@@ -36,16 +36,6 @@ class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Mo
*/
protected $_productIds;
- /**
- * Get shopping cart resource model
- *
- * @return Mage_Checkout_Model_Resource_Cart
- */
- protected function _getResource()
- {
- return Mage::getResourceSingleton('checkout/cart');
- }
-
/**
* Retrieve checkout session model
*
@@ -174,52 +164,6 @@ public function addOrderItem($orderItem, $qtyFlag = null)
return $this;
}
- /**
- * Get product object based on requested product information
- *
- * @param mixed $productInfo
- * @return Mage_Catalog_Model_Product
- */
- protected function _getProduct($productInfo)
- {
- $product = null;
- if ($productInfo instanceof Mage_Catalog_Model_Product) {
- $product = $productInfo;
- } elseif (is_int($productInfo) || is_string($productInfo)) {
- $product = Mage::getModel('catalog/product')
- ->setStoreId(Mage::app()->getStore()->getId())
- ->load($productInfo);
- }
- $currentWebsiteId = Mage::app()->getStore()->getWebsiteId();
- if (!$product
- || !$product->getId()
- || !is_array($product->getWebsiteIds())
- || !in_array($currentWebsiteId, $product->getWebsiteIds())
- ) {
- Mage::throwException(Mage::helper('checkout')->__('The product could not be found.'));
- }
- return $product;
- }
-
- /**
- * Get request for product add to cart procedure
- *
- * @param mixed $requestInfo
- * @return Varien_Object
- */
- protected function _getProductRequest($requestInfo)
- {
- if ($requestInfo instanceof Varien_Object) {
- $request = $requestInfo;
- } elseif (is_numeric($requestInfo)) {
- $request = new Varien_Object(['qty' => $requestInfo]);
- } else {
- $request = new Varien_Object($requestInfo);
- }
-
- return $request;
- }
-
/**
* Add product to shopping cart (quote)
*
@@ -598,4 +542,60 @@ public function updateItem($itemId, $requestInfo = null, $updatingParams = null)
$this->getCheckoutSession()->setLastAddedProductId($productId);
return $result;
}
+
+ /**
+ * Get shopping cart resource model
+ *
+ * @return Mage_Checkout_Model_Resource_Cart
+ */
+ protected function _getResource()
+ {
+ return Mage::getResourceSingleton('checkout/cart');
+ }
+
+ /**
+ * Get product object based on requested product information
+ *
+ * @param mixed $productInfo
+ * @return Mage_Catalog_Model_Product
+ */
+ protected function _getProduct($productInfo)
+ {
+ $product = null;
+ if ($productInfo instanceof Mage_Catalog_Model_Product) {
+ $product = $productInfo;
+ } elseif (is_int($productInfo) || is_string($productInfo)) {
+ $product = Mage::getModel('catalog/product')
+ ->setStoreId(Mage::app()->getStore()->getId())
+ ->load($productInfo);
+ }
+ $currentWebsiteId = Mage::app()->getStore()->getWebsiteId();
+ if (!$product
+ || !$product->getId()
+ || !is_array($product->getWebsiteIds())
+ || !in_array($currentWebsiteId, $product->getWebsiteIds())
+ ) {
+ Mage::throwException(Mage::helper('checkout')->__('The product could not be found.'));
+ }
+ return $product;
+ }
+
+ /**
+ * Get request for product add to cart procedure
+ *
+ * @param mixed $requestInfo
+ * @return Varien_Object
+ */
+ protected function _getProductRequest($requestInfo)
+ {
+ if ($requestInfo instanceof Varien_Object) {
+ $request = $requestInfo;
+ } elseif (is_numeric($requestInfo)) {
+ $request = new Varien_Object(['qty' => $requestInfo]);
+ } else {
+ $request = new Varien_Object($requestInfo);
+ }
+
+ return $request;
+ }
}
diff --git a/app/code/core/Mage/Checkout/Model/Cart/Payment/Api.php b/app/code/core/Mage/Checkout/Model/Cart/Payment/Api.php
index 649072f3c4e..ec1a0c438e4 100644
--- a/app/code/core/Mage/Checkout/Model/Cart/Payment/Api.php
+++ b/app/code/core/Mage/Checkout/Model/Cart/Payment/Api.php
@@ -22,72 +22,6 @@
*/
class Mage_Checkout_Model_Cart_Payment_Api extends Mage_Checkout_Model_Api_Resource
{
- /**
- * @param array $data
- * @return array
- */
- protected function _preparePaymentData($data)
- {
- if (!(is_array($data) && is_null($data[0]))) {
- return [];
- }
-
- return $data;
- }
-
- /**
- * @param Mage_Payment_Model_Method_Abstract $method
- * @param Mage_Sales_Model_Quote $quote
- * @return bool
- */
- protected function _canUsePaymentMethod($method, $quote)
- {
- if (!($method->isGateway() || $method->canUseInternal())) {
- return false;
- }
-
- if (!$method->canUseForCountry($quote->getBillingAddress()->getCountry())) {
- return false;
- }
-
- if (!$method->canUseForCurrency(Mage::app()->getStore($quote->getStoreId())->getBaseCurrencyCode())) {
- return false;
- }
-
- /**
- * Checking for min/max order total for assigned payment method
- */
- $total = $quote->getBaseGrandTotal();
- $minTotal = $method->getConfigData('min_order_total');
- $maxTotal = $method->getConfigData('max_order_total');
-
- if ((!empty($minTotal) && ($total < $minTotal)) || (!empty($maxTotal) && ($total > $maxTotal))) {
- return false;
- }
-
- return true;
- }
-
- /**
- * @param Mage_Payment_Model_Method_Abstract $method
- * @return array|null
- */
- protected function _getPaymentMethodAvailableCcTypes($method)
- {
- $ccTypes = Mage::getSingleton('payment/config')->getCcTypes();
- $methodCcTypes = explode(',', $method->getConfigData('cctypes'));
- foreach ($ccTypes as $code => $title) {
- if (!in_array($code, $methodCcTypes)) {
- unset($ccTypes[$code]);
- }
- }
- if (empty($ccTypes)) {
- return null;
- }
-
- return $ccTypes;
- }
-
/**
* Retrieve available payment methods for a quote
*
@@ -189,4 +123,69 @@ public function setPaymentMethod($quoteId, $paymentData, $store = null)
}
return true;
}
+ /**
+ * @param array $data
+ * @return array
+ */
+ protected function _preparePaymentData($data)
+ {
+ if (!(is_array($data) && is_null($data[0]))) {
+ return [];
+ }
+
+ return $data;
+ }
+
+ /**
+ * @param Mage_Payment_Model_Method_Abstract $method
+ * @param Mage_Sales_Model_Quote $quote
+ * @return bool
+ */
+ protected function _canUsePaymentMethod($method, $quote)
+ {
+ if (!($method->isGateway() || $method->canUseInternal())) {
+ return false;
+ }
+
+ if (!$method->canUseForCountry($quote->getBillingAddress()->getCountry())) {
+ return false;
+ }
+
+ if (!$method->canUseForCurrency(Mage::app()->getStore($quote->getStoreId())->getBaseCurrencyCode())) {
+ return false;
+ }
+
+ /**
+ * Checking for min/max order total for assigned payment method
+ */
+ $total = $quote->getBaseGrandTotal();
+ $minTotal = $method->getConfigData('min_order_total');
+ $maxTotal = $method->getConfigData('max_order_total');
+
+ if ((!empty($minTotal) && ($total < $minTotal)) || (!empty($maxTotal) && ($total > $maxTotal))) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * @param Mage_Payment_Model_Method_Abstract $method
+ * @return array|null
+ */
+ protected function _getPaymentMethodAvailableCcTypes($method)
+ {
+ $ccTypes = Mage::getSingleton('payment/config')->getCcTypes();
+ $methodCcTypes = explode(',', $method->getConfigData('cctypes'));
+ foreach ($ccTypes as $code => $title) {
+ if (!in_array($code, $methodCcTypes)) {
+ unset($ccTypes[$code]);
+ }
+ }
+ if (empty($ccTypes)) {
+ return null;
+ }
+
+ return $ccTypes;
+ }
}
diff --git a/app/code/core/Mage/Checkout/Model/Cart/Product/Api.php b/app/code/core/Mage/Checkout/Model/Cart/Product/Api.php
index 9d7c5fd8557..2afb21c3137 100644
--- a/app/code/core/Mage/Checkout/Model/Cart/Product/Api.php
+++ b/app/code/core/Mage/Checkout/Model/Cart/Product/Api.php
@@ -22,17 +22,6 @@
*/
class Mage_Checkout_Model_Cart_Product_Api extends Mage_Checkout_Model_Api_Resource_Product
{
- /**
- * Base preparation of product data
- *
- * @param mixed $data
- * @return null|array
- */
- protected function _prepareProductsData($data)
- {
- return is_array($data) ? $data : null;
- }
-
/**
* @param int $quoteId
* @param array $productsData
@@ -320,4 +309,14 @@ public function moveToCustomerQuote($quoteId, $productsData, $store = null)
return true;
}
+ /**
+ * Base preparation of product data
+ *
+ * @param mixed $data
+ * @return null|array
+ */
+ protected function _prepareProductsData($data)
+ {
+ return is_array($data) ? $data : null;
+ }
}
diff --git a/app/code/core/Mage/Checkout/Model/Resource/Agreement/Collection.php b/app/code/core/Mage/Checkout/Model/Resource/Agreement/Collection.php
index 2fee84a3ac0..5997169a6aa 100644
--- a/app/code/core/Mage/Checkout/Model/Resource/Agreement/Collection.php
+++ b/app/code/core/Mage/Checkout/Model/Resource/Agreement/Collection.php
@@ -33,15 +33,6 @@ class Mage_Checkout_Model_Resource_Agreement_Collection extends Mage_Core_Model_
*/
protected $_isStoreFilterWithAdmin = true;
- /**
- * Initialize resource
- *
- */
- protected function _construct()
- {
- $this->_init('checkout/agreement');
- }
-
/**
* Filter collection by specified store ids
*
@@ -97,4 +88,13 @@ public function setIsStoreFilterWithAdmin($value)
$this->_isStoreFilterWithAdmin = (bool) $value;
return $this;
}
+
+ /**
+ * Initialize resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('checkout/agreement');
+ }
}
diff --git a/app/code/core/Mage/Checkout/Model/Resource/Cart.php b/app/code/core/Mage/Checkout/Model/Resource/Cart.php
index 3174f2fe531..d4562a015a1 100644
--- a/app/code/core/Mage/Checkout/Model/Resource/Cart.php
+++ b/app/code/core/Mage/Checkout/Model/Resource/Cart.php
@@ -22,11 +22,6 @@
*/
class Mage_Checkout_Model_Resource_Cart extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/quote', 'entity_id');
- }
-
/**
* Fetch items summary
*
@@ -80,4 +75,8 @@ public function addExcludeProductFilter($collection, $quoteId)
$collection->getSelect()->where($condition);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote', 'entity_id');
+ }
}
diff --git a/app/code/core/Mage/Checkout/Model/Session.php b/app/code/core/Mage/Checkout/Model/Session.php
index aee6c546a9e..c38a85e21e8 100644
--- a/app/code/core/Mage/Checkout/Model/Session.php
+++ b/app/code/core/Mage/Checkout/Model/Session.php
@@ -248,15 +248,6 @@ public function getQuote()
return $this->_quote;
}
- /**
- * @return string
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _getQuoteIdKey()
- {
- return 'quote_id_' . Mage::app()->getStore()->getWebsiteId();
- }
-
/**
* @param int|null $quoteId
*/
@@ -525,6 +516,15 @@ public function getLastRealOrder()
return $this->_order;
}
+ /**
+ * @return string
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _getQuoteIdKey()
+ {
+ return 'quote_id_' . Mage::app()->getStore()->getWebsiteId();
+ }
+
/**
* Get order model
*
diff --git a/app/code/core/Mage/Checkout/Model/Type/Multishipping.php b/app/code/core/Mage/Checkout/Model/Type/Multishipping.php
index 87d196cddbf..b3ce622a6ac 100644
--- a/app/code/core/Mage/Checkout/Model/Type/Multishipping.php
+++ b/app/code/core/Mage/Checkout/Model/Type/Multishipping.php
@@ -40,64 +40,6 @@ public function __construct()
$this->_init();
}
- /**
- * Initialize multishipping checkout.
- * Split virtual/not virtual items between default billing/shipping addresses
- *
- * @return $this
- */
- protected function _init()
- {
- /**
- * reset quote shipping addresses and items
- */
- $quote = $this->getQuote();
- if (!$this->getCustomer()->getId()) {
- return $this;
- }
-
- if ($this->getCheckoutSession()->getCheckoutState() === Mage_Checkout_Model_Session::CHECKOUT_STATE_BEGIN) {
- $this->getCheckoutSession()->setCheckoutState(true);
- /**
- * Remove all addresses
- */
- $addresses = $quote->getAllAddresses();
- foreach ($addresses as $address) {
- $quote->removeAddress($address->getId());
- }
-
- if ($defaultShipping = $this->getCustomerDefaultShippingAddress()) {
- $quote->getShippingAddress()->importCustomerAddress($defaultShipping);
-
- foreach ($this->getQuoteItems() as $item) {
- /**
- * Items with parent id we add in importQuoteItem method.
- * Skip virtual items
- */
- if ($item->getParentItemId() || $item->getProduct()->getIsVirtual()) {
- continue;
- }
- $quote->getShippingAddress()->addItem($item);
- }
- }
-
- if ($this->getCustomerDefaultBillingAddress()) {
- $quote->getBillingAddress()
- ->importCustomerAddress($this->getCustomerDefaultBillingAddress());
- foreach ($this->getQuoteItems() as $item) {
- if ($item->getParentItemId()) {
- continue;
- }
- if ($item->getProduct()->getIsVirtual()) {
- $quote->getBillingAddress()->addItem($item);
- }
- }
- }
- $this->save();
- }
- return $this;
- }
-
/**
* Get quote items assigned to different quote addresses populated per item qty.
* Based on result array we can display each item separately
@@ -271,54 +213,6 @@ public function setShippingItemsInformation($info)
return $this;
}
- /**
- * Add quote item to specific shipping address based on customer address id
- *
- * @param int $quoteItemId
- * @param array $data array('qty'=>$qty, 'address'=>$customerAddressId)
- * @return $this
- */
- protected function _addShippingItem($quoteItemId, $data)
- {
- $qty = isset($data['qty']) ? (int) $data['qty'] : 1;
- //$qty = $qty > 0 ? $qty : 1;
- $addressId = $data['address'] ?? false;
- $quoteItem = $this->getQuote()->getItemById($quoteItemId);
-
- if ($addressId && $quoteItem) {
- /**
- * Skip item processing if qty 0
- */
- if ($qty === 0) {
- return $this;
- }
- $quoteItem->setMultishippingQty((int) $quoteItem->getMultishippingQty() + $qty);
- $quoteItem->setQty($quoteItem->getMultishippingQty());
- $address = $this->getCustomer()->getAddressById($addressId);
- if ($address->getId()) {
- if (!$quoteAddress = $this->getQuote()->getShippingAddressByCustomerAddressId($address->getId())) {
- $quoteAddress = Mage::getModel('sales/quote_address')->importCustomerAddress($address);
- $this->getQuote()->addShippingAddress($quoteAddress);
- if ($couponCode = $this->getCheckoutSession()->getCartCouponCode()) {
- $this->getQuote()->setCouponCode($couponCode);
- }
- }
-
- $quoteAddress = $this->getQuote()->getShippingAddressByCustomerAddressId($address->getId());
- if ($quoteAddressItem = $quoteAddress->getItemByQuoteItemId($quoteItemId)) {
- $quoteAddressItem->setQty((int) ($quoteAddressItem->getQty() + $qty));
- } else {
- $quoteAddress->addItem($quoteItem, $qty);
- }
- /**
- * Require shipping rate recollect
- */
- $quoteAddress->setCollectShippingRates((bool) $this->getCollectRatesFlag());
- }
- }
- return $this;
- }
-
/**
* Reimport customer address info to quote shipping address
*
@@ -396,92 +290,6 @@ public function setPaymentMethod($payment)
return $this;
}
- /**
- * Prepare order based on quote address
- *
- * @return Mage_Sales_Model_Order
- * @throws Mage_Checkout_Exception
- */
- protected function _prepareOrder(Mage_Sales_Model_Quote_Address $address)
- {
- $quote = $this->getQuote();
- $quote->unsReservedOrderId();
- $quote->reserveOrderId();
- $quote->collectTotals();
-
- $convertQuote = Mage::getSingleton('sales/convert_quote');
- $order = $convertQuote->addressToOrder($address);
- $order->setQuote($quote);
- $order->setBillingAddress(
- $convertQuote->addressToOrderAddress($quote->getBillingAddress()),
- );
-
- if ($address->getAddressType() == 'billing') {
- $order->setIsVirtual(1);
- } else {
- $order->setShippingAddress($convertQuote->addressToOrderAddress($address));
- }
-
- $order->setPayment($convertQuote->paymentToOrderPayment($quote->getPayment()));
- if (Mage::app()->getStore()->roundPrice($address->getGrandTotal()) == 0) {
- $order->getPayment()->setMethod('free');
- }
-
- foreach ($address->getAllItems() as $item) {
- $_quoteItem = $item->getQuoteItem();
- if (!$_quoteItem) {
- throw new Mage_Checkout_Exception(Mage::helper('checkout')->__('Item not found or already ordered'));
- }
- $item->setProductType($_quoteItem->getProductType())
- ->setProductOptions(
- $_quoteItem->getProduct()->getTypeInstance(true)->getOrderOptions($_quoteItem->getProduct()),
- );
- $orderItem = $convertQuote->itemToOrderItem($item);
- if ($item->getParentItem()) {
- $orderItem->setParentItem($order->getItemByQuoteItemId($item->getParentItem()->getId()));
- }
- $order->addItem($orderItem);
- }
-
- return $order;
- }
-
- /**
- * Validate quote data
- *
- * @return $this
- */
- protected function _validate()
- {
- $quote = $this->getQuote();
- if (!$quote->getIsMultiShipping()) {
- Mage::throwException(Mage::helper('checkout')->__('Invalid checkout type.'));
- }
-
- $paymentMethod = $quote->getPayment()->getMethodInstance();
- if (!empty($paymentMethod) && !$paymentMethod->isAvailable($quote)) {
- Mage::throwException(Mage::helper('checkout')->__('Please specify payment method.'));
- }
-
- $addresses = $quote->getAllShippingAddresses();
- foreach ($addresses as $address) {
- $addressValidation = $address->validate();
- if ($addressValidation !== true) {
- Mage::throwException(Mage::helper('checkout')->__('Please check shipping addresses information.'));
- }
- $method = $address->getShippingMethod();
- $rate = $address->getShippingRateByCode($method);
- if (!$method || !$rate) {
- Mage::throwException(Mage::helper('checkout')->__('Please specify shipping methods for all addresses.'));
- }
- }
- $addressValidation = $quote->getBillingAddress()->validate();
- if ($addressValidation !== true) {
- Mage::throwException(Mage::helper('checkout')->__('Please check billing address information.'));
- }
- return $this;
- }
-
/**
* Create orders per each quote address
*
@@ -620,4 +428,196 @@ public function getOrderIds($asAssoc = false)
$idsAssoc = Mage::getSingleton('core/session')->getOrderIds();
return $asAssoc ? $idsAssoc : array_keys($idsAssoc);
}
+
+ /**
+ * Initialize multishipping checkout.
+ * Split virtual/not virtual items between default billing/shipping addresses
+ *
+ * @return $this
+ */
+ protected function _init()
+ {
+ /**
+ * reset quote shipping addresses and items
+ */
+ $quote = $this->getQuote();
+ if (!$this->getCustomer()->getId()) {
+ return $this;
+ }
+
+ if ($this->getCheckoutSession()->getCheckoutState() === Mage_Checkout_Model_Session::CHECKOUT_STATE_BEGIN) {
+ $this->getCheckoutSession()->setCheckoutState(true);
+ /**
+ * Remove all addresses
+ */
+ $addresses = $quote->getAllAddresses();
+ foreach ($addresses as $address) {
+ $quote->removeAddress($address->getId());
+ }
+
+ if ($defaultShipping = $this->getCustomerDefaultShippingAddress()) {
+ $quote->getShippingAddress()->importCustomerAddress($defaultShipping);
+
+ foreach ($this->getQuoteItems() as $item) {
+ /**
+ * Items with parent id we add in importQuoteItem method.
+ * Skip virtual items
+ */
+ if ($item->getParentItemId() || $item->getProduct()->getIsVirtual()) {
+ continue;
+ }
+ $quote->getShippingAddress()->addItem($item);
+ }
+ }
+
+ if ($this->getCustomerDefaultBillingAddress()) {
+ $quote->getBillingAddress()
+ ->importCustomerAddress($this->getCustomerDefaultBillingAddress());
+ foreach ($this->getQuoteItems() as $item) {
+ if ($item->getParentItemId()) {
+ continue;
+ }
+ if ($item->getProduct()->getIsVirtual()) {
+ $quote->getBillingAddress()->addItem($item);
+ }
+ }
+ }
+ $this->save();
+ }
+ return $this;
+ }
+
+ /**
+ * Add quote item to specific shipping address based on customer address id
+ *
+ * @param int $quoteItemId
+ * @param array $data array('qty'=>$qty, 'address'=>$customerAddressId)
+ * @return $this
+ */
+ protected function _addShippingItem($quoteItemId, $data)
+ {
+ $qty = isset($data['qty']) ? (int) $data['qty'] : 1;
+ //$qty = $qty > 0 ? $qty : 1;
+ $addressId = $data['address'] ?? false;
+ $quoteItem = $this->getQuote()->getItemById($quoteItemId);
+
+ if ($addressId && $quoteItem) {
+ /**
+ * Skip item processing if qty 0
+ */
+ if ($qty === 0) {
+ return $this;
+ }
+ $quoteItem->setMultishippingQty((int) $quoteItem->getMultishippingQty() + $qty);
+ $quoteItem->setQty($quoteItem->getMultishippingQty());
+ $address = $this->getCustomer()->getAddressById($addressId);
+ if ($address->getId()) {
+ if (!$quoteAddress = $this->getQuote()->getShippingAddressByCustomerAddressId($address->getId())) {
+ $quoteAddress = Mage::getModel('sales/quote_address')->importCustomerAddress($address);
+ $this->getQuote()->addShippingAddress($quoteAddress);
+ if ($couponCode = $this->getCheckoutSession()->getCartCouponCode()) {
+ $this->getQuote()->setCouponCode($couponCode);
+ }
+ }
+
+ $quoteAddress = $this->getQuote()->getShippingAddressByCustomerAddressId($address->getId());
+ if ($quoteAddressItem = $quoteAddress->getItemByQuoteItemId($quoteItemId)) {
+ $quoteAddressItem->setQty((int) ($quoteAddressItem->getQty() + $qty));
+ } else {
+ $quoteAddress->addItem($quoteItem, $qty);
+ }
+ /**
+ * Require shipping rate recollect
+ */
+ $quoteAddress->setCollectShippingRates((bool) $this->getCollectRatesFlag());
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Prepare order based on quote address
+ *
+ * @return Mage_Sales_Model_Order
+ * @throws Mage_Checkout_Exception
+ */
+ protected function _prepareOrder(Mage_Sales_Model_Quote_Address $address)
+ {
+ $quote = $this->getQuote();
+ $quote->unsReservedOrderId();
+ $quote->reserveOrderId();
+ $quote->collectTotals();
+
+ $convertQuote = Mage::getSingleton('sales/convert_quote');
+ $order = $convertQuote->addressToOrder($address);
+ $order->setQuote($quote);
+ $order->setBillingAddress(
+ $convertQuote->addressToOrderAddress($quote->getBillingAddress()),
+ );
+
+ if ($address->getAddressType() == 'billing') {
+ $order->setIsVirtual(1);
+ } else {
+ $order->setShippingAddress($convertQuote->addressToOrderAddress($address));
+ }
+
+ $order->setPayment($convertQuote->paymentToOrderPayment($quote->getPayment()));
+ if (Mage::app()->getStore()->roundPrice($address->getGrandTotal()) == 0) {
+ $order->getPayment()->setMethod('free');
+ }
+
+ foreach ($address->getAllItems() as $item) {
+ $_quoteItem = $item->getQuoteItem();
+ if (!$_quoteItem) {
+ throw new Mage_Checkout_Exception(Mage::helper('checkout')->__('Item not found or already ordered'));
+ }
+ $item->setProductType($_quoteItem->getProductType())
+ ->setProductOptions(
+ $_quoteItem->getProduct()->getTypeInstance(true)->getOrderOptions($_quoteItem->getProduct()),
+ );
+ $orderItem = $convertQuote->itemToOrderItem($item);
+ if ($item->getParentItem()) {
+ $orderItem->setParentItem($order->getItemByQuoteItemId($item->getParentItem()->getId()));
+ }
+ $order->addItem($orderItem);
+ }
+
+ return $order;
+ }
+
+ /**
+ * Validate quote data
+ *
+ * @return $this
+ */
+ protected function _validate()
+ {
+ $quote = $this->getQuote();
+ if (!$quote->getIsMultiShipping()) {
+ Mage::throwException(Mage::helper('checkout')->__('Invalid checkout type.'));
+ }
+
+ $paymentMethod = $quote->getPayment()->getMethodInstance();
+ if (!empty($paymentMethod) && !$paymentMethod->isAvailable($quote)) {
+ Mage::throwException(Mage::helper('checkout')->__('Please specify payment method.'));
+ }
+
+ $addresses = $quote->getAllShippingAddresses();
+ foreach ($addresses as $address) {
+ $addressValidation = $address->validate();
+ if ($addressValidation !== true) {
+ Mage::throwException(Mage::helper('checkout')->__('Please check shipping addresses information.'));
+ }
+ $method = $address->getShippingMethod();
+ $rate = $address->getShippingRateByCode($method);
+ if (!$method || !$rate) {
+ Mage::throwException(Mage::helper('checkout')->__('Please specify shipping methods for all addresses.'));
+ }
+ }
+ $addressValidation = $quote->getBillingAddress()->validate();
+ if ($addressValidation !== true) {
+ Mage::throwException(Mage::helper('checkout')->__('Please check billing address information.'));
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Checkout/Model/Type/Onepage.php b/app/code/core/Mage/Checkout/Model/Type/Onepage.php
index 3ff917162cb..748201ed69b 100644
--- a/app/code/core/Mage/Checkout/Model/Type/Onepage.php
+++ b/app/code/core/Mage/Checkout/Model/Type/Onepage.php
@@ -29,13 +29,6 @@ class Mage_Checkout_Model_Type_Onepage
public const METHOD_REGISTER = 'register';
public const METHOD_CUSTOMER = 'customer';
- /**
- * Error message of "customer already exists"
- *
- * @var string
- */
- private $_customerEmailExistsMessage = '';
-
/**
* @var Mage_Customer_Model_Session
*/
@@ -56,6 +49,13 @@ class Mage_Checkout_Model_Type_Onepage
*/
protected $_helper;
+ /**
+ * Error message of "customer already exists"
+ *
+ * @var string
+ */
+ private $_customerEmailExistsMessage = '';
+
/**
* Class constructor
* Set customer already exists message
@@ -373,150 +373,6 @@ public function saveBilling($data, $customerAddressId)
return [];
}
- /**
- * Validate customer data and set some its data for further usage in quote
- * Will return either true or array with error messages
- *
- * @return true|array
- */
- protected function _validateCustomerData(array $data)
- {
- /** @var Mage_Customer_Model_Form $customerForm */
- $customerForm = Mage::getModel('customer/form');
- $customerForm->setFormCode('checkout_register')
- ->setIsAjaxRequest(Mage::app()->getRequest()->isAjax());
-
- $quote = $this->getQuote();
- if ($quote->getCustomerId()) {
- $customer = $quote->getCustomer();
- $customerForm->setEntity($customer);
- $customerData = $quote->getCustomer()->getData();
- } else {
- /** @var Mage_Customer_Model_Customer $customer */
- $customer = Mage::getModel('customer/customer');
- $customerForm->setEntity($customer);
- $customerRequest = $customerForm->prepareRequest($data);
- $customerData = $customerForm->extractData($customerRequest);
- }
-
- $customerErrors = $customerForm->validateData($customerData);
- if ($customerErrors !== true) {
- return [
- 'error' => -1,
- 'message' => implode(', ', $customerErrors),
- ];
- }
-
- if ($quote->getCustomerId()) {
- return true;
- }
-
- $customerForm->compactData($customerData);
-
- if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
- // set customer password
- $customer->setPassword($customerRequest->getParam('customer_password'));
- $customer->setPasswordConfirmation($customerRequest->getParam('confirm_password'));
- } else {
- // spoof customer password for guest
- $password = $customer->generatePassword();
- $customer->setPassword($password);
- $customer->setPasswordConfirmation($password);
- // set NOT LOGGED IN group id explicitly,
- // otherwise copyFieldset('customer_account', 'to_quote') will fill it with default group id value
- $customer->setGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
- }
-
- $result = $customer->validate();
- if ($result !== true && is_array($result)) {
- return [
- 'error' => -1,
- 'message' => implode(', ', $result),
- ];
- }
-
- if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
- // save customer encrypted password in quote
- $quote->setPasswordHash($customer->encryptPassword($customer->getPassword()));
- }
-
- // copy customer/guest email to address
- $quote->getBillingAddress()->setEmail($customer->getEmail());
-
- // copy customer data to quote
- Mage::helper('core')->copyFieldset('customer_account', 'to_quote', $customer, $quote);
-
- return true;
- }
-
- /**
- * Validate customer data and set some its data for further usage in quote
- * Will return either true or array with error messages
- *
- * @deprecated since 1.4.0.1
- * @return true|array
- */
- protected function _processValidateCustomer(Mage_Sales_Model_Quote_Address $address)
- {
- // set customer date of birth for further usage
- $dob = '';
- if ($address->getDob()) {
- $dob = Mage::app()->getLocale()->date($address->getDob(), null, null, false)->toString('yyyy-MM-dd');
- $this->getQuote()->setCustomerDob($dob);
- }
-
- // set customer tax/vat number for further usage
- if ($address->getTaxvat()) {
- $this->getQuote()->setCustomerTaxvat($address->getTaxvat());
- }
-
- // set customer gender for further usage
- if ($address->getGender()) {
- $this->getQuote()->setCustomerGender($address->getGender());
- }
-
- // invoke customer model, if it is registering
- if (self::METHOD_REGISTER == $this->getQuote()->getCheckoutMethod()) {
- // set customer password hash for further usage
- $customer = Mage::getModel('customer/customer');
- $this->getQuote()->setPasswordHash($customer->encryptPassword($address->getCustomerPassword()));
-
- // validate customer
- foreach ([
- 'firstname' => 'firstname',
- 'lastname' => 'lastname',
- 'email' => 'email',
- 'password' => 'customer_password',
- 'confirmation' => 'confirm_password',
- 'taxvat' => 'taxvat',
- 'gender' => 'gender',
- ] as $key => $dataKey
- ) {
- $customer->setData($key, $address->getData($dataKey));
- }
- if ($dob) {
- $customer->setDob($dob);
- }
- $validationResult = $customer->validate();
- if ($validationResult !== true && is_array($validationResult)) {
- return [
- 'error' => -1,
- 'message' => implode(', ', $validationResult),
- ];
- }
- } elseif (self::METHOD_GUEST == $this->getQuote()->getCheckoutMethod()) {
- $email = $address->getData('email');
- if (!Zend_Validate::is($email, 'EmailAddress')) {
- return [
- 'error' => -1,
- 'message' => Mage::helper('checkout')->__('Invalid email address "%s"', $email),
- ];
- }
- }
-
- return true;
- }
-
/**
* Save checkout shipping address
*
@@ -675,144 +531,41 @@ public function validate()
}
/**
- * Prepare quote for guest checkout order submit
+ * Create order based on checkout type. Create customer if necessary.
*
* @return $this
*/
- protected function _prepareGuestQuote()
- {
- $quote = $this->getQuote();
- $quote->setCustomerId(null)
- ->setCustomerEmail($quote->getBillingAddress()->getEmail())
- ->setCustomerIsGuest(true)
- ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
- return $this;
- }
-
- /**
- * Prepare quote for customer registration and customer order submit
- */
- protected function _prepareNewCustomerQuote()
+ public function saveOrder()
{
- $quote = $this->getQuote();
- $billing = $quote->getBillingAddress();
- $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress();
-
- //$customer = Mage::getModel('customer/customer');
- $customer = $quote->getCustomer();
- /** @var Mage_Customer_Model_Customer $customer */
- $customerBilling = $billing->exportCustomerAddress();
- $customer->addAddress($customerBilling);
- $billing->setCustomerAddress($customerBilling);
- $customerBilling->setIsDefaultBilling(true);
- if ($shipping && !$shipping->getSameAsBilling()) {
- $customerShipping = $shipping->exportCustomerAddress();
- $customer->addAddress($customerShipping);
- $shipping->setCustomerAddress($customerShipping);
- $customerShipping->setIsDefaultShipping(true);
- } else {
- $customerBilling->setIsDefaultShipping(true);
+ $this->validate();
+ $isNewCustomer = false;
+ switch ($this->getCheckoutMethod()) {
+ case self::METHOD_GUEST:
+ $this->_prepareGuestQuote();
+ break;
+ case self::METHOD_REGISTER:
+ $this->_prepareNewCustomerQuote();
+ $isNewCustomer = true;
+ break;
+ default:
+ $this->_prepareCustomerQuote();
+ break;
}
- Mage::helper('core')->copyFieldset('checkout_onepage_quote', 'to_customer', $quote, $customer);
- $customer->setPassword($customer->decryptPassword($quote->getPasswordHash()));
- $customer->setPasswordCreatedAt(time());
- $quote->setCustomer($customer)
- ->setCustomerId(true);
- $quote->setPasswordHash('');
- }
-
- /**
- * Prepare quote for customer order submit
- */
- protected function _prepareCustomerQuote()
- {
- $quote = $this->getQuote();
- $billing = $quote->getBillingAddress();
- $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress();
+ $service = Mage::getModel('sales/service_quote', $this->getQuote());
+ $service->submitAll();
- $customer = $this->getCustomerSession()->getCustomer();
- if (!$billing->getCustomerId() || $billing->getSaveInAddressBook()) {
- $customerBilling = $billing->exportCustomerAddress();
- $customer->addAddress($customerBilling);
- $billing->setCustomerAddress($customerBilling);
- }
- if ($shipping && !$shipping->getSameAsBilling() &&
- (!$shipping->getCustomerId() || $shipping->getSaveInAddressBook())
- ) {
- $customerShipping = $shipping->exportCustomerAddress();
- $customer->addAddress($customerShipping);
- $shipping->setCustomerAddress($customerShipping);
+ if ($isNewCustomer) {
+ try {
+ $this->_involveNewCustomer();
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
}
- if (isset($customerBilling) && !$customer->getDefaultBilling()) {
- $customerBilling->setIsDefaultBilling(true);
- }
- if ($shipping && isset($customerShipping) && !$customer->getDefaultShipping()) {
- $customerShipping->setIsDefaultShipping(true);
- } elseif (isset($customerBilling) && !$customer->getDefaultShipping()) {
- $customerBilling->setIsDefaultShipping(true);
- }
- $quote->setCustomer($customer);
- }
-
- /**
- * Involve new customer to system
- *
- * @return $this
- */
- protected function _involveNewCustomer()
- {
- $customer = $this->getQuote()->getCustomer();
- if ($customer->isConfirmationRequired()) {
- $customer->sendNewAccountEmail('confirmation', '', $this->getQuote()->getStoreId());
- $url = Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail());
- $this->getCustomerSession()->addSuccess(
- Mage::helper('customer')->__('Account confirmation is required. Please, check your e-mail for confirmation link. To resend confirmation email please click here.', $url),
- );
- } else {
- $customer->sendNewAccountEmail('registered', '', $this->getQuote()->getStoreId());
- $this->getCustomerSession()->loginById($customer->getId());
- }
- return $this;
- }
-
- /**
- * Create order based on checkout type. Create customer if necessary.
- *
- * @return $this
- */
- public function saveOrder()
- {
- $this->validate();
- $isNewCustomer = false;
- switch ($this->getCheckoutMethod()) {
- case self::METHOD_GUEST:
- $this->_prepareGuestQuote();
- break;
- case self::METHOD_REGISTER:
- $this->_prepareNewCustomerQuote();
- $isNewCustomer = true;
- break;
- default:
- $this->_prepareCustomerQuote();
- break;
- }
-
- $service = Mage::getModel('sales/service_quote', $this->getQuote());
- $service->submitAll();
-
- if ($isNewCustomer) {
- try {
- $this->_involveNewCustomer();
- } catch (Exception $e) {
- Mage::logException($e);
- }
- }
-
- $this->_checkoutSession->setLastQuoteId($this->getQuote()->getId())
- ->setLastSuccessQuoteId($this->getQuote()->getId())
- ->clearHelperData();
+ $this->_checkoutSession->setLastQuoteId($this->getQuote()->getId())
+ ->setLastSuccessQuoteId($this->getQuote()->getId())
+ ->clearHelperData();
$order = $service->getOrder();
if ($order) {
@@ -869,6 +622,270 @@ public function saveOrder()
return $this;
}
+ /**
+ * Get last order increment id by order id
+ *
+ * @return string
+ */
+ public function getLastOrderId()
+ {
+ $lastId = $this->getCheckout()->getLastOrderId();
+ $orderId = false;
+ if ($lastId) {
+ $order = Mage::getModel('sales/order');
+ $order->load($lastId);
+ $orderId = $order->getIncrementId();
+ }
+ return $orderId;
+ }
+
+ /**
+ * Validate customer data and set some its data for further usage in quote
+ * Will return either true or array with error messages
+ *
+ * @return true|array
+ */
+ protected function _validateCustomerData(array $data)
+ {
+ /** @var Mage_Customer_Model_Form $customerForm */
+ $customerForm = Mage::getModel('customer/form');
+ $customerForm->setFormCode('checkout_register')
+ ->setIsAjaxRequest(Mage::app()->getRequest()->isAjax());
+
+ $quote = $this->getQuote();
+ if ($quote->getCustomerId()) {
+ $customer = $quote->getCustomer();
+ $customerForm->setEntity($customer);
+ $customerData = $quote->getCustomer()->getData();
+ } else {
+ /** @var Mage_Customer_Model_Customer $customer */
+ $customer = Mage::getModel('customer/customer');
+ $customerForm->setEntity($customer);
+ $customerRequest = $customerForm->prepareRequest($data);
+ $customerData = $customerForm->extractData($customerRequest);
+ }
+
+ $customerErrors = $customerForm->validateData($customerData);
+ if ($customerErrors !== true) {
+ return [
+ 'error' => -1,
+ 'message' => implode(', ', $customerErrors),
+ ];
+ }
+
+ if ($quote->getCustomerId()) {
+ return true;
+ }
+
+ $customerForm->compactData($customerData);
+
+ if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
+ // set customer password
+ $customer->setPassword($customerRequest->getParam('customer_password'));
+ $customer->setPasswordConfirmation($customerRequest->getParam('confirm_password'));
+ } else {
+ // spoof customer password for guest
+ $password = $customer->generatePassword();
+ $customer->setPassword($password);
+ $customer->setPasswordConfirmation($password);
+ // set NOT LOGGED IN group id explicitly,
+ // otherwise copyFieldset('customer_account', 'to_quote') will fill it with default group id value
+ $customer->setGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
+ }
+
+ $result = $customer->validate();
+ if ($result !== true && is_array($result)) {
+ return [
+ 'error' => -1,
+ 'message' => implode(', ', $result),
+ ];
+ }
+
+ if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
+ // save customer encrypted password in quote
+ $quote->setPasswordHash($customer->encryptPassword($customer->getPassword()));
+ }
+
+ // copy customer/guest email to address
+ $quote->getBillingAddress()->setEmail($customer->getEmail());
+
+ // copy customer data to quote
+ Mage::helper('core')->copyFieldset('customer_account', 'to_quote', $customer, $quote);
+
+ return true;
+ }
+
+ /**
+ * Validate customer data and set some its data for further usage in quote
+ * Will return either true or array with error messages
+ *
+ * @deprecated since 1.4.0.1
+ * @return true|array
+ */
+ protected function _processValidateCustomer(Mage_Sales_Model_Quote_Address $address)
+ {
+ // set customer date of birth for further usage
+ $dob = '';
+ if ($address->getDob()) {
+ $dob = Mage::app()->getLocale()->date($address->getDob(), null, null, false)->toString('yyyy-MM-dd');
+ $this->getQuote()->setCustomerDob($dob);
+ }
+
+ // set customer tax/vat number for further usage
+ if ($address->getTaxvat()) {
+ $this->getQuote()->setCustomerTaxvat($address->getTaxvat());
+ }
+
+ // set customer gender for further usage
+ if ($address->getGender()) {
+ $this->getQuote()->setCustomerGender($address->getGender());
+ }
+
+ // invoke customer model, if it is registering
+ if (self::METHOD_REGISTER == $this->getQuote()->getCheckoutMethod()) {
+ // set customer password hash for further usage
+ $customer = Mage::getModel('customer/customer');
+ $this->getQuote()->setPasswordHash($customer->encryptPassword($address->getCustomerPassword()));
+
+ // validate customer
+ foreach ([
+ 'firstname' => 'firstname',
+ 'lastname' => 'lastname',
+ 'email' => 'email',
+ 'password' => 'customer_password',
+ 'confirmation' => 'confirm_password',
+ 'taxvat' => 'taxvat',
+ 'gender' => 'gender',
+ ] as $key => $dataKey
+ ) {
+ $customer->setData($key, $address->getData($dataKey));
+ }
+ if ($dob) {
+ $customer->setDob($dob);
+ }
+ $validationResult = $customer->validate();
+ if ($validationResult !== true && is_array($validationResult)) {
+ return [
+ 'error' => -1,
+ 'message' => implode(', ', $validationResult),
+ ];
+ }
+ } elseif (self::METHOD_GUEST == $this->getQuote()->getCheckoutMethod()) {
+ $email = $address->getData('email');
+ if (!Zend_Validate::is($email, 'EmailAddress')) {
+ return [
+ 'error' => -1,
+ 'message' => Mage::helper('checkout')->__('Invalid email address "%s"', $email),
+ ];
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Prepare quote for guest checkout order submit
+ *
+ * @return $this
+ */
+ protected function _prepareGuestQuote()
+ {
+ $quote = $this->getQuote();
+ $quote->setCustomerId(null)
+ ->setCustomerEmail($quote->getBillingAddress()->getEmail())
+ ->setCustomerIsGuest(true)
+ ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
+ return $this;
+ }
+
+ /**
+ * Prepare quote for customer registration and customer order submit
+ */
+ protected function _prepareNewCustomerQuote()
+ {
+ $quote = $this->getQuote();
+ $billing = $quote->getBillingAddress();
+ $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress();
+
+ //$customer = Mage::getModel('customer/customer');
+ $customer = $quote->getCustomer();
+ /** @var Mage_Customer_Model_Customer $customer */
+ $customerBilling = $billing->exportCustomerAddress();
+ $customer->addAddress($customerBilling);
+ $billing->setCustomerAddress($customerBilling);
+ $customerBilling->setIsDefaultBilling(true);
+ if ($shipping && !$shipping->getSameAsBilling()) {
+ $customerShipping = $shipping->exportCustomerAddress();
+ $customer->addAddress($customerShipping);
+ $shipping->setCustomerAddress($customerShipping);
+ $customerShipping->setIsDefaultShipping(true);
+ } else {
+ $customerBilling->setIsDefaultShipping(true);
+ }
+
+ Mage::helper('core')->copyFieldset('checkout_onepage_quote', 'to_customer', $quote, $customer);
+ $customer->setPassword($customer->decryptPassword($quote->getPasswordHash()));
+ $customer->setPasswordCreatedAt(time());
+ $quote->setCustomer($customer)
+ ->setCustomerId(true);
+ $quote->setPasswordHash('');
+ }
+
+ /**
+ * Prepare quote for customer order submit
+ */
+ protected function _prepareCustomerQuote()
+ {
+ $quote = $this->getQuote();
+ $billing = $quote->getBillingAddress();
+ $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress();
+
+ $customer = $this->getCustomerSession()->getCustomer();
+ if (!$billing->getCustomerId() || $billing->getSaveInAddressBook()) {
+ $customerBilling = $billing->exportCustomerAddress();
+ $customer->addAddress($customerBilling);
+ $billing->setCustomerAddress($customerBilling);
+ }
+ if ($shipping && !$shipping->getSameAsBilling() &&
+ (!$shipping->getCustomerId() || $shipping->getSaveInAddressBook())
+ ) {
+ $customerShipping = $shipping->exportCustomerAddress();
+ $customer->addAddress($customerShipping);
+ $shipping->setCustomerAddress($customerShipping);
+ }
+
+ if (isset($customerBilling) && !$customer->getDefaultBilling()) {
+ $customerBilling->setIsDefaultBilling(true);
+ }
+ if ($shipping && isset($customerShipping) && !$customer->getDefaultShipping()) {
+ $customerShipping->setIsDefaultShipping(true);
+ } elseif (isset($customerBilling) && !$customer->getDefaultShipping()) {
+ $customerBilling->setIsDefaultShipping(true);
+ }
+ $quote->setCustomer($customer);
+ }
+
+ /**
+ * Involve new customer to system
+ *
+ * @return $this
+ */
+ protected function _involveNewCustomer()
+ {
+ $customer = $this->getQuote()->getCustomer();
+ if ($customer->isConfirmationRequired()) {
+ $customer->sendNewAccountEmail('confirmation', '', $this->getQuote()->getStoreId());
+ $url = Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail());
+ $this->getCustomerSession()->addSuccess(
+ Mage::helper('customer')->__('Account confirmation is required. Please, check your e-mail for confirmation link. To resend confirmation email please click here.', $url),
+ );
+ } else {
+ $customer->sendNewAccountEmail('registered', '', $this->getQuote()->getStoreId());
+ $this->getCustomerSession()->loginById($customer->getId());
+ }
+ return $this;
+ }
+
/**
* Validate quote state to be able submitted from one page checkout page
*
@@ -924,23 +941,6 @@ protected function _customerEmailExists($email, $websiteId = null)
return false;
}
- /**
- * Get last order increment id by order id
- *
- * @return string
- */
- public function getLastOrderId()
- {
- $lastId = $this->getCheckout()->getLastOrderId();
- $orderId = false;
- if ($lastId) {
- $order = Mage::getModel('sales/order');
- $order->load($lastId);
- $orderId = $order->getIncrementId();
- }
- return $orderId;
- }
-
/**
* Sets cart coupon code from checkout to quote
*
diff --git a/app/code/core/Mage/Checkout/controllers/CartController.php b/app/code/core/Mage/Checkout/controllers/CartController.php
index a987bf157ab..96c28e012e4 100644
--- a/app/code/core/Mage/Checkout/controllers/CartController.php
+++ b/app/code/core/Mage/Checkout/controllers/CartController.php
@@ -29,87 +29,6 @@ class Mage_Checkout_CartController extends Mage_Core_Controller_Front_Action
*/
protected $_cookieCheckActions = ['add'];
- /**
- * Retrieve shopping cart model object
- *
- * @return Mage_Checkout_Model_Cart
- */
- protected function _getCart()
- {
- return Mage::getSingleton('checkout/cart');
- }
-
- /**
- * Get checkout session model instance
- *
- * @return Mage_Checkout_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('checkout/session');
- }
-
- /**
- * Get current active quote instance
- *
- * @return Mage_Sales_Model_Quote
- */
- protected function _getQuote()
- {
- return $this->_getCart()->getQuote();
- }
-
- /**
- * Set back redirect url to response
- *
- * @return $this
- * @throws Mage_Core_Exception
- */
- protected function _goBack()
- {
- $returnUrl = $this->getRequest()->getParam('return_url');
- if ($returnUrl) {
- if (!$this->_isUrlInternal($returnUrl)) {
- throw new Mage_Core_Exception('External urls redirect to "' . $returnUrl . '" denied!');
- }
-
- $this->_getSession()->getMessages(true);
- $this->getResponse()->setRedirect($returnUrl);
- } elseif (!Mage::getStoreConfig('checkout/cart/redirect_to_cart')
- && !$this->getRequest()->getParam('in_cart')
- && $backUrl = $this->_getRefererUrl()
- ) {
- $this->getResponse()->setRedirect($backUrl);
- } else {
- if ((strtolower($this->getRequest()->getActionName()) == 'add')
- && !$this->getRequest()->getParam('in_cart')
- ) {
- $this->_getSession()->setContinueShoppingUrl($this->_getRefererUrl());
- }
- $this->_redirect('checkout/cart');
- }
- return $this;
- }
-
- /**
- * Initialize product instance from request data
- *
- * @return Mage_Catalog_Model_Product|false
- */
- protected function _initProduct()
- {
- $productId = (int) $this->getRequest()->getParam('product');
- if ($productId) {
- $product = Mage::getModel('catalog/product')
- ->setStoreId(Mage::app()->getStore()->getId())
- ->load($productId);
- if ($product->getId()) {
- return $product;
- }
- }
- return false;
- }
-
/**
* Predispatch: remove isMultiShipping option from quote
*
@@ -451,54 +370,6 @@ public function updatePostAction()
$this->_goBack();
}
- /**
- * Update customer's shopping cart
- */
- protected function _updateShoppingCart()
- {
- try {
- $cartData = $this->getRequest()->getParam('cart');
- if (is_array($cartData)) {
- $filter = new Zend_Filter_LocalizedToNormalized(
- ['locale' => Mage::app()->getLocale()->getLocaleCode()],
- );
- foreach ($cartData as $index => $data) {
- if (isset($data['qty'])) {
- $cartData[$index]['qty'] = $filter->filter(trim($data['qty']));
- }
- }
- $cart = $this->_getCart();
- if (!$cart->getCustomerSession()->getCustomer()->getId() && $cart->getQuote()->getCustomerId()) {
- $cart->getQuote()->setCustomerId(null);
- }
-
- $cartData = $cart->suggestItemsQty($cartData);
- $cart->updateItems($cartData)
- ->save();
- }
- $this->_getSession()->setCartWasUpdated(true);
- } catch (Mage_Core_Exception $e) {
- $this->_getSession()->addError(Mage::helper('core')->escapeHtml($e->getMessage()));
- } catch (Exception $e) {
- $this->_getSession()->addException($e, $this->__('Cannot update shopping cart.'));
- }
- }
-
- /**
- * Empty customer's shopping cart
- */
- protected function _emptyShoppingCart()
- {
- try {
- $this->_getCart()->truncate()->save();
- $this->_getSession()->setCartWasUpdated(true);
- } catch (Mage_Core_Exception $exception) {
- $this->_getSession()->addError($exception->getMessage());
- } catch (Exception $exception) {
- $this->_getSession()->addException($exception, $this->__('Cannot update shopping cart.'));
- }
- }
-
/**
* Delete shoping cart item action
*/
@@ -714,6 +585,135 @@ public function ajaxUpdateAction()
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
+ /**
+ * Retrieve shopping cart model object
+ *
+ * @return Mage_Checkout_Model_Cart
+ */
+ protected function _getCart()
+ {
+ return Mage::getSingleton('checkout/cart');
+ }
+
+ /**
+ * Get checkout session model instance
+ *
+ * @return Mage_Checkout_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('checkout/session');
+ }
+
+ /**
+ * Get current active quote instance
+ *
+ * @return Mage_Sales_Model_Quote
+ */
+ protected function _getQuote()
+ {
+ return $this->_getCart()->getQuote();
+ }
+
+ /**
+ * Set back redirect url to response
+ *
+ * @return $this
+ * @throws Mage_Core_Exception
+ */
+ protected function _goBack()
+ {
+ $returnUrl = $this->getRequest()->getParam('return_url');
+ if ($returnUrl) {
+ if (!$this->_isUrlInternal($returnUrl)) {
+ throw new Mage_Core_Exception('External urls redirect to "' . $returnUrl . '" denied!');
+ }
+
+ $this->_getSession()->getMessages(true);
+ $this->getResponse()->setRedirect($returnUrl);
+ } elseif (!Mage::getStoreConfig('checkout/cart/redirect_to_cart')
+ && !$this->getRequest()->getParam('in_cart')
+ && $backUrl = $this->_getRefererUrl()
+ ) {
+ $this->getResponse()->setRedirect($backUrl);
+ } else {
+ if ((strtolower($this->getRequest()->getActionName()) == 'add')
+ && !$this->getRequest()->getParam('in_cart')
+ ) {
+ $this->_getSession()->setContinueShoppingUrl($this->_getRefererUrl());
+ }
+ $this->_redirect('checkout/cart');
+ }
+ return $this;
+ }
+
+ /**
+ * Initialize product instance from request data
+ *
+ * @return Mage_Catalog_Model_Product|false
+ */
+ protected function _initProduct()
+ {
+ $productId = (int) $this->getRequest()->getParam('product');
+ if ($productId) {
+ $product = Mage::getModel('catalog/product')
+ ->setStoreId(Mage::app()->getStore()->getId())
+ ->load($productId);
+ if ($product->getId()) {
+ return $product;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Update customer's shopping cart
+ */
+ protected function _updateShoppingCart()
+ {
+ try {
+ $cartData = $this->getRequest()->getParam('cart');
+ if (is_array($cartData)) {
+ $filter = new Zend_Filter_LocalizedToNormalized(
+ ['locale' => Mage::app()->getLocale()->getLocaleCode()],
+ );
+ foreach ($cartData as $index => $data) {
+ if (isset($data['qty'])) {
+ $cartData[$index]['qty'] = $filter->filter(trim($data['qty']));
+ }
+ }
+ $cart = $this->_getCart();
+ if (!$cart->getCustomerSession()->getCustomer()->getId() && $cart->getQuote()->getCustomerId()) {
+ $cart->getQuote()->setCustomerId(null);
+ }
+
+ $cartData = $cart->suggestItemsQty($cartData);
+ $cart->updateItems($cartData)
+ ->save();
+ }
+ $this->_getSession()->setCartWasUpdated(true);
+ } catch (Mage_Core_Exception $e) {
+ $this->_getSession()->addError(Mage::helper('core')->escapeHtml($e->getMessage()));
+ } catch (Exception $e) {
+ $this->_getSession()->addException($e, $this->__('Cannot update shopping cart.'));
+ }
+ }
+
+ /**
+ * Empty customer's shopping cart
+ */
+ protected function _emptyShoppingCart()
+ {
+ try {
+ $this->_getCart()->truncate()->save();
+ $this->_getSession()->setCartWasUpdated(true);
+ } catch (Mage_Core_Exception $exception) {
+ $this->_getSession()->addError($exception->getMessage());
+ } catch (Exception $exception) {
+ $this->_getSession()->addException($exception, $this->__('Cannot update shopping cart.'));
+ }
+ }
+
/**
* Get customer session model
*
diff --git a/app/code/core/Mage/Checkout/controllers/Multishipping/AddressController.php b/app/code/core/Mage/Checkout/controllers/Multishipping/AddressController.php
index 7681b1c0db4..d6eedc6a58f 100644
--- a/app/code/core/Mage/Checkout/controllers/Multishipping/AddressController.php
+++ b/app/code/core/Mage/Checkout/controllers/Multishipping/AddressController.php
@@ -22,26 +22,6 @@
*/
class Mage_Checkout_Multishipping_AddressController extends Mage_Core_Controller_Front_Action
{
- /**
- * Retrieve multishipping checkout model
- *
- * @return Mage_Checkout_Model_Type_Multishipping
- */
- protected function _getCheckout()
- {
- return Mage::getSingleton('checkout/type_multishipping');
- }
-
- /**
- * Retrieve checkout state model
- *
- * @return Mage_Checkout_Model_Type_Multishipping_State
- */
- protected function _getState()
- {
- return Mage::getSingleton('checkout/type_multishipping_state');
- }
-
/**
* Create New Shipping address Form
*/
@@ -188,4 +168,23 @@ public function saveBillingAction()
}
$this->_redirect('*/multishipping/overview');
}
+ /**
+ * Retrieve multishipping checkout model
+ *
+ * @return Mage_Checkout_Model_Type_Multishipping
+ */
+ protected function _getCheckout()
+ {
+ return Mage::getSingleton('checkout/type_multishipping');
+ }
+
+ /**
+ * Retrieve checkout state model
+ *
+ * @return Mage_Checkout_Model_Type_Multishipping_State
+ */
+ protected function _getState()
+ {
+ return Mage::getSingleton('checkout/type_multishipping_state');
+ }
}
diff --git a/app/code/core/Mage/Checkout/controllers/MultishippingController.php b/app/code/core/Mage/Checkout/controllers/MultishippingController.php
index 0351a2d811c..b779e2b3ac8 100644
--- a/app/code/core/Mage/Checkout/controllers/MultishippingController.php
+++ b/app/code/core/Mage/Checkout/controllers/MultishippingController.php
@@ -22,46 +22,6 @@
*/
class Mage_Checkout_MultishippingController extends Mage_Checkout_Controller_Action
{
- /**
- * Retrieve checkout model
- *
- * @return Mage_Checkout_Model_Type_Multishipping
- */
- protected function _getCheckout()
- {
- return Mage::getSingleton('checkout/type_multishipping');
- }
-
- /**
- * Retrieve checkout state model
- *
- * @return Mage_Checkout_Model_Type_Multishipping_State
- */
- protected function _getState()
- {
- return Mage::getSingleton('checkout/type_multishipping_state');
- }
-
- /**
- * Retrieve checkout url heler
- *
- * @return Mage_Checkout_Helper_Url
- */
- protected function _getHelper()
- {
- return Mage::helper('checkout/url');
- }
-
- /**
- * Retrieve checkout session
- *
- * @return Mage_Checkout_Model_Session
- */
- protected function _getCheckoutSession()
- {
- return Mage::getSingleton('checkout/session');
- }
-
/**
* Action predispatch
*
@@ -291,22 +251,6 @@ public function removeItemAction()
$this->_redirect('*/*/addresses');
}
- /**
- * Returns whether the minimum amount has been reached
- *
- * @return bool
- */
- protected function _validateMinimumAmount()
- {
- if (!$this->_getCheckout()->validateMinimumAmount()) {
- $error = $this->_getCheckout()->getMinimumAmountError();
- $this->_getCheckout()->getCheckoutSession()->addError($error);
- $this->_forward('backToAddresses');
- return false;
- }
- return true;
- }
-
/**
* Multishipping checkout shipping information page
*/
@@ -425,20 +369,6 @@ public function billingAction()
$this->renderLayout();
}
- /**
- * Validation of selecting of billing address
- *
- * @return bool
- */
- protected function _validateBilling()
- {
- if (!$this->_getCheckout()->getQuote()->getBillingAddress()->getFirstname()) {
- $this->_redirect('*/multishipping_address/selectBilling');
- return false;
- }
- return true;
- }
-
/**
* Multishipping checkout action to go back to billing
*/
@@ -598,4 +528,73 @@ public function redirectLogin()
$this->setFlag('', 'redirectLogin', true);
}
+ /**
+ * Retrieve checkout model
+ *
+ * @return Mage_Checkout_Model_Type_Multishipping
+ */
+ protected function _getCheckout()
+ {
+ return Mage::getSingleton('checkout/type_multishipping');
+ }
+
+ /**
+ * Retrieve checkout state model
+ *
+ * @return Mage_Checkout_Model_Type_Multishipping_State
+ */
+ protected function _getState()
+ {
+ return Mage::getSingleton('checkout/type_multishipping_state');
+ }
+
+ /**
+ * Retrieve checkout url heler
+ *
+ * @return Mage_Checkout_Helper_Url
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('checkout/url');
+ }
+
+ /**
+ * Retrieve checkout session
+ *
+ * @return Mage_Checkout_Model_Session
+ */
+ protected function _getCheckoutSession()
+ {
+ return Mage::getSingleton('checkout/session');
+ }
+
+ /**
+ * Returns whether the minimum amount has been reached
+ *
+ * @return bool
+ */
+ protected function _validateMinimumAmount()
+ {
+ if (!$this->_getCheckout()->validateMinimumAmount()) {
+ $error = $this->_getCheckout()->getMinimumAmountError();
+ $this->_getCheckout()->getCheckoutSession()->addError($error);
+ $this->_forward('backToAddresses');
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Validation of selecting of billing address
+ *
+ * @return bool
+ */
+ protected function _validateBilling()
+ {
+ if (!$this->_getCheckout()->getQuote()->getBillingAddress()->getFirstname()) {
+ $this->_redirect('*/multishipping_address/selectBilling');
+ return false;
+ }
+ return true;
+ }
}
diff --git a/app/code/core/Mage/Checkout/controllers/OnepageController.php b/app/code/core/Mage/Checkout/controllers/OnepageController.php
index f50e158520b..c4db99b5517 100644
--- a/app/code/core/Mage/Checkout/controllers/OnepageController.php
+++ b/app/code/core/Mage/Checkout/controllers/OnepageController.php
@@ -66,102 +66,6 @@ public function preDispatch()
return $this;
}
- /**
- * Send Ajax redirect response
- *
- * @return $this
- */
- protected function _ajaxRedirectResponse()
- {
- $this->getResponse()
- ->setHeader('HTTP/1.1', '403 Session Expired')
- ->setHeader('Login-Required', 'true')
- ->sendResponse();
- return $this;
- }
-
- /**
- * Validate ajax request and redirect on failure
- *
- * @return bool
- */
- protected function _expireAjax()
- {
- if (!$this->getOnepage()->getQuote()->hasItems()
- || $this->getOnepage()->getQuote()->getHasError()
- || $this->getOnepage()->getQuote()->getIsMultiShipping()
- ) {
- $this->_ajaxRedirectResponse();
- return true;
- }
- $action = strtolower($this->getRequest()->getActionName());
- if (Mage::getSingleton('checkout/session')->getCartWasUpdated(true)
- && !in_array($action, ['index', 'progress'])
- ) {
- $this->_ajaxRedirectResponse();
- return true;
- }
- return false;
- }
-
- /**
- * Get shipping method step html
- *
- * @return string
- */
- protected function _getShippingMethodsHtml()
- {
- $layout = $this->getLayout();
- $update = $layout->getUpdate();
- $update->load('checkout_onepage_shippingmethod');
- $layout->generateXml();
- $layout->generateBlocks();
- return $layout->getOutput();
- }
-
- /**
- * Get payment method step html
- *
- * @return string
- */
- protected function _getPaymentMethodsHtml()
- {
- $layout = $this->getLayout();
- $update = $layout->getUpdate();
- $update->load('checkout_onepage_paymentmethod');
- $layout->generateXml();
- $layout->generateBlocks();
- return $layout->getOutput();
- }
-
- /**
- * Return block content from the 'checkout_onepage_additional'
- * This is the additional content for shipping method
- *
- * @return string
- */
- protected function _getAdditionalHtml()
- {
- $layout = $this->getLayout();
- $update = $layout->getUpdate();
- $update->load('checkout_onepage_additional');
- $layout->generateXml();
- $layout->generateBlocks();
- $output = $layout->getOutput();
- Mage::getSingleton('core/translate_inline')->processResponseBody($output);
- return $output;
- }
-
- /**
- * Get order review step html
- *
- * @return string
- */
- protected function _getReviewHtml()
- {
- return $this->getLayout()->getBlock('root')->toHtml();
- }
-
/**
* Get one page checkout model
*
@@ -511,44 +415,6 @@ public function savePaymentAction()
$this->_prepareDataJSON($result);
}
- /**
- * Get Order by quoteId
- *
- * @throws Mage_Payment_Model_Info_Exception
- * @return Mage_Sales_Model_Order
- */
- protected function _getOrder()
- {
- if (is_null($this->_order)) {
- $this->_order = Mage::getModel('sales/order')->load($this->getOnepage()->getQuote()->getId(), 'quote_id');
- if (!$this->_order->getId()) {
- throw new Mage_Payment_Model_Info_Exception(Mage::helper('core')->__('Can not create invoice. Order was not found.'));
- }
- }
- return $this->_order;
- }
-
- /**
- * Create invoice
- *
- * @return Mage_Sales_Model_Service_Order
- * @throws Mage_Core_Exception
- * @throws Mage_Payment_Model_Info_Exception
- */
- protected function _initInvoice()
- {
- $items = [];
- foreach ($this->_getOrder()->getAllItems() as $item) {
- $items[$item->getId()] = $item->getQtyOrdered();
- }
- /** @var Mage_Sales_Model_Service_Order $invoice */
- $invoice = Mage::getModel('sales/service_order', $this->_getOrder())->prepareInvoice($items);
- $invoice->setEmailSent(true)->register();
-
- Mage::register('current_invoice', $invoice);
- return $invoice;
- }
-
/**
* Create order action
*/
@@ -645,6 +511,140 @@ public function saveOrderAction()
$this->_prepareDataJSON($result);
}
+ /**
+ * Send Ajax redirect response
+ *
+ * @return $this
+ */
+ protected function _ajaxRedirectResponse()
+ {
+ $this->getResponse()
+ ->setHeader('HTTP/1.1', '403 Session Expired')
+ ->setHeader('Login-Required', 'true')
+ ->sendResponse();
+ return $this;
+ }
+
+ /**
+ * Validate ajax request and redirect on failure
+ *
+ * @return bool
+ */
+ protected function _expireAjax()
+ {
+ if (!$this->getOnepage()->getQuote()->hasItems()
+ || $this->getOnepage()->getQuote()->getHasError()
+ || $this->getOnepage()->getQuote()->getIsMultiShipping()
+ ) {
+ $this->_ajaxRedirectResponse();
+ return true;
+ }
+ $action = strtolower($this->getRequest()->getActionName());
+ if (Mage::getSingleton('checkout/session')->getCartWasUpdated(true)
+ && !in_array($action, ['index', 'progress'])
+ ) {
+ $this->_ajaxRedirectResponse();
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Get shipping method step html
+ *
+ * @return string
+ */
+ protected function _getShippingMethodsHtml()
+ {
+ $layout = $this->getLayout();
+ $update = $layout->getUpdate();
+ $update->load('checkout_onepage_shippingmethod');
+ $layout->generateXml();
+ $layout->generateBlocks();
+ return $layout->getOutput();
+ }
+
+ /**
+ * Get payment method step html
+ *
+ * @return string
+ */
+ protected function _getPaymentMethodsHtml()
+ {
+ $layout = $this->getLayout();
+ $update = $layout->getUpdate();
+ $update->load('checkout_onepage_paymentmethod');
+ $layout->generateXml();
+ $layout->generateBlocks();
+ return $layout->getOutput();
+ }
+
+ /**
+ * Return block content from the 'checkout_onepage_additional'
+ * This is the additional content for shipping method
+ *
+ * @return string
+ */
+ protected function _getAdditionalHtml()
+ {
+ $layout = $this->getLayout();
+ $update = $layout->getUpdate();
+ $update->load('checkout_onepage_additional');
+ $layout->generateXml();
+ $layout->generateBlocks();
+ $output = $layout->getOutput();
+ Mage::getSingleton('core/translate_inline')->processResponseBody($output);
+ return $output;
+ }
+
+ /**
+ * Get order review step html
+ *
+ * @return string
+ */
+ protected function _getReviewHtml()
+ {
+ return $this->getLayout()->getBlock('root')->toHtml();
+ }
+
+ /**
+ * Get Order by quoteId
+ *
+ * @throws Mage_Payment_Model_Info_Exception
+ * @return Mage_Sales_Model_Order
+ */
+ protected function _getOrder()
+ {
+ if (is_null($this->_order)) {
+ $this->_order = Mage::getModel('sales/order')->load($this->getOnepage()->getQuote()->getId(), 'quote_id');
+ if (!$this->_order->getId()) {
+ throw new Mage_Payment_Model_Info_Exception(Mage::helper('core')->__('Can not create invoice. Order was not found.'));
+ }
+ }
+ return $this->_order;
+ }
+
+ /**
+ * Create invoice
+ *
+ * @return Mage_Sales_Model_Service_Order
+ * @throws Mage_Core_Exception
+ * @throws Mage_Payment_Model_Info_Exception
+ */
+ protected function _initInvoice()
+ {
+ $items = [];
+ foreach ($this->_getOrder()->getAllItems() as $item) {
+ $items[$item->getId()] = $item->getQtyOrdered();
+ }
+ /** @var Mage_Sales_Model_Service_Order $invoice */
+ $invoice = Mage::getModel('sales/service_order', $this->_getOrder())->prepareInvoice($items);
+ $invoice->setEmailSent(true)->register();
+
+ Mage::register('current_invoice', $invoice);
+ return $invoice;
+ }
+
/**
* Filtering posted data. Converting localized data if needed
*
diff --git a/app/code/core/Mage/Cms/Block/Block.php b/app/code/core/Mage/Cms/Block/Block.php
index 6d64961ca00..827ca639be1 100644
--- a/app/code/core/Mage/Cms/Block/Block.php
+++ b/app/code/core/Mage/Cms/Block/Block.php
@@ -25,6 +25,26 @@
*/
class Mage_Cms_Block_Block extends Mage_Core_Block_Abstract
{
+ /**
+ * Retrieve values of properties that unambiguously identify unique content
+ *
+ * @return array
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ public function getCacheKeyInfo()
+ {
+ $blockId = $this->getBlockId();
+ if ($blockId) {
+ $result = [
+ 'CMS_BLOCK',
+ $blockId,
+ Mage::app()->getStore()->getCode(),
+ ];
+ } else {
+ $result = parent::getCacheKeyInfo();
+ }
+ return $result;
+ }
/**
* Initialize cache
*/
@@ -62,25 +82,4 @@ protected function _toHtml()
}
return $html;
}
-
- /**
- * Retrieve values of properties that unambiguously identify unique content
- *
- * @return array
- * @throws Mage_Core_Model_Store_Exception
- */
- public function getCacheKeyInfo()
- {
- $blockId = $this->getBlockId();
- if ($blockId) {
- $result = [
- 'CMS_BLOCK',
- $blockId,
- Mage::app()->getStore()->getCode(),
- ];
- } else {
- $result = parent::getCacheKeyInfo();
- }
- return $result;
- }
}
diff --git a/app/code/core/Mage/Cms/Block/Widget/Block.php b/app/code/core/Mage/Cms/Block/Widget/Block.php
index 2b584e539d4..2a43bd68956 100644
--- a/app/code/core/Mage/Cms/Block/Widget/Block.php
+++ b/app/code/core/Mage/Cms/Block/Widget/Block.php
@@ -25,6 +25,37 @@
*/
class Mage_Cms_Block_Widget_Block extends Mage_Core_Block_Template implements Mage_Widget_Block_Interface
{
+ /**
+ * Storage for used widgets
+ *
+ * @var array
+ */
+ protected static $_widgetUsageMap = [];
+
+ /**
+ * Retrieve values of properties that unambiguously identify unique content
+ *
+ * @return array
+ */
+ public function getCacheKeyInfo()
+ {
+ $result = parent::getCacheKeyInfo();
+ $blockId = $this->getBlockId();
+ if ($blockId) {
+ $result[] = $blockId;
+ }
+ return $result;
+ }
+
+ /**
+ * Check is request goes from admin area
+ *
+ * @return bool
+ */
+ public function isRequestFromAdminArea()
+ {
+ return $this->getRequest()->getRouteName() === Mage_Core_Model_App_Area::AREA_ADMINHTML;
+ }
/**
* Initialize cache
*/
@@ -38,13 +69,6 @@ protected function _construct()
$this->setCacheLifetime(false);
}
- /**
- * Storage for used widgets
- *
- * @var array
- */
- protected static $_widgetUsageMap = [];
-
/**
* Prepare block text and determine whether block output enabled or not
* Prevent blocks recursion if needed
@@ -83,29 +107,4 @@ protected function _beforeToHtml()
unset(self::$_widgetUsageMap[$blockHash]);
return $this;
}
-
- /**
- * Retrieve values of properties that unambiguously identify unique content
- *
- * @return array
- */
- public function getCacheKeyInfo()
- {
- $result = parent::getCacheKeyInfo();
- $blockId = $this->getBlockId();
- if ($blockId) {
- $result[] = $blockId;
- }
- return $result;
- }
-
- /**
- * Check is request goes from admin area
- *
- * @return bool
- */
- public function isRequestFromAdminArea()
- {
- return $this->getRequest()->getRouteName() === Mage_Core_Model_App_Area::AREA_ADMINHTML;
- }
}
diff --git a/app/code/core/Mage/Cms/Helper/Page.php b/app/code/core/Mage/Cms/Helper/Page.php
index b81ae24d144..9e6679d57b4 100644
--- a/app/code/core/Mage/Cms/Helper/Page.php
+++ b/app/code/core/Mage/Cms/Helper/Page.php
@@ -41,6 +41,62 @@ public function renderPage(Mage_Core_Controller_Front_Action $action, $pageId =
return $this->_renderPage($action, $pageId);
}
+ /**
+ * Renders CMS Page with more flexibility then original renderPage function.
+ * Allows to use also backend action as first parameter.
+ * Also takes third parameter which allows not run renderLayout method.
+ *
+ * @param string $pageId
+ * @param bool $renderLayout
+ * @return bool
+ */
+ public function renderPageExtended(Mage_Core_Controller_Varien_Action $action, $pageId = null, $renderLayout = true)
+ {
+ return $this->_renderPage($action, $pageId, $renderLayout);
+ }
+
+ /**
+ * Retrieve page direct URL
+ *
+ * @param string $pageId
+ * @return string|null
+ */
+ public function getPageUrl($pageId = null)
+ {
+ $page = Mage::getModel('cms/page');
+ if (!is_null($pageId) && $pageId !== $page->getId()) {
+ $page->setStoreId(Mage::app()->getStore()->getId());
+ if (!$page->load($pageId)) {
+ return null;
+ }
+ }
+
+ if (!$page->getId()) {
+ return null;
+ }
+
+ return Mage::getUrl(null, ['_direct' => $page->getIdentifier()]);
+ }
+
+ public static function getUsedInStoreConfigPaths(?array $paths = []): array
+ {
+ $searchPaths = [
+ self::XML_PATH_NO_ROUTE_PAGE,
+ self::XML_PATH_NO_COOKIES_PAGE,
+ self::XML_PATH_HOME_PAGE,
+ ];
+
+ if (is_array($paths) && $paths !== []) {
+ $searchPaths = array_merge($searchPaths, $paths);
+ }
+
+ if (is_null($paths)) {
+ $searchPaths = [];
+ }
+
+ return $searchPaths;
+ }
+
/**
* Renders CMS page
*
@@ -126,60 +182,4 @@ protected function _renderPage(Mage_Core_Controller_Varien_Action $action, $pag
return true;
}
-
- /**
- * Renders CMS Page with more flexibility then original renderPage function.
- * Allows to use also backend action as first parameter.
- * Also takes third parameter which allows not run renderLayout method.
- *
- * @param string $pageId
- * @param bool $renderLayout
- * @return bool
- */
- public function renderPageExtended(Mage_Core_Controller_Varien_Action $action, $pageId = null, $renderLayout = true)
- {
- return $this->_renderPage($action, $pageId, $renderLayout);
- }
-
- /**
- * Retrieve page direct URL
- *
- * @param string $pageId
- * @return string|null
- */
- public function getPageUrl($pageId = null)
- {
- $page = Mage::getModel('cms/page');
- if (!is_null($pageId) && $pageId !== $page->getId()) {
- $page->setStoreId(Mage::app()->getStore()->getId());
- if (!$page->load($pageId)) {
- return null;
- }
- }
-
- if (!$page->getId()) {
- return null;
- }
-
- return Mage::getUrl(null, ['_direct' => $page->getIdentifier()]);
- }
-
- public static function getUsedInStoreConfigPaths(?array $paths = []): array
- {
- $searchPaths = [
- self::XML_PATH_NO_ROUTE_PAGE,
- self::XML_PATH_NO_COOKIES_PAGE,
- self::XML_PATH_HOME_PAGE,
- ];
-
- if (is_array($paths) && $paths !== []) {
- $searchPaths = array_merge($searchPaths, $paths);
- }
-
- if (is_null($paths)) {
- $searchPaths = [];
- }
-
- return $searchPaths;
- }
}
diff --git a/app/code/core/Mage/Cms/Model/Page.php b/app/code/core/Mage/Cms/Model/Page.php
index cf6ad8175b4..6ac9b6d4385 100644
--- a/app/code/core/Mage/Cms/Model/Page.php
+++ b/app/code/core/Mage/Cms/Model/Page.php
@@ -86,11 +86,6 @@ class Mage_Cms_Model_Page extends Mage_Core_Model_Abstract
*/
protected $_eventPrefix = 'cms_page';
- protected function _construct()
- {
- $this->_init('cms/page');
- }
-
/**
* @inheritDoc
*/
@@ -180,4 +175,9 @@ public function isUsedInStoreConfig(?array $paths = []): bool
{
return $this->_getResource()->isUsedInStoreConfig($this, $paths);
}
+
+ protected function _construct()
+ {
+ $this->_init('cms/page');
+ }
}
diff --git a/app/code/core/Mage/Cms/Model/Resource/Block.php b/app/code/core/Mage/Cms/Model/Resource/Block.php
index bcd2a81709a..8cd228f7af2 100644
--- a/app/code/core/Mage/Cms/Model/Resource/Block.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Block.php
@@ -22,6 +22,71 @@
*/
class Mage_Cms_Model_Resource_Block extends Mage_Core_Model_Resource_Db_Abstract
{
+ /**
+ * @inheritDoc
+ */
+ public function load(Mage_Core_Model_Abstract $object, $value, $field = null)
+ {
+ if (!is_numeric($value) && is_null($field)) {
+ $field = 'identifier';
+ }
+
+ return parent::load($object, $value, $field);
+ }
+
+ /**
+ * Check for unique of identifier of block to selected store(s).
+ *
+ * @return bool
+ */
+ public function getIsUniqueBlockToStores(Mage_Core_Model_Abstract $object)
+ {
+ if (Mage::app()->isSingleStoreMode()) {
+ $stores = [Mage_Core_Model_App::ADMIN_STORE_ID];
+ } else {
+ $stores = (array) $object->getData('stores');
+ }
+
+ $select = $this->_getReadAdapter()->select()
+ ->from(['cb' => $this->getMainTable()])
+ ->join(
+ ['cbs' => $this->getTable('cms/block_store')],
+ 'cb.block_id = cbs.block_id',
+ [],
+ )->where('cb.identifier = ?', $object->getData('identifier'))
+ ->where('cbs.store_id IN (?)', $stores);
+
+ if ($object->getId()) {
+ $select->where('cb.block_id <> ?', $object->getId());
+ }
+
+ if ($this->_getReadAdapter()->fetchRow($select)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Get store ids to which specified item is assigned
+ *
+ * @param int $id
+ * @return array
+ */
+ public function lookupStoreIds($id)
+ {
+ $adapter = $this->_getReadAdapter();
+
+ $select = $adapter->select()
+ ->from($this->getTable('cms/block_store'), 'store_id')
+ ->where('block_id = :block_id');
+
+ $binds = [
+ ':block_id' => (int) $id,
+ ];
+
+ return $adapter->fetchCol($select, $binds);
+ }
protected function _construct()
{
$this->_init('cms/block', 'block_id');
@@ -97,18 +162,6 @@ protected function _afterSave(Mage_Core_Model_Abstract $object)
return parent::_afterSave($object);
}
- /**
- * @inheritDoc
- */
- public function load(Mage_Core_Model_Abstract $object, $value, $field = null)
- {
- if (!is_numeric($value) && is_null($field)) {
- $field = 'identifier';
- }
-
- return parent::load($object, $value, $field);
- }
-
/**
* @inheritDoc
*/
@@ -153,58 +206,4 @@ protected function _getLoadSelect($field, $value, $object)
return $select;
}
-
- /**
- * Check for unique of identifier of block to selected store(s).
- *
- * @return bool
- */
- public function getIsUniqueBlockToStores(Mage_Core_Model_Abstract $object)
- {
- if (Mage::app()->isSingleStoreMode()) {
- $stores = [Mage_Core_Model_App::ADMIN_STORE_ID];
- } else {
- $stores = (array) $object->getData('stores');
- }
-
- $select = $this->_getReadAdapter()->select()
- ->from(['cb' => $this->getMainTable()])
- ->join(
- ['cbs' => $this->getTable('cms/block_store')],
- 'cb.block_id = cbs.block_id',
- [],
- )->where('cb.identifier = ?', $object->getData('identifier'))
- ->where('cbs.store_id IN (?)', $stores);
-
- if ($object->getId()) {
- $select->where('cb.block_id <> ?', $object->getId());
- }
-
- if ($this->_getReadAdapter()->fetchRow($select)) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Get store ids to which specified item is assigned
- *
- * @param int $id
- * @return array
- */
- public function lookupStoreIds($id)
- {
- $adapter = $this->_getReadAdapter();
-
- $select = $adapter->select()
- ->from($this->getTable('cms/block_store'), 'store_id')
- ->where('block_id = :block_id');
-
- $binds = [
- ':block_id' => (int) $id,
- ];
-
- return $adapter->fetchCol($select, $binds);
- }
}
diff --git a/app/code/core/Mage/Cms/Model/Resource/Block/Collection.php b/app/code/core/Mage/Cms/Model/Resource/Block/Collection.php
index 2fe69d64d86..49d6ae2876a 100644
--- a/app/code/core/Mage/Cms/Model/Resource/Block/Collection.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Block/Collection.php
@@ -22,16 +22,6 @@
*/
class Mage_Cms_Model_Resource_Block_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- $this->_init('cms/block');
- $this->_map['fields']['store'] = 'store_table.store_id';
- }
-
/**
* Returns pairs block_id - title
*
@@ -82,6 +72,15 @@ public function getSelectCountSql()
return $countSelect;
}
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('cms/block');
+ $this->_map['fields']['store'] = 'store_table.store_id';
+ }
/**
* Join store relation table if there is store filter
diff --git a/app/code/core/Mage/Cms/Model/Resource/Page.php b/app/code/core/Mage/Cms/Model/Resource/Page.php
index 5502c03afcf..8fa7d02666e 100644
--- a/app/code/core/Mage/Cms/Model/Resource/Page.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Page.php
@@ -29,6 +29,188 @@ class Mage_Cms_Model_Resource_Page extends Mage_Core_Model_Resource_Db_Abstract
*/
protected $_store = null;
+ /**
+ * @inheritDoc
+ */
+ public function load(Mage_Core_Model_Abstract $object, $value, $field = null)
+ {
+ if (!is_numeric($value) && is_null($field)) {
+ $field = 'identifier';
+ }
+
+ return parent::load($object, $value, $field);
+ }
+
+ /**
+ * Check for unique of identifier of page to selected store(s).
+ *
+ * @return bool
+ */
+ public function getIsUniquePageToStores(Mage_Core_Model_Abstract $object)
+ {
+ if (!$object->hasStores()) {
+ $stores = [Mage_Core_Model_App::ADMIN_STORE_ID];
+ } else {
+ $stores = (array) $object->getData('stores');
+ }
+
+ $select = $this->_getLoadByIdentifierSelect($object->getData('identifier'), $stores);
+
+ if ($object->getId()) {
+ $select->where('cps.page_id <> ?', $object->getId());
+ }
+
+ if ($this->_getWriteAdapter()->fetchRow($select)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ public function getUsedInStoreConfigCollection(Mage_Cms_Model_Page $page, ?array $paths = []): Mage_Core_Model_Resource_Db_Collection_Abstract
+ {
+ $storeIds = (array) $page->getStoreId();
+ $storeIds[] = Mage_Core_Model_App::ADMIN_STORE_ID;
+ $config = Mage::getResourceModel('core/config_data_collection')
+ ->addFieldToFilter('value', $page->getIdentifier())
+ ->addFieldToFilter('scope_id', ['in' => $storeIds]);
+
+ if (!is_null($paths)) {
+ $paths = Mage_Cms_Helper_Page::getUsedInStoreConfigPaths($paths);
+ $config->addFieldToFilter('path', ['in' => $paths]);
+ }
+
+ return $config;
+ }
+
+ public function isUsedInStoreConfig(?Mage_Cms_Model_Page $page = null, ?array $paths = []): bool
+ {
+ return (bool) $this->getUsedInStoreConfigCollection($page, $paths)->count();
+ }
+
+ /**
+ * Check if page identifier exist for specific store
+ * return page id if page exists
+ *
+ * @param string $identifier
+ * @param int $storeId
+ * @return string
+ */
+ public function checkIdentifier($identifier, $storeId)
+ {
+ $stores = [Mage_Core_Model_App::ADMIN_STORE_ID, $storeId];
+ $select = $this->_getLoadByIdentifierSelect($identifier, $stores, 1);
+ $select->reset(Zend_Db_Select::COLUMNS)
+ ->columns('cp.page_id')
+ ->order('cps.store_id DESC')
+ ->limit(1);
+
+ return $this->_getReadAdapter()->fetchOne($select);
+ }
+
+ /**
+ * Retrieves cms page title from DB by passed identifier.
+ *
+ * @param string|int $identifier
+ * @return string
+ */
+ public function getCmsPageTitleByIdentifier($identifier)
+ {
+ $stores = [Mage_Core_Model_App::ADMIN_STORE_ID];
+ if ($this->_store) {
+ $stores[] = (int) $this->getStore()->getId();
+ }
+
+ $select = $this->_getLoadByIdentifierSelect($identifier, $stores);
+ $select->reset(Zend_Db_Select::COLUMNS)
+ ->columns('cp.title')
+ ->order('cps.store_id DESC')
+ ->limit(1);
+
+ return $this->_getReadAdapter()->fetchOne($select);
+ }
+
+ /**
+ * Retrieves cms page title from DB by passed id.
+ *
+ * @param string|int $id
+ * @return string
+ */
+ public function getCmsPageTitleById($id)
+ {
+ $adapter = $this->_getReadAdapter();
+
+ $select = $adapter->select()
+ ->from($this->getMainTable(), 'title')
+ ->where('page_id = :page_id');
+
+ $binds = [
+ 'page_id' => (int) $id,
+ ];
+
+ return $adapter->fetchOne($select, $binds);
+ }
+
+ /**
+ * Retrieves cms page identifier from DB by passed id.
+ *
+ * @param string $id
+ * @return string|false
+ */
+ public function getCmsPageIdentifierById($id)
+ {
+ $adapter = $this->_getReadAdapter();
+
+ $select = $adapter->select()
+ ->from($this->getMainTable(), 'identifier')
+ ->where('page_id = :page_id');
+
+ $binds = [
+ 'page_id' => (int) $id,
+ ];
+
+ return $adapter->fetchOne($select, $binds);
+ }
+
+ /**
+ * Get store ids to which specified item is assigned
+ *
+ * @param string $pageId
+ * @return array
+ */
+ public function lookupStoreIds($pageId)
+ {
+ $adapter = $this->_getReadAdapter();
+
+ $select = $adapter->select()
+ ->from($this->getTable('cms/page_store'), 'store_id')
+ ->where('page_id = ?', (int) $pageId);
+
+ return $adapter->fetchCol($select);
+ }
+
+ /**
+ * Set store model
+ *
+ * @param Mage_Core_Model_Store $store
+ * @return $this
+ */
+ public function setStore($store)
+ {
+ $this->_store = $store;
+ return $this;
+ }
+
+ /**
+ * Retrieve store model
+ *
+ * @return Mage_Core_Model_Store
+ */
+ public function getStore()
+ {
+ return Mage::app()->getStore($this->_store);
+ }
+
protected function _construct()
{
$this->_init('cms/page', 'page_id');
@@ -159,18 +341,6 @@ protected function _afterSave(Mage_Core_Model_Abstract $object)
return parent::_afterSave($object);
}
- /**
- * @inheritDoc
- */
- public function load(Mage_Core_Model_Abstract $object, $value, $field = null)
- {
- if (!is_numeric($value) && is_null($field)) {
- $field = 'identifier';
- }
-
- return parent::load($object, $value, $field);
- }
-
/**
* @inheritDoc
*/
@@ -240,32 +410,6 @@ protected function _getLoadByIdentifierSelect($identifier, $store, $isActive = n
return $select;
}
- /**
- * Check for unique of identifier of page to selected store(s).
- *
- * @return bool
- */
- public function getIsUniquePageToStores(Mage_Core_Model_Abstract $object)
- {
- if (!$object->hasStores()) {
- $stores = [Mage_Core_Model_App::ADMIN_STORE_ID];
- } else {
- $stores = (array) $object->getData('stores');
- }
-
- $select = $this->_getLoadByIdentifierSelect($object->getData('identifier'), $stores);
-
- if ($object->getId()) {
- $select->where('cps.page_id <> ?', $object->getId());
- }
-
- if ($this->_getWriteAdapter()->fetchRow($select)) {
- return false;
- }
-
- return true;
- }
-
/**
* Check whether page identifier is numeric
*
@@ -286,148 +430,4 @@ protected function isValidPageIdentifier(Mage_Core_Model_Abstract $object)
{
return preg_match('/^[a-z0-9][a-z0-9_\/-]+(\.[a-z0-9_-]+)?$/', $object->getData('identifier'));
}
-
- public function getUsedInStoreConfigCollection(Mage_Cms_Model_Page $page, ?array $paths = []): Mage_Core_Model_Resource_Db_Collection_Abstract
- {
- $storeIds = (array) $page->getStoreId();
- $storeIds[] = Mage_Core_Model_App::ADMIN_STORE_ID;
- $config = Mage::getResourceModel('core/config_data_collection')
- ->addFieldToFilter('value', $page->getIdentifier())
- ->addFieldToFilter('scope_id', ['in' => $storeIds]);
-
- if (!is_null($paths)) {
- $paths = Mage_Cms_Helper_Page::getUsedInStoreConfigPaths($paths);
- $config->addFieldToFilter('path', ['in' => $paths]);
- }
-
- return $config;
- }
-
- public function isUsedInStoreConfig(?Mage_Cms_Model_Page $page = null, ?array $paths = []): bool
- {
- return (bool) $this->getUsedInStoreConfigCollection($page, $paths)->count();
- }
-
- /**
- * Check if page identifier exist for specific store
- * return page id if page exists
- *
- * @param string $identifier
- * @param int $storeId
- * @return string
- */
- public function checkIdentifier($identifier, $storeId)
- {
- $stores = [Mage_Core_Model_App::ADMIN_STORE_ID, $storeId];
- $select = $this->_getLoadByIdentifierSelect($identifier, $stores, 1);
- $select->reset(Zend_Db_Select::COLUMNS)
- ->columns('cp.page_id')
- ->order('cps.store_id DESC')
- ->limit(1);
-
- return $this->_getReadAdapter()->fetchOne($select);
- }
-
- /**
- * Retrieves cms page title from DB by passed identifier.
- *
- * @param string|int $identifier
- * @return string
- */
- public function getCmsPageTitleByIdentifier($identifier)
- {
- $stores = [Mage_Core_Model_App::ADMIN_STORE_ID];
- if ($this->_store) {
- $stores[] = (int) $this->getStore()->getId();
- }
-
- $select = $this->_getLoadByIdentifierSelect($identifier, $stores);
- $select->reset(Zend_Db_Select::COLUMNS)
- ->columns('cp.title')
- ->order('cps.store_id DESC')
- ->limit(1);
-
- return $this->_getReadAdapter()->fetchOne($select);
- }
-
- /**
- * Retrieves cms page title from DB by passed id.
- *
- * @param string|int $id
- * @return string
- */
- public function getCmsPageTitleById($id)
- {
- $adapter = $this->_getReadAdapter();
-
- $select = $adapter->select()
- ->from($this->getMainTable(), 'title')
- ->where('page_id = :page_id');
-
- $binds = [
- 'page_id' => (int) $id,
- ];
-
- return $adapter->fetchOne($select, $binds);
- }
-
- /**
- * Retrieves cms page identifier from DB by passed id.
- *
- * @param string $id
- * @return string|false
- */
- public function getCmsPageIdentifierById($id)
- {
- $adapter = $this->_getReadAdapter();
-
- $select = $adapter->select()
- ->from($this->getMainTable(), 'identifier')
- ->where('page_id = :page_id');
-
- $binds = [
- 'page_id' => (int) $id,
- ];
-
- return $adapter->fetchOne($select, $binds);
- }
-
- /**
- * Get store ids to which specified item is assigned
- *
- * @param string $pageId
- * @return array
- */
- public function lookupStoreIds($pageId)
- {
- $adapter = $this->_getReadAdapter();
-
- $select = $adapter->select()
- ->from($this->getTable('cms/page_store'), 'store_id')
- ->where('page_id = ?', (int) $pageId);
-
- return $adapter->fetchCol($select);
- }
-
- /**
- * Set store model
- *
- * @param Mage_Core_Model_Store $store
- * @return $this
- */
- public function setStore($store)
- {
- $this->_store = $store;
- return $this;
- }
-
- /**
- * Retrieve store model
- *
- * @return Mage_Core_Model_Store
- */
- public function getStore()
- {
- return Mage::app()->getStore($this->_store);
- }
}
diff --git a/app/code/core/Mage/Cms/Model/Resource/Page/Collection.php b/app/code/core/Mage/Cms/Model/Resource/Page/Collection.php
index 5608da66c82..ecce73f5930 100644
--- a/app/code/core/Mage/Cms/Model/Resource/Page/Collection.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Page/Collection.php
@@ -29,17 +29,6 @@ class Mage_Cms_Model_Resource_Page_Collection extends Mage_Core_Model_Resource_D
*/
protected $_previewFlag;
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- $this->_init('cms/page');
- $this->_map['fields']['page_id'] = 'main_table.page_id';
- $this->_map['fields']['store'] = 'store_table.store_id';
- }
-
/**
* @deprecated after 1.4.0.1, use toOptionIdArray()
*
@@ -90,6 +79,59 @@ public function setFirstStoreFlag($flag = false)
return $this;
}
+ /**
+ * Add filter by store
+ *
+ * @param int|Mage_Core_Model_Store $store
+ * @param bool $withAdmin
+ * @return $this
+ */
+ public function addStoreFilter($store, $withAdmin = true)
+ {
+ if (!$this->getFlag('store_filter_added')) {
+ if ($store instanceof Mage_Core_Model_Store) {
+ $store = [$store->getId()];
+ }
+
+ if (!is_array($store)) {
+ $store = [$store];
+ }
+
+ if ($withAdmin) {
+ $store[] = Mage_Core_Model_App::ADMIN_STORE_ID;
+ }
+
+ $this->addFilter('store', ['in' => $store], 'public');
+ }
+ return $this;
+ }
+
+ /**
+ * Get SQL for get record count.
+ * Extra GROUP BY strip added.
+ *
+ * @return Varien_Db_Select
+ */
+ public function getSelectCountSql()
+ {
+ $countSelect = parent::getSelectCountSql();
+
+ $countSelect->reset(Zend_Db_Select::GROUP);
+
+ return $countSelect;
+ }
+
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('cms/page');
+ $this->_map['fields']['page_id'] = 'main_table.page_id';
+ $this->_map['fields']['store'] = 'store_table.store_id';
+ }
+
/**
* @inheritDoc
*/
@@ -126,33 +168,6 @@ protected function _afterLoad()
return parent::_afterLoad();
}
- /**
- * Add filter by store
- *
- * @param int|Mage_Core_Model_Store $store
- * @param bool $withAdmin
- * @return $this
- */
- public function addStoreFilter($store, $withAdmin = true)
- {
- if (!$this->getFlag('store_filter_added')) {
- if ($store instanceof Mage_Core_Model_Store) {
- $store = [$store->getId()];
- }
-
- if (!is_array($store)) {
- $store = [$store];
- }
-
- if ($withAdmin) {
- $store[] = Mage_Core_Model_App::ADMIN_STORE_ID;
- }
-
- $this->addFilter('store', ['in' => $store], 'public');
- }
- return $this;
- }
-
/**
* Join store relation table if there is store filter
*/
@@ -173,19 +188,4 @@ protected function _renderFiltersBefore()
}
parent::_renderFiltersBefore();
}
-
- /**
- * Get SQL for get record count.
- * Extra GROUP BY strip added.
- *
- * @return Varien_Db_Select
- */
- public function getSelectCountSql()
- {
- $countSelect = parent::getSelectCountSql();
-
- $countSelect->reset(Zend_Db_Select::GROUP);
-
- return $countSelect;
- }
}
diff --git a/app/code/core/Mage/Cms/Model/Resource/Page/Service.php b/app/code/core/Mage/Cms/Model/Resource/Page/Service.php
index 176f7c501dc..3062cf9df58 100644
--- a/app/code/core/Mage/Cms/Model/Resource/Page/Service.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Page/Service.php
@@ -22,15 +22,6 @@
*/
class Mage_Cms_Model_Resource_Page_Service extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Init cms page service model
- *
- */
- protected function _construct()
- {
- $this->_init('cms/page', 'page_id');
- }
-
/**
* Unlinks from $fromStoreId store pages that have same identifiers as pages in $byStoreId
*
@@ -85,4 +76,12 @@ public function unlinkConflicts($fromStoreId, $byStoreId, $byLinkTable = null)
}
return $this;
}
+ /**
+ * Init cms page service model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('cms/page', 'page_id');
+ }
}
diff --git a/app/code/core/Mage/ConfigurableSwatches/Block/Catalog/Media/Js/Abstract.php b/app/code/core/Mage/ConfigurableSwatches/Block/Catalog/Media/Js/Abstract.php
index d269da1101b..a4893c8487d 100644
--- a/app/code/core/Mage/ConfigurableSwatches/Block/Catalog/Media/Js/Abstract.php
+++ b/app/code/core/Mage/ConfigurableSwatches/Block/Catalog/Media/Js/Abstract.php
@@ -36,26 +36,6 @@ abstract class Mage_ConfigurableSwatches_Block_Catalog_Media_Js_Abstract extends
*/
abstract public function getProducts();
- /**
- * json encode image fallback array
- *
- * @return string
- */
- protected function _getJsImageFallbackString(array $imageFallback)
- {
- /** @var Mage_Core_Helper_Data $coreHelper */
- $coreHelper = Mage::helper('core');
-
- return $coreHelper->jsonEncode($imageFallback);
- }
-
- /**
- * Image size(s) to attach to children products as array
- *
- * @return array
- */
- abstract protected function _getImageSizes();
-
/**
* Get image fallbacks by product as
* array(product ID => array( product => product, image_fallback => image fallback ) )
@@ -118,6 +98,26 @@ public function getImageType()
return parent::getImageType();
}
+ /**
+ * json encode image fallback array
+ *
+ * @return string
+ */
+ protected function _getJsImageFallbackString(array $imageFallback)
+ {
+ /** @var Mage_Core_Helper_Data $coreHelper */
+ $coreHelper = Mage::helper('core');
+
+ return $coreHelper->jsonEncode($imageFallback);
+ }
+
+ /**
+ * Image size(s) to attach to children products as array
+ *
+ * @return array
+ */
+ abstract protected function _getImageSizes();
+
/**
* Prevent actual block render if we are disabled, and i.e. via the module
* config as opposed to the advanced module settings page
diff --git a/app/code/core/Mage/ConfigurableSwatches/Block/Catalog/Product/List/Price.php b/app/code/core/Mage/ConfigurableSwatches/Block/Catalog/Product/List/Price.php
index 47c8d63b1d2..83d87ea5333 100644
--- a/app/code/core/Mage/ConfigurableSwatches/Block/Catalog/Product/List/Price.php
+++ b/app/code/core/Mage/ConfigurableSwatches/Block/Catalog/Product/List/Price.php
@@ -29,17 +29,6 @@ class Mage_ConfigurableSwatches_Block_Catalog_Product_List_Price extends Mage_Co
*/
protected $_template = 'configurableswatches/catalog/product/list/price/js.phtml';
- /**
- * Get target product IDs from product collection
- * which was set on block
- *
- * @return Mage_Eav_Model_Entity_Collection_Abstract
- */
- protected function getProducts()
- {
- return $this->getProductCollection();
- }
-
/**
* Get configuration for configurable swatches price change
*
@@ -79,6 +68,17 @@ public function getJsonConfig()
return $helper->jsonEncode($config);
}
+ /**
+ * Get target product IDs from product collection
+ * which was set on block
+ *
+ * @return Mage_Eav_Model_Entity_Collection_Abstract
+ */
+ protected function getProducts()
+ {
+ return $this->getProductCollection();
+ }
+
/**
* Disable output if all preconditions doesn't meet
*
diff --git a/app/code/core/Mage/ConfigurableSwatches/Helper/List/Price.php b/app/code/core/Mage/ConfigurableSwatches/Helper/List/Price.php
index 25f1043823d..a64f6f05fa9 100644
--- a/app/code/core/Mage/ConfigurableSwatches/Helper/List/Price.php
+++ b/app/code/core/Mage/ConfigurableSwatches/Helper/List/Price.php
@@ -89,22 +89,22 @@ public function attachConfigurableProductChildrenPricesMapping(array $products,
}
/**
- * Get helper for calculation purposes
+ * Check if option for swatches price change is enabled
*
- * @return Mage_Catalog_Helper_Product_Type_Composite
+ * @return bool
*/
- protected function _getHelper()
+ public function isEnabled()
{
- return Mage::helper('catalog/product_type_composite');
+ return Mage::getStoreConfigFlag(self::XML_PATH_SWATCH_PRICE);
}
/**
- * Check if option for swatches price change is enabled
+ * Get helper for calculation purposes
*
- * @return bool
+ * @return Mage_Catalog_Helper_Product_Type_Composite
*/
- public function isEnabled()
+ protected function _getHelper()
{
- return Mage::getStoreConfigFlag(self::XML_PATH_SWATCH_PRICE);
+ return Mage::helper('catalog/product_type_composite');
}
}
diff --git a/app/code/core/Mage/ConfigurableSwatches/Helper/Mediafallback.php b/app/code/core/Mage/ConfigurableSwatches/Helper/Mediafallback.php
index feaf52931cc..cf0d2229fe5 100644
--- a/app/code/core/Mage/ConfigurableSwatches/Helper/Mediafallback.php
+++ b/app/code/core/Mage/ConfigurableSwatches/Helper/Mediafallback.php
@@ -258,41 +258,6 @@ public function getConfigurableImagesFallbackArray(
return $product->getConfigurableImagesFallbackArray();
}
- /**
- * Resize specified type of image on the product for use in the fallback and returns the image URL
- * or returns the image URL for the specified image path if present
- *
- * @param Mage_Catalog_Model_Product $product
- * @param string $type
- * @param bool $keepFrame
- * @param string $image
- * @param bool $placeholder
- * @return string|bool
- */
- protected function _resizeProductImage($product, $type, $keepFrame, $image = null, $placeholder = false)
- {
- $hasTypeData = $product->hasData($type) && $product->getData($type) != 'no_selection';
- if ($image == 'no_selection') {
- $image = null;
- }
- if ($hasTypeData || $placeholder || $image) {
- $helper = Mage::helper('catalog/image')
- ->init($product, $type, $image)
- ->keepFrame(($hasTypeData || $image) ? $keepFrame : false) // don't keep frame if placeholder
- ;
-
- $size = Mage::getStoreConfig(Mage_Catalog_Helper_Image::XML_NODE_PRODUCT_BASE_IMAGE_WIDTH);
- if ($type == 'small_image') {
- $size = Mage::getStoreConfig(Mage_Catalog_Helper_Image::XML_NODE_PRODUCT_SMALL_IMAGE_WIDTH);
- }
- if (is_numeric($size)) {
- $helper->constrainOnly(true)->resize($size);
- }
- return (string) $helper;
- }
- return false;
- }
-
/**
* Groups media gallery images by local images and child images
*/
@@ -390,23 +355,6 @@ public function attachGallerySetToCollection(array $products, $storeId)
}
}
- /**
- * Determines which product attributes should be selected
- * when children products are attached to parent products
- *
- * @return array
- */
- protected function _getChildrenProductsAttributes()
- {
- return [
- 'small_image',
- 'image',
- 'image_label',
- 'small_image_label',
- Mage::helper('configurableswatches/productlist')->getSwatchAttribute()->getAttributeCode(),
- ];
- }
-
/**
* Attaches children product to each product via
* ->setChildrenProducts()
@@ -448,4 +396,56 @@ public function attachChildrenProducts(array $products, $storeId)
$products[$parentId]->setChildrenProducts($childrenProducts);
}
}
+
+ /**
+ * Resize specified type of image on the product for use in the fallback and returns the image URL
+ * or returns the image URL for the specified image path if present
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param string $type
+ * @param bool $keepFrame
+ * @param string $image
+ * @param bool $placeholder
+ * @return string|bool
+ */
+ protected function _resizeProductImage($product, $type, $keepFrame, $image = null, $placeholder = false)
+ {
+ $hasTypeData = $product->hasData($type) && $product->getData($type) != 'no_selection';
+ if ($image == 'no_selection') {
+ $image = null;
+ }
+ if ($hasTypeData || $placeholder || $image) {
+ $helper = Mage::helper('catalog/image')
+ ->init($product, $type, $image)
+ ->keepFrame(($hasTypeData || $image) ? $keepFrame : false) // don't keep frame if placeholder
+ ;
+
+ $size = Mage::getStoreConfig(Mage_Catalog_Helper_Image::XML_NODE_PRODUCT_BASE_IMAGE_WIDTH);
+ if ($type == 'small_image') {
+ $size = Mage::getStoreConfig(Mage_Catalog_Helper_Image::XML_NODE_PRODUCT_SMALL_IMAGE_WIDTH);
+ }
+ if (is_numeric($size)) {
+ $helper->constrainOnly(true)->resize($size);
+ }
+ return (string) $helper;
+ }
+ return false;
+ }
+
+ /**
+ * Determines which product attributes should be selected
+ * when children products are attached to parent products
+ *
+ * @return array
+ */
+ protected function _getChildrenProductsAttributes()
+ {
+ return [
+ 'small_image',
+ 'image',
+ 'image_label',
+ 'small_image_label',
+ Mage::helper('configurableswatches/productlist')->getSwatchAttribute()->getAttributeCode(),
+ ];
+ }
}
diff --git a/app/code/core/Mage/ConfigurableSwatches/Helper/Productimg.php b/app/code/core/Mage/ConfigurableSwatches/Helper/Productimg.php
index f58f9ddd6dc..90703b92228 100644
--- a/app/code/core/Mage/ConfigurableSwatches/Helper/Productimg.php
+++ b/app/code/core/Mage/ConfigurableSwatches/Helper/Productimg.php
@@ -22,6 +22,16 @@
*/
class Mage_ConfigurableSwatches_Helper_Productimg extends Mage_Core_Helper_Abstract
{
+ public const SWATCH_LABEL_SUFFIX = '-swatch';
+ public const SWATCH_FALLBACK_MEDIA_DIR = 'wysiwyg/swatches';
+ public const SWATCH_CACHE_DIR = 'catalog/swatches';
+ public const SWATCH_FILE_EXT = '.png';
+
+ public const MEDIA_IMAGE_TYPE_BASE = 'base_image';
+ public const MEDIA_IMAGE_TYPE_SMALL = 'small_image';
+
+ public const SWATCH_DEFAULT_WIDTH = 21;
+ public const SWATCH_DEFAULT_HEIGHT = 21;
protected $_moduleName = 'Mage_ConfigurableSwatches';
/**
@@ -40,17 +50,6 @@ class Mage_ConfigurableSwatches_Helper_Productimg extends Mage_Core_Helper_Abstr
*/
protected $_productImageFilters = [];
- public const SWATCH_LABEL_SUFFIX = '-swatch';
- public const SWATCH_FALLBACK_MEDIA_DIR = 'wysiwyg/swatches';
- public const SWATCH_CACHE_DIR = 'catalog/swatches';
- public const SWATCH_FILE_EXT = '.png';
-
- public const MEDIA_IMAGE_TYPE_BASE = 'base_image';
- public const MEDIA_IMAGE_TYPE_SMALL = 'small_image';
-
- public const SWATCH_DEFAULT_WIDTH = 21;
- public const SWATCH_DEFAULT_HEIGHT = 21;
-
/**
* Determine if the passed text matches the label of any of the passed product's images
*
@@ -310,6 +309,46 @@ public function createSwatchImage($value, $width, $height)
return $destPath;
}
+ /**
+ * Cleans out the swatch image cache dir
+ */
+ public function clearSwatchesCache()
+ {
+ $directory = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . self::SWATCH_CACHE_DIR;
+ $io = new Varien_Io_File();
+ $io->rmdir($directory, true);
+
+ Mage::helper('core/file_storage_database')->deleteFolder($directory);
+ }
+
+ /**
+ * Determine whether to show an image in the product media gallery
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param Varien_Object $image
+ * @return bool
+ */
+ public function filterImageInGallery($product, $image)
+ {
+ if (!Mage::helper('configurableswatches')->isEnabled()) {
+ return true;
+ }
+
+ if (!isset($this->_productImageFilters[$product->getId()])) {
+ $mapping = call_user_func_array('array_merge_recursive', array_values($product->getChildAttributeLabelMapping()));
+ $filters = array_unique($mapping['labels']);
+ $filters = array_merge($filters, array_map(function ($label) {
+ return $label . Mage_ConfigurableSwatches_Helper_Productimg::SWATCH_LABEL_SUFFIX;
+ }, $filters));
+ $this->_productImageFilters[$product->getId()] = $filters;
+ }
+
+ return !in_array(
+ Mage_ConfigurableSwatches_Helper_Data::normalizeKey($image->getLabel()),
+ $this->_productImageFilters[$product->getId()],
+ );
+ }
+
/**
* Performs the resize operation on the given swatch image file and returns a
* relative path to the resulting image file
@@ -356,44 +395,4 @@ protected function _resizeSwatchImage($filename, $tag, $width, $height)
return $destPath;
}
-
- /**
- * Cleans out the swatch image cache dir
- */
- public function clearSwatchesCache()
- {
- $directory = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . self::SWATCH_CACHE_DIR;
- $io = new Varien_Io_File();
- $io->rmdir($directory, true);
-
- Mage::helper('core/file_storage_database')->deleteFolder($directory);
- }
-
- /**
- * Determine whether to show an image in the product media gallery
- *
- * @param Mage_Catalog_Model_Product $product
- * @param Varien_Object $image
- * @return bool
- */
- public function filterImageInGallery($product, $image)
- {
- if (!Mage::helper('configurableswatches')->isEnabled()) {
- return true;
- }
-
- if (!isset($this->_productImageFilters[$product->getId()])) {
- $mapping = call_user_func_array('array_merge_recursive', array_values($product->getChildAttributeLabelMapping()));
- $filters = array_unique($mapping['labels']);
- $filters = array_merge($filters, array_map(function ($label) {
- return $label . Mage_ConfigurableSwatches_Helper_Productimg::SWATCH_LABEL_SUFFIX;
- }, $filters));
- $this->_productImageFilters[$product->getId()] = $filters;
- }
-
- return !in_array(
- Mage_ConfigurableSwatches_Helper_Data::normalizeKey($image->getLabel()),
- $this->_productImageFilters[$product->getId()],
- );
- }
}
diff --git a/app/code/core/Mage/ConfigurableSwatches/Helper/Productlist.php b/app/code/core/Mage/ConfigurableSwatches/Helper/Productlist.php
index fc409ae1642..af8dce9ce62 100644
--- a/app/code/core/Mage/ConfigurableSwatches/Helper/Productlist.php
+++ b/app/code/core/Mage/ConfigurableSwatches/Helper/Productlist.php
@@ -105,6 +105,17 @@ public function getSwatchAttribute()
return $this->_swatchAttribute;
}
+ /**
+ * See if the swatch matches a filter currently applied to the product list.
+ *
+ * @param int $optionId
+ * @return bool
+ */
+ public function swatchMatchesFilter($optionId)
+ {
+ return ($optionId == $this->_getSwatchAttributeFilteredValue());
+ }
+
/**
* If the product list is currently filtered by the swatch attribute, get the selected value.
*
@@ -126,15 +137,4 @@ protected function _getSwatchAttributeFilteredValue()
}
return $this->_swatchAttributeFilteredValue;
}
-
- /**
- * See if the swatch matches a filter currently applied to the product list.
- *
- * @param int $optionId
- * @return bool
- */
- public function swatchMatchesFilter($optionId)
- {
- return ($optionId == $this->_getSwatchAttributeFilteredValue());
- }
}
diff --git a/app/code/core/Mage/Core/Block/Abstract.php b/app/code/core/Mage/Core/Block/Abstract.php
index 2477a32543e..4bb91d3a886 100644
--- a/app/code/core/Mage/Core/Block/Abstract.php
+++ b/app/code/core/Mage/Core/Block/Abstract.php
@@ -163,12 +163,6 @@ abstract class Mage_Core_Block_Abstract extends Varien_Object
*/
protected static $_urlModel;
- /**
- * @var Varien_Object
- */
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private static $_transportObject;
-
/**
* Array of block sort priority instructions
*
@@ -190,6 +184,12 @@ abstract class Mage_Core_Block_Abstract extends Varien_Object
*/
protected $_app;
+ /**
+ * @var Varien_Object
+ */
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private static $_transportObject;
+
/**
* Initialize factory instance
*/
@@ -205,36 +205,19 @@ public function __construct(array $args = [])
}
/**
- * Internal constructor, that is called from real constructor
- *
- * Please override this one instead of overriding real __construct constructor
- *
- */
- protected function _construct()
- {
- /**
- * Please override this one instead of overriding real __construct constructor
- */
- }
-
- /**
- * Retrieve factory instance
+ * Translate block sentence
*
- * @return Mage_Core_Model_Factory
- */
- protected function _getFactory()
- {
- return is_null($this->_factory) ? Mage::getSingleton('core/factory') : $this->_factory;
- }
-
- /**
- * Retrieve application instance
+ * @return string
*
- * @return Mage_Core_Model_App
+ * @SuppressWarnings("PHPMD.CamelCaseMethodName")
+ * @SuppressWarnings("PHPMD.ShortMethodName")
*/
- protected function _getApp()
+ public function __()
{
- return is_null($this->_app) ? Mage::app() : $this->_app;
+ $args = func_get_args();
+ $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->getModuleName());
+ array_unshift($args, $expr);
+ return $this->_getApp()->getTranslator()->translate($args);
}
/**
@@ -299,18 +282,6 @@ public function setLayout(Mage_Core_Model_Layout $layout)
return $this;
}
- /**
- * Preparing global layout
- *
- * You can redefine this method in child classes for changing layout
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- return $this;
- }
-
/**
* Retrieve layout object
*
@@ -619,40 +590,6 @@ public function getSortedChildBlocks()
return $children;
}
- /**
- * Retrieve child block HTML
- *
- * @param string $name
- * @param bool $useCache
- * @return string
- */
- protected function _getChildHtml($name, $useCache = true)
- {
- if ($useCache && isset($this->_childrenHtmlCache[$name])) {
- return $this->_childrenHtmlCache[$name];
- }
-
- $child = $this->getChild($name);
-
- if (!$child) {
- $html = '';
- } else {
- $this->_beforeChildToHtml($name, $child);
- $html = $child->toHtml();
- }
-
- $this->_childrenHtmlCache[$name] = $html;
- return $html;
- }
-
- /**
- * Prepare child block before generate html
- *
- * @param string $name
- * @param Mage_Core_Block_Abstract $child
- */
- protected function _beforeChildToHtml($name, $child) {}
-
/**
* Retrieve block html
*
@@ -872,16 +809,6 @@ public function getChildData($alias, $key = '')
}
}
- /**
- * Before rendering html, but after trying to load cache
- *
- * @return $this
- */
- protected function _beforeToHtml()
- {
- return $this;
- }
-
/**
* Specify block output frame tags
*
@@ -953,49 +880,6 @@ final public function toHtml()
return self::$_transportObject->getHtml();
}
- /**
- * Processing block html after rendering
- *
- * @param string $html
- * @return string
- */
- protected function _afterToHtml($html)
- {
- return $html;
- }
-
- /**
- * Override this method in descendants to produce html
- *
- * @return string
- */
- protected function _toHtml()
- {
- return '';
- }
-
- /**
- * Returns url model class name
- *
- * @return string
- */
- protected function _getUrlModelClass()
- {
- return 'core/url';
- }
-
- /**
- * Create and return url object
- *
- * @return Mage_Core_Model_Url
- */
- protected function _getUrlModel()
- {
- /** @var Mage_Core_Model_Url $model */
- $model = Mage::getModel($this->_getUrlModelClass());
- return $model;
- }
-
/**
* Generate url by route and parameters
*
@@ -1170,22 +1054,6 @@ public function getModuleName()
return $module;
}
- /**
- * Translate block sentence
- *
- * @return string
- *
- * @SuppressWarnings("PHPMD.CamelCaseMethodName")
- * @SuppressWarnings("PHPMD.ShortMethodName")
- */
- public function __()
- {
- $args = func_get_args();
- $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->getModuleName());
- array_unshift($args, $expr);
- return $this->_getApp()->getTranslator()->translate($args);
- }
-
/**
* @param string|array $data
* @param array $allowedTags
@@ -1320,38 +1188,6 @@ public function countChildren()
return count($this->_children);
}
- /**
- * Prepare url for save to cache
- *
- * @return $this
- */
- protected function _beforeCacheUrl()
- {
- if ($this->_getApp()->useCache(self::CACHE_GROUP)) {
- $this->_getApp()->setUseSessionVar(true);
- }
- return $this;
- }
-
- /**
- * Replace URLs from cache
- *
- * @param string $html
- * @return string
- */
- protected function _afterCacheUrl($html)
- {
- if ($this->_getApp()->useCache(self::CACHE_GROUP)) {
- $this->_getApp()->setUseSessionVar(false);
- Varien_Profiler::start('CACHE_URL');
- /** @var Mage_Core_Model_Url $model */
- $model = Mage::getSingleton($this->_getUrlModelClass());
- $html = $model->sessionUrlVar($html);
- Varien_Profiler::stop('CACHE_URL');
- }
- return $html;
- }
-
/**
* Get cache key informative items
* Provide string array key to share specific info item with FPC placeholder
@@ -1464,6 +1300,215 @@ public function getFormKey()
return Mage::getSingleton('core/session')->getFormKey();
}
+ /**
+ * Collect and retrieve items tags.
+ * Item should implement Mage_Core_Model_Abstract::getCacheIdTags method
+ *
+ * @param array|Varien_Data_Collection $items
+ * @return array
+ */
+ public function getItemsTags($items)
+ {
+ $tags = [];
+ /** @var Mage_Core_Model_Abstract $item */
+ foreach ($items as $item) {
+ $itemTags = $item->getCacheIdTags();
+ if ($itemTags === false) {
+ continue;
+ }
+ $tags = array_merge($tags, $itemTags);
+ }
+ return $tags;
+ }
+
+ public function isModuleEnabled(?string $moduleName = null, string $helperAlias = 'core'): bool
+ {
+ if ($moduleName === null) {
+ $moduleName = $this->getModuleName();
+ }
+
+ return Mage::helper($helperAlias)->isModuleEnabled($moduleName);
+ }
+
+ /**
+ * Check whether the module output is enabled
+ *
+ * Because many module blocks belong to Adminhtml module,
+ * the feature "Disable module output" doesn't cover Admin area
+ */
+ public function isModuleOutputEnabled(?string $moduleName = null, string $helperAlias = 'core'): bool
+ {
+ if ($moduleName === null) {
+ $moduleName = $this->getModuleName();
+ }
+
+ return Mage::helper($helperAlias)->isModuleOutputEnabled($moduleName);
+ }
+
+ /**
+ * Internal constructor, that is called from real constructor
+ *
+ * Please override this one instead of overriding real __construct constructor
+ *
+ */
+ protected function _construct()
+ {
+ /**
+ * Please override this one instead of overriding real __construct constructor
+ */
+ }
+
+ /**
+ * Retrieve factory instance
+ *
+ * @return Mage_Core_Model_Factory
+ */
+ protected function _getFactory()
+ {
+ return is_null($this->_factory) ? Mage::getSingleton('core/factory') : $this->_factory;
+ }
+
+ /**
+ * Retrieve application instance
+ *
+ * @return Mage_Core_Model_App
+ */
+ protected function _getApp()
+ {
+ return is_null($this->_app) ? Mage::app() : $this->_app;
+ }
+
+ /**
+ * Preparing global layout
+ *
+ * You can redefine this method in child classes for changing layout
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ return $this;
+ }
+
+ /**
+ * Retrieve child block HTML
+ *
+ * @param string $name
+ * @param bool $useCache
+ * @return string
+ */
+ protected function _getChildHtml($name, $useCache = true)
+ {
+ if ($useCache && isset($this->_childrenHtmlCache[$name])) {
+ return $this->_childrenHtmlCache[$name];
+ }
+
+ $child = $this->getChild($name);
+
+ if (!$child) {
+ $html = '';
+ } else {
+ $this->_beforeChildToHtml($name, $child);
+ $html = $child->toHtml();
+ }
+
+ $this->_childrenHtmlCache[$name] = $html;
+ return $html;
+ }
+
+ /**
+ * Prepare child block before generate html
+ *
+ * @param string $name
+ * @param Mage_Core_Block_Abstract $child
+ */
+ protected function _beforeChildToHtml($name, $child) {}
+
+ /**
+ * Before rendering html, but after trying to load cache
+ *
+ * @return $this
+ */
+ protected function _beforeToHtml()
+ {
+ return $this;
+ }
+
+ /**
+ * Processing block html after rendering
+ *
+ * @param string $html
+ * @return string
+ */
+ protected function _afterToHtml($html)
+ {
+ return $html;
+ }
+
+ /**
+ * Override this method in descendants to produce html
+ *
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ return '';
+ }
+
+ /**
+ * Returns url model class name
+ *
+ * @return string
+ */
+ protected function _getUrlModelClass()
+ {
+ return 'core/url';
+ }
+
+ /**
+ * Create and return url object
+ *
+ * @return Mage_Core_Model_Url
+ */
+ protected function _getUrlModel()
+ {
+ /** @var Mage_Core_Model_Url $model */
+ $model = Mage::getModel($this->_getUrlModelClass());
+ return $model;
+ }
+
+ /**
+ * Prepare url for save to cache
+ *
+ * @return $this
+ */
+ protected function _beforeCacheUrl()
+ {
+ if ($this->_getApp()->useCache(self::CACHE_GROUP)) {
+ $this->_getApp()->setUseSessionVar(true);
+ }
+ return $this;
+ }
+
+ /**
+ * Replace URLs from cache
+ *
+ * @param string $html
+ * @return string
+ */
+ protected function _afterCacheUrl($html)
+ {
+ if ($this->_getApp()->useCache(self::CACHE_GROUP)) {
+ $this->_getApp()->setUseSessionVar(false);
+ Varien_Profiler::start('CACHE_URL');
+ /** @var Mage_Core_Model_Url $model */
+ $model = Mage::getSingleton($this->_getUrlModelClass());
+ $html = $model->sessionUrlVar($html);
+ Varien_Profiler::stop('CACHE_URL');
+ }
+ return $html;
+ }
+
/**
* Load block html from cache storage
*
@@ -1547,27 +1592,6 @@ protected function _getSidPlaceholder($cacheKey = null)
return '';
}
- /**
- * Collect and retrieve items tags.
- * Item should implement Mage_Core_Model_Abstract::getCacheIdTags method
- *
- * @param array|Varien_Data_Collection $items
- * @return array
- */
- public function getItemsTags($items)
- {
- $tags = [];
- /** @var Mage_Core_Model_Abstract $item */
- foreach ($items as $item) {
- $itemTags = $item->getCacheIdTags();
- if ($itemTags === false) {
- continue;
- }
- $tags = array_merge($tags, $itemTags);
- }
- return $tags;
- }
-
/**
* Checks is request Url is secure
*
@@ -1577,28 +1601,4 @@ protected function _isSecure()
{
return $this->_getApp()->getFrontController()->getRequest()->isSecure();
}
-
- public function isModuleEnabled(?string $moduleName = null, string $helperAlias = 'core'): bool
- {
- if ($moduleName === null) {
- $moduleName = $this->getModuleName();
- }
-
- return Mage::helper($helperAlias)->isModuleEnabled($moduleName);
- }
-
- /**
- * Check whether the module output is enabled
- *
- * Because many module blocks belong to Adminhtml module,
- * the feature "Disable module output" doesn't cover Admin area
- */
- public function isModuleOutputEnabled(?string $moduleName = null, string $helperAlias = 'core'): bool
- {
- if ($moduleName === null) {
- $moduleName = $this->getModuleName();
- }
-
- return Mage::helper($helperAlias)->isModuleOutputEnabled($moduleName);
- }
}
diff --git a/app/code/core/Mage/Core/Block/Html/Calendar.php b/app/code/core/Mage/Core/Block/Html/Calendar.php
index 40d6da462c2..bc6dfaabe2d 100644
--- a/app/code/core/Mage/Core/Block/Html/Calendar.php
+++ b/app/code/core/Mage/Core/Block/Html/Calendar.php
@@ -23,6 +23,26 @@
*/
class Mage_Core_Block_Html_Calendar extends Mage_Core_Block_Template
{
+ /**
+ * Return offset of current timezone with GMT in seconds
+ *
+ * @return int
+ */
+ public function getTimezoneOffsetSeconds()
+ {
+ return Mage::getSingleton('core/date')->getGmtOffset();
+ }
+
+ /**
+ * Getter for store timestamp based on store timezone settings
+ *
+ * @param mixed $store
+ * @return int
+ */
+ public function getStoreTimestamp($store = null)
+ {
+ return Mage::getSingleton('core/locale')->storeTimeStamp($store);
+ }
/**
* @return string
* @throws Zend_Locale_Exception
@@ -72,25 +92,4 @@ protected function _toHtml()
return parent::_toHtml();
}
-
- /**
- * Return offset of current timezone with GMT in seconds
- *
- * @return int
- */
- public function getTimezoneOffsetSeconds()
- {
- return Mage::getSingleton('core/date')->getGmtOffset();
- }
-
- /**
- * Getter for store timestamp based on store timezone settings
- *
- * @param mixed $store
- * @return int
- */
- public function getStoreTimestamp($store = null)
- {
- return Mage::getSingleton('core/locale')->storeTimeStamp($store);
- }
}
diff --git a/app/code/core/Mage/Core/Block/Html/Date.php b/app/code/core/Mage/Core/Block/Html/Date.php
index b075ce37376..073343079e0 100644
--- a/app/code/core/Mage/Core/Block/Html/Date.php
+++ b/app/code/core/Mage/Core/Block/Html/Date.php
@@ -40,6 +40,26 @@
*/
class Mage_Core_Block_Html_Date extends Mage_Core_Block_Template
{
+ /**
+ * @param null $index deprecated
+ * @return string
+ */
+ public function getEscapedValue($index = null)
+ {
+ if ($this->getFormat() && $this->getValue()) {
+ return strftime($this->getFormat(), strtotime($this->getValue()));
+ }
+
+ return htmlspecialchars($this->getValue());
+ }
+
+ /**
+ * @return string
+ */
+ public function getHtml()
+ {
+ return $this->toHtml();
+ }
/**
* @return string
*/
@@ -77,25 +97,4 @@ protected function _toHtml()
//]]>
';
}
-
- /**
- * @param null $index deprecated
- * @return string
- */
- public function getEscapedValue($index = null)
- {
- if ($this->getFormat() && $this->getValue()) {
- return strftime($this->getFormat(), strtotime($this->getValue()));
- }
-
- return htmlspecialchars($this->getValue());
- }
-
- /**
- * @return string
- */
- public function getHtml()
- {
- return $this->toHtml();
- }
}
diff --git a/app/code/core/Mage/Core/Block/Html/Link.php b/app/code/core/Mage/Core/Block/Html/Link.php
index 5ef261b6847..68fc8c57717 100644
--- a/app/code/core/Mage/Core/Block/Html/Link.php
+++ b/app/code/core/Mage/Core/Block/Html/Link.php
@@ -22,11 +22,6 @@
*/
class Mage_Core_Block_Html_Link extends Mage_Core_Block_Template
{
- protected function _construct()
- {
- $this->setTemplate('core/link.phtml');
- parent::_construct();
- }
/**
* Prepare link attributes as serialized and formatted string
*
@@ -76,4 +71,9 @@ public function serialize($attributes = [], $valueSeparator = '=', $fieldSeparat
}
return implode($fieldSeparator, $data);
}
+ protected function _construct()
+ {
+ $this->setTemplate('core/link.phtml');
+ parent::_construct();
+ }
}
diff --git a/app/code/core/Mage/Core/Block/Html/Select.php b/app/code/core/Mage/Core/Block/Html/Select.php
index b21a1f3364b..fbfc3caf675 100644
--- a/app/code/core/Mage/Core/Block/Html/Select.php
+++ b/app/code/core/Mage/Core/Block/Html/Select.php
@@ -134,6 +134,27 @@ public function getTitle()
return $this->getData('title');
}
+ /**
+ * Alias for toHtml()
+ *
+ * @return string
+ */
+ public function getHtml()
+ {
+ return $this->toHtml();
+ }
+
+ /**
+ * Calculate CRC32 hash for option value
+ *
+ * @param string $optionValue Value of the option
+ * @return string
+ */
+ public function calcOptionHash($optionValue)
+ {
+ return sprintf('%u', crc32($this->getName() . $this->getId() . $optionValue));
+ }
+
/**
* Render HTML
*
@@ -234,25 +255,4 @@ protected function _optionToHtml($option, $selected = false)
$this->escapeHtml($option['label']),
);
}
-
- /**
- * Alias for toHtml()
- *
- * @return string
- */
- public function getHtml()
- {
- return $this->toHtml();
- }
-
- /**
- * Calculate CRC32 hash for option value
- *
- * @param string $optionValue Value of the option
- * @return string
- */
- public function calcOptionHash($optionValue)
- {
- return sprintf('%u', crc32($this->getName() . $this->getId() . $optionValue));
- }
}
diff --git a/app/code/core/Mage/Core/Block/Messages.php b/app/code/core/Mage/Core/Block/Messages.php
index 4691e512270..c242fc52c07 100644
--- a/app/code/core/Mage/Core/Block/Messages.php
+++ b/app/code/core/Mage/Core/Block/Messages.php
@@ -248,14 +248,6 @@ public function getGroupedHtml()
return $html;
}
- /**
- * @return string
- */
- protected function _toHtml()
- {
- return $this->getGroupedHtml();
- }
-
/**
* Set messages first level html tag name for output messages as html
*
@@ -297,4 +289,12 @@ public function addStorageType($type)
{
$this->_usedStorageTypes[] = $type;
}
+
+ /**
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ return $this->getGroupedHtml();
+ }
}
diff --git a/app/code/core/Mage/Core/Block/Store/Switcher.php b/app/code/core/Mage/Core/Block/Store/Switcher.php
index 2be9dc7d044..c2c1d951584 100644
--- a/app/code/core/Mage/Core/Block/Store/Switcher.php
+++ b/app/code/core/Mage/Core/Block/Store/Switcher.php
@@ -39,41 +39,6 @@ public function __construct()
parent::__construct();
}
- /**
- * @return $this
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _loadData()
- {
- if ($this->_loaded) {
- return $this;
- }
-
- $websiteId = Mage::app()->getStore()->getWebsiteId();
- $storeCollection = Mage::getModel('core/store')
- ->getCollection()
- ->addWebsiteFilter($websiteId);
- $groupCollection = Mage::getModel('core/store_group')
- ->getCollection()
- ->addWebsiteFilter($websiteId);
- /** @var Mage_Core_Model_Store_Group $group */
- foreach ($groupCollection as $group) {
- $this->_groups[$group->getId()] = $group;
- }
- /** @var Mage_Core_Model_Store $store */
- foreach ($storeCollection as $store) {
- if (!$store->getIsActive()) {
- continue;
- }
- $store->setLocaleCode(Mage::getStoreConfig('general/locale/code', $store->getId()));
- $this->_stores[$store->getGroupId()][$store->getId()] = $store;
- }
-
- $this->_loaded = true;
-
- return $this;
- }
-
/**
* @return int
*/
@@ -134,4 +99,39 @@ public function getCurrentStoreCode()
{
return Mage::app()->getStore()->getCode();
}
+
+ /**
+ * @return $this
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _loadData()
+ {
+ if ($this->_loaded) {
+ return $this;
+ }
+
+ $websiteId = Mage::app()->getStore()->getWebsiteId();
+ $storeCollection = Mage::getModel('core/store')
+ ->getCollection()
+ ->addWebsiteFilter($websiteId);
+ $groupCollection = Mage::getModel('core/store_group')
+ ->getCollection()
+ ->addWebsiteFilter($websiteId);
+ /** @var Mage_Core_Model_Store_Group $group */
+ foreach ($groupCollection as $group) {
+ $this->_groups[$group->getId()] = $group;
+ }
+ /** @var Mage_Core_Model_Store $store */
+ foreach ($storeCollection as $store) {
+ if (!$store->getIsActive()) {
+ continue;
+ }
+ $store->setLocaleCode(Mage::getStoreConfig('general/locale/code', $store->getId()));
+ $this->_stores[$store->getGroupId()][$store->getId()] = $store;
+ }
+
+ $this->_loaded = true;
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Core/Block/Template.php b/app/code/core/Mage/Core/Block/Template.php
index 8274366c9ff..a5c0cb34665 100644
--- a/app/code/core/Mage/Core/Block/Template.php
+++ b/app/code/core/Mage/Core/Block/Template.php
@@ -65,26 +65,6 @@ class Mage_Core_Block_Template extends Mage_Core_Block_Abstract
*/
protected $_template = '';
- /**
- * Internal constructor, that is called from real constructor
- *
- * @return void
- */
- protected function _construct()
- {
- parent::_construct();
-
- /*
- * In case template was passed through constructor
- * we assign it to block's property _template
- * Mainly for those cases when block created
- * not via Mage_Core_Model_Layout::addBlock()
- */
- if ($this->hasData('template')) {
- $this->setTemplate($this->getData('template'));
- }
- }
-
/**
* Get relevant path to template
*
@@ -207,26 +187,6 @@ public function getShowTemplateHints()
return self::$_showTemplateHints;
}
- /**
- * Retrieve block cache status
- */
- private function _getCacheHintStatusColor(): string
- {
- if (!is_null($this->getCacheLifetime())) {
- return 'green';
- } else {
- $currentParentBlock = $this;
- $i = 0;
- while ($i++ < 20 && $currentParentBlock instanceof Mage_Core_Block_Abstract) {
- if (!is_null($currentParentBlock->getCacheLifetime())) {
- return 'orange'; // not cached, but within cached
- }
- $currentParentBlock = $currentParentBlock->getParentBlock();
- }
- }
- return 'red';
- }
-
/**
* Retrieve block view from file (template)
*
@@ -310,19 +270,6 @@ public function renderView()
return $this->fetchView($this->getTemplateFile());
}
- /**
- * Render block HTML
- *
- * @return string
- */
- protected function _toHtml()
- {
- if (!$this->getTemplate()) {
- return '';
- }
- return $this->renderView();
- }
-
/**
* Get base url of the application
*
@@ -376,6 +323,39 @@ public function getCacheKeyInfo()
];
}
+ /**
+ * Internal constructor, that is called from real constructor
+ *
+ * @return void
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+
+ /*
+ * In case template was passed through constructor
+ * we assign it to block's property _template
+ * Mainly for those cases when block created
+ * not via Mage_Core_Model_Layout::addBlock()
+ */
+ if ($this->hasData('template')) {
+ $this->setTemplate($this->getData('template'));
+ }
+ }
+
+ /**
+ * Render block HTML
+ *
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ if (!$this->getTemplate()) {
+ return '';
+ }
+ return $this->renderView();
+ }
+
/**
* Get is allowed symlinks flag
*
@@ -386,4 +366,24 @@ protected function _getAllowSymlinks()
{
return false;
}
+
+ /**
+ * Retrieve block cache status
+ */
+ private function _getCacheHintStatusColor(): string
+ {
+ if (!is_null($this->getCacheLifetime())) {
+ return 'green';
+ } else {
+ $currentParentBlock = $this;
+ $i = 0;
+ while ($i++ < 20 && $currentParentBlock instanceof Mage_Core_Block_Abstract) {
+ if (!is_null($currentParentBlock->getCacheLifetime())) {
+ return 'orange'; // not cached, but within cached
+ }
+ $currentParentBlock = $currentParentBlock->getParentBlock();
+ }
+ }
+ return 'red';
+ }
}
diff --git a/app/code/core/Mage/Core/Block/Text/Tag.php b/app/code/core/Mage/Core/Block/Text/Tag.php
index 0a79c1db11a..b67043cf686 100644
--- a/app/code/core/Mage/Core/Block/Text/Tag.php
+++ b/app/code/core/Mage/Core/Block/Text/Tag.php
@@ -28,12 +28,6 @@
*/
class Mage_Core_Block_Text_Tag extends Mage_Core_Block_Text
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTagParams([]);
- }
-
/**
* @param string|array $param
* @param string|null $value
@@ -62,6 +56,11 @@ public function setContents($text)
$this->setTagContents($text);
return $this;
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTagParams([]);
+ }
/**
* @inheritDoc
diff --git a/app/code/core/Mage/Core/Block/Text/Tag/Css.php b/app/code/core/Mage/Core/Block/Text/Tag/Css.php
index d9a42332e4c..2c1ea9afe15 100644
--- a/app/code/core/Mage/Core/Block/Text/Tag/Css.php
+++ b/app/code/core/Mage/Core/Block/Text/Tag/Css.php
@@ -25,13 +25,6 @@
*/
class Mage_Core_Block_Text_Tag_Css extends Mage_Core_Block_Text_Tag
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTagName('link');
- $this->setTagParams(['rel' => 'stylesheet', 'type' => 'text/css', 'media' => 'all']);
- }
-
/**
* @param string $href
* @param string|null $type
@@ -47,4 +40,10 @@ public function setHref($href, $type = null)
return $this->setTagParam('href', $url);
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTagName('link');
+ $this->setTagParams(['rel' => 'stylesheet', 'type' => 'text/css', 'media' => 'all']);
+ }
}
diff --git a/app/code/core/Mage/Core/Block/Text/Tag/Css/Admin.php b/app/code/core/Mage/Core/Block/Text/Tag/Css/Admin.php
index 419bf9e4076..fed32272658 100644
--- a/app/code/core/Mage/Core/Block/Text/Tag/Css/Admin.php
+++ b/app/code/core/Mage/Core/Block/Text/Tag/Css/Admin.php
@@ -24,16 +24,6 @@
*/
class Mage_Core_Block_Text_Tag_Css_Admin extends Mage_Core_Block_Text_Tag_Css
{
- /**
- * @SuppressWarnings("PHPMD.Superglobals")
- */
- protected function _construct()
- {
- parent::_construct();
- $theme = empty($_COOKIE['admtheme']) ? 'default' : $_COOKIE['admtheme'];
- $this->setAttribute('theme', $theme);
- }
-
/**
* @param string $href
* @param string|null $type
@@ -48,4 +38,13 @@ public function setHref($href, $type = null)
$url = Mage::getBaseUrl($type) . $href . $this->getTheme() . '.css';
return $this->setTagParam('href', $url);
}
+ /**
+ * @SuppressWarnings("PHPMD.Superglobals")
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $theme = empty($_COOKIE['admtheme']) ? 'default' : $_COOKIE['admtheme'];
+ $this->setAttribute('theme', $theme);
+ }
}
diff --git a/app/code/core/Mage/Core/Block/Text/Tag/Debug.php b/app/code/core/Mage/Core/Block/Text/Tag/Debug.php
index 5cd0f678b4e..d9aad0d4e5e 100644
--- a/app/code/core/Mage/Core/Block/Text/Tag/Debug.php
+++ b/app/code/core/Mage/Core/Block/Text/Tag/Debug.php
@@ -22,14 +22,6 @@
*/
class Mage_Core_Block_Text_Tag_Debug extends Mage_Core_Block_Text_Tag
{
- protected function _construct()
- {
- parent::_construct();
- $this->setAttribute([
- 'tagName' => 'xmp',
- ]);
- }
-
/**
* @param mixed $value
* @return $this
@@ -39,4 +31,11 @@ public function setValue($value)
{
return $this->setContents(print_r($value, true));
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setAttribute([
+ 'tagName' => 'xmp',
+ ]);
+ }
}
diff --git a/app/code/core/Mage/Core/Block/Text/Tag/Js.php b/app/code/core/Mage/Core/Block/Text/Tag/Js.php
index b8679728c56..5b516157beb 100644
--- a/app/code/core/Mage/Core/Block/Text/Tag/Js.php
+++ b/app/code/core/Mage/Core/Block/Text/Tag/Js.php
@@ -25,13 +25,6 @@
*/
class Mage_Core_Block_Text_Tag_Js extends Mage_Core_Block_Text_Tag
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTagName('script');
- $this->setTagParams(['language' => 'javascript', 'type' => 'text/javascript']);
- }
-
/**
* @param string $src
* @param string|null $type
@@ -47,4 +40,10 @@ public function setSrc($src, $type = null)
return $this->setTagParam('src', $url);
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTagName('script');
+ $this->setTagParams(['language' => 'javascript', 'type' => 'text/javascript']);
+ }
}
diff --git a/app/code/core/Mage/Core/Controller/Front/Action.php b/app/code/core/Mage/Core/Controller/Front/Action.php
index 8ba40b38a25..feae1aab08c 100644
--- a/app/code/core/Mage/Core/Controller/Front/Action.php
+++ b/app/code/core/Mage/Core/Controller/Front/Action.php
@@ -46,6 +46,21 @@ class Mage_Core_Controller_Front_Action extends Mage_Core_Controller_Varien_Acti
*/
protected $_sessionNamespace = self::SESSION_NAMESPACE;
+ /**
+ * Translate a phrase
+ *
+ * @return string
+ * @SuppressWarnings("PHPMD.CamelCaseMethodName")
+ * @SuppressWarnings("PHPMD.ShortMethodName")
+ */
+ public function __()
+ {
+ $args = func_get_args();
+ $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getRealModuleName());
+ array_unshift($args, $expr);
+ return Mage::app()->getTranslator()->translate($args);
+ }
+
/**
* Predispatch: should set layout area
*
@@ -73,21 +88,6 @@ public function postDispatch()
return $this;
}
- /**
- * Translate a phrase
- *
- * @return string
- * @SuppressWarnings("PHPMD.CamelCaseMethodName")
- * @SuppressWarnings("PHPMD.ShortMethodName")
- */
- public function __()
- {
- $args = func_get_args();
- $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getRealModuleName());
- array_unshift($args, $expr);
- return Mage::app()->getTranslator()->translate($args);
- }
-
/**
* Declare headers and content file in response for file download
*
diff --git a/app/code/core/Mage/Core/Controller/Request/Http.php b/app/code/core/Mage/Core/Controller/Request/Http.php
index a0de03dc98b..e4cac990aad 100644
--- a/app/code/core/Mage/Core/Controller/Request/Http.php
+++ b/app/code/core/Mage/Core/Controller/Request/Http.php
@@ -189,16 +189,6 @@ public function rewritePathInfo($pathInfo)
return $this;
}
- /**
- * Check if can be store code as part of url
- *
- * @return bool
- */
- protected function _canBeStoreCodeInUrl()
- {
- return Mage::isInstalled() && Mage::getStoreConfigFlag(Mage_Core_Model_Store::XML_PATH_STORE_IN_URL);
- }
-
/**
* Check if code declared as direct access frontend name
* this mean what this url can be used without store code
@@ -592,4 +582,14 @@ public function getInternallyForwarded()
{
return $this->_internallyForwarded;
}
+
+ /**
+ * Check if can be store code as part of url
+ *
+ * @return bool
+ */
+ protected function _canBeStoreCodeInUrl()
+ {
+ return Mage::isInstalled() && Mage::getStoreConfigFlag(Mage_Core_Model_Store::XML_PATH_STORE_IN_URL);
+ }
}
diff --git a/app/code/core/Mage/Core/Controller/Varien/Action.php b/app/code/core/Mage/Core/Controller/Varien/Action.php
index 5c36b16ba40..4367610c421 100644
--- a/app/code/core/Mage/Core/Controller/Varien/Action.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Action.php
@@ -126,11 +126,6 @@ public function __construct(Zend_Controller_Request_Abstract $request, Zend_Cont
$this->_construct();
}
- /**
- * @return void
- */
- protected function _construct() {}
-
/**
* @param string $action
* @return bool
@@ -600,6 +595,44 @@ public function noCookiesAction()
$this->getRequest()->setDispatched(true);
}
+ /**
+ * Initializing layout messages by message storage(s), loading and adding messages to layout messages block
+ *
+ * @param string|array $messagesStorage
+ * @return $this
+ */
+ public function initLayoutMessages($messagesStorage)
+ {
+ return $this->_initLayoutMessages($messagesStorage);
+ }
+
+ /**
+ * Set redirect into response with session id in URL if it is enabled.
+ * It allows to distinguish primordial request from browser with cookies disabled.
+ *
+ * @param string $path
+ * @return $this
+ */
+ public function setRedirectWithCookieCheck($path, array $arguments = [])
+ {
+ /** @var Mage_Core_Model_Session $session */
+ $session = Mage::getSingleton('core/session', ['name' => $this->_sessionNamespace]);
+ if ($session->getCookieShouldBeReceived() && Mage::app()->getUseSessionInUrl()
+ && $this->_sessionNamespace != Mage_Adminhtml_Controller_Action::SESSION_NAMESPACE
+ ) {
+ $arguments += ['_query' => [
+ $session->getSessionIdQueryParam() => $session->getSessionId(),
+ ]];
+ }
+ $this->getResponse()->setRedirect(Mage::getUrl($path, $arguments));
+ return $this;
+ }
+
+ /**
+ * @return void
+ */
+ protected function _construct() {}
+
/**
* Throw control to different action (control and module if was specified).
*
@@ -657,17 +690,6 @@ protected function _initLayoutMessages($messagesStorage)
return $this;
}
- /**
- * Initializing layout messages by message storage(s), loading and adding messages to layout messages block
- *
- * @param string|array $messagesStorage
- * @return $this
- */
- public function initLayoutMessages($messagesStorage)
- {
- return $this->_initLayoutMessages($messagesStorage);
- }
-
/**
* Set redirect url into response
*
@@ -692,28 +714,6 @@ protected function _redirect($path, $arguments = [])
return $this->setRedirectWithCookieCheck($path, $arguments);
}
- /**
- * Set redirect into response with session id in URL if it is enabled.
- * It allows to distinguish primordial request from browser with cookies disabled.
- *
- * @param string $path
- * @return $this
- */
- public function setRedirectWithCookieCheck($path, array $arguments = [])
- {
- /** @var Mage_Core_Model_Session $session */
- $session = Mage::getSingleton('core/session', ['name' => $this->_sessionNamespace]);
- if ($session->getCookieShouldBeReceived() && Mage::app()->getUseSessionInUrl()
- && $this->_sessionNamespace != Mage_Adminhtml_Controller_Action::SESSION_NAMESPACE
- ) {
- $arguments += ['_query' => [
- $session->getSessionIdQueryParam() => $session->getSessionId(),
- ]];
- }
- $this->getResponse()->setRedirect(Mage::getUrl($path, $arguments));
- return $this;
- }
-
/**
* Redirect to success page
*
diff --git a/app/code/core/Mage/Core/Controller/Varien/Front.php b/app/code/core/Mage/Core/Controller/Varien/Front.php
index 381e705ea44..589c4a3c429 100644
--- a/app/code/core/Mage/Core/Controller/Varien/Front.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Front.php
@@ -24,6 +24,7 @@
*/
class Mage_Core_Controller_Varien_Front extends Varien_Object
{
+ public const XML_STORE_ROUTERS_PATH = 'web/routers';
protected $_defaults = [];
/**
@@ -35,8 +36,6 @@ class Mage_Core_Controller_Varien_Front extends Varien_Object
protected $_urlCache = [];
- public const XML_STORE_ROUTERS_PATH = 'web/routers';
-
/**
* @param array|string $key
* @param string|null $value
@@ -197,20 +196,6 @@ public function dispatch()
return $this;
}
- /**
- * Returns request rewrite instance.
- * Class name alias is declared in the configuration
- *
- * @return Mage_Core_Model_Url_Rewrite_Request
- */
- protected function _getRequestRewriteController()
- {
- $className = (string) Mage::getConfig()->getNode('global/request_rewrite/model');
- return Mage::getSingleton('core/factory')->getModel($className, [
- 'routers' => $this->getRouters(),
- ]);
- }
-
/**
* Returns router instance by route name
*
@@ -294,6 +279,20 @@ public function rewrite()
}
}
+ /**
+ * Returns request rewrite instance.
+ * Class name alias is declared in the configuration
+ *
+ * @return Mage_Core_Model_Url_Rewrite_Request
+ */
+ protected function _getRequestRewriteController()
+ {
+ $className = (string) Mage::getConfig()->getNode('global/request_rewrite/model');
+ return Mage::getSingleton('core/factory')->getModel($className, [
+ 'routers' => $this->getRouters(),
+ ]);
+ }
+
/**
* Replace route name placeholders in url to front name
*
diff --git a/app/code/core/Mage/Core/Controller/Varien/Router/Admin.php b/app/code/core/Mage/Core/Controller/Varien/Router/Admin.php
index 02277d060c1..428264599bc 100644
--- a/app/code/core/Mage/Core/Controller/Varien/Router/Admin.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Router/Admin.php
@@ -34,6 +34,44 @@ public function fetchDefault()
]);
}
+ /**
+ * Emulate custom admin url
+ *
+ * @param string $configArea
+ * @param bool $useRouterName
+ */
+ public function collectRoutes($configArea, $useRouterName)
+ {
+ if ((string) Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_USE_CUSTOM_ADMIN_PATH)) {
+ $customUrl = (string) Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_CUSTOM_ADMIN_PATH);
+ $xmlPath = Mage_Adminhtml_Helper_Data::XML_PATH_ADMINHTML_ROUTER_FRONTNAME;
+ if ((string) Mage::getConfig()->getNode($xmlPath) != $customUrl) {
+ Mage::getConfig()->setNode($xmlPath, $customUrl, true);
+ }
+ }
+ parent::collectRoutes($configArea, $useRouterName);
+ }
+
+ /**
+ * Add module definition to routes.
+ *
+ * @inheritDoc
+ */
+ public function addModule($frontName, $moduleName, $routeName)
+ {
+ $isExtensionsCompatibilityMode = (bool) (string) Mage::getConfig()->getNode(
+ 'default/admin/security/extensions_compatibility_mode',
+ );
+ $configRouterFrontName = (string) Mage::getConfig()->getNode(
+ Mage_Adminhtml_Helper_Data::XML_PATH_ADMINHTML_ROUTER_FRONTNAME,
+ );
+ if ($isExtensionsCompatibilityMode || ($frontName == $configRouterFrontName)) {
+ return parent::addModule($frontName, $moduleName, $routeName);
+ } else {
+ return $this;
+ }
+ }
+
/**
* Get router default request path
* @return string
@@ -106,44 +144,6 @@ protected function _getCurrentSecureUrl($request)
->getBaseUrl('link', true) . ltrim($request->getPathInfo(), '/');
}
- /**
- * Emulate custom admin url
- *
- * @param string $configArea
- * @param bool $useRouterName
- */
- public function collectRoutes($configArea, $useRouterName)
- {
- if ((string) Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_USE_CUSTOM_ADMIN_PATH)) {
- $customUrl = (string) Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_CUSTOM_ADMIN_PATH);
- $xmlPath = Mage_Adminhtml_Helper_Data::XML_PATH_ADMINHTML_ROUTER_FRONTNAME;
- if ((string) Mage::getConfig()->getNode($xmlPath) != $customUrl) {
- Mage::getConfig()->setNode($xmlPath, $customUrl, true);
- }
- }
- parent::collectRoutes($configArea, $useRouterName);
- }
-
- /**
- * Add module definition to routes.
- *
- * @inheritDoc
- */
- public function addModule($frontName, $moduleName, $routeName)
- {
- $isExtensionsCompatibilityMode = (bool) (string) Mage::getConfig()->getNode(
- 'default/admin/security/extensions_compatibility_mode',
- );
- $configRouterFrontName = (string) Mage::getConfig()->getNode(
- Mage_Adminhtml_Helper_Data::XML_PATH_ADMINHTML_ROUTER_FRONTNAME,
- );
- if ($isExtensionsCompatibilityMode || ($frontName == $configRouterFrontName)) {
- return parent::addModule($frontName, $moduleName, $routeName);
- } else {
- return $this;
- }
- }
-
/**
* Check if current controller instance is allowed in current router.
*
diff --git a/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php b/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php
index 1eed35c0711..a438acfc12e 100644
--- a/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php
@@ -77,29 +77,6 @@ public function fetchDefault()
]);
}
- /**
- * checking if this admin if yes then we don't use this router
- *
- * @return bool
- */
- protected function _beforeModuleMatch()
- {
- if (Mage::app()->getStore()->isAdmin()) {
- return false;
- }
- return true;
- }
-
- /**
- * dummy call to pass through checking
- *
- * @return bool
- */
- protected function _afterModuleMatch()
- {
- return true;
- }
-
/**
* Match the request
*
@@ -258,100 +235,6 @@ public function match(Zend_Controller_Request_Http $request)
return true;
}
- /**
- * Get router default request path
- * @return string
- */
- protected function _getDefaultPath()
- {
- return Mage::getStoreConfig('web/default/front');
- }
-
- /**
- * Allow to control if we need to enable no route functionality in current router
- *
- * @return bool
- */
- protected function _noRouteShouldBeApplied()
- {
- return false;
- }
-
- /**
- * Check if current controller instance is allowed in current router.
- *
- * @param Mage_Core_Controller_Varien_Action $controllerInstance
- * @return bool
- */
- protected function _validateControllerInstance($controllerInstance)
- {
- return $controllerInstance instanceof Mage_Core_Controller_Front_Action;
- }
-
- /**
- * Generating and validating class file name,
- * class and if everything ok do include if needed and return of class name
- *
- * @param string $realModule
- * @param string $controller
- * @return false|string
- * @throws Mage_Core_Exception
- */
- protected function _validateControllerClassName($realModule, $controller)
- {
- $controllerFileName = $this->getControllerFileName($realModule, $controller);
- if (!$this->validateControllerFileName($controllerFileName)) {
- return false;
- }
-
- $controllerClassName = $this->getControllerClassName($realModule, $controller);
- if (!$controllerClassName) {
- return false;
- }
-
- // include controller file if needed
- if (!$this->_includeControllerClass($controllerFileName, $controllerClassName)) {
- return false;
- }
-
- return $controllerClassName;
- }
-
- /**
- * @param string $controllerFileName
- * @param string $controllerClassName
- * @return bool
- * @throws Mage_Core_Exception
- * @deprecated
- * @see _includeControllerClass()
- */
- protected function _inludeControllerClass($controllerFileName, $controllerClassName)
- {
- return $this->_includeControllerClass($controllerFileName, $controllerClassName);
- }
-
- /**
- * Include the file containing controller class if this class is not defined yet
- *
- * @param string $controllerFileName
- * @param string $controllerClassName
- * @return bool
- */
- protected function _includeControllerClass($controllerFileName, $controllerClassName)
- {
- if (!class_exists($controllerClassName, false)) {
- if (!file_exists($controllerFileName)) {
- return false;
- }
- include $controllerFileName;
-
- if (!class_exists($controllerClassName, false)) {
- throw Mage::exception('Mage_Core', Mage::helper('core')->__('Controller file was loaded but class does not exist'));
- }
- }
- return true;
- }
-
/**
* @param string $frontName
* @param array $moduleNames
@@ -472,6 +355,123 @@ public function rewrite(array $p)
return $p;
}
+ /**
+ * checking if this admin if yes then we don't use this router
+ *
+ * @return bool
+ */
+ protected function _beforeModuleMatch()
+ {
+ if (Mage::app()->getStore()->isAdmin()) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * dummy call to pass through checking
+ *
+ * @return bool
+ */
+ protected function _afterModuleMatch()
+ {
+ return true;
+ }
+
+ /**
+ * Get router default request path
+ * @return string
+ */
+ protected function _getDefaultPath()
+ {
+ return Mage::getStoreConfig('web/default/front');
+ }
+
+ /**
+ * Allow to control if we need to enable no route functionality in current router
+ *
+ * @return bool
+ */
+ protected function _noRouteShouldBeApplied()
+ {
+ return false;
+ }
+
+ /**
+ * Check if current controller instance is allowed in current router.
+ *
+ * @param Mage_Core_Controller_Varien_Action $controllerInstance
+ * @return bool
+ */
+ protected function _validateControllerInstance($controllerInstance)
+ {
+ return $controllerInstance instanceof Mage_Core_Controller_Front_Action;
+ }
+
+ /**
+ * Generating and validating class file name,
+ * class and if everything ok do include if needed and return of class name
+ *
+ * @param string $realModule
+ * @param string $controller
+ * @return false|string
+ * @throws Mage_Core_Exception
+ */
+ protected function _validateControllerClassName($realModule, $controller)
+ {
+ $controllerFileName = $this->getControllerFileName($realModule, $controller);
+ if (!$this->validateControllerFileName($controllerFileName)) {
+ return false;
+ }
+
+ $controllerClassName = $this->getControllerClassName($realModule, $controller);
+ if (!$controllerClassName) {
+ return false;
+ }
+
+ // include controller file if needed
+ if (!$this->_includeControllerClass($controllerFileName, $controllerClassName)) {
+ return false;
+ }
+
+ return $controllerClassName;
+ }
+
+ /**
+ * @param string $controllerFileName
+ * @param string $controllerClassName
+ * @return bool
+ * @throws Mage_Core_Exception
+ * @deprecated
+ * @see _includeControllerClass()
+ */
+ protected function _inludeControllerClass($controllerFileName, $controllerClassName)
+ {
+ return $this->_includeControllerClass($controllerFileName, $controllerClassName);
+ }
+
+ /**
+ * Include the file containing controller class if this class is not defined yet
+ *
+ * @param string $controllerFileName
+ * @param string $controllerClassName
+ * @return bool
+ */
+ protected function _includeControllerClass($controllerFileName, $controllerClassName)
+ {
+ if (!class_exists($controllerClassName, false)) {
+ if (!file_exists($controllerFileName)) {
+ return false;
+ }
+ include $controllerFileName;
+
+ if (!class_exists($controllerClassName, false)) {
+ throw Mage::exception('Mage_Core', Mage::helper('core')->__('Controller file was loaded but class does not exist'));
+ }
+ }
+ return true;
+ }
+
/**
* Check that request uses https protocol if it should.
* Function redirects user to correct URL if needed.
diff --git a/app/code/core/Mage/Core/Helper/Abstract.php b/app/code/core/Mage/Core/Helper/Abstract.php
index bf5bbc2f38a..2dea7283cbb 100644
--- a/app/code/core/Mage/Core/Helper/Abstract.php
+++ b/app/code/core/Mage/Core/Helper/Abstract.php
@@ -46,80 +46,18 @@ abstract class Mage_Core_Helper_Abstract
protected array $modulesDisabled = [];
/**
- * Retrieve request object
- *
- * @return Mage_Core_Controller_Request_Http
- */
- protected function _getRequest()
- {
- if (!$this->_request) {
- $this->_request = Mage::app()->getRequest();
- }
- return $this->_request;
- }
-
- /**
- * Loading cache data
- *
- * @param string $id
- * @return mixed
- */
- protected function _loadCache($id)
- {
- return Mage::app()->loadCache($id);
- }
-
- /**
- * Saving cache
- *
- * @param mixed $data
- * @param string $id
- * @param array $tags
- * @param null|false|int $lifeTime
- * @return Mage_Core_Helper_Abstract
- */
- protected function _saveCache($data, $id, $tags = [], $lifeTime = false)
- {
- Mage::app()->saveCache($data, $id, $tags, $lifeTime);
- return $this;
- }
-
- /**
- * Removing cache
- *
- * @param string $id
- * @return Mage_Core_Helper_Abstract
- */
- protected function _removeCache($id)
- {
- Mage::app()->removeCache($id);
- return $this;
- }
-
- /**
- * Cleaning cache
- *
- * @param array $tags
- * @return Mage_Core_Helper_Abstract
- */
- protected function _cleanCache($tags = [])
- {
- Mage::app()->cleanCache($tags);
- return $this;
- }
-
- /**
- * Retrieve helper module name
+ * Translate
*
* @return string
+ * @SuppressWarnings("PHPMD.CamelCaseMethodName")
+ * @SuppressWarnings("PHPMD.ShortMethodName")
*/
- protected function _getModuleName()
+ public function __()
{
- if (!$this->_moduleName) {
- $class = get_class($this);
- $this->_moduleName = implode('_', array_slice(explode('_', $class), 0, 2));
- }
- return $this->_moduleName;
+ $args = func_get_args();
+ $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getModuleName());
+ array_unshift($args, $expr);
+ return Mage::app()->getTranslator()->translate($args);
}
/**
@@ -168,21 +106,6 @@ public function isModuleEnabled($moduleName = null)
return $this->modulesDisabled[$moduleName] = true;
}
- /**
- * Translate
- *
- * @return string
- * @SuppressWarnings("PHPMD.CamelCaseMethodName")
- * @SuppressWarnings("PHPMD.ShortMethodName")
- */
- public function __()
- {
- $args = func_get_args();
- $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getModuleName());
- array_unshift($args, $expr);
- return Mage::app()->getTranslator()->translate($args);
- }
-
/**
* @param string|string[] $data
* @param array|null $allowedTags
@@ -362,18 +285,6 @@ public function quoteEscape($data, $addSlashes = false)
return htmlspecialchars($data, ENT_QUOTES, null, false);
}
- /**
- * Retrieve url
- *
- * @param string $route
- * @param array $params
- * @return string
- */
- protected function _getUrl($route, $params = [])
- {
- return Mage::getUrl($route, $params);
- }
-
/**
* Declare layout
*
@@ -488,4 +399,93 @@ public function hasTags($data, array $arrayKeys = [], $skipTags = true)
}
return false;
}
+
+ /**
+ * Retrieve request object
+ *
+ * @return Mage_Core_Controller_Request_Http
+ */
+ protected function _getRequest()
+ {
+ if (!$this->_request) {
+ $this->_request = Mage::app()->getRequest();
+ }
+ return $this->_request;
+ }
+
+ /**
+ * Loading cache data
+ *
+ * @param string $id
+ * @return mixed
+ */
+ protected function _loadCache($id)
+ {
+ return Mage::app()->loadCache($id);
+ }
+
+ /**
+ * Saving cache
+ *
+ * @param mixed $data
+ * @param string $id
+ * @param array $tags
+ * @param null|false|int $lifeTime
+ * @return Mage_Core_Helper_Abstract
+ */
+ protected function _saveCache($data, $id, $tags = [], $lifeTime = false)
+ {
+ Mage::app()->saveCache($data, $id, $tags, $lifeTime);
+ return $this;
+ }
+
+ /**
+ * Removing cache
+ *
+ * @param string $id
+ * @return Mage_Core_Helper_Abstract
+ */
+ protected function _removeCache($id)
+ {
+ Mage::app()->removeCache($id);
+ return $this;
+ }
+
+ /**
+ * Cleaning cache
+ *
+ * @param array $tags
+ * @return Mage_Core_Helper_Abstract
+ */
+ protected function _cleanCache($tags = [])
+ {
+ Mage::app()->cleanCache($tags);
+ return $this;
+ }
+
+ /**
+ * Retrieve helper module name
+ *
+ * @return string
+ */
+ protected function _getModuleName()
+ {
+ if (!$this->_moduleName) {
+ $class = get_class($this);
+ $this->_moduleName = implode('_', array_slice(explode('_', $class), 0, 2));
+ }
+ return $this->_moduleName;
+ }
+
+ /**
+ * Retrieve url
+ *
+ * @param string $route
+ * @param array $params
+ * @return string
+ */
+ protected function _getUrl($route, $params = [])
+ {
+ return Mage::getUrl($route, $params);
+ }
}
diff --git a/app/code/core/Mage/Core/Helper/Cookie.php b/app/code/core/Mage/Core/Helper/Cookie.php
index 032811714aa..33e91c03c20 100644
--- a/app/code/core/Mage/Core/Helper/Cookie.php
+++ b/app/code/core/Mage/Core/Helper/Cookie.php
@@ -115,18 +115,6 @@ public function getAcceptedSaveCookiesWebsiteIds()
return json_encode($acceptedSaveCookiesWebsites);
}
- /**
- * Get accepted save cookies websites
- *
- * @return array
- */
- protected function _getAcceptedSaveCookiesWebsites()
- {
- $serializedList = $this->_cookieModel->get(self::IS_USER_ALLOWED_SAVE_COOKIE);
- $unSerializedList = $serializedList ? json_decode($serializedList, true) : null;
- return is_array($unSerializedList) ? $unSerializedList : [];
- }
-
/**
* Get cookie restriction lifetime (in seconds)
*
@@ -146,4 +134,16 @@ public function getCookieRestrictionNoticeCmsBlockIdentifier()
{
return self::COOKIE_RESTRICTION_NOTICE_CMS_BLOCK_IDENTIFIER;
}
+
+ /**
+ * Get accepted save cookies websites
+ *
+ * @return array
+ */
+ protected function _getAcceptedSaveCookiesWebsites()
+ {
+ $serializedList = $this->_cookieModel->get(self::IS_USER_ALLOWED_SAVE_COOKIE);
+ $unSerializedList = $serializedList ? json_decode($serializedList, true) : null;
+ return is_array($unSerializedList) ? $unSerializedList : [];
+ }
}
diff --git a/app/code/core/Mage/Core/Helper/Data.php b/app/code/core/Mage/Core/Helper/Data.php
index 695521a2dfb..fc8be83e1e4 100644
--- a/app/code/core/Mage/Core/Helper/Data.php
+++ b/app/code/core/Mage/Core/Helper/Data.php
@@ -582,24 +582,6 @@ public function decorateArray($array, $prefix = 'decorated_', $forceSetAll = fal
return $array;
}
- /**
- * @param Varien_Object $element
- * @param string $key
- * @param mixed $value
- * @param bool $dontSkip
- */
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private function _decorateArrayObject($element, $key, $value, $dontSkip)
- {
- if ($dontSkip) {
- if ($element instanceof Varien_Object) {
- $element->setData($key, $value);
- } else {
- $element->$key = $value;
- }
- }
- }
-
/**
* Transform an assoc array to SimpleXMLElement object
* Array has some limitations. Appropriate exceptions will be thrown
@@ -627,40 +609,6 @@ public function assocToXml(array $array, $rootName = '_')
return self::_assocToXml($array, $rootName, $xml);
}
- /**
- * Function, that actually recursively transforms array to xml
- *
- * @param string $rootName
- * @return SimpleXMLElement
- * @throws Exception
- */
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private function _assocToXml(array $array, $rootName, SimpleXMLElement &$xml)
- {
- $hasNumericKey = false;
- $hasStringKey = false;
- foreach ($array as $key => $value) {
- if (!is_array($value)) {
- if (is_string($key)) {
- if ($key === $rootName) {
- throw new Exception('Associative key must not be the same as its parent associative key.');
- }
- $hasStringKey = true;
- $xml->$key = $value;
- } elseif (is_int($key)) {
- $hasNumericKey = true;
- $xml->{$rootName}[$key] = $value;
- }
- } else {
- self::_assocToXml($value, $key, $xml->$key);
- }
- }
- if ($hasNumericKey && $hasStringKey) {
- throw new Exception('Associative and numeric keys must not be mixed at one level.');
- }
- return $xml;
- }
-
/**
* Transform SimpleXMLElement to associative array
* SimpleXMLElement must be conform structure, generated by assocToXml()
@@ -1050,4 +998,56 @@ public function recordRateLimitHit(): void
Mage::app()->saveCache(1, $cacheTag, ['brute_force'], Mage::getStoreConfig('system/rate_limit/timeframe'));
}
}
+
+ /**
+ * @param Varien_Object $element
+ * @param string $key
+ * @param mixed $value
+ * @param bool $dontSkip
+ */
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private function _decorateArrayObject($element, $key, $value, $dontSkip)
+ {
+ if ($dontSkip) {
+ if ($element instanceof Varien_Object) {
+ $element->setData($key, $value);
+ } else {
+ $element->$key = $value;
+ }
+ }
+ }
+
+ /**
+ * Function, that actually recursively transforms array to xml
+ *
+ * @param string $rootName
+ * @return SimpleXMLElement
+ * @throws Exception
+ */
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private function _assocToXml(array $array, $rootName, SimpleXMLElement &$xml)
+ {
+ $hasNumericKey = false;
+ $hasStringKey = false;
+ foreach ($array as $key => $value) {
+ if (!is_array($value)) {
+ if (is_string($key)) {
+ if ($key === $rootName) {
+ throw new Exception('Associative key must not be the same as its parent associative key.');
+ }
+ $hasStringKey = true;
+ $xml->$key = $value;
+ } elseif (is_int($key)) {
+ $hasNumericKey = true;
+ $xml->{$rootName}[$key] = $value;
+ }
+ } else {
+ self::_assocToXml($value, $key, $xml->$key);
+ }
+ }
+ if ($hasNumericKey && $hasStringKey) {
+ throw new Exception('Associative and numeric keys must not be mixed at one level.');
+ }
+ return $xml;
+ }
}
diff --git a/app/code/core/Mage/Core/Helper/File/Storage/Database.php b/app/code/core/Mage/Core/Helper/File/Storage/Database.php
index d39d095e23c..ae3bb91c66d 100644
--- a/app/code/core/Mage/Core/Helper/File/Storage/Database.php
+++ b/app/code/core/Mage/Core/Helper/File/Storage/Database.php
@@ -276,27 +276,27 @@ public function saveUploadedFile($result = [])
}
/**
- * Convert full file path to local (as used by model)
- * If not - returns just a filename
+ * Return Media base dir
*
- * @param string $filename
* @return string
*/
- protected function _removeAbsPathFromFileName($filename)
+ public function getMediaBaseDir()
{
- return $this->getMediaRelativePath($filename);
+ if ($this->_mediaBaseDirectory === null) {
+ $this->_mediaBaseDirectory = rtrim(Mage::getBaseDir('media'), '\\/');
+ }
+ return $this->_mediaBaseDirectory;
}
/**
- * Return Media base dir
+ * Convert full file path to local (as used by model)
+ * If not - returns just a filename
*
+ * @param string $filename
* @return string
*/
- public function getMediaBaseDir()
+ protected function _removeAbsPathFromFileName($filename)
{
- if ($this->_mediaBaseDirectory === null) {
- $this->_mediaBaseDirectory = rtrim(Mage::getBaseDir('media'), '\\/');
- }
- return $this->_mediaBaseDirectory;
+ return $this->getMediaRelativePath($filename);
}
}
diff --git a/app/code/core/Mage/Core/Helper/Http.php b/app/code/core/Mage/Core/Helper/Http.php
index ab5e0fb002f..f05f7eae8cb 100644
--- a/app/code/core/Mage/Core/Helper/Http.php
+++ b/app/code/core/Mage/Core/Helper/Http.php
@@ -161,23 +161,6 @@ public function getServerAddr($ipToLong = false)
return $ipToLong ? inet_pton($address) : $address;
}
- /**
- * Retrieve HTTP "clean" value
- *
- * @param string $var
- * @param bool $clean clean non UTF-8 characters
- * @return string
- */
- protected function _getHttpCleanValue($var, $clean = true)
- {
- $value = $this->_getRequest()->getServer($var, '');
- if ($clean) {
- $value = Mage::helper('core/string')->cleanString($value);
- }
-
- return $value;
- }
-
/**
* Retrieve HTTP HOST
*
@@ -259,4 +242,21 @@ public function validateIpAddr($address)
{
return preg_match('#^(1?\d{1,2}|2([0-4]\d|5[0-5]))(\.(1?\d{1,2}|2([0-4]\d|5[0-5]))){3}$#', $address);
}
+
+ /**
+ * Retrieve HTTP "clean" value
+ *
+ * @param string $var
+ * @param bool $clean clean non UTF-8 characters
+ * @return string
+ */
+ protected function _getHttpCleanValue($var, $clean = true)
+ {
+ $value = $this->_getRequest()->getServer($var, '');
+ if ($clean) {
+ $value = Mage::helper('core/string')->cleanString($value);
+ }
+
+ return $value;
+ }
}
diff --git a/app/code/core/Mage/Core/Helper/Js.php b/app/code/core/Mage/Core/Helper/Js.php
index e60ddbb70cf..ea9376c18e0 100644
--- a/app/code/core/Mage/Core/Helper/Js.php
+++ b/app/code/core/Mage/Core/Helper/Js.php
@@ -126,6 +126,54 @@ public function getJsSkinUrl($file)
return Mage::getDesign()->getSkinUrl($file, []);
}
+ /**
+ * Helper for "onclick.deleteConfirm"
+ *
+ * @param string|null $message null for default message, do not use jsQuoteEscape() before
+ * @uses Mage_Core_Helper_Abstract::jsQuoteEscape()
+ */
+ public function getDeleteConfirmJs(string $url, ?string $message = null): string
+ {
+ if (is_null($message)) {
+ $message = Mage::helper('adminhtml')->__('Are you sure you want to do this?');
+ }
+
+ $message = Mage::helper('core')->jsQuoteEscape($message);
+ return 'deleteConfirm(\'' . $message . '\', \'' . $url . '\')';
+ }
+
+ /**
+ * Helper for "onclick.confirmSetLocation"
+ *
+ * @param string|null $message null for default message, do not use jsQuoteEscape() before
+ * @uses Mage_Core_Helper_Abstract::jsQuoteEscape()
+ */
+ public function getConfirmSetLocationJs(string $url, ?string $message = null): string
+ {
+ if (is_null($message)) {
+ $message = Mage::helper('adminhtml')->__('Are you sure you want to do this?');
+ }
+
+ $message = Mage::helper('core')->jsQuoteEscape($message);
+ return "confirmSetLocation('{$message}', '{$url}')";
+ }
+
+ /**
+ * Helper for "onclick.setLocation"
+ */
+ public function getSetLocationJs(string $url): string
+ {
+ return 'setLocation(\'' . $url . '\')';
+ }
+
+ /**
+ * Helper for "onclick.saveAndContinueEdit"
+ */
+ public function getSaveAndContinueEditJs(string $url): string
+ {
+ return 'saveAndContinueEdit(\'' . $url . '\')';
+ }
+
/**
* Retrieve JS translation array
*
@@ -182,52 +230,4 @@ protected function _getXmlConfig()
}
return $this->_config;
}
-
- /**
- * Helper for "onclick.deleteConfirm"
- *
- * @param string|null $message null for default message, do not use jsQuoteEscape() before
- * @uses Mage_Core_Helper_Abstract::jsQuoteEscape()
- */
- public function getDeleteConfirmJs(string $url, ?string $message = null): string
- {
- if (is_null($message)) {
- $message = Mage::helper('adminhtml')->__('Are you sure you want to do this?');
- }
-
- $message = Mage::helper('core')->jsQuoteEscape($message);
- return 'deleteConfirm(\'' . $message . '\', \'' . $url . '\')';
- }
-
- /**
- * Helper for "onclick.confirmSetLocation"
- *
- * @param string|null $message null for default message, do not use jsQuoteEscape() before
- * @uses Mage_Core_Helper_Abstract::jsQuoteEscape()
- */
- public function getConfirmSetLocationJs(string $url, ?string $message = null): string
- {
- if (is_null($message)) {
- $message = Mage::helper('adminhtml')->__('Are you sure you want to do this?');
- }
-
- $message = Mage::helper('core')->jsQuoteEscape($message);
- return "confirmSetLocation('{$message}', '{$url}')";
- }
-
- /**
- * Helper for "onclick.setLocation"
- */
- public function getSetLocationJs(string $url): string
- {
- return 'setLocation(\'' . $url . '\')';
- }
-
- /**
- * Helper for "onclick.saveAndContinueEdit"
- */
- public function getSaveAndContinueEditJs(string $url): string
- {
- return 'saveAndContinueEdit(\'' . $url . '\')';
- }
}
diff --git a/app/code/core/Mage/Core/Helper/String.php b/app/code/core/Mage/Core/Helper/String.php
index ef23fe93223..4d23fb6dcba 100644
--- a/app/code/core/Mage/Core/Helper/String.php
+++ b/app/code/core/Mage/Core/Helper/String.php
@@ -343,6 +343,115 @@ public function parseQueryStr($str)
return $result;
}
+ /**
+ * Set array helper
+ *
+ * @param Mage_Core_Helper_Array $helper
+ * @return $this
+ */
+ public function setArrayHelper(Mage_Core_Helper_Abstract $helper)
+ {
+ $this->_arrayHelper = $helper;
+ return $this;
+ }
+
+ /**
+ * Get Array Helper
+ *
+ * @return Mage_Core_Helper_Array
+ */
+ public function getArrayHelper()
+ {
+ if (!$this->_arrayHelper) {
+ $this->_arrayHelper = Mage::helper('core/array');
+ }
+ return $this->_arrayHelper;
+ }
+
+ /**
+ * Unicode compatible ord() method
+ *
+ * @param string $c char to get value from
+ * @return int
+ */
+ public function uniOrd($c)
+ {
+ $ord = 0;
+ $h = ord($c[0]);
+
+ if ($h <= 0x7F) {
+ $ord = $h;
+ } elseif ($h < 0xC2) {
+ $ord = 0;
+ } elseif ($h <= 0xDF) {
+ $ord = (($h & 0x1F) << 6 | (ord($c[1]) & 0x3F));
+ } elseif ($h <= 0xEF) {
+ $ord = (($h & 0x0F) << 12 | (ord($c[1]) & 0x3F) << 6 | (ord($c[2]) & 0x3F));
+ } elseif ($h <= 0xF4) {
+ $ord = (($h & 0x0F) << 18 | (ord($c[1]) & 0x3F) << 12 |
+ (ord($c[2]) & 0x3F) << 6 | (ord($c[3]) & 0x3F));
+ }
+
+ return $ord;
+ }
+
+ /**
+ * UnSerialize string
+ * @param string|null $str
+ * @return null|void
+ * @throws Exception
+ */
+ public function unserialize($str)
+ {
+ if (is_null($str)) {
+ return null;
+ }
+ $reader = new Unserialize_Reader_ArrValue('data');
+ $prevChar = null;
+
+ $strLen = strlen($str);
+ for ($i = 0; $i < $strLen; $i++) {
+ $char = $str[$i];
+ $result = $reader->read($char, $prevChar);
+ if (!is_null($result)) {
+ return $result;
+ }
+ $prevChar = $char;
+ }
+ }
+
+ /**
+ * Detect serialization of data Array or Object
+ *
+ * @param mixed $data
+ * @return bool
+ */
+ public function isSerializedArrayOrObject($data)
+ {
+ $pattern =
+ '/^a:\d+:\{(i:\d+;|s:\d+:\".+\";|N;|O:\d+:\"\w+\":\d+:\{\w:\d+:)+|^O:\d+:\"\w+\":\d+:\{(s:\d+:\"|i:\d+;)/';
+ return is_string($data) && preg_match($pattern, $data);
+ }
+
+ /**
+ * Validate is Serialized Data Object in string
+ *
+ * @param string $str
+ * @return bool
+ */
+ public function validateSerializedObject($str)
+ {
+ if ($this->isSerializedArrayOrObject($str)) {
+ try {
+ $this->unserialize($str);
+ } catch (Exception $e) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
/**
* Validate query pair string
*
@@ -460,113 +569,4 @@ protected function _getLastSubkey($key, $withBrackets = true)
}
return $subKey;
}
-
- /**
- * Set array helper
- *
- * @param Mage_Core_Helper_Array $helper
- * @return $this
- */
- public function setArrayHelper(Mage_Core_Helper_Abstract $helper)
- {
- $this->_arrayHelper = $helper;
- return $this;
- }
-
- /**
- * Get Array Helper
- *
- * @return Mage_Core_Helper_Array
- */
- public function getArrayHelper()
- {
- if (!$this->_arrayHelper) {
- $this->_arrayHelper = Mage::helper('core/array');
- }
- return $this->_arrayHelper;
- }
-
- /**
- * Unicode compatible ord() method
- *
- * @param string $c char to get value from
- * @return int
- */
- public function uniOrd($c)
- {
- $ord = 0;
- $h = ord($c[0]);
-
- if ($h <= 0x7F) {
- $ord = $h;
- } elseif ($h < 0xC2) {
- $ord = 0;
- } elseif ($h <= 0xDF) {
- $ord = (($h & 0x1F) << 6 | (ord($c[1]) & 0x3F));
- } elseif ($h <= 0xEF) {
- $ord = (($h & 0x0F) << 12 | (ord($c[1]) & 0x3F) << 6 | (ord($c[2]) & 0x3F));
- } elseif ($h <= 0xF4) {
- $ord = (($h & 0x0F) << 18 | (ord($c[1]) & 0x3F) << 12 |
- (ord($c[2]) & 0x3F) << 6 | (ord($c[3]) & 0x3F));
- }
-
- return $ord;
- }
-
- /**
- * UnSerialize string
- * @param string|null $str
- * @return null|void
- * @throws Exception
- */
- public function unserialize($str)
- {
- if (is_null($str)) {
- return null;
- }
- $reader = new Unserialize_Reader_ArrValue('data');
- $prevChar = null;
-
- $strLen = strlen($str);
- for ($i = 0; $i < $strLen; $i++) {
- $char = $str[$i];
- $result = $reader->read($char, $prevChar);
- if (!is_null($result)) {
- return $result;
- }
- $prevChar = $char;
- }
- }
-
- /**
- * Detect serialization of data Array or Object
- *
- * @param mixed $data
- * @return bool
- */
- public function isSerializedArrayOrObject($data)
- {
- $pattern =
- '/^a:\d+:\{(i:\d+;|s:\d+:\".+\";|N;|O:\d+:\"\w+\":\d+:\{\w:\d+:)+|^O:\d+:\"\w+\":\d+:\{(s:\d+:\"|i:\d+;)/';
- return is_string($data) && preg_match($pattern, $data);
- }
-
- /**
- * Validate is Serialized Data Object in string
- *
- * @param string $str
- * @return bool
- */
- public function validateSerializedObject($str)
- {
- if ($this->isSerializedArrayOrObject($str)) {
- try {
- $this->unserialize($str);
- } catch (Exception $e) {
- return false;
- }
- }
-
- return true;
- }
}
diff --git a/app/code/core/Mage/Core/Helper/Url.php b/app/code/core/Mage/Core/Helper/Url.php
index 143c31dbef8..5e33382be69 100644
--- a/app/code/core/Mage/Core/Helper/Url.php
+++ b/app/code/core/Mage/Core/Helper/Url.php
@@ -78,20 +78,6 @@ public function getHomeUrl()
return Mage::getBaseUrl();
}
- /**
- * Formatting string
- *
- * @param string $string
- * @return string
- */
- protected function _prepareString($string)
- {
- $string = preg_replace('#[^0-9a-z]+#i', '-', $string);
- $string = strtolower($string);
-
- return trim($string, '-');
- }
-
/**
* Add request parameter into url
*
@@ -154,18 +140,6 @@ public function removeRequestParam($url, $paramKey, $caseSensitive = false)
return $baseUrl . ($params === [] ? '' : '?' . http_build_query($params));
}
- /**
- * Return singleton model instance
- *
- * @param string $name
- * @param array $arguments
- * @return Mage_Core_Model_Abstract
- */
- protected function _getSingletonModel($name, $arguments = [])
- {
- return Mage::getSingleton($name, $arguments);
- }
-
/**
* Retrieve encoding domain name in punycode
*
@@ -201,6 +175,32 @@ public function decodePunycode($url)
return $url;
}
+ /**
+ * Formatting string
+ *
+ * @param string $string
+ * @return string
+ */
+ protected function _prepareString($string)
+ {
+ $string = preg_replace('#[^0-9a-z]+#i', '-', $string);
+ $string = strtolower($string);
+
+ return trim($string, '-');
+ }
+
+ /**
+ * Return singleton model instance
+ *
+ * @param string $name
+ * @param array $arguments
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _getSingletonModel($name, $arguments = [])
+ {
+ return Mage::getSingleton($name, $arguments);
+ }
+
/**
* Check domain name for IDN using ACE prefix http://tools.ietf.org/html/rfc3490#section-5
*
diff --git a/app/code/core/Mage/Core/Helper/Url/Rewrite.php b/app/code/core/Mage/Core/Helper/Url/Rewrite.php
index 8206b32e775..54495ce7fe0 100644
--- a/app/code/core/Mage/Core/Helper/Url/Rewrite.php
+++ b/app/code/core/Mage/Core/Helper/Url/Rewrite.php
@@ -35,37 +35,6 @@ class Mage_Core_Helper_Url_Rewrite extends Mage_Core_Helper_Abstract
protected $_moduleName = 'Mage_Core';
- /**
- * Core func to validate request path
- * If something is wrong with a path it throws localized error message and error code,
- * that can be checked to by wrapper func to alternate error message
- *
- * @throws Mage_Core_Exception
- * @param string $requestPath
- * @return bool
- */
- protected function _validateRequestPath($requestPath)
- {
- if (strlen($requestPath) > self::TARGET_PATH_ALLOWED_LENGTH) {
- throw new Mage_Core_Exception(
- $this->__('Request path length exceeds allowed %s symbols.', self::TARGET_PATH_ALLOWED_LENGTH),
- );
- }
- if (str_contains($requestPath, '//')) {
- throw new Mage_Core_Exception(
- $this->__('Two and more slashes together are not permitted in request path'),
- self::VERR_MANYSLASHES,
- );
- }
- if (strpos($requestPath, '#') !== false) {
- throw new Mage_Core_Exception(
- $this->__('Anchor symbol (#) is not supported in request path'),
- self::VERR_ANCHOR,
- );
- }
- return true;
- }
-
/**
* Validates request path
* Either returns TRUE (success) or throws error (validation failed)
@@ -103,4 +72,35 @@ public function validateSuffix($suffix)
}
return true;
}
+
+ /**
+ * Core func to validate request path
+ * If something is wrong with a path it throws localized error message and error code,
+ * that can be checked to by wrapper func to alternate error message
+ *
+ * @throws Mage_Core_Exception
+ * @param string $requestPath
+ * @return bool
+ */
+ protected function _validateRequestPath($requestPath)
+ {
+ if (strlen($requestPath) > self::TARGET_PATH_ALLOWED_LENGTH) {
+ throw new Mage_Core_Exception(
+ $this->__('Request path length exceeds allowed %s symbols.', self::TARGET_PATH_ALLOWED_LENGTH),
+ );
+ }
+ if (str_contains($requestPath, '//')) {
+ throw new Mage_Core_Exception(
+ $this->__('Two and more slashes together are not permitted in request path'),
+ self::VERR_MANYSLASHES,
+ );
+ }
+ if (strpos($requestPath, '#') !== false) {
+ throw new Mage_Core_Exception(
+ $this->__('Anchor symbol (#) is not supported in request path'),
+ self::VERR_ANCHOR,
+ );
+ }
+ return true;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Abstract.php b/app/code/core/Mage/Core/Model/Abstract.php
index 208eb1aa091..f89d1fa51fa 100644
--- a/app/code/core/Mage/Core/Model/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Abstract.php
@@ -99,16 +99,6 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
*/
protected $_isObjectNew = null;
- /**
- * Standard model initialization
- *
- * @param string $resourceModel
- */
- protected function _init($resourceModel)
- {
- $this->_setResourceModel($resourceModel);
- }
-
/**
* Get object loaded data (original data)
*
@@ -154,42 +144,6 @@ public function dataHasChangedFor($field)
return $newData != $origData;
}
- /**
- * Set resource names
- *
- * If collection name is omitted, resource name will be used with _collection appended
- *
- * @param string $resourceName
- * @param string|null $resourceCollectionName
- */
- protected function _setResourceModel($resourceName, $resourceCollectionName = null)
- {
- $this->_resourceName = $resourceName;
- if (is_null($resourceCollectionName)) {
- $resourceCollectionName = $resourceName . '_collection';
- }
- $this->_resourceCollectionName = $resourceCollectionName;
- }
-
- /**
- * Get resource instance
- *
- * @return Mage_Core_Model_Resource_Db_Abstract|object
- */
- protected function _getResource()
- {
- if (empty($this->_resourceName)) {
- Mage::throwException(Mage::helper('core')->__('Resource is not set.'));
- }
-
- $resource = Mage::getResourceSingleton($this->_resourceName);
- if (!$resource) {
- Mage::throwException(Mage::helper('core')->__('Resource "%s" is not found.', $this->_resourceName));
- }
-
- return $resource;
- }
-
/**
* Retrieve identifier field name for model
*
@@ -290,47 +244,6 @@ public function load($id, $field = null)
return $this;
}
- /**
- * Get array of objects transferred to default events processing
- *
- * @return array
- */
- protected function _getEventData()
- {
- return [
- 'data_object' => $this,
- $this->_eventObject => $this,
- ];
- }
-
- /**
- * Processing object before load data
- *
- * @param int $id
- * @param string|null $field
- * @return $this
- */
- protected function _beforeLoad($id, $field = null)
- {
- $params = ['object' => $this, 'field' => $field, 'value' => $id];
- Mage::dispatchEvent('model_load_before', $params);
- $params = array_merge($params, $this->_getEventData());
- Mage::dispatchEvent($this->_eventPrefix . '_load_before', $params);
- return $this;
- }
-
- /**
- * Processing object after load data
- *
- * @return $this
- */
- protected function _afterLoad()
- {
- Mage::dispatchEvent('model_load_after', ['object' => $this]);
- Mage::dispatchEvent($this->_eventPrefix . '_load_after', $this->_getEventData());
- return $this;
- }
-
/**
* Object after load processing. Implemented as public interface for supporting objects after load in collections
*
@@ -343,18 +256,6 @@ public function afterLoad()
return $this;
}
- /**
- * Check whether model has changed data.
- * Can be overloaded in child classes to perform advanced check whether model needs to be saved
- * e.g. using resourceModel->hasDataChanged() or any other technique
- *
- * @return bool
- */
- protected function _hasModelChanged()
- {
- return $this->hasDataChanges();
- }
-
/**
* Save object data
*
@@ -422,21 +323,6 @@ public function isObjectNew($flag = null)
return $this->_isObjectNew ?? !(bool) $this->getId();
}
- /**
- * Processing object before save data
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- if (!$this->getId()) {
- $this->isObjectNew(true);
- }
- Mage::dispatchEvent('model_save_before', ['object' => $this]);
- Mage::dispatchEvent($this->_eventPrefix . '_save_before', $this->_getEventData());
- return $this;
- }
-
/**
* Get list of cache tags applied to model object.
* Return false if cache tags are not supported by model
@@ -499,18 +385,6 @@ public function cleanModelCache()
return $this;
}
- /**
- * Processing object after save data
- *
- * @return $this
- */
- protected function _afterSave()
- {
- Mage::dispatchEvent('model_save_after', ['object' => $this]);
- Mage::dispatchEvent($this->_eventPrefix . '_save_after', $this->_getEventData());
- return $this;
- }
-
/**
* Delete object from database
*
@@ -534,6 +408,168 @@ public function delete()
return $this;
}
+ /**
+ * Retrieve model resource
+ *
+ * @return Mage_Core_Model_Resource_Db_Abstract
+ */
+ public function getResource()
+ {
+ return $this->_getResource();
+ }
+
+ /**
+ * @return int
+ */
+ public function getEntityId()
+ {
+ return $this->_getData('entity_id');
+ }
+
+ /**
+ * Clearing object for correct deleting by garbage collector
+ *
+ * @return $this
+ */
+ final public function clearInstance()
+ {
+ $this->_clearReferences();
+ Mage::dispatchEvent($this->_eventPrefix . '_clear', $this->_getEventData());
+ $this->_clearData();
+ return $this;
+ }
+
+ public function isModuleEnabled(string $moduleName, string $helperAlias = 'core'): bool
+ {
+ return Mage::helper($helperAlias)->isModuleEnabled($moduleName);
+ }
+
+ /**
+ * Standard model initialization
+ *
+ * @param string $resourceModel
+ */
+ protected function _init($resourceModel)
+ {
+ $this->_setResourceModel($resourceModel);
+ }
+
+ /**
+ * Set resource names
+ *
+ * If collection name is omitted, resource name will be used with _collection appended
+ *
+ * @param string $resourceName
+ * @param string|null $resourceCollectionName
+ */
+ protected function _setResourceModel($resourceName, $resourceCollectionName = null)
+ {
+ $this->_resourceName = $resourceName;
+ if (is_null($resourceCollectionName)) {
+ $resourceCollectionName = $resourceName . '_collection';
+ }
+ $this->_resourceCollectionName = $resourceCollectionName;
+ }
+
+ /**
+ * Get resource instance
+ *
+ * @return Mage_Core_Model_Resource_Db_Abstract|object
+ */
+ protected function _getResource()
+ {
+ if (empty($this->_resourceName)) {
+ Mage::throwException(Mage::helper('core')->__('Resource is not set.'));
+ }
+
+ $resource = Mage::getResourceSingleton($this->_resourceName);
+ if (!$resource) {
+ Mage::throwException(Mage::helper('core')->__('Resource "%s" is not found.', $this->_resourceName));
+ }
+
+ return $resource;
+ }
+
+ /**
+ * Get array of objects transferred to default events processing
+ *
+ * @return array
+ */
+ protected function _getEventData()
+ {
+ return [
+ 'data_object' => $this,
+ $this->_eventObject => $this,
+ ];
+ }
+
+ /**
+ * Processing object before load data
+ *
+ * @param int $id
+ * @param string|null $field
+ * @return $this
+ */
+ protected function _beforeLoad($id, $field = null)
+ {
+ $params = ['object' => $this, 'field' => $field, 'value' => $id];
+ Mage::dispatchEvent('model_load_before', $params);
+ $params = array_merge($params, $this->_getEventData());
+ Mage::dispatchEvent($this->_eventPrefix . '_load_before', $params);
+ return $this;
+ }
+
+ /**
+ * Processing object after load data
+ *
+ * @return $this
+ */
+ protected function _afterLoad()
+ {
+ Mage::dispatchEvent('model_load_after', ['object' => $this]);
+ Mage::dispatchEvent($this->_eventPrefix . '_load_after', $this->_getEventData());
+ return $this;
+ }
+
+ /**
+ * Check whether model has changed data.
+ * Can be overloaded in child classes to perform advanced check whether model needs to be saved
+ * e.g. using resourceModel->hasDataChanged() or any other technique
+ *
+ * @return bool
+ */
+ protected function _hasModelChanged()
+ {
+ return $this->hasDataChanges();
+ }
+
+ /**
+ * Processing object before save data
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ if (!$this->getId()) {
+ $this->isObjectNew(true);
+ }
+ Mage::dispatchEvent('model_save_before', ['object' => $this]);
+ Mage::dispatchEvent($this->_eventPrefix . '_save_before', $this->_getEventData());
+ return $this;
+ }
+
+ /**
+ * Processing object after save data
+ *
+ * @return $this
+ */
+ protected function _afterSave()
+ {
+ Mage::dispatchEvent('model_save_after', ['object' => $this]);
+ Mage::dispatchEvent($this->_eventPrefix . '_save_after', $this->_getEventData());
+ return $this;
+ }
+
/**
* Processing object before delete data
*
@@ -586,37 +622,6 @@ protected function _afterDeleteCommit()
return $this;
}
- /**
- * Retrieve model resource
- *
- * @return Mage_Core_Model_Resource_Db_Abstract
- */
- public function getResource()
- {
- return $this->_getResource();
- }
-
- /**
- * @return int
- */
- public function getEntityId()
- {
- return $this->_getData('entity_id');
- }
-
- /**
- * Clearing object for correct deleting by garbage collector
- *
- * @return $this
- */
- final public function clearInstance()
- {
- $this->_clearReferences();
- Mage::dispatchEvent($this->_eventPrefix . '_clear', $this->_getEventData());
- $this->_clearData();
- return $this;
- }
-
/**
* Clearing cyclic references
*
@@ -636,9 +641,4 @@ protected function _clearData()
{
return $this;
}
-
- public function isModuleEnabled(string $moduleName, string $helperAlias = 'core'): bool
- {
- return Mage::helper($helperAlias)->isModuleEnabled($moduleName);
- }
}
diff --git a/app/code/core/Mage/Core/Model/App.php b/app/code/core/Mage/Core/Model/App.php
index 3063d14f296..cca0e3c5f7e 100644
--- a/app/code/core/Mage/Core/Model/App.php
+++ b/app/code/core/Mage/Core/Model/App.php
@@ -377,892 +377,512 @@ public function run($params)
}
/**
- * Initialize PHP environment
+ * Retrieve cookie object
*
- * @return $this
+ * @return Mage_Core_Model_Cookie
*/
- protected function _initEnvironment()
+ public function getCookie()
{
- $this->setErrorHandler(self::DEFAULT_ERROR_HANDLER);
- date_default_timezone_set(Mage_Core_Model_Locale::DEFAULT_TIMEZONE);
- return $this;
+ return Mage::getSingleton('core/cookie');
}
- /**
- * Initialize base system configuration (local.xml and config.xml files).
- * Base configuration provide ability initialize DB connection and cache backend
- *
- * @return $this
- */
- protected function _initBaseConfig()
+ public function reinitStores()
{
- Varien_Profiler::start('mage::app::init::system_config');
- $this->_config->loadBase();
- Varien_Profiler::stop('mage::app::init::system_config');
- return $this;
+ $this->_initStores();
}
/**
- * Initialize application cache instance
+ * Is single Store mode (only one store without default)
*
- * @return $this
+ * @return bool
*/
- protected function _initCache(array $cacheInitOptions = [])
+ public function isSingleStoreMode()
{
- $this->_isCacheLocked = true;
- $options = $this->_config->getNode('global/cache');
- if ($options) {
- $options = $options->asArray();
- } else {
- $options = [];
+ if ($this->_isInstalled === null) {
+ $this->_isInstalled = Mage::isInstalled();
}
- $options = array_merge($options, $cacheInitOptions);
- $this->_cache = Mage::getModel('core/cache', $options);
- $this->_isCacheLocked = false;
- return $this;
+
+ if (!$this->_isInstalled) {
+ return false;
+ }
+ return $this->_isSingleStore;
}
/**
- * Initialize active modules configuration and data
+ * Set current default store
*
+ * @param null|string|bool|int|Mage_Core_Model_Store $store
* @return $this
*/
- protected function _initModules()
+ public function setCurrentStore($store)
{
- if (!$this->_config->loadModulesCache()) {
- try {
- $this->_config->getCacheSaveLock();
- if (!$this->_config->loadModulesCache()) {
- $this->_config->loadModules();
- if ($this->_config->isLocalConfigLoaded() && !$this->_shouldSkipProcessModulesUpdates()) {
- Varien_Profiler::start('mage::app::init::apply_db_schema_updates');
- Mage_Core_Model_Resource_Setup::applyAllUpdates();
- Varien_Profiler::stop('mage::app::init::apply_db_schema_updates');
- }
- $this->_config->loadDb();
- $this->_config->loadEnv();
- $this->_config->saveCache();
- }
- } finally {
- $this->_config->releaseCacheSaveLock();
- }
- }
+ $this->_currentStore = $store;
return $this;
}
/**
- * Check whether modules updates processing should be skipped
+ * Redeclare custom error handler
*
- * @return bool
+ * @param string $handler
+ * @return $this
*/
- protected function _shouldSkipProcessModulesUpdates()
+ public function setErrorHandler($handler)
{
- if (!Mage::isInstalled()) {
- return false;
- }
-
- $ignoreDevelopmentMode = (bool) (string) $this->_config->getNode(self::XML_PATH_IGNORE_DEV_MODE);
- if (Mage::getIsDeveloperMode() && !$ignoreDevelopmentMode) {
- return false;
- }
-
- return (bool) (string) $this->_config->getNode(self::XML_PATH_SKIP_PROCESS_MODULES_UPDATES);
+ set_error_handler($handler);
+ return $this;
}
/**
- * Init request object
+ * Loading application area
*
- * @return $this
+ * @param string $code
+ * @return $this
*/
- protected function _initRequest()
+ public function loadArea($code)
{
- $this->getRequest()->setPathInfo();
+ $this->getArea($code)->load();
return $this;
}
/**
- * Initialize currently ran store
+ * Loading part of area data
*
- * @param string $scopeCode code of default scope (website/store_group/store code)
- * @param string $scopeType type of default scope (website/group/store)
- * @return $this
+ * @param string $area
+ * @param string $part
+ * @return $this
*/
- protected function _initCurrentStore($scopeCode, $scopeType)
+ public function loadAreaPart($area, $part)
{
- Varien_Profiler::start('mage::app::init::stores');
- $this->_initStores();
- Varien_Profiler::stop('mage::app::init::stores');
-
- if (empty($scopeCode) && !is_null($this->_website)) {
- $scopeCode = $this->_website->getCode();
- $scopeType = 'website';
- }
- switch ($scopeType) {
- case 'store':
- $this->_currentStore = $scopeCode;
- break;
- case 'group':
- $this->_currentStore = $this->_getStoreByGroup($scopeCode);
- break;
- case 'website':
- $this->_currentStore = $this->_getStoreByWebsite($scopeCode);
- break;
- default:
- $this->throwStoreException();
- }
-
- if (!empty($this->_currentStore)) {
- $this->_checkCookieStore($scopeType);
- $this->_checkGetStore($scopeType);
- }
- $this->_useSessionInUrl = $this->getStore()->getConfig(
- Mage_Core_Model_Session_Abstract::XML_PATH_USE_FRONTEND_SID,
- );
+ $this->getArea($area)->load($part);
return $this;
}
/**
- * Retrieve cookie object
+ * Retrieve application area
*
- * @return Mage_Core_Model_Cookie
+ * @param string $code
+ * @return Mage_Core_Model_App_Area
*/
- public function getCookie()
+ public function getArea($code)
{
- return Mage::getSingleton('core/cookie');
+ if (!isset($this->_areas[$code])) {
+ $this->_areas[$code] = new Mage_Core_Model_App_Area($code, $this);
+ }
+ return $this->_areas[$code];
}
/**
- * Check get store
+ * Retrieve application store object
*
- * @param string $type
- * @return $this
- * @SuppressWarnings("PHPMD.Superglobals")
+ * @param null|string|bool|int|Mage_Core_Model_Store $id
+ * @return Mage_Core_Model_Store|null
+ * @throws Mage_Core_Model_Store_Exception
*/
- protected function _checkGetStore($type)
+ public function getStore($id = null)
{
- if (empty($_GET)) {
- return $this;
+ if ($this->_isInstalled === null) {
+ $this->_isInstalled = Mage::isInstalled();
}
- /**
- * @todo check XML_PATH_STORE_IN_URL
- */
- if (!isset($_GET['___store'])) {
- return $this;
+ if (!$this->_isInstalled || $this->getUpdateMode()) {
+ return $this->_getDefaultStore();
}
- $store = $_GET['___store'];
- if (!isset($this->_stores[$store])) {
- return $this;
+ if ($id === true && $this->isSingleStoreMode()) {
+ return $this->_store;
}
- $storeObj = $this->_stores[$store];
- if (!$storeObj->getId() || !$storeObj->getIsActive()) {
- return $this;
+ if (!isset($id) || $id === '' || $id === true) {
+ $id = $this->_currentStore;
+ }
+ if ($id instanceof Mage_Core_Model_Store) {
+ return $id;
+ }
+ if (!isset($id)) {
+ $this->throwStoreException('Invalid store id requested.');
}
- /**
- * prevent running a store from another website or store group,
- * if website or store group was specified explicitly in Mage::run()
- */
- $curStoreObj = $this->_stores[$this->_currentStore];
- if ($type == 'website' && $storeObj->getWebsiteId() == $curStoreObj->getWebsiteId()) {
- $this->_currentStore = $store;
- } elseif ($type == 'group' && $storeObj->getGroupId() == $curStoreObj->getGroupId()) {
- $this->_currentStore = $store;
- } elseif ($type == 'store') {
- $this->_currentStore = $store;
+ if (empty($this->_stores[$id])) {
+ $store = Mage::getModel('core/store');
+ /** @var Mage_Core_Model_Store $store */
+ if (is_numeric($id)) {
+ $store->load($id);
+ } elseif (is_string($id)) {
+ $store->load($id, 'code');
+ }
+
+ if (!$store->getCode()) {
+ $this->throwStoreException('Invalid store code requested.');
+ }
+ $this->_stores[$store->getStoreId()] = $store;
+ $this->_stores[$store->getCode()] = $store;
}
+ return $this->_stores[$id];
+ }
- if ($this->_currentStore == $store) {
- $store = $this->getStore($store);
- if ($store->getWebsite()->getDefaultStore()->getId() == $store->getId()) {
- $this->getCookie()->delete(Mage_Core_Model_Store::COOKIE_NAME);
+ /**
+ * Retrieve application store object without Store_Exception
+ *
+ * @param string|int|Mage_Core_Model_Store $id
+ * @return Mage_Core_Model_Store|Varien_Object
+ */
+ public function getSafeStore($id = null)
+ {
+ try {
+ return $this->getStore($id);
+ } catch (Exception $e) {
+ if ($this->_currentStore) {
+ $this->getRequest()->setActionName('noRoute');
+ return new Varien_Object();
} else {
- $this->getCookie()->set(Mage_Core_Model_Store::COOKIE_NAME, $this->_currentStore, true);
+ Mage::throwException(Mage::helper('core')->__('Requested invalid store "%s"', $id));
}
}
- return $this;
}
/**
- * Check cookie store
+ * Retrieve stores array
*
- * @param string $type
- * @return $this
+ * @param bool $withDefault
+ * @param bool $codeKey
+ * @return Mage_Core_Model_Store[]
*/
- protected function _checkCookieStore($type)
+ public function getStores($withDefault = false, $codeKey = false)
{
- if (!$this->getCookie()->get()) {
- return $this;
+ $stores = [];
+ foreach ($this->_stores as $store) {
+ if (!$withDefault && $store->getId() == 0) {
+ continue;
+ }
+ if ($codeKey) {
+ $stores[$store->getCode()] = $store;
+ } else {
+ $stores[$store->getId()] = $store;
+ }
}
- $store = $this->getCookie()->get(Mage_Core_Model_Store::COOKIE_NAME);
- if ($store && isset($this->_stores[$store])
- && $this->_stores[$store]->getId()
- && $this->_stores[$store]->getIsActive()
- ) {
- if ($type == 'website'
- && $this->_stores[$store]->getWebsiteId() == $this->_stores[$this->_currentStore]->getWebsiteId()
- ) {
- $this->_currentStore = $store;
- }
- if ($type == 'group'
- && $this->_stores[$store]->getGroupId() == $this->_stores[$this->_currentStore]->getGroupId()
- ) {
- $this->_currentStore = $store;
- }
- if ($type == 'store') {
- $this->_currentStore = $store;
+ return $stores;
+ }
+
+ /**
+ * Retrieve default store for default group and website
+ *
+ * @return Mage_Core_Model_Store|null
+ */
+ public function getDefaultStoreView()
+ {
+ foreach ($this->getWebsites() as $website) {
+ if ($website->getIsDefault()) {
+ $defaultStore = $this->getGroup($website->getDefaultGroupId())->getDefaultStore();
+ if ($defaultStore) {
+ return $defaultStore;
+ }
}
}
- return $this;
+ return null;
}
- public function reinitStores()
+ /**
+ * @return string
+ */
+ public function getDistroLocaleCode()
{
- $this->_initStores();
+ return self::DISTRO_LOCALE_CODE;
}
/**
- * Init store, group and website collections
+ * Retrieve application website object
*
+ * @param null|Mage_Core_Model_Website|true|int|string $id
+ * @return Mage_Core_Model_Website
*/
- protected function _initStores()
+ public function getWebsite($id = null)
{
- $this->_stores = [];
- $this->_groups = [];
- $this->_website = null;
- $this->_websites = [];
-
- /** @var Mage_Core_Model_Resource_Website_Collection $websiteCollection */
- $websiteCollection = Mage::getModel('core/website')->getCollection()
- ->initCache($this->getCache(), 'app', [Mage_Core_Model_Website::CACHE_TAG])
- ->setLoadDefault(true);
-
- /** @var Mage_Core_Model_Resource_Store_Group_Collection $groupCollection */
- $groupCollection = Mage::getModel('core/store_group')->getCollection()
- ->initCache($this->getCache(), 'app', [Mage_Core_Model_Store_Group::CACHE_TAG])
- ->setLoadDefault(true);
-
- /** @var Mage_Core_Model_Resource_Store_Collection $storeCollection */
- $storeCollection = Mage::getModel('core/store')->getCollection()
- ->initCache($this->getCache(), 'app', [Mage_Core_Model_Store::CACHE_TAG])
- ->setLoadDefault(true);
-
- $this->_isSingleStore = false;
- if ($this->_isSingleStoreAllowed) {
- $this->_isSingleStore = $storeCollection->count() < 3;
- }
-
- $websiteStores = [];
- $websiteGroups = [];
- $groupStores = [];
-
- $storeCollection->initConfigCache();
-
- foreach ($storeCollection as $store) {
- /** @var Mage_Core_Model_Store $store */
- $store->setWebsite($websiteCollection->getItemById($store->getWebsiteId()));
- $store->setGroup($groupCollection->getItemById($store->getGroupId()));
-
- $this->_stores[$store->getId()] = $store;
- $this->_stores[$store->getCode()] = $store;
-
- $websiteStores[$store->getWebsiteId()][$store->getId()] = $store;
- $groupStores[$store->getGroupId()][$store->getId()] = $store;
-
- if (is_null($this->_store) && $store->getId()) {
- $this->_store = $store;
- }
- }
-
- foreach ($groupCollection as $group) {
- /** @var Mage_Core_Model_Store_Group $group */
- if (!isset($groupStores[$group->getId()])) {
- $groupStores[$group->getId()] = [];
- }
- $group->setStores($groupStores[$group->getId()]);
- $group->setWebsite($websiteCollection->getItemById($group->getWebsiteId()));
-
- $websiteGroups[$group->getWebsiteId()][$group->getId()] = $group;
-
- $this->_groups[$group->getId()] = $group;
+ if (is_null($id)) {
+ $id = $this->getStore()->getWebsiteId();
+ } elseif ($id instanceof Mage_Core_Model_Website) {
+ return $id;
+ } elseif ($id === true) {
+ return $this->_website;
}
- foreach ($websiteCollection as $website) {
- /** @var Mage_Core_Model_Website $website */
- if (!isset($websiteGroups[$website->getId()])) {
- $websiteGroups[$website->getId()] = [];
- }
- if (!isset($websiteStores[$website->getId()])) {
- $websiteStores[$website->getId()] = [];
- }
- if ($website->getIsDefault()) {
- $this->_website = $website;
+ if (empty($this->_websites[$id])) {
+ $website = Mage::getModel('core/website');
+ if (is_numeric($id)) {
+ $website->load($id);
+ if (!$website->hasWebsiteId()) {
+ throw Mage::exception('Mage_Core', 'Invalid website id requested.');
+ }
+ } elseif (is_string($id)) {
+ $websiteConfig = $this->_config->getNode('websites/' . $id);
+ if (!$websiteConfig) {
+ throw Mage::exception('Mage_Core', 'Invalid website code requested: ' . $id);
+ }
+ $website->loadConfig($id);
}
- $website->setGroups($websiteGroups[$website->getId()]);
- $website->setStores($websiteStores[$website->getId()]);
-
- $this->_websites[$website->getId()] = $website;
+ $this->_websites[$website->getWebsiteId()] = $website;
$this->_websites[$website->getCode()] = $website;
}
+ return $this->_websites[$id];
}
/**
- * Is single Store mode (only one store without default)
- *
- * @return bool
+ * @param bool $withDefault
+ * @param bool $codeKey
+ * @return Mage_Core_Model_Website[]
*/
- public function isSingleStoreMode()
+ public function getWebsites($withDefault = false, $codeKey = false)
{
- if ($this->_isInstalled === null) {
- $this->_isInstalled = Mage::isInstalled();
+ $websites = [];
+ if (is_array($this->_websites)) {
+ foreach ($this->_websites as $website) {
+ $id = $website->getId();
+ if (!$withDefault && $id == 0) {
+ continue;
+ }
+ if ($codeKey) {
+ $websites[$website->getCode()] = $website;
+ } else {
+ $websites[$id] = $website;
+ }
+ }
}
- if (!$this->_isInstalled) {
- return false;
- }
- return $this->_isSingleStore;
+ return $websites;
}
/**
- * Retrieve store code or null by store group
+ * Retrieve application store group object
*
- * @param int $group
- * @return string|null
+ * @param null|Mage_Core_Model_Store_Group|int|string $id
+ * @return Mage_Core_Model_Store_Group
*/
- protected function _getStoreByGroup($group)
+ public function getGroup($id = null)
{
- if (!isset($this->_groups[$group])) {
- return null;
+ if (is_null($id)) {
+ $id = $this->getStore()->getGroup()->getId();
+ } elseif ($id instanceof Mage_Core_Model_Store_Group) {
+ return $id;
}
- if (!$this->_groups[$group]->getDefaultStoreId()) {
- return null;
+ if (empty($this->_groups[$id])) {
+ $group = Mage::getModel('core/store_group');
+ if (is_numeric($id)) {
+ $group->load($id);
+ if (!$group->hasGroupId()) {
+ throw Mage::exception('Mage_Core', 'Invalid store group id requested.');
+ }
+ }
+ $this->_groups[$group->getGroupId()] = $group;
}
- return $this->_stores[$this->_groups[$group]->getDefaultStoreId()]->getCode();
+ return $this->_groups[$id];
}
/**
- * Retrieve store code or null by website
+ * Retrieve application locale object
*
- * @param int|string $website
- * @return string|null
+ * @return Mage_Core_Model_Locale
*/
- protected function _getStoreByWebsite($website)
+ public function getLocale()
{
- if (!isset($this->_websites[$website])) {
- return null;
- }
- if (!$this->_websites[$website]->getDefaultGroupId()) {
- return null;
+ if (!$this->_locale) {
+ $this->_locale = Mage::getSingleton('core/locale');
}
- return $this->_getStoreByGroup($this->_websites[$website]->getDefaultGroupId());
+ return $this->_locale;
}
/**
- * Set current default store
+ * Retrieve layout object
*
- * @param null|string|bool|int|Mage_Core_Model_Store $store
- * @return $this
+ * @return Mage_Core_Model_Layout
*/
- public function setCurrentStore($store)
+ public function getLayout()
{
- $this->_currentStore = $store;
- return $this;
+ if (!$this->_layout) {
+ if ($this->getFrontController()->getAction()) {
+ $this->_layout = $this->getFrontController()->getAction()->getLayout();
+ } else {
+ $this->_layout = Mage::getSingleton('core/layout');
+ }
+ }
+ return $this->_layout;
}
/**
- * Initialize application front controller
+ * Retrieve translate object
*
- * @return $this
+ * @return Mage_Core_Model_Translate
*/
- protected function _initFrontController()
+ public function getTranslator()
{
- $this->_frontController = new Mage_Core_Controller_Varien_Front();
- Mage::register('controller', $this->_frontController);
- Varien_Profiler::start('mage::app::init_front_controller');
- $this->_frontController->init();
- Varien_Profiler::stop('mage::app::init_front_controller');
- return $this;
+ if (!$this->_translator) {
+ $this->_translator = Mage::getSingleton('core/translate');
+ }
+ return $this->_translator;
}
/**
- * Redeclare custom error handler
+ * Retrieve helper object
*
- * @param string $handler
- * @return $this
+ * @param string $name
+ * @return Mage_Core_Helper_Abstract
*/
- public function setErrorHandler($handler)
+ public function getHelper($name)
{
- set_error_handler($handler);
- return $this;
+ return Mage::helper($name);
}
/**
- * Loading application area
+ * Retrieve application base currency code
*
- * @param string $code
- * @return $this
+ * @return string
*/
- public function loadArea($code)
+ public function getBaseCurrencyCode()
{
- $this->getArea($code)->load();
- return $this;
+ //return Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE, 0);
+ return (string) Mage::app()->getConfig()
+ ->getNode('default/' . Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
}
/**
- * Loading part of area data
+ * Retrieve configuration object
*
- * @param string $area
- * @param string $part
- * @return $this
+ * @return Mage_Core_Model_Config
*/
- public function loadAreaPart($area, $part)
+ public function getConfig()
{
- $this->getArea($area)->load($part);
- return $this;
+ return $this->_config;
}
/**
- * Retrieve application area
+ * Retrieve front controller object
*
- * @param string $code
- * @return Mage_Core_Model_App_Area
+ * @return Mage_Core_Controller_Varien_Front
*/
- public function getArea($code)
+ public function getFrontController()
{
- if (!isset($this->_areas[$code])) {
- $this->_areas[$code] = new Mage_Core_Model_App_Area($code, $this);
+ if (!$this->_frontController) {
+ $this->_initFrontController();
}
- return $this->_areas[$code];
+
+ return $this->_frontController;
}
/**
- * Retrieve application store object
+ * Get core cache model
*
- * @param null|string|bool|int|Mage_Core_Model_Store $id
- * @return Mage_Core_Model_Store|null
- * @throws Mage_Core_Model_Store_Exception
+ * @return Mage_Core_Model_Cache
*/
- public function getStore($id = null)
+ public function getCacheInstance()
{
- if ($this->_isInstalled === null) {
- $this->_isInstalled = Mage::isInstalled();
- }
-
- if (!$this->_isInstalled || $this->getUpdateMode()) {
- return $this->_getDefaultStore();
- }
-
- if ($id === true && $this->isSingleStoreMode()) {
- return $this->_store;
- }
-
- if (!isset($id) || $id === '' || $id === true) {
- $id = $this->_currentStore;
- }
- if ($id instanceof Mage_Core_Model_Store) {
- return $id;
- }
- if (!isset($id)) {
- $this->throwStoreException('Invalid store id requested.');
- }
-
- if (empty($this->_stores[$id])) {
- $store = Mage::getModel('core/store');
- /** @var Mage_Core_Model_Store $store */
- if (is_numeric($id)) {
- $store->load($id);
- } elseif (is_string($id)) {
- $store->load($id, 'code');
- }
-
- if (!$store->getCode()) {
- $this->throwStoreException('Invalid store code requested.');
- }
- $this->_stores[$store->getStoreId()] = $store;
- $this->_stores[$store->getCode()] = $store;
+ if (!$this->_cache) {
+ $this->_initCache();
}
- return $this->_stores[$id];
+ return $this->_cache;
}
/**
- * Retrieve application store object without Store_Exception
+ * Retrieve cache object
*
- * @param string|int|Mage_Core_Model_Store $id
- * @return Mage_Core_Model_Store|Varien_Object
+ * @return Zend_Cache_Core
*/
- public function getSafeStore($id = null)
+ public function getCache()
{
- try {
- return $this->getStore($id);
- } catch (Exception $e) {
- if ($this->_currentStore) {
- $this->getRequest()->setActionName('noRoute');
- return new Varien_Object();
- } else {
- Mage::throwException(Mage::helper('core')->__('Requested invalid store "%s"', $id));
- }
+ if (!$this->_cache) {
+ $this->_initCache();
}
+ return $this->_cache->getFrontend();
}
/**
- * Retrieve stores array
+ * Loading cache data
*
- * @param bool $withDefault
- * @param bool $codeKey
- * @return Mage_Core_Model_Store[]
+ * @param string $id
+ * @return string|false
*/
- public function getStores($withDefault = false, $codeKey = false)
+ public function loadCache($id)
{
- $stores = [];
- foreach ($this->_stores as $store) {
- if (!$withDefault && $store->getId() == 0) {
- continue;
- }
- if ($codeKey) {
- $stores[$store->getCode()] = $store;
- } else {
- $stores[$store->getId()] = $store;
- }
- }
-
- return $stores;
+ return $this->_cache->load($id);
}
/**
- * @return Mage_Core_Model_Store
+ * Saving cache data
+ *
+ * @param mixed $data
+ * @param string $id
+ * @param array $tags
+ * @param null|false|int $lifeTime
+ * @return $this
*/
- protected function _getDefaultStore()
+ public function saveCache($data, $id, $tags = [], $lifeTime = false)
{
- if (empty($this->_store)) {
- $this->_store = Mage::getModel('core/store')
- ->setId(self::DISTRO_STORE_ID)
- ->setCode(self::DISTRO_STORE_CODE);
- }
- return $this->_store;
+ $this->_cache->save($data, $id, $tags, $lifeTime);
+ return $this;
}
/**
- * Retrieve default store for default group and website
+ * Test cache record availability
*
- * @return Mage_Core_Model_Store|null
+ * @param string $id
+ * @return false|int
*/
- public function getDefaultStoreView()
+ public function testCache($id)
{
- foreach ($this->getWebsites() as $website) {
- if ($website->getIsDefault()) {
- $defaultStore = $this->getGroup($website->getDefaultGroupId())->getDefaultStore();
- if ($defaultStore) {
- return $defaultStore;
- }
- }
- }
- return null;
+ return $this->_cache->test($id);
}
/**
- * @return string
+ * Remove cache
+ *
+ * @param string $id
+ * @return $this
*/
- public function getDistroLocaleCode()
+ public function removeCache($id)
{
- return self::DISTRO_LOCALE_CODE;
+ $this->_cache->remove($id);
+ return $this;
}
/**
- * Retrieve application website object
+ * Cleaning cache
*
- * @param null|Mage_Core_Model_Website|true|int|string $id
- * @return Mage_Core_Model_Website
+ * @param array $tags
+ * @return $this
*/
- public function getWebsite($id = null)
+ public function cleanCache($tags = [])
{
- if (is_null($id)) {
- $id = $this->getStore()->getWebsiteId();
- } elseif ($id instanceof Mage_Core_Model_Website) {
- return $id;
- } elseif ($id === true) {
- return $this->_website;
- }
-
- if (empty($this->_websites[$id])) {
- $website = Mage::getModel('core/website');
- if (is_numeric($id)) {
- $website->load($id);
- if (!$website->hasWebsiteId()) {
- throw Mage::exception('Mage_Core', 'Invalid website id requested.');
- }
- } elseif (is_string($id)) {
- $websiteConfig = $this->_config->getNode('websites/' . $id);
- if (!$websiteConfig) {
- throw Mage::exception('Mage_Core', 'Invalid website code requested: ' . $id);
- }
- $website->loadConfig($id);
- }
- $this->_websites[$website->getWebsiteId()] = $website;
- $this->_websites[$website->getCode()] = $website;
- }
- return $this->_websites[$id];
+ $this->_cache->clean($tags);
+ Mage::dispatchEvent('application_clean_cache', ['tags' => $tags]);
+ return $this;
}
/**
- * @param bool $withDefault
- * @param bool $codeKey
- * @return Mage_Core_Model_Website[]
+ * Check whether to use cache for specific component
+ *
+ * @param null|string $type
+ * @return false|array
*/
- public function getWebsites($withDefault = false, $codeKey = false)
+ public function useCache($type = null)
{
- $websites = [];
- if (is_array($this->_websites)) {
- foreach ($this->_websites as $website) {
- $id = $website->getId();
- if (!$withDefault && $id == 0) {
- continue;
- }
- if ($codeKey) {
- $websites[$website->getCode()] = $website;
- } else {
- $websites[$id] = $website;
- }
- }
- }
+ return $this->_cache->canUse($type);
+ }
- return $websites;
+ /**
+ * Save cache usage settings
+ *
+ * @param array $data
+ * @return $this
+ */
+ public function saveUseCache($data)
+ {
+ $this->_cache->saveOptions($data);
+ return $this;
}
/**
- * Retrieve application store group object
+ * Deletes all session files
*
- * @param null|Mage_Core_Model_Store_Group|int|string $id
- * @return Mage_Core_Model_Store_Group
*/
- public function getGroup($id = null)
- {
- if (is_null($id)) {
- $id = $this->getStore()->getGroup()->getId();
- } elseif ($id instanceof Mage_Core_Model_Store_Group) {
- return $id;
- }
- if (empty($this->_groups[$id])) {
- $group = Mage::getModel('core/store_group');
- if (is_numeric($id)) {
- $group->load($id);
- if (!$group->hasGroupId()) {
- throw Mage::exception('Mage_Core', 'Invalid store group id requested.');
- }
- }
- $this->_groups[$group->getGroupId()] = $group;
- }
- return $this->_groups[$id];
- }
-
- /**
- * Retrieve application locale object
- *
- * @return Mage_Core_Model_Locale
- */
- public function getLocale()
- {
- if (!$this->_locale) {
- $this->_locale = Mage::getSingleton('core/locale');
- }
- return $this->_locale;
- }
-
- /**
- * Retrieve layout object
- *
- * @return Mage_Core_Model_Layout
- */
- public function getLayout()
- {
- if (!$this->_layout) {
- if ($this->getFrontController()->getAction()) {
- $this->_layout = $this->getFrontController()->getAction()->getLayout();
- } else {
- $this->_layout = Mage::getSingleton('core/layout');
- }
- }
- return $this->_layout;
- }
-
- /**
- * Retrieve translate object
- *
- * @return Mage_Core_Model_Translate
- */
- public function getTranslator()
- {
- if (!$this->_translator) {
- $this->_translator = Mage::getSingleton('core/translate');
- }
- return $this->_translator;
- }
-
- /**
- * Retrieve helper object
- *
- * @param string $name
- * @return Mage_Core_Helper_Abstract
- */
- public function getHelper($name)
- {
- return Mage::helper($name);
- }
-
- /**
- * Retrieve application base currency code
- *
- * @return string
- */
- public function getBaseCurrencyCode()
- {
- //return Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE, 0);
- return (string) Mage::app()->getConfig()
- ->getNode('default/' . Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
- }
-
- /**
- * Retrieve configuration object
- *
- * @return Mage_Core_Model_Config
- */
- public function getConfig()
- {
- return $this->_config;
- }
-
- /**
- * Retrieve front controller object
- *
- * @return Mage_Core_Controller_Varien_Front
- */
- public function getFrontController()
- {
- if (!$this->_frontController) {
- $this->_initFrontController();
- }
-
- return $this->_frontController;
- }
-
- /**
- * Get core cache model
- *
- * @return Mage_Core_Model_Cache
- */
- public function getCacheInstance()
- {
- if (!$this->_cache) {
- $this->_initCache();
- }
- return $this->_cache;
- }
-
- /**
- * Retrieve cache object
- *
- * @return Zend_Cache_Core
- */
- public function getCache()
- {
- if (!$this->_cache) {
- $this->_initCache();
- }
- return $this->_cache->getFrontend();
- }
-
- /**
- * Loading cache data
- *
- * @param string $id
- * @return string|false
- */
- public function loadCache($id)
- {
- return $this->_cache->load($id);
- }
-
- /**
- * Saving cache data
- *
- * @param mixed $data
- * @param string $id
- * @param array $tags
- * @param null|false|int $lifeTime
- * @return $this
- */
- public function saveCache($data, $id, $tags = [], $lifeTime = false)
- {
- $this->_cache->save($data, $id, $tags, $lifeTime);
- return $this;
- }
-
- /**
- * Test cache record availability
- *
- * @param string $id
- * @return false|int
- */
- public function testCache($id)
- {
- return $this->_cache->test($id);
- }
-
- /**
- * Remove cache
- *
- * @param string $id
- * @return $this
- */
- public function removeCache($id)
- {
- $this->_cache->remove($id);
- return $this;
- }
-
- /**
- * Cleaning cache
- *
- * @param array $tags
- * @return $this
- */
- public function cleanCache($tags = [])
- {
- $this->_cache->clean($tags);
- Mage::dispatchEvent('application_clean_cache', ['tags' => $tags]);
- return $this;
- }
-
- /**
- * Check whether to use cache for specific component
- *
- * @param null|string $type
- * @return false|array
- */
- public function useCache($type = null)
- {
- return $this->_cache->canUse($type);
- }
-
- /**
- * Save cache usage settings
- *
- * @param array $data
- * @return $this
- */
- public function saveUseCache($data)
- {
- $this->_cache->saveOptions($data);
- return $this;
- }
-
- /**
- * Deletes all session files
- *
- */
- public function cleanAllSessions()
+ public function cleanAllSessions()
{
if (session_module_name() == 'files') {
$dir = session_save_path();
@@ -1428,170 +1048,607 @@ public function dispatchEvent($eventName, $args)
Varien_Profiler::stop('OBSERVER: ' . $obsName);
}
}
- return $this;
- }
+ return $this;
+ }
+
+ /**
+ * @param bool $value
+ */
+ public function setUpdateMode($value)
+ {
+ $this->_updateMode = $value;
+ }
+
+ /**
+ * @return bool
+ */
+ public function getUpdateMode()
+ {
+ return $this->_updateMode;
+ }
+
+ /**
+ * @param string $text
+ * @throws Mage_Core_Model_Store_Exception
+ * @return never
+ */
+ public function throwStoreException($text = '')
+ {
+ throw new Mage_Core_Model_Store_Exception($text);
+ }
+
+ /**
+ * Set use session var instead of SID for URL
+ *
+ * @param bool $var
+ * @return $this
+ */
+ public function setUseSessionVar($var)
+ {
+ $this->_useSessionVar = (bool) $var;
+ return $this;
+ }
+
+ /**
+ * Retrieve use flag session var instead of SID for URL
+ *
+ * @return bool
+ */
+ public function getUseSessionVar()
+ {
+ return $this->_useSessionVar;
+ }
+
+ /**
+ * Get either default or any store view
+ *
+ * @return Mage_Core_Model_Store|void
+ */
+ public function getAnyStoreView()
+ {
+ $store = $this->getDefaultStoreView();
+ if ($store) {
+ return $store;
+ }
+ foreach ($this->getStores() as $store) {
+ return $store;
+ }
+ }
+
+ /**
+ * Set Use session in URL flag
+ *
+ * @param bool $flag
+ * @return $this
+ */
+ public function setUseSessionInUrl($flag = true)
+ {
+ $this->_useSessionInUrl = (bool) $flag;
+ return $this;
+ }
+
+ /**
+ * Retrieve use session in URL flag
+ *
+ * @return bool
+ */
+ public function getUseSessionInUrl()
+ {
+ return $this->_useSessionInUrl;
+ }
+
+ /**
+ * Allow or disallow single store mode
+ *
+ * @param bool $value
+ * @return $this
+ */
+ public function setIsSingleStoreModeAllowed($value)
+ {
+ $this->_isSingleStoreAllowed = (bool) $value;
+ return $this;
+ }
+
+ /**
+ * Prepare array of store groups
+ * can be filtered to contain default store group or not by $withDefault flag
+ * depending on flag $codeKey array keys can be group id or group code
+ *
+ * @param bool $withDefault
+ * @param bool $codeKey
+ * @return Mage_Core_Model_Store_Group[]
+ */
+ public function getGroups($withDefault = false, $codeKey = false)
+ {
+ $groups = [];
+ if (is_array($this->_groups)) {
+ foreach ($this->_groups as $group) {
+ if (!$withDefault && $group->getId() == 0) {
+ continue;
+ }
+ if ($codeKey) {
+ $groups[$group->getCode()] = $group;
+ } else {
+ $groups[$group->getId()] = $group;
+ }
+ }
+ }
+
+ return $groups;
+ }
+
+ /**
+ * Retrieve application installation flag
+ *
+ * @deprecated since 1.2
+ * @return bool
+ */
+ public function isInstalled()
+ {
+ return Mage::isInstalled();
+ }
+
+ /**
+ * Get file name with cache configuration settings
+ *
+ * @deprecated after 1.4.0.0-alpha3, functionality implemented in Mage_Core_Model_Cache
+ * @return string
+ */
+ public function getUseCacheFilename()
+ {
+ return $this->_config->getOptions()->getEtcDir() . DS . 'use_cache.ser';
+ }
+
+ /**
+ * Prepare identifier which can be used as cache id or cache tag
+ *
+ * @deprecated after 1.4.0.0-alpha3, functionality implemented in Mage_Core_Model_Cache
+ * @param string $id
+ * @return string
+ */
+ public function prepareCacheId($id)
+ {
+ $id = strtoupper($id);
+ return preg_replace('/([^a-zA-Z0-9_]{1,1})/', '_', $id);
+ }
+
+ /**
+ * Get is cache locked
+ *
+ * @return bool
+ */
+ public function getIsCacheLocked()
+ {
+ return (bool) $this->_isCacheLocked;
+ }
+
+ /**
+ * Unset website by id from app cache
+ *
+ * @param null|bool|int|string|Mage_Core_Model_Website $id
+ */
+ public function clearWebsiteCache($id = null)
+ {
+ if (is_null($id)) {
+ $id = $this->getStore()->getWebsiteId();
+ } elseif ($id instanceof Mage_Core_Model_Website) {
+ $id = $id->getId();
+ } elseif ($id === true) {
+ $id = $this->_website->getId();
+ }
+
+ if (!empty($this->_websites[$id])) {
+ $website = $this->_websites[$id];
+
+ unset($this->_websites[$website->getWebsiteId()]);
+ unset($this->_websites[$website->getCode()]);
+ }
+ }
+
+ /**
+ * Initialize PHP environment
+ *
+ * @return $this
+ */
+ protected function _initEnvironment()
+ {
+ $this->setErrorHandler(self::DEFAULT_ERROR_HANDLER);
+ date_default_timezone_set(Mage_Core_Model_Locale::DEFAULT_TIMEZONE);
+ return $this;
+ }
+
+ /**
+ * Initialize base system configuration (local.xml and config.xml files).
+ * Base configuration provide ability initialize DB connection and cache backend
+ *
+ * @return $this
+ */
+ protected function _initBaseConfig()
+ {
+ Varien_Profiler::start('mage::app::init::system_config');
+ $this->_config->loadBase();
+ Varien_Profiler::stop('mage::app::init::system_config');
+ return $this;
+ }
+
+ /**
+ * Initialize application cache instance
+ *
+ * @return $this
+ */
+ protected function _initCache(array $cacheInitOptions = [])
+ {
+ $this->_isCacheLocked = true;
+ $options = $this->_config->getNode('global/cache');
+ if ($options) {
+ $options = $options->asArray();
+ } else {
+ $options = [];
+ }
+ $options = array_merge($options, $cacheInitOptions);
+ $this->_cache = Mage::getModel('core/cache', $options);
+ $this->_isCacheLocked = false;
+ return $this;
+ }
+
+ /**
+ * Initialize active modules configuration and data
+ *
+ * @return $this
+ */
+ protected function _initModules()
+ {
+ if (!$this->_config->loadModulesCache()) {
+ try {
+ $this->_config->getCacheSaveLock();
+ if (!$this->_config->loadModulesCache()) {
+ $this->_config->loadModules();
+ if ($this->_config->isLocalConfigLoaded() && !$this->_shouldSkipProcessModulesUpdates()) {
+ Varien_Profiler::start('mage::app::init::apply_db_schema_updates');
+ Mage_Core_Model_Resource_Setup::applyAllUpdates();
+ Varien_Profiler::stop('mage::app::init::apply_db_schema_updates');
+ }
+ $this->_config->loadDb();
+ $this->_config->loadEnv();
+ $this->_config->saveCache();
+ }
+ } finally {
+ $this->_config->releaseCacheSaveLock();
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Check whether modules updates processing should be skipped
+ *
+ * @return bool
+ */
+ protected function _shouldSkipProcessModulesUpdates()
+ {
+ if (!Mage::isInstalled()) {
+ return false;
+ }
+
+ $ignoreDevelopmentMode = (bool) (string) $this->_config->getNode(self::XML_PATH_IGNORE_DEV_MODE);
+ if (Mage::getIsDeveloperMode() && !$ignoreDevelopmentMode) {
+ return false;
+ }
+
+ return (bool) (string) $this->_config->getNode(self::XML_PATH_SKIP_PROCESS_MODULES_UPDATES);
+ }
+
+ /**
+ * Init request object
+ *
+ * @return $this
+ */
+ protected function _initRequest()
+ {
+ $this->getRequest()->setPathInfo();
+ return $this;
+ }
+
+ /**
+ * Initialize currently ran store
+ *
+ * @param string $scopeCode code of default scope (website/store_group/store code)
+ * @param string $scopeType type of default scope (website/group/store)
+ * @return $this
+ */
+ protected function _initCurrentStore($scopeCode, $scopeType)
+ {
+ Varien_Profiler::start('mage::app::init::stores');
+ $this->_initStores();
+ Varien_Profiler::stop('mage::app::init::stores');
+
+ if (empty($scopeCode) && !is_null($this->_website)) {
+ $scopeCode = $this->_website->getCode();
+ $scopeType = 'website';
+ }
+ switch ($scopeType) {
+ case 'store':
+ $this->_currentStore = $scopeCode;
+ break;
+ case 'group':
+ $this->_currentStore = $this->_getStoreByGroup($scopeCode);
+ break;
+ case 'website':
+ $this->_currentStore = $this->_getStoreByWebsite($scopeCode);
+ break;
+ default:
+ $this->throwStoreException();
+ }
+
+ if (!empty($this->_currentStore)) {
+ $this->_checkCookieStore($scopeType);
+ $this->_checkGetStore($scopeType);
+ }
+ $this->_useSessionInUrl = $this->getStore()->getConfig(
+ Mage_Core_Model_Session_Abstract::XML_PATH_USE_FRONTEND_SID,
+ );
+ return $this;
+ }
+
+ /**
+ * Check get store
+ *
+ * @param string $type
+ * @return $this
+ * @SuppressWarnings("PHPMD.Superglobals")
+ */
+ protected function _checkGetStore($type)
+ {
+ if (empty($_GET)) {
+ return $this;
+ }
+
+ /**
+ * @todo check XML_PATH_STORE_IN_URL
+ */
+ if (!isset($_GET['___store'])) {
+ return $this;
+ }
+
+ $store = $_GET['___store'];
+ if (!isset($this->_stores[$store])) {
+ return $this;
+ }
+
+ $storeObj = $this->_stores[$store];
+ if (!$storeObj->getId() || !$storeObj->getIsActive()) {
+ return $this;
+ }
+
+ /**
+ * prevent running a store from another website or store group,
+ * if website or store group was specified explicitly in Mage::run()
+ */
+ $curStoreObj = $this->_stores[$this->_currentStore];
+ if ($type == 'website' && $storeObj->getWebsiteId() == $curStoreObj->getWebsiteId()) {
+ $this->_currentStore = $store;
+ } elseif ($type == 'group' && $storeObj->getGroupId() == $curStoreObj->getGroupId()) {
+ $this->_currentStore = $store;
+ } elseif ($type == 'store') {
+ $this->_currentStore = $store;
+ }
+
+ if ($this->_currentStore == $store) {
+ $store = $this->getStore($store);
+ if ($store->getWebsite()->getDefaultStore()->getId() == $store->getId()) {
+ $this->getCookie()->delete(Mage_Core_Model_Store::COOKIE_NAME);
+ } else {
+ $this->getCookie()->set(Mage_Core_Model_Store::COOKIE_NAME, $this->_currentStore, true);
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Check cookie store
+ *
+ * @param string $type
+ * @return $this
+ */
+ protected function _checkCookieStore($type)
+ {
+ if (!$this->getCookie()->get()) {
+ return $this;
+ }
+
+ $store = $this->getCookie()->get(Mage_Core_Model_Store::COOKIE_NAME);
+ if ($store && isset($this->_stores[$store])
+ && $this->_stores[$store]->getId()
+ && $this->_stores[$store]->getIsActive()
+ ) {
+ if ($type == 'website'
+ && $this->_stores[$store]->getWebsiteId() == $this->_stores[$this->_currentStore]->getWebsiteId()
+ ) {
+ $this->_currentStore = $store;
+ }
+ if ($type == 'group'
+ && $this->_stores[$store]->getGroupId() == $this->_stores[$this->_currentStore]->getGroupId()
+ ) {
+ $this->_currentStore = $store;
+ }
+ if ($type == 'store') {
+ $this->_currentStore = $store;
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Init store, group and website collections
+ *
+ */
+ protected function _initStores()
+ {
+ $this->_stores = [];
+ $this->_groups = [];
+ $this->_website = null;
+ $this->_websites = [];
+
+ /** @var Mage_Core_Model_Resource_Website_Collection $websiteCollection */
+ $websiteCollection = Mage::getModel('core/website')->getCollection()
+ ->initCache($this->getCache(), 'app', [Mage_Core_Model_Website::CACHE_TAG])
+ ->setLoadDefault(true);
+
+ /** @var Mage_Core_Model_Resource_Store_Group_Collection $groupCollection */
+ $groupCollection = Mage::getModel('core/store_group')->getCollection()
+ ->initCache($this->getCache(), 'app', [Mage_Core_Model_Store_Group::CACHE_TAG])
+ ->setLoadDefault(true);
+
+ /** @var Mage_Core_Model_Resource_Store_Collection $storeCollection */
+ $storeCollection = Mage::getModel('core/store')->getCollection()
+ ->initCache($this->getCache(), 'app', [Mage_Core_Model_Store::CACHE_TAG])
+ ->setLoadDefault(true);
+
+ $this->_isSingleStore = false;
+ if ($this->_isSingleStoreAllowed) {
+ $this->_isSingleStore = $storeCollection->count() < 3;
+ }
+
+ $websiteStores = [];
+ $websiteGroups = [];
+ $groupStores = [];
+
+ $storeCollection->initConfigCache();
+
+ foreach ($storeCollection as $store) {
+ /** @var Mage_Core_Model_Store $store */
+ $store->setWebsite($websiteCollection->getItemById($store->getWebsiteId()));
+ $store->setGroup($groupCollection->getItemById($store->getGroupId()));
+
+ $this->_stores[$store->getId()] = $store;
+ $this->_stores[$store->getCode()] = $store;
+
+ $websiteStores[$store->getWebsiteId()][$store->getId()] = $store;
+ $groupStores[$store->getGroupId()][$store->getId()] = $store;
+
+ if (is_null($this->_store) && $store->getId()) {
+ $this->_store = $store;
+ }
+ }
- /**
- * Performs non-existent observer method calls protection
- *
- * @param object $object
- * @param string $method
- * @param Varien_Event_Observer $observer
- * @param string $observerName
- * @return $this
- * @throws Mage_Core_Exception
- */
- protected function _callObserverMethod($object, $method, $observer, $observerName = 'undefined')
- {
- if (is_object($object) && method_exists($object, $method)) {
- $object->$method($observer);
- } elseif (Mage::getIsDeveloperMode()) {
- if (is_object($object)) {
- $message = 'Method "' . $method . '" is not defined in "' . get_class($object) . '"';
- } else {
- $message = 'Class from observer "' . $observerName . '" is not initialized';
+ foreach ($groupCollection as $group) {
+ /** @var Mage_Core_Model_Store_Group $group */
+ if (!isset($groupStores[$group->getId()])) {
+ $groupStores[$group->getId()] = [];
}
+ $group->setStores($groupStores[$group->getId()]);
+ $group->setWebsite($websiteCollection->getItemById($group->getWebsiteId()));
- Mage::throwException($message);
- }
- return $this;
- }
-
- /**
- * @param bool $value
- */
- public function setUpdateMode($value)
- {
- $this->_updateMode = $value;
- }
+ $websiteGroups[$group->getWebsiteId()][$group->getId()] = $group;
- /**
- * @return bool
- */
- public function getUpdateMode()
- {
- return $this->_updateMode;
- }
+ $this->_groups[$group->getId()] = $group;
+ }
- /**
- * @param string $text
- * @throws Mage_Core_Model_Store_Exception
- * @return never
- */
- public function throwStoreException($text = '')
- {
- throw new Mage_Core_Model_Store_Exception($text);
- }
+ foreach ($websiteCollection as $website) {
+ /** @var Mage_Core_Model_Website $website */
+ if (!isset($websiteGroups[$website->getId()])) {
+ $websiteGroups[$website->getId()] = [];
+ }
+ if (!isset($websiteStores[$website->getId()])) {
+ $websiteStores[$website->getId()] = [];
+ }
+ if ($website->getIsDefault()) {
+ $this->_website = $website;
+ }
+ $website->setGroups($websiteGroups[$website->getId()]);
+ $website->setStores($websiteStores[$website->getId()]);
- /**
- * Set use session var instead of SID for URL
- *
- * @param bool $var
- * @return $this
- */
- public function setUseSessionVar($var)
- {
- $this->_useSessionVar = (bool) $var;
- return $this;
+ $this->_websites[$website->getId()] = $website;
+ $this->_websites[$website->getCode()] = $website;
+ }
}
/**
- * Retrieve use flag session var instead of SID for URL
+ * Retrieve store code or null by store group
*
- * @return bool
+ * @param int $group
+ * @return string|null
*/
- public function getUseSessionVar()
+ protected function _getStoreByGroup($group)
{
- return $this->_useSessionVar;
+ if (!isset($this->_groups[$group])) {
+ return null;
+ }
+ if (!$this->_groups[$group]->getDefaultStoreId()) {
+ return null;
+ }
+ return $this->_stores[$this->_groups[$group]->getDefaultStoreId()]->getCode();
}
/**
- * Get either default or any store view
+ * Retrieve store code or null by website
*
- * @return Mage_Core_Model_Store|void
+ * @param int|string $website
+ * @return string|null
*/
- public function getAnyStoreView()
+ protected function _getStoreByWebsite($website)
{
- $store = $this->getDefaultStoreView();
- if ($store) {
- return $store;
+ if (!isset($this->_websites[$website])) {
+ return null;
}
- foreach ($this->getStores() as $store) {
- return $store;
+ if (!$this->_websites[$website]->getDefaultGroupId()) {
+ return null;
}
+ return $this->_getStoreByGroup($this->_websites[$website]->getDefaultGroupId());
}
/**
- * Set Use session in URL flag
+ * Initialize application front controller
*
- * @param bool $flag
* @return $this
*/
- public function setUseSessionInUrl($flag = true)
+ protected function _initFrontController()
{
- $this->_useSessionInUrl = (bool) $flag;
+ $this->_frontController = new Mage_Core_Controller_Varien_Front();
+ Mage::register('controller', $this->_frontController);
+ Varien_Profiler::start('mage::app::init_front_controller');
+ $this->_frontController->init();
+ Varien_Profiler::stop('mage::app::init_front_controller');
return $this;
}
/**
- * Retrieve use session in URL flag
- *
- * @return bool
+ * @return Mage_Core_Model_Store
*/
- public function getUseSessionInUrl()
+ protected function _getDefaultStore()
{
- return $this->_useSessionInUrl;
+ if (empty($this->_store)) {
+ $this->_store = Mage::getModel('core/store')
+ ->setId(self::DISTRO_STORE_ID)
+ ->setCode(self::DISTRO_STORE_CODE);
+ }
+ return $this->_store;
}
/**
- * Allow or disallow single store mode
+ * Performs non-existent observer method calls protection
*
- * @param bool $value
+ * @param object $object
+ * @param string $method
+ * @param Varien_Event_Observer $observer
+ * @param string $observerName
* @return $this
+ * @throws Mage_Core_Exception
*/
- public function setIsSingleStoreModeAllowed($value)
- {
- $this->_isSingleStoreAllowed = (bool) $value;
- return $this;
- }
-
- /**
- * Prepare array of store groups
- * can be filtered to contain default store group or not by $withDefault flag
- * depending on flag $codeKey array keys can be group id or group code
- *
- * @param bool $withDefault
- * @param bool $codeKey
- * @return Mage_Core_Model_Store_Group[]
- */
- public function getGroups($withDefault = false, $codeKey = false)
+ protected function _callObserverMethod($object, $method, $observer, $observerName = 'undefined')
{
- $groups = [];
- if (is_array($this->_groups)) {
- foreach ($this->_groups as $group) {
- if (!$withDefault && $group->getId() == 0) {
- continue;
- }
- if ($codeKey) {
- $groups[$group->getCode()] = $group;
- } else {
- $groups[$group->getId()] = $group;
- }
+ if (is_object($object) && method_exists($object, $method)) {
+ $object->$method($observer);
+ } elseif (Mage::getIsDeveloperMode()) {
+ if (is_object($object)) {
+ $message = 'Method "' . $method . '" is not defined in "' . get_class($object) . '"';
+ } else {
+ $message = 'Class from observer "' . $observerName . '" is not initialized';
}
- }
- return $groups;
- }
-
- /**
- * Retrieve application installation flag
- *
- * @deprecated since 1.2
- * @return bool
- */
- public function isInstalled()
- {
- return Mage::isInstalled();
+ Mage::throwException($message);
+ }
+ return $this;
}
/**
@@ -1609,17 +1666,6 @@ protected function _getCacheTags($tags = [])
return $tags;
}
- /**
- * Get file name with cache configuration settings
- *
- * @deprecated after 1.4.0.0-alpha3, functionality implemented in Mage_Core_Model_Cache
- * @return string
- */
- public function getUseCacheFilename()
- {
- return $this->_config->getOptions()->getEtcDir() . DS . 'use_cache.ser';
- }
-
/**
* Generate cache id with application specific data
*
@@ -1634,50 +1680,4 @@ protected function _getCacheId($id = null)
}
return $id;
}
-
- /**
- * Prepare identifier which can be used as cache id or cache tag
- *
- * @deprecated after 1.4.0.0-alpha3, functionality implemented in Mage_Core_Model_Cache
- * @param string $id
- * @return string
- */
- public function prepareCacheId($id)
- {
- $id = strtoupper($id);
- return preg_replace('/([^a-zA-Z0-9_]{1,1})/', '_', $id);
- }
-
- /**
- * Get is cache locked
- *
- * @return bool
- */
- public function getIsCacheLocked()
- {
- return (bool) $this->_isCacheLocked;
- }
-
- /**
- * Unset website by id from app cache
- *
- * @param null|bool|int|string|Mage_Core_Model_Website $id
- */
- public function clearWebsiteCache($id = null)
- {
- if (is_null($id)) {
- $id = $this->getStore()->getWebsiteId();
- } elseif ($id instanceof Mage_Core_Model_Website) {
- $id = $id->getId();
- } elseif ($id === true) {
- $id = $this->_website->getId();
- }
-
- if (!empty($this->_websites[$id])) {
- $website = $this->_websites[$id];
-
- unset($this->_websites[$website->getWebsiteId()]);
- unset($this->_websites[$website->getCode()]);
- }
- }
}
diff --git a/app/code/core/Mage/Core/Model/Cache.php b/app/code/core/Mage/Core/Model/Cache.php
index b16b49f1417..2085b063c61 100644
--- a/app/code/core/Mage/Core/Model/Cache.php
+++ b/app/code/core/Mage/Core/Model/Cache.php
@@ -140,207 +140,6 @@ public function __construct(array $options = [])
}
}
- /**
- * Get cache backend options. Result array contain backend type ('type' key) and backend options ('options')
- *
- * @return array
- */
- protected function _getBackendOptions(array $cacheOptions)
- {
- $enable2levels = false;
- $type = $cacheOptions['backend'] ?? $this->_defaultBackend;
- if (isset($cacheOptions['backend_options']) && is_array($cacheOptions['backend_options'])) {
- $options = $cacheOptions['backend_options'];
- } else {
- $options = [];
- }
-
- $backendType = false;
- switch (strtolower($type)) {
- case 'sqlite':
- if (extension_loaded('sqlite') && isset($options['cache_db_complete_path'])) {
- $backendType = 'Sqlite';
- }
- break;
- case 'memcached':
- if (extension_loaded('memcached')) {
- if (isset($cacheOptions['memcached'])) {
- $options = $cacheOptions['memcached'];
- }
- $enable2levels = true;
- $backendType = 'Libmemcached';
- } elseif (extension_loaded('memcache')) {
- if (isset($cacheOptions['memcached'])) {
- $options = $cacheOptions['memcached'];
- }
- $enable2levels = true;
- $backendType = 'Memcached';
- }
- break;
- case 'apc':
- if (extension_loaded('apcu') && ini_get('apc.enabled')) {
- $enable2levels = true;
- $backendType = 'Apc';
- }
- break;
- case 'xcache':
- if (extension_loaded('xcache')) {
- $enable2levels = true;
- $backendType = 'Xcache';
- }
- break;
- case 'varien_cache_backend_database':
- case 'database':
- $backendType = 'Varien_Cache_Backend_Database';
- $options = $this->getDbAdapterOptions($options);
- break;
- default:
- if ($type != $this->_defaultBackend) {
- try {
- if (class_exists($type, true)) {
- $implements = class_implements($type, true);
- if (in_array('Zend_Cache_Backend_Interface', $implements)) {
- $backendType = $type;
- if (isset($options['enable_two_levels'])) {
- $enable2levels = true;
- }
- }
- }
- } catch (Exception $e) {
- }
- }
- }
-
- if (!$backendType) {
- $backendType = $this->_defaultBackend;
- foreach ($this->_defaultBackendOptions as $option => $value) {
- if (!array_key_exists($option, $options)) {
- $options[$option] = $value;
- }
- }
- }
-
- $backendOptions = ['type' => $backendType, 'options' => $options];
- if ($enable2levels) {
- $backendOptions = $this->_getTwoLevelsBackendOptions($backendOptions, $cacheOptions);
- }
- return $backendOptions;
- }
-
- /**
- * Get options for database backend type
- *
- * @return array
- */
- protected function getDbAdapterOptions(array $options = [])
- {
- if (isset($options['connection'])) {
- $this->_dbConnection = $options['connection'];
- }
-
- $options['adapter_callback'] = [$this, 'getDbAdapter'];
- $options['data_table'] = Mage::getSingleton('core/resource')->getTableName('core/cache');
- $options['tags_table'] = Mage::getSingleton('core/resource')->getTableName('core/cache_tag');
- return $options;
- }
-
- /**
- * Initialize two levels backend model options
- *
- * @param array $fastOptions fast level backend type and options
- * @param array $cacheOptions all cache options
- * @return array
- */
- protected function _getTwoLevelsBackendOptions($fastOptions, $cacheOptions)
- {
- $options = [];
- $options['fast_backend'] = $fastOptions['type'];
- $options['fast_backend_options'] = $fastOptions['options'];
- $options['fast_backend_custom_naming'] = true;
- $options['fast_backend_autoload'] = true;
- $options['slow_backend_custom_naming'] = true;
- $options['slow_backend_autoload'] = true;
-
- if (isset($cacheOptions['auto_refresh_fast_cache'])) {
- $options['auto_refresh_fast_cache'] = (bool) $cacheOptions['auto_refresh_fast_cache'];
- } else {
- $options['auto_refresh_fast_cache'] = false;
- }
- if (isset($cacheOptions['slow_backend'])) {
- $options['slow_backend'] = $cacheOptions['slow_backend'];
- } else {
- $options['slow_backend'] = $this->_defaultBackend;
- }
- if (isset($cacheOptions['slow_backend_options'])) {
- $options['slow_backend_options'] = $cacheOptions['slow_backend_options'];
- } else {
- $options['slow_backend_options'] = $this->_defaultBackendOptions;
- }
- if ($options['slow_backend'] == 'database') {
- $options['slow_backend'] = 'Varien_Cache_Backend_Database';
- $options['slow_backend_options'] = $this->getDbAdapterOptions($options['slow_backend_options']);
- if (isset($cacheOptions['slow_backend_store_data'])) {
- $options['slow_backend_options']['store_data'] = (bool) $cacheOptions['slow_backend_store_data'];
- } else {
- $options['slow_backend_options']['store_data'] = false;
- }
- }
-
- return [
- 'type' => 'TwoLevels',
- 'options' => $options,
- ];
- }
-
- /**
- * Get options of cache frontend (options of Zend_Cache_Core)
- *
- * @return array
- */
- protected function _getFrontendOptions(array $cacheOptions)
- {
- $options = $cacheOptions['frontend_options'] ?? [];
- if (!array_key_exists('caching', $options)) {
- $options['caching'] = true;
- }
- if (!array_key_exists('lifetime', $options)) {
- $options['lifetime'] = $cacheOptions['lifetime'] ?? self::DEFAULT_LIFETIME;
- }
- if (!array_key_exists('automatic_cleaning_factor', $options)) {
- $options['automatic_cleaning_factor'] = 0;
- }
- $options['cache_id_prefix'] = $this->_idPrefix;
- return $options;
- }
-
- /**
- * Prepare unified valid identifier with prefix
- *
- * @param string $id
- * @return string
- */
- protected function _id($id)
- {
- if ($id) {
- $id = strtoupper($id);
- }
- return $id;
- }
-
- /**
- * Prepare cache tags.
- *
- * @param array $tags
- * @return array
- */
- protected function _tags($tags = [])
- {
- foreach ($tags as $key => $value) {
- $tags[$key] = $this->_id($value);
- }
- return $tags;
- }
-
/**
* Get cache frontend API object
*
@@ -441,45 +240,6 @@ public function getDbAdapter()
return Mage::getSingleton('core/resource')->getConnection($this->_dbConnection);
}
- /**
- * Get cache resource model
- *
- * @return Mage_Core_Model_Resource_Cache
- */
- protected function _getResource()
- {
- return Mage::getResourceSingleton('core/cache');
- }
-
- /**
- * Initialize cache types options
- *
- * @return $this
- */
- protected function _initOptions()
- {
- $options = $this->load(self::OPTIONS_CACHE_ID);
- if ($options === false) {
- $options = $this->_getResource()->getAllOptions();
- if (is_array($options)) {
- $this->_allowedCacheOptions = $options;
- $this->save(serialize($this->_allowedCacheOptions), self::OPTIONS_CACHE_ID);
- } else {
- $this->_allowedCacheOptions = [];
- }
- } else {
- $this->_allowedCacheOptions = unserialize($options, ['allowed_classes' => false]);
- }
-
- if (Mage::getConfig()->getOptions()->getData('global_ban_use_cache')) {
- foreach ($this->_allowedCacheOptions as $key => $val) {
- $this->_allowedCacheOptions[$key] = false;
- }
- }
-
- return $this;
- }
-
/**
* Save cache usage options
*
@@ -583,49 +343,21 @@ public function getTypes()
}
/**
- * Get invalidate types codes
+ * Get array of all invalidated cache types
*
* @return array
*/
- protected function _getInvalidatedTypes()
+ public function getInvalidatedTypes()
{
- $types = $this->load(self::INVALIDATED_TYPES);
+ $invalidatedTypes = [];
+ $types = $this->_getInvalidatedTypes();
if ($types) {
- $types = unserialize($types, ['allowed_classes' => false]);
- } else {
- $types = [];
- }
- return $types;
- }
-
- /**
- * Save invalidated cache types
- *
- * @param array $types
- * @return $this
- */
- protected function _saveInvalidatedTypes($types)
- {
- $this->save(serialize($types), self::INVALIDATED_TYPES);
- return $this;
- }
-
- /**
- * Get array of all invalidated cache types
- *
- * @return array
- */
- public function getInvalidatedTypes()
- {
- $invalidatedTypes = [];
- $types = $this->_getInvalidatedTypes();
- if ($types) {
- $allTypes = $this->getTypes();
- foreach (array_keys($types) as $type) {
- if (isset($allTypes[$type]) && $this->canUse($type)) {
- $invalidatedTypes[$type] = $allTypes[$type];
- }
- }
+ $allTypes = $this->getTypes();
+ foreach (array_keys($types) as $type) {
+ if (isset($allTypes[$type]) && $this->canUse($type)) {
+ $invalidatedTypes[$type] = $allTypes[$type];
+ }
+ }
}
return $invalidatedTypes;
}
@@ -692,6 +424,274 @@ public function processRequest()
return false;
}
+ /**
+ * Get cache backend options. Result array contain backend type ('type' key) and backend options ('options')
+ *
+ * @return array
+ */
+ protected function _getBackendOptions(array $cacheOptions)
+ {
+ $enable2levels = false;
+ $type = $cacheOptions['backend'] ?? $this->_defaultBackend;
+ if (isset($cacheOptions['backend_options']) && is_array($cacheOptions['backend_options'])) {
+ $options = $cacheOptions['backend_options'];
+ } else {
+ $options = [];
+ }
+
+ $backendType = false;
+ switch (strtolower($type)) {
+ case 'sqlite':
+ if (extension_loaded('sqlite') && isset($options['cache_db_complete_path'])) {
+ $backendType = 'Sqlite';
+ }
+ break;
+ case 'memcached':
+ if (extension_loaded('memcached')) {
+ if (isset($cacheOptions['memcached'])) {
+ $options = $cacheOptions['memcached'];
+ }
+ $enable2levels = true;
+ $backendType = 'Libmemcached';
+ } elseif (extension_loaded('memcache')) {
+ if (isset($cacheOptions['memcached'])) {
+ $options = $cacheOptions['memcached'];
+ }
+ $enable2levels = true;
+ $backendType = 'Memcached';
+ }
+ break;
+ case 'apc':
+ if (extension_loaded('apcu') && ini_get('apc.enabled')) {
+ $enable2levels = true;
+ $backendType = 'Apc';
+ }
+ break;
+ case 'xcache':
+ if (extension_loaded('xcache')) {
+ $enable2levels = true;
+ $backendType = 'Xcache';
+ }
+ break;
+ case 'varien_cache_backend_database':
+ case 'database':
+ $backendType = 'Varien_Cache_Backend_Database';
+ $options = $this->getDbAdapterOptions($options);
+ break;
+ default:
+ if ($type != $this->_defaultBackend) {
+ try {
+ if (class_exists($type, true)) {
+ $implements = class_implements($type, true);
+ if (in_array('Zend_Cache_Backend_Interface', $implements)) {
+ $backendType = $type;
+ if (isset($options['enable_two_levels'])) {
+ $enable2levels = true;
+ }
+ }
+ }
+ } catch (Exception $e) {
+ }
+ }
+ }
+
+ if (!$backendType) {
+ $backendType = $this->_defaultBackend;
+ foreach ($this->_defaultBackendOptions as $option => $value) {
+ if (!array_key_exists($option, $options)) {
+ $options[$option] = $value;
+ }
+ }
+ }
+
+ $backendOptions = ['type' => $backendType, 'options' => $options];
+ if ($enable2levels) {
+ $backendOptions = $this->_getTwoLevelsBackendOptions($backendOptions, $cacheOptions);
+ }
+ return $backendOptions;
+ }
+
+ /**
+ * Get options for database backend type
+ *
+ * @return array
+ */
+ protected function getDbAdapterOptions(array $options = [])
+ {
+ if (isset($options['connection'])) {
+ $this->_dbConnection = $options['connection'];
+ }
+
+ $options['adapter_callback'] = [$this, 'getDbAdapter'];
+ $options['data_table'] = Mage::getSingleton('core/resource')->getTableName('core/cache');
+ $options['tags_table'] = Mage::getSingleton('core/resource')->getTableName('core/cache_tag');
+ return $options;
+ }
+
+ /**
+ * Initialize two levels backend model options
+ *
+ * @param array $fastOptions fast level backend type and options
+ * @param array $cacheOptions all cache options
+ * @return array
+ */
+ protected function _getTwoLevelsBackendOptions($fastOptions, $cacheOptions)
+ {
+ $options = [];
+ $options['fast_backend'] = $fastOptions['type'];
+ $options['fast_backend_options'] = $fastOptions['options'];
+ $options['fast_backend_custom_naming'] = true;
+ $options['fast_backend_autoload'] = true;
+ $options['slow_backend_custom_naming'] = true;
+ $options['slow_backend_autoload'] = true;
+
+ if (isset($cacheOptions['auto_refresh_fast_cache'])) {
+ $options['auto_refresh_fast_cache'] = (bool) $cacheOptions['auto_refresh_fast_cache'];
+ } else {
+ $options['auto_refresh_fast_cache'] = false;
+ }
+ if (isset($cacheOptions['slow_backend'])) {
+ $options['slow_backend'] = $cacheOptions['slow_backend'];
+ } else {
+ $options['slow_backend'] = $this->_defaultBackend;
+ }
+ if (isset($cacheOptions['slow_backend_options'])) {
+ $options['slow_backend_options'] = $cacheOptions['slow_backend_options'];
+ } else {
+ $options['slow_backend_options'] = $this->_defaultBackendOptions;
+ }
+ if ($options['slow_backend'] == 'database') {
+ $options['slow_backend'] = 'Varien_Cache_Backend_Database';
+ $options['slow_backend_options'] = $this->getDbAdapterOptions($options['slow_backend_options']);
+ if (isset($cacheOptions['slow_backend_store_data'])) {
+ $options['slow_backend_options']['store_data'] = (bool) $cacheOptions['slow_backend_store_data'];
+ } else {
+ $options['slow_backend_options']['store_data'] = false;
+ }
+ }
+
+ return [
+ 'type' => 'TwoLevels',
+ 'options' => $options,
+ ];
+ }
+
+ /**
+ * Get options of cache frontend (options of Zend_Cache_Core)
+ *
+ * @return array
+ */
+ protected function _getFrontendOptions(array $cacheOptions)
+ {
+ $options = $cacheOptions['frontend_options'] ?? [];
+ if (!array_key_exists('caching', $options)) {
+ $options['caching'] = true;
+ }
+ if (!array_key_exists('lifetime', $options)) {
+ $options['lifetime'] = $cacheOptions['lifetime'] ?? self::DEFAULT_LIFETIME;
+ }
+ if (!array_key_exists('automatic_cleaning_factor', $options)) {
+ $options['automatic_cleaning_factor'] = 0;
+ }
+ $options['cache_id_prefix'] = $this->_idPrefix;
+ return $options;
+ }
+
+ /**
+ * Prepare unified valid identifier with prefix
+ *
+ * @param string $id
+ * @return string
+ */
+ protected function _id($id)
+ {
+ if ($id) {
+ $id = strtoupper($id);
+ }
+ return $id;
+ }
+
+ /**
+ * Prepare cache tags.
+ *
+ * @param array $tags
+ * @return array
+ */
+ protected function _tags($tags = [])
+ {
+ foreach ($tags as $key => $value) {
+ $tags[$key] = $this->_id($value);
+ }
+ return $tags;
+ }
+
+ /**
+ * Get cache resource model
+ *
+ * @return Mage_Core_Model_Resource_Cache
+ */
+ protected function _getResource()
+ {
+ return Mage::getResourceSingleton('core/cache');
+ }
+
+ /**
+ * Initialize cache types options
+ *
+ * @return $this
+ */
+ protected function _initOptions()
+ {
+ $options = $this->load(self::OPTIONS_CACHE_ID);
+ if ($options === false) {
+ $options = $this->_getResource()->getAllOptions();
+ if (is_array($options)) {
+ $this->_allowedCacheOptions = $options;
+ $this->save(serialize($this->_allowedCacheOptions), self::OPTIONS_CACHE_ID);
+ } else {
+ $this->_allowedCacheOptions = [];
+ }
+ } else {
+ $this->_allowedCacheOptions = unserialize($options, ['allowed_classes' => false]);
+ }
+
+ if (Mage::getConfig()->getOptions()->getData('global_ban_use_cache')) {
+ foreach ($this->_allowedCacheOptions as $key => $val) {
+ $this->_allowedCacheOptions[$key] = false;
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get invalidate types codes
+ *
+ * @return array
+ */
+ protected function _getInvalidatedTypes()
+ {
+ $types = $this->load(self::INVALIDATED_TYPES);
+ if ($types) {
+ $types = unserialize($types, ['allowed_classes' => false]);
+ } else {
+ $types = [];
+ }
+ return $types;
+ }
+
+ /**
+ * Save invalidated cache types
+ *
+ * @param array $types
+ * @return $this
+ */
+ protected function _saveInvalidatedTypes($types)
+ {
+ $this->save(serialize($types), self::INVALIDATED_TYPES);
+ return $this;
+ }
+
/**
* Get request processor object
* @param string $processor
diff --git a/app/code/core/Mage/Core/Model/Config.php b/app/code/core/Mage/Core/Model/Config.php
index f88d34aa119..acc56463348 100644
--- a/app/code/core/Mage/Core/Model/Config.php
+++ b/app/code/core/Mage/Core/Model/Config.php
@@ -236,13 +236,6 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
*/
protected $_canUseLocalModules = null;
- /**
- * Active modules array per namespace
- * @var array
- */
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private $_moduleNamespaces = null;
-
/**
* Modules allowed to load
* If empty - all modules are allowed
@@ -251,6 +244,13 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
*/
protected $_allowedModules = [];
+ /**
+ * Active modules array per namespace
+ * @var array
+ */
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private $_moduleNamespaces = null;
+
/**
* Class construct
*
@@ -453,51 +453,6 @@ public function reinit($options = [])
return $this->init($options);
}
- /**
- * Check local modules enable/disable flag
- * If local modules are disabled remove local modules path from include dirs
- *
- * return true if local modules enabled and false if disabled
- *
- * @return bool
- */
- protected function _canUseLocalModules()
- {
- if ($this->_canUseLocalModules !== null) {
- return $this->_canUseLocalModules;
- }
-
- $disableLocalModules = (string) $this->getNode('global/disable_local_modules');
- if (!empty($disableLocalModules)) {
- $disableLocalModules = (($disableLocalModules === 'true') || ($disableLocalModules === '1'));
- } else {
- $disableLocalModules = false;
- }
-
- if ($disableLocalModules === true) {
- set_include_path(
- BP . DS . 'app' . DS . 'code' . DS . 'community' . PS .
- BP . DS . 'app' . DS . 'code' . DS . 'core' . PS .
- BP . DS . 'lib' . PS .
- Mage::registry('original_include_path'),
- );
- }
- $this->_canUseLocalModules = !$disableLocalModules;
- return $this->_canUseLocalModules;
- }
-
- /**
- * Check if cache can be used for config initialization
- *
- * @return bool
- */
- protected function _canUseCacheForInit()
- {
- return $this->_allowCacheForInit
- && Mage::isInstalled(['etc_dir' => $this->getOptions()->getEtcDir()])
- && Mage::app()->useCache('config');
- }
-
/**
* Retrieve cache object
*
@@ -588,95 +543,6 @@ public function saveCache($tags = [])
return $this;
}
- /**
- * Save cache of specified
- *
- * @param string $idPrefix cache id prefix
- * @param string $sectionName
- * @param Varien_Simplexml_Element $source
- * @param int $recursionLevel
- * @param array $tags
- * @return Mage_Core_Model_Config
- */
- protected function _saveSectionCache($idPrefix, $sectionName, $source, $recursionLevel = 0, $tags = [])
- {
- if ($source && $source->$sectionName) {
- $cacheId = $idPrefix . '_' . $sectionName;
- if ($recursionLevel > 0) {
- foreach ($source->$sectionName->children() as $subSectionName => $node) {
- $this->_saveSectionCache(
- $cacheId,
- $subSectionName,
- $source->$sectionName,
- $recursionLevel - 1,
- $tags,
- );
- }
- }
- $this->_cachePartsForSave[$cacheId] = $source->$sectionName->asNiceXml('', false);
- }
- return $this;
- }
-
- /**
- * Load config section cached data
- *
- * @param string $sectionName
- * @return false|SimpleXMLElement
- */
- protected function _loadSectionCache($sectionName)
- {
- $cacheId = $this->getCacheId() . '_' . $sectionName;
- $xmlString = $this->_loadCache($cacheId);
-
- /**
- * If we can't load section cache (problems with cache storage)
- */
- if (!$xmlString) {
- $this->_useCache = false;
- $this->reinit($this->_options);
- return false;
- } else {
- return simplexml_load_string($xmlString, $this->_elementClass);
- }
- }
-
- /**
- * Load cached data by identifier
- *
- * @param string $id
- * @return string
- */
- protected function _loadCache($id)
- {
- return Mage::app()->loadCache($id);
- }
-
- /**
- * Save cache data
- *
- * @param string $data
- * @param string $id
- * @param array $tags
- * @param false|int $lifetime
- * @return Mage_Core_Model_App
- */
- protected function _saveCache($data, $id, $tags = [], $lifetime = false)
- {
- return Mage::app()->saveCache($data, $id, $tags, $lifetime);
- }
-
- /**
- * Clear cache data by id
- *
- * @param string $id
- * @return Mage_Core_Model_App
- */
- protected function _removeCache($id)
- {
- return Mage::app()->removeCache($id);
- }
-
/**
* Remove configuration cache
*
@@ -698,29 +564,6 @@ public function cleanCache()
return $this->reinit();
}
- /**
- * Getter for section configuration object
- *
- * @param array $path
- * @return false|Mage_Core_Model_Config_Element
- */
- protected function _getSectionConfig($path)
- {
- $section = $path[0];
- if (!isset($this->_cacheSections[$section])) {
- return false;
- }
- $sectionPath = array_slice($path, 0, $this->_cacheSections[$section] + 1);
- $sectionKey = implode('_', $sectionPath);
-
- if (!isset($this->_cacheLoadedSections[$sectionKey])) {
- Varien_Profiler::start('init_config_section:' . $sectionKey);
- $this->_cacheLoadedSections[$sectionKey] = $this->_loadSectionCache($sectionKey);
- Varien_Profiler::stop('init_config_section:' . $sectionKey);
- }
- return $this->_cacheLoadedSections[$sectionKey];
- }
-
/**
* Get node value from cached section data
*
@@ -800,44 +643,6 @@ public function setNode($path, $value, $overwrite = true)
return parent::setNode($path, $value, $overwrite);
}
- /**
- * Retrieve Declared Module file list
- *
- * @return array|false
- */
- protected function _getDeclaredModuleFiles()
- {
- $etcDir = $this->getOptions()->getEtcDir();
- $moduleFiles = glob($etcDir . DS . 'modules' . DS . '*.xml');
-
- if (!$moduleFiles) {
- return false;
- }
-
- $collectModuleFiles = [
- 'mage' => [],
- 'custom' => [],
- ];
-
- foreach ($moduleFiles as $v) {
- $name = explode(DIRECTORY_SEPARATOR, $v);
- $name = substr($name[count($name) - 1], 0, -4);
-
- if (array_key_exists($name, self::MAGE_MODULES)) {
- $collectModuleFiles['mage'][self::MAGE_MODULES[$name]] = $v;
- } else {
- $collectModuleFiles['custom'][] = $v;
- }
- }
-
- ksort($collectModuleFiles['mage']);
-
- return array_merge(
- $collectModuleFiles['mage'],
- $collectModuleFiles['custom'],
- );
- }
-
/**
* Add module(s) to allowed list
*
@@ -858,182 +663,47 @@ public function addAllowedModules($module)
}
/**
- * Define if module is allowed
+ * Determine whether provided name begins from any available modules, according to namespaces priority
+ * If matched, returns as the matched module "factory" name or a fully qualified module name
*
- * @param string $moduleName
- * @return bool
+ * @param string $name
+ * @param bool $asFullModuleName
+ * @return string
*/
- protected function _isAllowedModule($moduleName)
+ public function determineOmittedNamespace($name, $asFullModuleName = false)
{
- if (empty($this->_allowedModules)) {
- return true;
- } else {
- return in_array($moduleName, $this->_allowedModules);
+ if ($this->_moduleNamespaces === null) {
+ $this->_moduleNamespaces = [];
+ foreach ($this->_xml->xpath('modules/*') as $m) {
+ if ((string) $m->active == 'true') {
+ $moduleName = $m->getName();
+ $module = strtolower($moduleName);
+ $this->_moduleNamespaces[substr($module, 0, strpos($module, '_'))][$module] = $moduleName;
+ }
+ }
+ }
+
+ $name = explode('_', strtolower($name));
+ $partsNum = count($name);
+ $defaultNamespaceFlag = false;
+ foreach ($this->_moduleNamespaces as $namespaceName => $namespace) {
+ // assume the namespace is omitted (default namespace only, which comes first)
+ if ($defaultNamespaceFlag === false) {
+ $defaultNamespaceFlag = true;
+ $defaultNS = $namespaceName . '_' . $name[0];
+ if (isset($namespace[$defaultNS])) {
+ return $asFullModuleName ? $namespace[$defaultNS] : $name[0]; // return omitted as well
+ }
+ }
+ // assume namespace is qualified
+ if (isset($name[1])) {
+ $fullNS = $name[0] . '_' . $name[1];
+ if (2 <= $partsNum && isset($namespace[$fullNS])) {
+ return $asFullModuleName ? $namespace[$fullNS] : $fullNS;
+ }
+ }
}
- }
-
- /**
- * Load declared modules configuration
- *
- * @param null $mergeConfig deprecated
- * @return $this|void
- */
- protected function _loadDeclaredModules($mergeConfig = null)
- {
- $moduleFiles = $this->_getDeclaredModuleFiles();
- if (!$moduleFiles) {
- return ;
- }
-
- Varien_Profiler::start('config/load-modules-declaration');
-
- $unsortedConfig = new Mage_Core_Model_Config_Base();
- $unsortedConfig->loadString('');
- $fileConfig = new Mage_Core_Model_Config_Base();
-
- // load modules declarations
- foreach ($moduleFiles as $file) {
- $fileConfig->loadFile($file);
- $unsortedConfig->extend($fileConfig);
- }
-
- $moduleDepends = [];
- foreach ($unsortedConfig->getNode('modules')->children() as $moduleName => $moduleNode) {
- if (!$this->_isAllowedModule($moduleName)) {
- continue;
- }
-
- $depends = [];
- if ($moduleNode->depends) {
- foreach ($moduleNode->depends->children() as $depend) {
- $depends[$depend->getName()] = true;
- }
- }
- $moduleDepends[$moduleName] = [
- 'module' => $moduleName,
- 'depends' => $depends,
- 'active' => (string) $moduleNode->active === 'true',
- ];
- }
-
- // check and sort module dependence
- $moduleDepends = $this->_sortModuleDepends($moduleDepends);
-
- // create sorted config
- $sortedConfig = new Mage_Core_Model_Config_Base();
- $sortedConfig->loadString('');
-
- foreach ($unsortedConfig->getNode()->children() as $nodeName => $node) {
- if ($nodeName != 'modules') {
- $sortedConfig->getNode()->appendChild($node);
- }
- }
-
- foreach ($moduleDepends as $moduleProp) {
- $node = $unsortedConfig->getNode('modules/' . $moduleProp['module']);
- $sortedConfig->getNode('modules')->appendChild($node);
- }
-
- $this->extend($sortedConfig);
-
- Varien_Profiler::stop('config/load-modules-declaration');
- return $this;
- }
-
- /**
- * Sort modules and check depends
- *
- * @param array $modules
- * @return array
- */
- protected function _sortModuleDepends($modules)
- {
- foreach ($modules as $moduleName => $moduleProps) {
- if ($moduleProps['active']) {
- $depends = $moduleProps['depends'];
- foreach ($moduleProps['depends'] as $depend => $true) {
- if (!isset($modules[$depend]) || empty($modules[$depend]['active'])) {
- Mage::throwException(
- Mage::helper('core')->__('Module "%1$s" requires module "%2$s".', $moduleName, $depend),
- );
- }
- $depends = array_merge($depends, $modules[$depend]['depends']);
- }
- $modules[$moduleName]['depends'] = $depends;
- }
- }
- $modules = array_values($modules);
-
- $size = count($modules) - 1;
- for ($i = $size; $i >= 0; $i--) {
- for ($j = $size; $i < $j; $j--) {
- if (isset($modules[$i]['depends'][$modules[$j]['module']])) {
- $value = $modules[$i];
- $modules[$i] = $modules[$j];
- $modules[$j] = $value;
- }
- }
- }
-
- $definedModules = [];
- foreach ($modules as $moduleProp) {
- if ($moduleProp['active']) {
- foreach ($moduleProp['depends'] as $dependModule => $true) {
- if (!isset($definedModules[$dependModule])) {
- Mage::throwException(
- Mage::helper('core')->__('Module "%1$s" cannot depend on "%2$s".', $moduleProp['module'], $dependModule),
- );
- }
- }
- $definedModules[$moduleProp['module']] = true;
- }
- }
-
- return $modules;
- }
-
- /**
- * Determine whether provided name begins from any available modules, according to namespaces priority
- * If matched, returns as the matched module "factory" name or a fully qualified module name
- *
- * @param string $name
- * @param bool $asFullModuleName
- * @return string
- */
- public function determineOmittedNamespace($name, $asFullModuleName = false)
- {
- if ($this->_moduleNamespaces === null) {
- $this->_moduleNamespaces = [];
- foreach ($this->_xml->xpath('modules/*') as $m) {
- if ((string) $m->active == 'true') {
- $moduleName = $m->getName();
- $module = strtolower($moduleName);
- $this->_moduleNamespaces[substr($module, 0, strpos($module, '_'))][$module] = $moduleName;
- }
- }
- }
-
- $name = explode('_', strtolower($name));
- $partsNum = count($name);
- $defaultNamespaceFlag = false;
- foreach ($this->_moduleNamespaces as $namespaceName => $namespace) {
- // assume the namespace is omitted (default namespace only, which comes first)
- if ($defaultNamespaceFlag === false) {
- $defaultNamespaceFlag = true;
- $defaultNS = $namespaceName . '_' . $name[0];
- if (isset($namespace[$defaultNS])) {
- return $asFullModuleName ? $namespace[$defaultNS] : $name[0]; // return omitted as well
- }
- }
- // assume namespace is qualified
- if (isset($name[1])) {
- $fullNS = $name[0] . '_' . $name[1];
- if (2 <= $partsNum && isset($namespace[$fullNS])) {
- return $asFullModuleName ? $namespace[$fullNS] : $fullNS;
- }
- }
- }
- return '';
+ return '';
}
/**
@@ -1727,66 +1397,396 @@ public function getFieldset($name, $root = 'global')
}
/**
- * Retrieve resource connection model name
+ * Get a resource model class name
*
- * @param string $moduleName
- * @return string
+ * @param string $modelClass
+ * @return string|false
*/
- protected function _getResourceConnectionModel($moduleName = null)
+ public function getResourceModelClassName($modelClass)
{
- $config = null;
- if (!is_null($moduleName)) {
- $setupResource = $moduleName . '_setup';
- $config = $this->getResourceConnectionConfig($setupResource);
- }
- if (!$config) {
- $config = $this->getResourceConnectionConfig(Mage_Core_Model_Resource::DEFAULT_SETUP_RESOURCE);
+ $factoryName = $this->_getResourceModelFactoryClassName($modelClass);
+ if ($factoryName) {
+ return $this->getModelClassName($factoryName);
}
-
- return (string) $config->model;
+ return false;
}
/**
- * Get factory class name for a resource
+ * Check local modules enable/disable flag
+ * If local modules are disabled remove local modules path from include dirs
*
- * @param string $modelClass
- * @return string|false
+ * return true if local modules enabled and false if disabled
+ *
+ * @return bool
*/
- protected function _getResourceModelFactoryClassName($modelClass)
+ protected function _canUseLocalModules()
{
- $classArray = explode('/', $modelClass);
- if (count($classArray) != 2) {
- return false;
+ if ($this->_canUseLocalModules !== null) {
+ return $this->_canUseLocalModules;
}
- list($module, $model) = $classArray;
- if (!isset($this->_xml->global->models->{$module})) {
- return false;
+ $disableLocalModules = (string) $this->getNode('global/disable_local_modules');
+ if (!empty($disableLocalModules)) {
+ $disableLocalModules = (($disableLocalModules === 'true') || ($disableLocalModules === '1'));
+ } else {
+ $disableLocalModules = false;
}
- $moduleNode = $this->_xml->global->models->{$module};
- if (!empty($moduleNode->resourceModel)) {
- $resourceModel = (string) $moduleNode->resourceModel;
- } else {
- return false;
+ if ($disableLocalModules === true) {
+ set_include_path(
+ BP . DS . 'app' . DS . 'code' . DS . 'community' . PS .
+ BP . DS . 'app' . DS . 'code' . DS . 'core' . PS .
+ BP . DS . 'lib' . PS .
+ Mage::registry('original_include_path'),
+ );
}
+ $this->_canUseLocalModules = !$disableLocalModules;
+ return $this->_canUseLocalModules;
+ }
- return $resourceModel . '/' . $model;
+ /**
+ * Check if cache can be used for config initialization
+ *
+ * @return bool
+ */
+ protected function _canUseCacheForInit()
+ {
+ return $this->_allowCacheForInit
+ && Mage::isInstalled(['etc_dir' => $this->getOptions()->getEtcDir()])
+ && Mage::app()->useCache('config');
}
/**
- * Get a resource model class name
+ * Save cache of specified
*
- * @param string $modelClass
- * @return string|false
+ * @param string $idPrefix cache id prefix
+ * @param string $sectionName
+ * @param Varien_Simplexml_Element $source
+ * @param int $recursionLevel
+ * @param array $tags
+ * @return Mage_Core_Model_Config
*/
- public function getResourceModelClassName($modelClass)
+ protected function _saveSectionCache($idPrefix, $sectionName, $source, $recursionLevel = 0, $tags = [])
{
- $factoryName = $this->_getResourceModelFactoryClassName($modelClass);
- if ($factoryName) {
- return $this->getModelClassName($factoryName);
- }
- return false;
+ if ($source && $source->$sectionName) {
+ $cacheId = $idPrefix . '_' . $sectionName;
+ if ($recursionLevel > 0) {
+ foreach ($source->$sectionName->children() as $subSectionName => $node) {
+ $this->_saveSectionCache(
+ $cacheId,
+ $subSectionName,
+ $source->$sectionName,
+ $recursionLevel - 1,
+ $tags,
+ );
+ }
+ }
+ $this->_cachePartsForSave[$cacheId] = $source->$sectionName->asNiceXml('', false);
+ }
+ return $this;
+ }
+
+ /**
+ * Load config section cached data
+ *
+ * @param string $sectionName
+ * @return false|SimpleXMLElement
+ */
+ protected function _loadSectionCache($sectionName)
+ {
+ $cacheId = $this->getCacheId() . '_' . $sectionName;
+ $xmlString = $this->_loadCache($cacheId);
+
+ /**
+ * If we can't load section cache (problems with cache storage)
+ */
+ if (!$xmlString) {
+ $this->_useCache = false;
+ $this->reinit($this->_options);
+ return false;
+ } else {
+ return simplexml_load_string($xmlString, $this->_elementClass);
+ }
+ }
+
+ /**
+ * Load cached data by identifier
+ *
+ * @param string $id
+ * @return string
+ */
+ protected function _loadCache($id)
+ {
+ return Mage::app()->loadCache($id);
+ }
+
+ /**
+ * Save cache data
+ *
+ * @param string $data
+ * @param string $id
+ * @param array $tags
+ * @param false|int $lifetime
+ * @return Mage_Core_Model_App
+ */
+ protected function _saveCache($data, $id, $tags = [], $lifetime = false)
+ {
+ return Mage::app()->saveCache($data, $id, $tags, $lifetime);
+ }
+
+ /**
+ * Clear cache data by id
+ *
+ * @param string $id
+ * @return Mage_Core_Model_App
+ */
+ protected function _removeCache($id)
+ {
+ return Mage::app()->removeCache($id);
+ }
+
+ /**
+ * Getter for section configuration object
+ *
+ * @param array $path
+ * @return false|Mage_Core_Model_Config_Element
+ */
+ protected function _getSectionConfig($path)
+ {
+ $section = $path[0];
+ if (!isset($this->_cacheSections[$section])) {
+ return false;
+ }
+ $sectionPath = array_slice($path, 0, $this->_cacheSections[$section] + 1);
+ $sectionKey = implode('_', $sectionPath);
+
+ if (!isset($this->_cacheLoadedSections[$sectionKey])) {
+ Varien_Profiler::start('init_config_section:' . $sectionKey);
+ $this->_cacheLoadedSections[$sectionKey] = $this->_loadSectionCache($sectionKey);
+ Varien_Profiler::stop('init_config_section:' . $sectionKey);
+ }
+ return $this->_cacheLoadedSections[$sectionKey];
+ }
+
+ /**
+ * Retrieve Declared Module file list
+ *
+ * @return array|false
+ */
+ protected function _getDeclaredModuleFiles()
+ {
+ $etcDir = $this->getOptions()->getEtcDir();
+ $moduleFiles = glob($etcDir . DS . 'modules' . DS . '*.xml');
+
+ if (!$moduleFiles) {
+ return false;
+ }
+
+ $collectModuleFiles = [
+ 'mage' => [],
+ 'custom' => [],
+ ];
+
+ foreach ($moduleFiles as $v) {
+ $name = explode(DIRECTORY_SEPARATOR, $v);
+ $name = substr($name[count($name) - 1], 0, -4);
+
+ if (array_key_exists($name, self::MAGE_MODULES)) {
+ $collectModuleFiles['mage'][self::MAGE_MODULES[$name]] = $v;
+ } else {
+ $collectModuleFiles['custom'][] = $v;
+ }
+ }
+
+ ksort($collectModuleFiles['mage']);
+
+ return array_merge(
+ $collectModuleFiles['mage'],
+ $collectModuleFiles['custom'],
+ );
+ }
+
+ /**
+ * Define if module is allowed
+ *
+ * @param string $moduleName
+ * @return bool
+ */
+ protected function _isAllowedModule($moduleName)
+ {
+ if (empty($this->_allowedModules)) {
+ return true;
+ } else {
+ return in_array($moduleName, $this->_allowedModules);
+ }
+ }
+
+ /**
+ * Load declared modules configuration
+ *
+ * @param null $mergeConfig deprecated
+ * @return $this|void
+ */
+ protected function _loadDeclaredModules($mergeConfig = null)
+ {
+ $moduleFiles = $this->_getDeclaredModuleFiles();
+ if (!$moduleFiles) {
+ return ;
+ }
+
+ Varien_Profiler::start('config/load-modules-declaration');
+
+ $unsortedConfig = new Mage_Core_Model_Config_Base();
+ $unsortedConfig->loadString('');
+ $fileConfig = new Mage_Core_Model_Config_Base();
+
+ // load modules declarations
+ foreach ($moduleFiles as $file) {
+ $fileConfig->loadFile($file);
+ $unsortedConfig->extend($fileConfig);
+ }
+
+ $moduleDepends = [];
+ foreach ($unsortedConfig->getNode('modules')->children() as $moduleName => $moduleNode) {
+ if (!$this->_isAllowedModule($moduleName)) {
+ continue;
+ }
+
+ $depends = [];
+ if ($moduleNode->depends) {
+ foreach ($moduleNode->depends->children() as $depend) {
+ $depends[$depend->getName()] = true;
+ }
+ }
+ $moduleDepends[$moduleName] = [
+ 'module' => $moduleName,
+ 'depends' => $depends,
+ 'active' => (string) $moduleNode->active === 'true',
+ ];
+ }
+
+ // check and sort module dependence
+ $moduleDepends = $this->_sortModuleDepends($moduleDepends);
+
+ // create sorted config
+ $sortedConfig = new Mage_Core_Model_Config_Base();
+ $sortedConfig->loadString('');
+
+ foreach ($unsortedConfig->getNode()->children() as $nodeName => $node) {
+ if ($nodeName != 'modules') {
+ $sortedConfig->getNode()->appendChild($node);
+ }
+ }
+
+ foreach ($moduleDepends as $moduleProp) {
+ $node = $unsortedConfig->getNode('modules/' . $moduleProp['module']);
+ $sortedConfig->getNode('modules')->appendChild($node);
+ }
+
+ $this->extend($sortedConfig);
+
+ Varien_Profiler::stop('config/load-modules-declaration');
+ return $this;
+ }
+
+ /**
+ * Sort modules and check depends
+ *
+ * @param array $modules
+ * @return array
+ */
+ protected function _sortModuleDepends($modules)
+ {
+ foreach ($modules as $moduleName => $moduleProps) {
+ if ($moduleProps['active']) {
+ $depends = $moduleProps['depends'];
+ foreach ($moduleProps['depends'] as $depend => $true) {
+ if (!isset($modules[$depend]) || empty($modules[$depend]['active'])) {
+ Mage::throwException(
+ Mage::helper('core')->__('Module "%1$s" requires module "%2$s".', $moduleName, $depend),
+ );
+ }
+ $depends = array_merge($depends, $modules[$depend]['depends']);
+ }
+ $modules[$moduleName]['depends'] = $depends;
+ }
+ }
+ $modules = array_values($modules);
+
+ $size = count($modules) - 1;
+ for ($i = $size; $i >= 0; $i--) {
+ for ($j = $size; $i < $j; $j--) {
+ if (isset($modules[$i]['depends'][$modules[$j]['module']])) {
+ $value = $modules[$i];
+ $modules[$i] = $modules[$j];
+ $modules[$j] = $value;
+ }
+ }
+ }
+
+ $definedModules = [];
+ foreach ($modules as $moduleProp) {
+ if ($moduleProp['active']) {
+ foreach ($moduleProp['depends'] as $dependModule => $true) {
+ if (!isset($definedModules[$dependModule])) {
+ Mage::throwException(
+ Mage::helper('core')->__('Module "%1$s" cannot depend on "%2$s".', $moduleProp['module'], $dependModule),
+ );
+ }
+ }
+ $definedModules[$moduleProp['module']] = true;
+ }
+ }
+
+ return $modules;
+ }
+
+ /**
+ * Retrieve resource connection model name
+ *
+ * @param string $moduleName
+ * @return string
+ */
+ protected function _getResourceConnectionModel($moduleName = null)
+ {
+ $config = null;
+ if (!is_null($moduleName)) {
+ $setupResource = $moduleName . '_setup';
+ $config = $this->getResourceConnectionConfig($setupResource);
+ }
+ if (!$config) {
+ $config = $this->getResourceConnectionConfig(Mage_Core_Model_Resource::DEFAULT_SETUP_RESOURCE);
+ }
+
+ return (string) $config->model;
+ }
+
+ /**
+ * Get factory class name for a resource
+ *
+ * @param string $modelClass
+ * @return string|false
+ */
+ protected function _getResourceModelFactoryClassName($modelClass)
+ {
+ $classArray = explode('/', $modelClass);
+ if (count($classArray) != 2) {
+ return false;
+ }
+
+ list($module, $model) = $classArray;
+ if (!isset($this->_xml->global->models->{$module})) {
+ return false;
+ }
+
+ $moduleNode = $this->_xml->global->models->{$module};
+ if (!empty($moduleNode->resourceModel)) {
+ $resourceModel = (string) $moduleNode->resourceModel;
+ } else {
+ return false;
+ }
+
+ return $resourceModel . '/' . $model;
}
/**
diff --git a/app/code/core/Mage/Core/Model/Config/Data.php b/app/code/core/Mage/Core/Model/Config/Data.php
index 898a3218082..e076d9dc883 100644
--- a/app/code/core/Mage/Core/Model/Config/Data.php
+++ b/app/code/core/Mage/Core/Model/Config/Data.php
@@ -66,14 +66,6 @@ class Mage_Core_Model_Config_Data extends Mage_Core_Model_Abstract
*/
protected $_eventObject = 'config_data';
- /**
- * Varien model constructor
- */
- protected function _construct()
- {
- $this->_init('core/config_data');
- }
-
/**
* Add availability call after load as public
* @return $this
@@ -125,4 +117,12 @@ public function getFieldsetDataValue($key)
$data = $this->_getData('fieldset_data');
return (is_array($data) && isset($data[$key])) ? $data[$key] : null;
}
+
+ /**
+ * Varien model constructor
+ */
+ protected function _construct()
+ {
+ $this->_init('core/config_data');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Config/Options.php b/app/code/core/Mage/Core/Model/Config/Options.php
index 49c5556d447..8ffeba97178 100644
--- a/app/code/core/Mage/Core/Model/Config/Options.php
+++ b/app/code/core/Mage/Core/Model/Config/Options.php
@@ -35,32 +35,6 @@ class Mage_Core_Model_Config_Options extends Varien_Object
*/
protected $_dirExists = [];
- /**
- * Initialize default values of the options
- */
- protected function _construct()
- {
- $appRoot = Mage::getRoot();
- $root = dirname($appRoot);
-
- $this->_data['app_dir'] = $appRoot;
- $this->_data['base_dir'] = $root;
- $this->_data['code_dir'] = $appRoot . DS . 'code';
- $this->_data['design_dir'] = $appRoot . DS . 'design';
- $this->_data['etc_dir'] = $appRoot . DS . 'etc';
- $this->_data['lib_dir'] = $root . DS . 'lib';
- $this->_data['locale_dir'] = $appRoot . DS . 'locale';
- $this->_data['media_dir'] = $root . DS . 'media';
- $this->_data['skin_dir'] = $root . DS . 'skin';
- $this->_data['var_dir'] = $this->getVarDir();
- $this->_data['tmp_dir'] = $this->_data['var_dir'] . DS . 'tmp';
- $this->_data['cache_dir'] = $this->_data['var_dir'] . DS . 'cache';
- $this->_data['log_dir'] = $this->_data['var_dir'] . DS . 'log';
- $this->_data['session_dir'] = $this->_data['var_dir'] . DS . 'session';
- $this->_data['upload_dir'] = $this->_data['media_dir'] . DS . 'upload';
- $this->_data['export_dir'] = $this->_data['var_dir'] . DS . 'export';
- }
-
/**
* @param string $type
* @return mixed
@@ -282,4 +256,30 @@ public function createDirIfNotExists($dir)
$this->_dirExists[$dir] = true;
return true;
}
+
+ /**
+ * Initialize default values of the options
+ */
+ protected function _construct()
+ {
+ $appRoot = Mage::getRoot();
+ $root = dirname($appRoot);
+
+ $this->_data['app_dir'] = $appRoot;
+ $this->_data['base_dir'] = $root;
+ $this->_data['code_dir'] = $appRoot . DS . 'code';
+ $this->_data['design_dir'] = $appRoot . DS . 'design';
+ $this->_data['etc_dir'] = $appRoot . DS . 'etc';
+ $this->_data['lib_dir'] = $root . DS . 'lib';
+ $this->_data['locale_dir'] = $appRoot . DS . 'locale';
+ $this->_data['media_dir'] = $root . DS . 'media';
+ $this->_data['skin_dir'] = $root . DS . 'skin';
+ $this->_data['var_dir'] = $this->getVarDir();
+ $this->_data['tmp_dir'] = $this->_data['var_dir'] . DS . 'tmp';
+ $this->_data['cache_dir'] = $this->_data['var_dir'] . DS . 'cache';
+ $this->_data['log_dir'] = $this->_data['var_dir'] . DS . 'log';
+ $this->_data['session_dir'] = $this->_data['var_dir'] . DS . 'session';
+ $this->_data['upload_dir'] = $this->_data['media_dir'] . DS . 'upload';
+ $this->_data['export_dir'] = $this->_data['var_dir'] . DS . 'export';
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Cookie.php b/app/code/core/Mage/Core/Model/Cookie.php
index 265eda55430..780addec367 100644
--- a/app/code/core/Mage/Core/Model/Cookie.php
+++ b/app/code/core/Mage/Core/Model/Cookie.php
@@ -62,26 +62,6 @@ public function getStore()
return $this->_store;
}
- /**
- * Retrieve Request object
- *
- * @return Mage_Core_Controller_Request_Http
- */
- protected function _getRequest()
- {
- return Mage::app()->getRequest();
- }
-
- /**
- * Retrieve Response object
- *
- * @return Mage_Core_Controller_Response_Http
- */
- protected function _getResponse()
- {
- return Mage::app()->getResponse();
- }
-
/**
* Retrieve Domain for cookie
*
@@ -321,4 +301,24 @@ public function delete($name, $path = null, $domain = null, $secure = null, $htt
return $this->set($name, '', null, $path, $domain, $secure, $httponly, $sameSite);
}
+
+ /**
+ * Retrieve Request object
+ *
+ * @return Mage_Core_Controller_Request_Http
+ */
+ protected function _getRequest()
+ {
+ return Mage::app()->getRequest();
+ }
+
+ /**
+ * Retrieve Response object
+ *
+ * @return Mage_Core_Controller_Response_Http
+ */
+ protected function _getResponse()
+ {
+ return Mage::app()->getResponse();
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Date.php b/app/code/core/Mage/Core/Model/Date.php
index 9260e371875..d0e3bf9e3bf 100644
--- a/app/code/core/Mage/Core/Model/Date.php
+++ b/app/code/core/Mage/Core/Model/Date.php
@@ -46,16 +46,6 @@ public function __construct()
$this->_systemOffset = $this->calculateOffset();
}
- /**
- * Gets the store config timezone
- *
- * @return string
- */
- protected function _getConfigTimezone()
- {
- return Mage::app()->getStore()->getConfig('general/locale/timezone');
- }
-
/**
* Calculates timezone offset
*
@@ -285,4 +275,14 @@ public function parseDateTime($dateTimeString, $dateTimeFormat)
return $result;
}
+
+ /**
+ * Gets the store config timezone
+ *
+ * @return string
+ */
+ protected function _getConfigTimezone()
+ {
+ return Mage::app()->getStore()->getConfig('general/locale/timezone');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Design.php b/app/code/core/Mage/Core/Model/Design.php
index c7b7077bc44..3448faa697a 100644
--- a/app/code/core/Mage/Core/Model/Design.php
+++ b/app/code/core/Mage/Core/Model/Design.php
@@ -33,11 +33,6 @@
*/
class Mage_Core_Model_Design extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('core/design');
- }
-
/**
* @return $this
*/
@@ -69,4 +64,8 @@ public function loadChange($storeId, $date = null)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('core/design');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Design/Package.php b/app/code/core/Mage/Core/Model/Design/Package.php
index 39f59b30606..1b806a82a99 100644
--- a/app/code/core/Mage/Core/Model/Design/Package.php
+++ b/app/code/core/Mage/Core/Model/Design/Package.php
@@ -30,12 +30,6 @@ class Mage_Core_Model_Design_Package
*/
public const FALLBACK_THEME = 'default';
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private static $_regexMatchCache = [];
-
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private static $_customThemeTypeCache = [];
-
/**
* Current Store for generation ofr base_dir and base_url
*
@@ -95,6 +89,12 @@ class Mage_Core_Model_Design_Package
*/
protected $_shouldFallback = true;
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private static $_regexMatchCache = [];
+
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private static $_customThemeTypeCache = [];
+
public function __construct()
{
if (is_null($this->_config)) {
@@ -386,56 +386,6 @@ public function validateFile($file, array $params)
return $fileName;
}
- /**
- * Get filename by specified theme parameters
- *
- * @param string $file
- * @return string
- */
- protected function _renderFilename($file, array $params)
- {
- switch ($params['_type']) {
- case 'skin':
- $dir = $this->getSkinBaseDir($params);
- break;
-
- case 'locale':
- $dir = $this->getLocaleBaseDir($params);
- break;
-
- default:
- $dir = $this->getBaseDir($params);
- break;
- }
- return $dir . DS . $file;
- }
-
- /**
- * Check for files existence by specified scheme
- *
- * If fallback enabled, the first found file will be returned. Otherwise the base package / default theme file,
- * regardless of found or not.
- * If disabled, the lookup won't be performed to spare filesystem calls.
- *
- * @param string $file
- * @return string
- */
- protected function _fallback($file, array &$params, array $fallbackScheme = [[]])
- {
- if ($this->_shouldFallback) {
- foreach ($fallbackScheme as $try) {
- $params = array_merge($params, $try);
- $filename = $this->validateFile($file, $params);
- if ($filename) {
- return $filename;
- }
- }
- $params['_package'] = self::BASE_PACKAGE;
- $params['_theme'] = self::DEFAULT_THEME;
- }
- return $this->_renderFilename($file, $params);
- }
-
/**
* Use this one to get existing file name with fallback to default
*
@@ -570,76 +520,6 @@ public function getThemeList($package = null)
return $result;
}
- /**
- * Directories lister utility method
- *
- * @param string $path
- * @param string|bool $fullPath
- * @return array
- */
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private function _listDirectories($path, $fullPath = false)
- {
- $result = [];
- $dir = opendir($path);
- if ($dir) {
- while ($entry = readdir($dir)) {
- if (substr($entry, 0, 1) == '.' || !is_dir($path . DS . $entry)) {
- continue;
- }
- if ($fullPath) {
- $entry = $path . DS . $entry;
- }
- $result[] = $entry;
- }
- unset($entry);
- closedir($dir);
- }
-
- return $result;
- }
-
- /**
- * Get regex rules from config and check user-agent against them
- *
- * Rules must be stored in config as a serialized array(['regexp']=>'...', ['value'] => '...')
- * Will return false or found string.
- *
- * @param string $regexpsConfigPath
- * @return false|string
- *
- * @SuppressWarnings("PHPMD.CamelCaseVariableName"))
- * @SuppressWarnings("PHPMD.Superglobals")
- */
- protected function _checkUserAgentAgainstRegexps($regexpsConfigPath)
- {
- if (empty($_SERVER['HTTP_USER_AGENT'])) {
- return false;
- }
-
- if (!empty(self::$_customThemeTypeCache[$regexpsConfigPath])) {
- return self::$_customThemeTypeCache[$regexpsConfigPath];
- }
-
- $configValueSerialized = Mage::getStoreConfig($regexpsConfigPath, $this->getStore());
-
- if (!$configValueSerialized) {
- return false;
- }
-
- try {
- $regexps = Mage::helper('core/unserializeArray')->unserialize($configValueSerialized);
- } catch (Exception $e) {
- Mage::logException($e);
- }
-
- if (empty($regexps)) {
- return false;
- }
-
- return self::getPackageByUserAgent($regexps, $regexpsConfigPath);
- }
-
/**
* Return package name based on design exception rules
*
@@ -746,6 +626,138 @@ public function getMergedCssUrl($files)
return '';
}
+ /**
+ * Remove all merged js/css files
+ *
+ * @return bool
+ */
+ public function cleanMergedJsCss()
+ {
+ $result = (bool) $this->_initMergerDir('js', true);
+ $result = $this->_initMergerDir('css', true) && $result;
+ return $this->_initMergerDir('css_secure', true) && $result;
+ }
+
+ /**
+ * Before merge css callback function
+ *
+ * @param string $file
+ * @param string $contents
+ * @return string
+ */
+ public function beforeMergeCss($file, $contents)
+ {
+ $this->_setCallbackFileDir($file);
+
+ $cssImport = '/@import\\s+([\'"])(.*?)[\'"]/';
+ $contents = preg_replace_callback($cssImport, [$this, '_cssMergerImportCallback'], $contents);
+
+ $cssUrl = '/url\\(\\s*(?![\\\'\\"]?data:)([^\\)\\s]+)\\s*\\)?/';
+
+ return preg_replace_callback($cssUrl, [$this, '_cssMergerUrlCallback'], $contents);
+ }
+
+ /**
+ * Default theme getter
+ * @return string
+ * @deprecated since 1.8.2.0
+ */
+ public function getFallbackTheme()
+ {
+ return Mage::getStoreConfig('design/theme/default', $this->getStore());
+ }
+
+ /**
+ * Get filename by specified theme parameters
+ *
+ * @param string $file
+ * @return string
+ */
+ protected function _renderFilename($file, array $params)
+ {
+ switch ($params['_type']) {
+ case 'skin':
+ $dir = $this->getSkinBaseDir($params);
+ break;
+
+ case 'locale':
+ $dir = $this->getLocaleBaseDir($params);
+ break;
+
+ default:
+ $dir = $this->getBaseDir($params);
+ break;
+ }
+ return $dir . DS . $file;
+ }
+
+ /**
+ * Check for files existence by specified scheme
+ *
+ * If fallback enabled, the first found file will be returned. Otherwise the base package / default theme file,
+ * regardless of found or not.
+ * If disabled, the lookup won't be performed to spare filesystem calls.
+ *
+ * @param string $file
+ * @return string
+ */
+ protected function _fallback($file, array &$params, array $fallbackScheme = [[]])
+ {
+ if ($this->_shouldFallback) {
+ foreach ($fallbackScheme as $try) {
+ $params = array_merge($params, $try);
+ $filename = $this->validateFile($file, $params);
+ if ($filename) {
+ return $filename;
+ }
+ }
+ $params['_package'] = self::BASE_PACKAGE;
+ $params['_theme'] = self::DEFAULT_THEME;
+ }
+ return $this->_renderFilename($file, $params);
+ }
+
+ /**
+ * Get regex rules from config and check user-agent against them
+ *
+ * Rules must be stored in config as a serialized array(['regexp']=>'...', ['value'] => '...')
+ * Will return false or found string.
+ *
+ * @param string $regexpsConfigPath
+ * @return false|string
+ *
+ * @SuppressWarnings("PHPMD.CamelCaseVariableName"))
+ * @SuppressWarnings("PHPMD.Superglobals")
+ */
+ protected function _checkUserAgentAgainstRegexps($regexpsConfigPath)
+ {
+ if (empty($_SERVER['HTTP_USER_AGENT'])) {
+ return false;
+ }
+
+ if (!empty(self::$_customThemeTypeCache[$regexpsConfigPath])) {
+ return self::$_customThemeTypeCache[$regexpsConfigPath];
+ }
+
+ $configValueSerialized = Mage::getStoreConfig($regexpsConfigPath, $this->getStore());
+
+ if (!$configValueSerialized) {
+ return false;
+ }
+
+ try {
+ $regexps = Mage::helper('core/unserializeArray')->unserialize($configValueSerialized);
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+
+ if (empty($regexps)) {
+ return false;
+ }
+
+ return self::getPackageByUserAgent($regexps, $regexpsConfigPath);
+ }
+
/**
* Merges files into one and saves it into DB (if DB file storage is on)
*
@@ -794,18 +806,6 @@ protected function _mergeFiles(
}
}
- /**
- * Remove all merged js/css files
- *
- * @return bool
- */
- public function cleanMergedJsCss()
- {
- $result = (bool) $this->_initMergerDir('js', true);
- $result = $this->_initMergerDir('css', true) && $result;
- return $this->_initMergerDir('css_secure', true) && $result;
- }
-
/**
* Make sure merger dir exists and writeable
* Also can clean it up
@@ -832,25 +832,6 @@ protected function _initMergerDir($dirRelativeName, $cleanup = false)
return false;
}
- /**
- * Before merge css callback function
- *
- * @param string $file
- * @param string $contents
- * @return string
- */
- public function beforeMergeCss($file, $contents)
- {
- $this->_setCallbackFileDir($file);
-
- $cssImport = '/@import\\s+([\'"])(.*?)[\'"]/';
- $contents = preg_replace_callback($cssImport, [$this, '_cssMergerImportCallback'], $contents);
-
- $cssUrl = '/url\\(\\s*(?![\\\'\\"]?data:)([^\\)\\s]+)\\s*\\)?/';
-
- return preg_replace_callback($cssUrl, [$this, '_cssMergerUrlCallback'], $contents);
- }
-
/**
* Set file dir for css file
*
@@ -943,12 +924,31 @@ protected function _prepareUrl($uri)
}
/**
- * Default theme getter
- * @return string
- * @deprecated since 1.8.2.0
+ * Directories lister utility method
+ *
+ * @param string $path
+ * @param string|bool $fullPath
+ * @return array
*/
- public function getFallbackTheme()
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private function _listDirectories($path, $fullPath = false)
{
- return Mage::getStoreConfig('design/theme/default', $this->getStore());
+ $result = [];
+ $dir = opendir($path);
+ if ($dir) {
+ while ($entry = readdir($dir)) {
+ if (substr($entry, 0, 1) == '.' || !is_dir($path . DS . $entry)) {
+ continue;
+ }
+ if ($fullPath) {
+ $entry = $path . DS . $entry;
+ }
+ $result[] = $entry;
+ }
+ unset($entry);
+ closedir($dir);
+ }
+
+ return $result;
}
}
diff --git a/app/code/core/Mage/Core/Model/Email/Queue.php b/app/code/core/Mage/Core/Model/Email/Queue.php
index 5d3a84f4a3d..5bf8fda5a01 100644
--- a/app/code/core/Mage/Core/Model/Email/Queue.php
+++ b/app/code/core/Mage/Core/Model/Email/Queue.php
@@ -60,39 +60,6 @@ class Mage_Core_Model_Email_Queue extends Mage_Core_Model_Abstract
*/
protected $_recipients = [];
- /**
- * Initialize object
- */
- protected function _construct()
- {
- $this->_init('core/email_queue');
- }
-
- /**
- * Save bind recipients to message
- *
- * @inheritDoc
- */
- protected function _afterSave()
- {
- $this->_getResource()->saveRecipients($this->getId(), $this->getRecipients());
- return parent::_afterSave();
- }
-
- /**
- * Validate recipients before saving
- *
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- if (empty($this->_recipients) || !is_array($this->_recipients) || empty($this->_recipients[0])) { // additional check of recipients information (email address)
- $error = Mage::helper('core')->__('Message recipients data must be set.');
- Mage::throwException("{$error} - ID: " . $this->getId());
- }
- return parent::_beforeSave();
- }
-
/**
* Add message to queue
*
@@ -275,4 +242,37 @@ public function cleanQueue()
$this->_getResource()->removeSentMessages();
return $this;
}
+
+ /**
+ * Initialize object
+ */
+ protected function _construct()
+ {
+ $this->_init('core/email_queue');
+ }
+
+ /**
+ * Save bind recipients to message
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave()
+ {
+ $this->_getResource()->saveRecipients($this->getId(), $this->getRecipients());
+ return parent::_afterSave();
+ }
+
+ /**
+ * Validate recipients before saving
+ *
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ if (empty($this->_recipients) || !is_array($this->_recipients) || empty($this->_recipients[0])) { // additional check of recipients information (email address)
+ $error = Mage::helper('core')->__('Message recipients data must be set.');
+ Mage::throwException("{$error} - ID: " . $this->getId());
+ }
+ return parent::_beforeSave();
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Email/Template.php b/app/code/core/Mage/Core/Model/Email/Template.php
index 1b827f271cf..9f2cc46f2de 100644
--- a/app/code/core/Mage/Core/Model/Email/Template.php
+++ b/app/code/core/Mage/Core/Model/Email/Template.php
@@ -88,15 +88,6 @@ class Mage_Core_Model_Email_Template extends Mage_Core_Model_Email_Template_Abst
protected static $_defaultTemplates;
- /**
- * Initialize email template model
- *
- */
- protected function _construct()
- {
- $this->_init('core/email_template');
- }
-
/**
* Retrieve mail object instance
*
@@ -601,22 +592,6 @@ public function setReplyTo($email)
return $this;
}
- /**
- * Parse variables string into array of variables
- *
- * @param string $variablesString
- * @return array
- */
- protected function _parseVariablesString($variablesString)
- {
- $variables = [];
- if ($variablesString && is_string($variablesString)) {
- $variablesString = str_replace("\n", '', $variablesString);
- $variables = Zend_Json::decode($variablesString);
- }
- return $variables;
- }
-
/**
* Retrieve option array of variables
*
@@ -644,6 +619,31 @@ public function getVariablesOptionArray($withGroup = false)
return $optionArray;
}
+ /**
+ * Initialize email template model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('core/email_template');
+ }
+
+ /**
+ * Parse variables string into array of variables
+ *
+ * @param string $variablesString
+ * @return array
+ */
+ protected function _parseVariablesString($variablesString)
+ {
+ $variables = [];
+ if ($variablesString && is_string($variablesString)) {
+ $variablesString = str_replace("\n", '', $variablesString);
+ $variables = Zend_Json::decode($variablesString);
+ }
+ return $variables;
+ }
+
/**
* Validate email template code
*
diff --git a/app/code/core/Mage/Core/Model/Email/Template/Filter.php b/app/code/core/Mage/Core/Model/Email/Template/Filter.php
index f6b2bcf32e1..a694ec23e2c 100644
--- a/app/code/core/Mage/Core/Model/Email/Template/Filter.php
+++ b/app/code/core/Mage/Core/Model/Email/Template/Filter.php
@@ -247,20 +247,6 @@ public function layoutDirective($construction)
return $layout->getOutput();
}
- /**
- * Retrieve block parameters
- *
- * @param mixed $value
- * @return array
- */
- protected function _getBlockParameters($value)
- {
- $tokenizer = new Varien_Filter_Template_Tokenizer_Parameter();
- $tokenizer->setString($value);
-
- return $tokenizer->tokenize();
- }
-
/**
* Retrieve Skin URL directive
*
@@ -371,35 +357,6 @@ public function varDirective($construction)
return $this->_getVariable($construction[2], '');
}
- /**
- * Apply modifiers one by one, with specified params
- *
- * Modifier syntax: modifier1[:param1:param2:...][|modifier2:...]
- *
- * @param string $value
- * @param string $modifiers
- * @return string
- */
- protected function _amplifyModifiers($value, $modifiers)
- {
- foreach (explode('|', $modifiers) as $part) {
- if (empty($part)) {
- continue;
- }
- $params = explode(':', $part);
- $modifier = array_shift($params);
- if (isset($this->_modifiers[$modifier])) {
- $callback = $this->_modifiers[$modifier];
- if (!$callback) {
- $callback = $modifier;
- }
- array_unshift($params, $value);
- $value = call_user_func_array($callback, $params);
- }
- }
- return $value;
- }
-
/**
* Escape specified string
*
@@ -516,18 +473,6 @@ public function inlinecssDirective($construction)
return '';
}
- /**
- * Set filename of CSS file to inline
- *
- * @param string $filename
- * @return $this
- */
- protected function _setInlineCssFile($filename)
- {
- $this->_inlineCssFile = $filename;
- return $this;
- }
-
/**
* Get filename of CSS file to inline
*
@@ -556,6 +501,61 @@ public function filter($value)
return $value;
}
+ /**
+ * Retrieve block parameters
+ *
+ * @param mixed $value
+ * @return array
+ */
+ protected function _getBlockParameters($value)
+ {
+ $tokenizer = new Varien_Filter_Template_Tokenizer_Parameter();
+ $tokenizer->setString($value);
+
+ return $tokenizer->tokenize();
+ }
+
+ /**
+ * Apply modifiers one by one, with specified params
+ *
+ * Modifier syntax: modifier1[:param1:param2:...][|modifier2:...]
+ *
+ * @param string $value
+ * @param string $modifiers
+ * @return string
+ */
+ protected function _amplifyModifiers($value, $modifiers)
+ {
+ foreach (explode('|', $modifiers) as $part) {
+ if (empty($part)) {
+ continue;
+ }
+ $params = explode(':', $part);
+ $modifier = array_shift($params);
+ if (isset($this->_modifiers[$modifier])) {
+ $callback = $this->_modifiers[$modifier];
+ if (!$callback) {
+ $callback = $modifier;
+ }
+ array_unshift($params, $value);
+ $value = call_user_func_array($callback, $params);
+ }
+ }
+ return $value;
+ }
+
+ /**
+ * Set filename of CSS file to inline
+ *
+ * @param string $filename
+ * @return $this
+ */
+ protected function _setInlineCssFile($filename)
+ {
+ $this->_inlineCssFile = $filename;
+ return $this;
+ }
+
/**
* Return variable value for var construction
*
diff --git a/app/code/core/Mage/Core/Model/Encryption.php b/app/code/core/Mage/Core/Model/Encryption.php
index e5c778027d8..b242e63e546 100644
--- a/app/code/core/Mage/Core/Model/Encryption.php
+++ b/app/code/core/Mage/Core/Model/Encryption.php
@@ -158,23 +158,6 @@ public function validateHashByVersion($password, $hash, $version = self::HASH_VE
return hash_equals($this->hash($salt . $password, $version), $hash);
}
- /**
- * Instantiate crypt model
- *
- * @param string $key
- * @return Varien_Crypt_Mcrypt
- */
- protected function _getCrypt($key = null)
- {
- if (!$this->_crypt) {
- if ($key === null) {
- $key = (string) Mage::getConfig()->getNode('global/crypt/key');
- }
- $this->_crypt = Varien_Crypt::factory()->init($key);
- }
- return $this->_crypt;
- }
-
/**
* Encrypt a string
*
@@ -207,4 +190,21 @@ public function validateKey($key)
{
return $this->_getCrypt($key);
}
+
+ /**
+ * Instantiate crypt model
+ *
+ * @param string $key
+ * @return Varien_Crypt_Mcrypt
+ */
+ protected function _getCrypt($key = null)
+ {
+ if (!$this->_crypt) {
+ if ($key === null) {
+ $key = (string) Mage::getConfig()->getNode('global/crypt/key');
+ }
+ $this->_crypt = Varien_Crypt::factory()->init($key);
+ }
+ return $this->_crypt;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/File/Storage.php b/app/code/core/Mage/Core/Model/File/Storage.php
index 8661f637117..18c1b474a06 100644
--- a/app/code/core/Mage/Core/Model/File/Storage.php
+++ b/app/code/core/Mage/Core/Model/File/Storage.php
@@ -45,22 +45,6 @@ class Mage_Core_Model_File_Storage extends Mage_Core_Model_Abstract
*/
protected $_eventPrefix = 'core_file_storage';
- /**
- * Show if there were errors while synchronize process
- *
- * @return bool
- */
- protected function _synchronizeHasErrors(
- Mage_Core_Model_Abstract $sourceModel,
- Mage_Core_Model_Abstract $destinationModel
- ) {
- if (!$sourceModel || !$destinationModel) {
- return true;
- }
-
- return $sourceModel->hasErrors() || $destinationModel->hasErrors();
- }
-
/**
* Return synchronize process status flag
*
@@ -222,4 +206,20 @@ public static function getScriptConfig()
return $config;
}
+
+ /**
+ * Show if there were errors while synchronize process
+ *
+ * @return bool
+ */
+ protected function _synchronizeHasErrors(
+ Mage_Core_Model_Abstract $sourceModel,
+ Mage_Core_Model_Abstract $destinationModel
+ ) {
+ if (!$sourceModel || !$destinationModel) {
+ return true;
+ }
+
+ return $sourceModel->hasErrors() || $destinationModel->hasErrors();
+ }
}
diff --git a/app/code/core/Mage/Core/Model/File/Storage/Database/Abstract.php b/app/code/core/Mage/Core/Model/File/Storage/Database/Abstract.php
index b9fa48b1be3..462a52ee43b 100644
--- a/app/code/core/Mage/Core/Model/File/Storage/Database/Abstract.php
+++ b/app/code/core/Mage/Core/Model/File/Storage/Database/Abstract.php
@@ -55,20 +55,6 @@ public function getConfigConnectionName()
return $connectionName;
}
- /**
- * Get resource instance
- *
- * @return Mage_Core_Model_Resource_File_Storage_Database
- */
- protected function _getResource()
- {
- /** @var Mage_Core_Model_Resource_File_Storage_Database $resource */
- $resource = parent::_getResource();
- $resource->setConnectionName($this->getConnectionName());
-
- return $resource;
- }
-
/**
* Prepare data storage
*
@@ -96,4 +82,18 @@ public function setConnectionName($connectionName)
return $this;
}
+
+ /**
+ * Get resource instance
+ *
+ * @return Mage_Core_Model_Resource_File_Storage_Database
+ */
+ protected function _getResource()
+ {
+ /** @var Mage_Core_Model_Resource_File_Storage_Database $resource */
+ $resource = parent::_getResource();
+ $resource->setConnectionName($this->getConnectionName());
+
+ return $resource;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/File/Uploader.php b/app/code/core/Mage/Core/Model/File/Uploader.php
index 3ea45218067..4b0b8f385e3 100644
--- a/app/code/core/Mage/Core/Model/File/Uploader.php
+++ b/app/code/core/Mage/Core/Model/File/Uploader.php
@@ -36,32 +36,6 @@ class Mage_Core_Model_File_Uploader extends Varien_File_Uploader
*/
protected $_fileNameMaxLength = 200;
- /**
- * Save file to storage
- *
- * @param array $result
- * @return $this
- */
- protected function _afterSave($result)
- {
- if (empty($result['path']) || empty($result['file'])) {
- return $this;
- }
-
- /** @var Mage_Core_Helper_File_Storage $helper */
- $helper = Mage::helper('core/file_storage');
-
- if ($helper->isInternalStorage() || $this->skipDbProcessing()) {
- return $this;
- }
-
- /** @var Mage_Core_Helper_File_Storage_Database $dbHelper */
- $dbHelper = Mage::helper('core/file_storage_database');
- $this->_result['file'] = $dbHelper->saveUploadedFile($result);
-
- return $this;
- }
-
/**
* Getter/Setter for _skipDbProcessing flag
*
@@ -115,4 +89,30 @@ public function save($destinationFolder, $newFileName = null)
}
return parent::save($destinationFolder, $newFileName);
}
+
+ /**
+ * Save file to storage
+ *
+ * @param array $result
+ * @return $this
+ */
+ protected function _afterSave($result)
+ {
+ if (empty($result['path']) || empty($result['file'])) {
+ return $this;
+ }
+
+ /** @var Mage_Core_Helper_File_Storage $helper */
+ $helper = Mage::helper('core/file_storage');
+
+ if ($helper->isInternalStorage() || $this->skipDbProcessing()) {
+ return $this;
+ }
+
+ /** @var Mage_Core_Helper_File_Storage_Database $dbHelper */
+ $dbHelper = Mage::helper('core/file_storage_database');
+ $this->_result['file'] = $dbHelper->saveUploadedFile($result);
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/File/Validator/AvailablePath.php b/app/code/core/Mage/Core/Model/File/Validator/AvailablePath.php
index 9d087dc73e6..10630f21324 100644
--- a/app/code/core/Mage/Core/Model/File/Validator/AvailablePath.php
+++ b/app/code/core/Mage/Core/Model/File/Validator/AvailablePath.php
@@ -74,26 +74,6 @@ public function __construct()
$this->_initMessageTemplates();
}
- /**
- * Initialize message templates with translating
- *
- * @return $this
- */
- protected function _initMessageTemplates()
- {
- if (!$this->_messageTemplates) {
- $this->_messageTemplates = [
- self::PROTECTED_PATH =>
- Mage::helper('core')->__('Path "%value%" is protected and cannot be used.'),
- self::NOT_AVAILABLE_PATH =>
- Mage::helper('core')->__('Path "%value%" is not available and cannot be used.'),
- self::PROTECTED_LFI =>
- Mage::helper('core')->__('Path "%value%" may not include parent directory traversal ("../", "..\\").'),
- ];
- }
- return $this;
- }
-
/**
* Set paths masks
*
@@ -238,6 +218,26 @@ public function isValid($value)
return true;
}
+ /**
+ * Initialize message templates with translating
+ *
+ * @return $this
+ */
+ protected function _initMessageTemplates()
+ {
+ if (!$this->_messageTemplates) {
+ $this->_messageTemplates = [
+ self::PROTECTED_PATH =>
+ Mage::helper('core')->__('Path "%value%" is protected and cannot be used.'),
+ self::NOT_AVAILABLE_PATH =>
+ Mage::helper('core')->__('Path "%value%" is not available and cannot be used.'),
+ self::PROTECTED_LFI =>
+ Mage::helper('core')->__('Path "%value%" may not include parent directory traversal ("../", "..\\").'),
+ ];
+ }
+ return $this;
+ }
+
/**
* Validate value by path masks
*
diff --git a/app/code/core/Mage/Core/Model/File/Validator/NotProtectedExtension.php b/app/code/core/Mage/Core/Model/File/Validator/NotProtectedExtension.php
index 4f4058afa20..84d8feac03b 100644
--- a/app/code/core/Mage/Core/Model/File/Validator/NotProtectedExtension.php
+++ b/app/code/core/Mage/Core/Model/File/Validator/NotProtectedExtension.php
@@ -44,6 +44,29 @@ public function __construct()
$this->_initProtectedFileExtensions();
}
+ /**
+ * Returns true if and only if $value meets the validation requirements
+ *
+ * If $value fails validation, then this method returns false, and
+ * getMessages() will return an array of messages that explain why the
+ * validation failed.
+ *
+ * @param string $value Extension of file
+ * @return bool
+ */
+ public function isValid($value)
+ {
+ $value = strtolower(trim($value));
+ $this->_setValue($value);
+
+ if (in_array($this->_value, $this->_protectedFileExtensions)) {
+ $this->_error(self::PROTECTED_EXTENSION, $this->_value);
+ return false;
+ }
+
+ return true;
+ }
+
/**
* Initialize message templates with translating
*
@@ -80,27 +103,4 @@ protected function _initProtectedFileExtensions()
}
return $this;
}
-
- /**
- * Returns true if and only if $value meets the validation requirements
- *
- * If $value fails validation, then this method returns false, and
- * getMessages() will return an array of messages that explain why the
- * validation failed.
- *
- * @param string $value Extension of file
- * @return bool
- */
- public function isValid($value)
- {
- $value = strtolower(trim($value));
- $this->_setValue($value);
-
- if (in_array($this->_value, $this->_protectedFileExtensions)) {
- $this->_error(self::PROTECTED_EXTENSION, $this->_value);
- return false;
- }
-
- return true;
- }
}
diff --git a/app/code/core/Mage/Core/Model/Flag.php b/app/code/core/Mage/Core/Model/Flag.php
index 80317e0a3fe..b53ec1ccea5 100644
--- a/app/code/core/Mage/Core/Model/Flag.php
+++ b/app/code/core/Mage/Core/Model/Flag.php
@@ -39,34 +39,6 @@ class Mage_Core_Model_Flag extends Mage_Core_Model_Abstract
*/
protected $_flagCode = null;
- /**
- * Init resource model
- * Set flag_code if it is specified in arguments
- *
- */
- protected function _construct()
- {
- if ($this->hasData('flag_code')) {
- $this->_flagCode = $this->getData('flag_code');
- }
- $this->_init('core/flag');
- }
-
- /**
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- if (is_null($this->_flagCode)) {
- Mage::throwException(Mage::helper('core')->__('Please define flag code.'));
- }
-
- $this->setFlagCode($this->_flagCode);
- $this->setLastUpdate(date(Varien_Db_Adapter_Pdo_Mysql::TIMESTAMP_FORMAT));
-
- return parent::_beforeSave();
- }
-
/**
* Retrieve flag data
*
@@ -105,4 +77,32 @@ public function loadSelf()
return $this->load($this->_flagCode, 'flag_code');
}
+
+ /**
+ * Init resource model
+ * Set flag_code if it is specified in arguments
+ *
+ */
+ protected function _construct()
+ {
+ if ($this->hasData('flag_code')) {
+ $this->_flagCode = $this->getData('flag_code');
+ }
+ $this->_init('core/flag');
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ if (is_null($this->_flagCode)) {
+ Mage::throwException(Mage::helper('core')->__('Please define flag code.'));
+ }
+
+ $this->setFlagCode($this->_flagCode);
+ $this->setLastUpdate(date(Varien_Db_Adapter_Pdo_Mysql::TIMESTAMP_FORMAT));
+
+ return parent::_beforeSave();
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Layout.php b/app/code/core/Mage/Core/Model/Layout.php
index 576c5a32476..3cbac878a58 100644
--- a/app/code/core/Mage/Core/Model/Layout.php
+++ b/app/code/core/Mage/Core/Model/Layout.php
@@ -213,6 +213,226 @@ public function generateBlocks($parent = null)
}
}
+ /**
+ * Save block in blocks registry
+ *
+ * @param string $name
+ * @param Mage_Core_Block_Abstract $block
+ * @return $this
+ */
+ public function setBlock($name, $block)
+ {
+ $this->_blocks[$name] = $block;
+ return $this;
+ }
+
+ /**
+ * Remove block from registry
+ *
+ * @param string $name
+ * @return $this
+ */
+ public function unsetBlock($name)
+ {
+ $this->_blocks[$name] = null;
+ unset($this->_blocks[$name]);
+ return $this;
+ }
+
+ /**
+ * Block Factory
+ *
+ * @param string $type
+ * @param string|null $name
+ * @return Mage_Core_Block_Abstract|false
+ */
+ public function createBlock($type, $name = '', array $attributes = [])
+ {
+ try {
+ $block = $this->_getBlockInstance($type, $attributes);
+ } catch (Exception $e) {
+ Mage::logException($e);
+ return false;
+ }
+
+ if (empty($name) || $name[0] === '.') {
+ $block->setIsAnonymous(true);
+ if (!empty($name)) {
+ $block->setAnonSuffix(substr($name, 1));
+ }
+ $name = 'ANONYMOUS_' . count($this->_blocks);
+ } elseif (isset($this->_blocks[$name]) && Mage::getIsDeveloperMode()) {
+ //Mage::throwException(Mage::helper('core')->__('Block with name "%s" already exists', $name));
+ }
+
+ $block->setType($type);
+ $block->setNameInLayout($name);
+ $block->addData($attributes);
+ $block->setLayout($this);
+
+ $this->_blocks[$name] = $block;
+ Mage::dispatchEvent('core_layout_block_create_after', ['block' => $block]);
+ return $this->_blocks[$name];
+ }
+
+ /**
+ * Add a block to registry, create new object if needed
+ *
+ * @param string|Mage_Core_Block_Abstract $block
+ * @param string $blockName
+ * @return Mage_Core_Block_Abstract
+ */
+ public function addBlock($block, $blockName)
+ {
+ return $this->createBlock($block, $blockName);
+ }
+
+ /**
+ * Retrieve all blocks from registry as array
+ *
+ * @return array
+ */
+ public function getAllBlocks()
+ {
+ return $this->_blocks;
+ }
+
+ /**
+ * Get block object by name
+ *
+ * @param string $name
+ * @return Mage_Core_Block_Abstract|false
+ */
+ public function getBlock($name)
+ {
+ return $this->_blocks[$name] ?? false;
+ }
+
+ /**
+ * Add a block to output
+ *
+ * @param string $blockName
+ * @param string $method
+ * @return $this
+ */
+ public function addOutputBlock($blockName, $method = 'toHtml')
+ {
+ //$this->_output[] = array($blockName, $method);
+ $this->_output[$blockName] = [$blockName, $method];
+ return $this;
+ }
+
+ /**
+ * @param string $blockName
+ * @return $this
+ */
+ public function removeOutputBlock($blockName)
+ {
+ unset($this->_output[$blockName]);
+ return $this;
+ }
+
+ /**
+ * Get all blocks marked for output
+ *
+ * @return string
+ */
+ public function getOutput()
+ {
+ $out = '';
+ if (!empty($this->_output)) {
+ foreach ($this->_output as $callback) {
+ $out .= $this->getBlock($callback[0])->{$callback[1]}();
+ }
+ }
+
+ return $out;
+ }
+
+ /**
+ * Retrieve messages block
+ *
+ * @return Mage_Core_Block_Messages
+ */
+ public function getMessagesBlock()
+ {
+ $block = $this->getBlock('messages');
+ if ($block) {
+ return $block;
+ }
+ return $this->createBlock('core/messages', 'messages');
+ }
+
+ /**
+ * @param string $type
+ * @return Mage_Core_Block_Abstract|object
+ */
+ public function getBlockSingleton($type)
+ {
+ if (!isset($this->_helpers[$type])) {
+ $className = Mage::getConfig()->getBlockClassName($type);
+ if (!$className) {
+ Mage::throwException(Mage::helper('core')->__('Invalid block type: %s', $type));
+ }
+
+ $helper = new $className();
+ if ($helper) {
+ if ($helper instanceof Mage_Core_Block_Abstract) {
+ $helper->setLayout($this);
+ }
+ $this->_helpers[$type] = $helper;
+ }
+ }
+ return $this->_helpers[$type];
+ }
+
+ /**
+ * Retrieve helper object
+ *
+ * @param string $name
+ * @return Mage_Core_Helper_Abstract|false
+ */
+ public function helper($name)
+ {
+ $helper = Mage::helper($name);
+ if (!$helper) {
+ return false;
+ }
+ return $helper->setLayout($this);
+ }
+
+ /**
+ * Lookup module name for translation from current specified layout node
+ *
+ * Priorities:
+ * 1) "module" attribute in the element
+ * 2) "module" attribute in any ancestor element
+ * 3) layout handle name - first 1 or 2 parts (namespace is determined automatically)
+ *
+ * @return string
+ */
+ public static function findTranslationModuleName(Varien_Simplexml_Element $node)
+ {
+ $result = $node->getAttribute('module');
+ if ($result) {
+ return (string) $result;
+ }
+ /** @var Varien_Simplexml_Element $element */
+ foreach (array_reverse($node->xpath('ancestor::*[@module]')) as $element) {
+ $result = $element->getAttribute('module');
+ if ($result) {
+ return (string) $result;
+ }
+ }
+ foreach ($node->xpath('ancestor-or-self::*[last()-1]') as $handle) {
+ $name = Mage::getConfig()->determineOmittedNamespace($handle->getName());
+ if ($name) {
+ return $name;
+ }
+ }
+ return 'core';
+ }
+
/**
* Add block object to layout based on xml node data
*
@@ -417,80 +637,6 @@ protected function _translateLayoutNode($node, &$args)
}
}
- /**
- * Save block in blocks registry
- *
- * @param string $name
- * @param Mage_Core_Block_Abstract $block
- * @return $this
- */
- public function setBlock($name, $block)
- {
- $this->_blocks[$name] = $block;
- return $this;
- }
-
- /**
- * Remove block from registry
- *
- * @param string $name
- * @return $this
- */
- public function unsetBlock($name)
- {
- $this->_blocks[$name] = null;
- unset($this->_blocks[$name]);
- return $this;
- }
-
- /**
- * Block Factory
- *
- * @param string $type
- * @param string|null $name
- * @return Mage_Core_Block_Abstract|false
- */
- public function createBlock($type, $name = '', array $attributes = [])
- {
- try {
- $block = $this->_getBlockInstance($type, $attributes);
- } catch (Exception $e) {
- Mage::logException($e);
- return false;
- }
-
- if (empty($name) || $name[0] === '.') {
- $block->setIsAnonymous(true);
- if (!empty($name)) {
- $block->setAnonSuffix(substr($name, 1));
- }
- $name = 'ANONYMOUS_' . count($this->_blocks);
- } elseif (isset($this->_blocks[$name]) && Mage::getIsDeveloperMode()) {
- //Mage::throwException(Mage::helper('core')->__('Block with name "%s" already exists', $name));
- }
-
- $block->setType($type);
- $block->setNameInLayout($name);
- $block->addData($attributes);
- $block->setLayout($this);
-
- $this->_blocks[$name] = $block;
- Mage::dispatchEvent('core_layout_block_create_after', ['block' => $block]);
- return $this->_blocks[$name];
- }
-
- /**
- * Add a block to registry, create new object if needed
- *
- * @param string|Mage_Core_Block_Abstract $block
- * @param string $blockName
- * @return Mage_Core_Block_Abstract
- */
- public function addBlock($block, $blockName)
- {
- return $this->createBlock($block, $blockName);
- }
-
/**
* Create block object instance based on block type
*
@@ -515,150 +661,4 @@ protected function _getBlockInstance($block, array $attributes = [])
}
return $block;
}
-
- /**
- * Retrieve all blocks from registry as array
- *
- * @return array
- */
- public function getAllBlocks()
- {
- return $this->_blocks;
- }
-
- /**
- * Get block object by name
- *
- * @param string $name
- * @return Mage_Core_Block_Abstract|false
- */
- public function getBlock($name)
- {
- return $this->_blocks[$name] ?? false;
- }
-
- /**
- * Add a block to output
- *
- * @param string $blockName
- * @param string $method
- * @return $this
- */
- public function addOutputBlock($blockName, $method = 'toHtml')
- {
- //$this->_output[] = array($blockName, $method);
- $this->_output[$blockName] = [$blockName, $method];
- return $this;
- }
-
- /**
- * @param string $blockName
- * @return $this
- */
- public function removeOutputBlock($blockName)
- {
- unset($this->_output[$blockName]);
- return $this;
- }
-
- /**
- * Get all blocks marked for output
- *
- * @return string
- */
- public function getOutput()
- {
- $out = '';
- if (!empty($this->_output)) {
- foreach ($this->_output as $callback) {
- $out .= $this->getBlock($callback[0])->{$callback[1]}();
- }
- }
-
- return $out;
- }
-
- /**
- * Retrieve messages block
- *
- * @return Mage_Core_Block_Messages
- */
- public function getMessagesBlock()
- {
- $block = $this->getBlock('messages');
- if ($block) {
- return $block;
- }
- return $this->createBlock('core/messages', 'messages');
- }
-
- /**
- * @param string $type
- * @return Mage_Core_Block_Abstract|object
- */
- public function getBlockSingleton($type)
- {
- if (!isset($this->_helpers[$type])) {
- $className = Mage::getConfig()->getBlockClassName($type);
- if (!$className) {
- Mage::throwException(Mage::helper('core')->__('Invalid block type: %s', $type));
- }
-
- $helper = new $className();
- if ($helper) {
- if ($helper instanceof Mage_Core_Block_Abstract) {
- $helper->setLayout($this);
- }
- $this->_helpers[$type] = $helper;
- }
- }
- return $this->_helpers[$type];
- }
-
- /**
- * Retrieve helper object
- *
- * @param string $name
- * @return Mage_Core_Helper_Abstract|false
- */
- public function helper($name)
- {
- $helper = Mage::helper($name);
- if (!$helper) {
- return false;
- }
- return $helper->setLayout($this);
- }
-
- /**
- * Lookup module name for translation from current specified layout node
- *
- * Priorities:
- * 1) "module" attribute in the element
- * 2) "module" attribute in any ancestor element
- * 3) layout handle name - first 1 or 2 parts (namespace is determined automatically)
- *
- * @return string
- */
- public static function findTranslationModuleName(Varien_Simplexml_Element $node)
- {
- $result = $node->getAttribute('module');
- if ($result) {
- return (string) $result;
- }
- /** @var Varien_Simplexml_Element $element */
- foreach (array_reverse($node->xpath('ancestor::*[@module]')) as $element) {
- $result = $element->getAttribute('module');
- if ($result) {
- return (string) $result;
- }
- }
- foreach ($node->xpath('ancestor-or-self::*[last()-1]') as $handle) {
- $name = Mage::getConfig()->determineOmittedNamespace($handle->getName());
- if ($name) {
- return $name;
- }
- }
- return 'core';
- }
}
diff --git a/app/code/core/Mage/Core/Model/Layout/Update.php b/app/code/core/Mage/Core/Model/Layout/Update.php
index 17620f607f0..78100e90f56 100644
--- a/app/code/core/Mage/Core/Model/Layout/Update.php
+++ b/app/code/core/Mage/Core/Model/Layout/Update.php
@@ -381,17 +381,6 @@ public function fetchDbLayoutUpdates($handle)
return true;
}
- /**
- * Get update string
- *
- * @param string $handle
- * @return mixed
- */
- protected function _getUpdateString($handle)
- {
- return Mage::getResourceModel('core/layout')->fetchUpdatesByHandle($handle);
- }
-
/**
* @param SimpleXMLElement $updateXml
* @return $this
@@ -473,4 +462,15 @@ public function getFileLayoutUpdatesXml($area, $package, $theme, $storeId = null
}
return simplexml_load_string('' . $layoutStr . '', $elementClass);
}
+
+ /**
+ * Get update string
+ *
+ * @param string $handle
+ * @return mixed
+ */
+ protected function _getUpdateString($handle)
+ {
+ return Mage::getResourceModel('core/layout')->fetchUpdatesByHandle($handle);
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Layout/Validator.php b/app/code/core/Mage/Core/Model/Layout/Validator.php
index bef5e8b25d5..4dd5adc3e83 100644
--- a/app/code/core/Mage/Core/Model/Layout/Validator.php
+++ b/app/code/core/Mage/Core/Model/Layout/Validator.php
@@ -78,29 +78,6 @@ public function __construct()
$this->getDisallowedBlocks();
}
- /**
- * Initialize messages templates with translating
- *
- * @return Mage_Core_Model_Layout_Validator
- */
- protected function _initMessageTemplates()
- {
- if (!$this->_messageTemplates) {
- $this->_messageTemplates = [
- self::PROTECTED_ATTR_HELPER_IN_TAG_ACTION_VAR =>
- Mage::helper('core')->__('Helper attributes should not be used in custom layout updates.'),
- self::XML_INVALID => Mage::helper('core')->__('XML data is invalid.'),
- self::INVALID_TEMPLATE_PATH => Mage::helper('core')->__(
- 'Invalid template path used in layout update.',
- ),
- self::INVALID_BLOCK_NAME => Mage::helper('core')->__('Disallowed block name for frontend.'),
- self::INVALID_XML_OBJECT_EXCEPTION =>
- Mage::helper('core')->__('XML object is not instance of "Varien_Simplexml_Element".'),
- ];
- }
- return $this;
- }
-
/**
* @return array
*/
@@ -117,14 +94,6 @@ public function getDisallowedBlocks()
return $this->_disallowedBlock;
}
- /**
- * @return mixed
- */
- protected function _getDisallowedBlockConfigValue()
- {
- return Mage::getStoreConfig(self::XML_PATH_LAYOUT_DISALLOWED_BLOCKS);
- }
-
/**
* Returns true if and only if $value meets the validation requirements
*
@@ -239,4 +208,35 @@ public function validateTemplatePath(array $templatePaths)
}
}
}
+
+ /**
+ * Initialize messages templates with translating
+ *
+ * @return Mage_Core_Model_Layout_Validator
+ */
+ protected function _initMessageTemplates()
+ {
+ if (!$this->_messageTemplates) {
+ $this->_messageTemplates = [
+ self::PROTECTED_ATTR_HELPER_IN_TAG_ACTION_VAR =>
+ Mage::helper('core')->__('Helper attributes should not be used in custom layout updates.'),
+ self::XML_INVALID => Mage::helper('core')->__('XML data is invalid.'),
+ self::INVALID_TEMPLATE_PATH => Mage::helper('core')->__(
+ 'Invalid template path used in layout update.',
+ ),
+ self::INVALID_BLOCK_NAME => Mage::helper('core')->__('Disallowed block name for frontend.'),
+ self::INVALID_XML_OBJECT_EXCEPTION =>
+ Mage::helper('core')->__('XML object is not instance of "Varien_Simplexml_Element".'),
+ ];
+ }
+ return $this;
+ }
+
+ /**
+ * @return mixed
+ */
+ protected function _getDisallowedBlockConfigValue()
+ {
+ return Mage::getStoreConfig(self::XML_PATH_LAYOUT_DISALLOWED_BLOCKS);
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Locale.php b/app/code/core/Mage/Core/Model/Locale.php
index c7457f72589..58964c6fb39 100644
--- a/app/code/core/Mage/Core/Model/Locale.php
+++ b/app/code/core/Mage/Core/Model/Locale.php
@@ -218,61 +218,6 @@ public function getTranslatedOptionLocales()
return $this->_getOptionLocales(true);
}
- /**
- * Get options array for locale dropdown
- *
- * @param bool $translatedName translation flag
- * @return array
- */
- protected function _getOptionLocales($translatedName = false)
- {
- $options = [];
- $zendLocales = $this->getLocale()->getLocaleList();
- $languages = $this->getLocale()->getTranslationList('language', $this->getLocale());
- $countries = $this->getCountryTranslationList();
-
- //Zend locale codes for internal allowed locale codes
- $allowed = $this->getAllowLocales();
- $allowedAliases = [];
- foreach ($allowed as $code) {
- $allowedAliases[Zend_Locale::getAlias($code)] = $code;
- }
-
- //Internal locale codes translated from Zend locale codes
- $locales = [];
- foreach ($zendLocales as $code => $active) {
- if (array_key_exists($code, $allowedAliases)) {
- $locales[$allowedAliases[$code]] = $active;
- } else {
- $locales[$code] = $active;
- }
- }
-
- foreach (array_keys($locales) as $code) {
- if (strstr($code, '_')) {
- if (!in_array($code, $allowed)) {
- continue;
- }
- $data = explode('_', $code);
- if (!isset($languages[$data[0]]) || !isset($countries[$data[1]])) {
- continue;
- }
- if ($translatedName) {
- $label = ucwords($this->getLocale()->getTranslation($data[0], 'language', $code))
- . ' (' . $this->getLocale()->getTranslation($data[1], 'country', $code) . ') / '
- . $languages[$data[0]] . ' (' . $countries[$data[1]] . ')';
- } else {
- $label = $languages[$data[0]] . ' (' . $countries[$data[1]] . ')';
- }
- $options[] = [
- 'value' => $code,
- 'label' => $label,
- ];
- }
- }
- return $this->_sortOptionArray($options);
- }
-
/**
* Retrieve timezone option list
*
@@ -386,27 +331,6 @@ public function getOptionAllCurrencies()
return $this->_sortOptionArray($options);
}
- /**
- * @param array $option
- * @return array
- */
- protected function _sortOptionArray($option)
- {
- $data = [];
- foreach ($option as $item) {
- $data[$item['value']] = $item['label'];
- }
- asort($data);
- $option = [];
- foreach ($data as $key => $label) {
- $option[] = [
- 'value' => $key,
- 'label' => $label,
- ];
- }
- return $option;
- }
-
/**
* Retrieve array of allowed locales
*
@@ -789,17 +713,6 @@ public function getTranslation($value = null, $path = null)
return $this->getLocale()->getTranslation($value, $path, $this->getLocale());
}
- /**
- * Replace all yy date format to yyyy
- *
- * @param string $currentFormat
- * @return string|string[]|null
- */
- protected function _convertYearTwoDigitTo4($currentFormat)
- {
- return preg_replace('/(\byy\b)/', 'yyyy', $currentFormat);
- }
-
/**
* Returns the localized country name
*
@@ -852,4 +765,91 @@ public function isStoreDateInInterval($store, $dateFrom = null, $dateTo = null)
return $result;
}
+
+ /**
+ * Get options array for locale dropdown
+ *
+ * @param bool $translatedName translation flag
+ * @return array
+ */
+ protected function _getOptionLocales($translatedName = false)
+ {
+ $options = [];
+ $zendLocales = $this->getLocale()->getLocaleList();
+ $languages = $this->getLocale()->getTranslationList('language', $this->getLocale());
+ $countries = $this->getCountryTranslationList();
+
+ //Zend locale codes for internal allowed locale codes
+ $allowed = $this->getAllowLocales();
+ $allowedAliases = [];
+ foreach ($allowed as $code) {
+ $allowedAliases[Zend_Locale::getAlias($code)] = $code;
+ }
+
+ //Internal locale codes translated from Zend locale codes
+ $locales = [];
+ foreach ($zendLocales as $code => $active) {
+ if (array_key_exists($code, $allowedAliases)) {
+ $locales[$allowedAliases[$code]] = $active;
+ } else {
+ $locales[$code] = $active;
+ }
+ }
+
+ foreach (array_keys($locales) as $code) {
+ if (strstr($code, '_')) {
+ if (!in_array($code, $allowed)) {
+ continue;
+ }
+ $data = explode('_', $code);
+ if (!isset($languages[$data[0]]) || !isset($countries[$data[1]])) {
+ continue;
+ }
+ if ($translatedName) {
+ $label = ucwords($this->getLocale()->getTranslation($data[0], 'language', $code))
+ . ' (' . $this->getLocale()->getTranslation($data[1], 'country', $code) . ') / '
+ . $languages[$data[0]] . ' (' . $countries[$data[1]] . ')';
+ } else {
+ $label = $languages[$data[0]] . ' (' . $countries[$data[1]] . ')';
+ }
+ $options[] = [
+ 'value' => $code,
+ 'label' => $label,
+ ];
+ }
+ }
+ return $this->_sortOptionArray($options);
+ }
+
+ /**
+ * @param array $option
+ * @return array
+ */
+ protected function _sortOptionArray($option)
+ {
+ $data = [];
+ foreach ($option as $item) {
+ $data[$item['value']] = $item['label'];
+ }
+ asort($data);
+ $option = [];
+ foreach ($data as $key => $label) {
+ $option[] = [
+ 'value' => $key,
+ 'label' => $label,
+ ];
+ }
+ return $option;
+ }
+
+ /**
+ * Replace all yy date format to yyyy
+ *
+ * @param string $currentFormat
+ * @return string|string[]|null
+ */
+ protected function _convertYearTwoDigitTo4($currentFormat)
+ {
+ return preg_replace('/(\byy\b)/', 'yyyy', $currentFormat);
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Message.php b/app/code/core/Mage/Core/Model/Message.php
index 6cda1a7d705..8047f55b81a 100644
--- a/app/code/core/Mage/Core/Model/Message.php
+++ b/app/code/core/Mage/Core/Model/Message.php
@@ -29,31 +29,13 @@ class Mage_Core_Model_Message
/**
* @param string $code
- * @param string $type
* @param string $class
* @param string $method
* @return Mage_Core_Model_Message_Error|Mage_Core_Model_Message_Notice|Mage_Core_Model_Message_Success|Mage_Core_Model_Message_Warning
*/
- protected function _factory($code, $type, $class = '', $method = '')
+ public function error($code, $class = '', $method = '')
{
- switch (strtolower($type)) {
- case self::ERROR:
- $message = new Mage_Core_Model_Message_Error($code);
- break;
- case self::WARNING:
- $message = new Mage_Core_Model_Message_Warning($code);
- break;
- case self::SUCCESS:
- $message = new Mage_Core_Model_Message_Success($code);
- break;
- default:
- $message = new Mage_Core_Model_Message_Notice($code);
- break;
- }
- $message->setClass($class);
- $message->setMethod($method);
-
- return $message;
+ return $this->_factory($code, self::ERROR, $class, $method);
}
/**
@@ -62,9 +44,9 @@ protected function _factory($code, $type, $class = '', $method = '')
* @param string $method
* @return Mage_Core_Model_Message_Error|Mage_Core_Model_Message_Notice|Mage_Core_Model_Message_Success|Mage_Core_Model_Message_Warning
*/
- public function error($code, $class = '', $method = '')
+ public function warning($code, $class = '', $method = '')
{
- return $this->_factory($code, self::ERROR, $class, $method);
+ return $this->_factory($code, self::WARNING, $class, $method);
}
/**
@@ -73,9 +55,9 @@ public function error($code, $class = '', $method = '')
* @param string $method
* @return Mage_Core_Model_Message_Error|Mage_Core_Model_Message_Notice|Mage_Core_Model_Message_Success|Mage_Core_Model_Message_Warning
*/
- public function warning($code, $class = '', $method = '')
+ public function notice($code, $class = '', $method = '')
{
- return $this->_factory($code, self::WARNING, $class, $method);
+ return $this->_factory($code, self::NOTICE, $class, $method);
}
/**
@@ -84,19 +66,37 @@ public function warning($code, $class = '', $method = '')
* @param string $method
* @return Mage_Core_Model_Message_Error|Mage_Core_Model_Message_Notice|Mage_Core_Model_Message_Success|Mage_Core_Model_Message_Warning
*/
- public function notice($code, $class = '', $method = '')
+ public function success($code, $class = '', $method = '')
{
- return $this->_factory($code, self::NOTICE, $class, $method);
+ return $this->_factory($code, self::SUCCESS, $class, $method);
}
/**
* @param string $code
+ * @param string $type
* @param string $class
* @param string $method
* @return Mage_Core_Model_Message_Error|Mage_Core_Model_Message_Notice|Mage_Core_Model_Message_Success|Mage_Core_Model_Message_Warning
*/
- public function success($code, $class = '', $method = '')
+ protected function _factory($code, $type, $class = '', $method = '')
{
- return $this->_factory($code, self::SUCCESS, $class, $method);
+ switch (strtolower($type)) {
+ case self::ERROR:
+ $message = new Mage_Core_Model_Message_Error($code);
+ break;
+ case self::WARNING:
+ $message = new Mage_Core_Model_Message_Warning($code);
+ break;
+ case self::SUCCESS:
+ $message = new Mage_Core_Model_Message_Success($code);
+ break;
+ default:
+ $message = new Mage_Core_Model_Message_Notice($code);
+ break;
+ }
+ $message->setClass($class);
+ $message->setMethod($method);
+
+ return $message;
}
}
diff --git a/app/code/core/Mage/Core/Model/Resource.php b/app/code/core/Mage/Core/Model/Resource.php
index 11ef2212c3f..2bbbe037090 100644
--- a/app/code/core/Mage/Core/Model/Resource.php
+++ b/app/code/core/Mage/Core/Model/Resource.php
@@ -126,81 +126,6 @@ public function getConnections()
return $this->_connections;
}
- /**
- * Retrieve connection adapter class name by connection type
- *
- * @param string $type the connection type
- * @return string|false
- */
- protected function _getConnectionAdapterClassName($type)
- {
- $config = Mage::getConfig()->getResourceTypeConfig($type);
- if (!empty($config->adapter)) {
- return (string) $config->adapter;
- }
- return false;
- }
-
- /**
- * Create new connection adapter instance by connection type and config
- *
- * @param string $type the connection type
- * @param Mage_Core_Model_Config_Element|array $config the connection configuration
- * @return Varien_Db_Adapter_Interface|false
- */
- protected function _newConnection($type, $config)
- {
- if ($config instanceof Mage_Core_Model_Config_Element) {
- $config = $config->asArray();
- }
- if (!is_array($config)) {
- return false;
- }
-
- $connection = false;
- // try to get adapter and create connection
- $className = $this->_getConnectionAdapterClassName($type);
- if ($className) {
- // define profiler settings
- $config['profiler'] = isset($config['profiler']) && $config['profiler'] != 'false';
-
- $connection = new $className($config);
- if ($connection instanceof Varien_Db_Adapter_Interface) {
- // run after initialization statements
- if (!empty($config['initStatements'])) {
- $connection->query($config['initStatements']);
- }
- } else {
- $connection = false;
- }
- }
-
- // try to get connection from type
- if (!$connection) {
- $typeInstance = $this->getConnectionTypeInstance($type);
- $connection = $typeInstance->getConnection($config);
- if (!$connection instanceof Varien_Db_Adapter_Interface) {
- $connection = false;
- }
- }
-
- return $connection;
- }
-
- /**
- * Retrieve default connection name by required connection name
- *
- * @param string $requiredConnectionName
- * @return string
- */
- protected function _getDefaultConnection($requiredConnectionName)
- {
- if (str_contains($requiredConnectionName, 'read')) {
- return $this->getConnection(self::DEFAULT_READ_RESOURCE);
- }
- return $this->getConnection(self::DEFAULT_WRITE_RESOURCE);
- }
-
/**
* Get connection type instance
*
@@ -417,4 +342,79 @@ public function getFkName($priTableName, $priColumnName, $refTableName, $refColu
$refColumnName,
);
}
+
+ /**
+ * Retrieve connection adapter class name by connection type
+ *
+ * @param string $type the connection type
+ * @return string|false
+ */
+ protected function _getConnectionAdapterClassName($type)
+ {
+ $config = Mage::getConfig()->getResourceTypeConfig($type);
+ if (!empty($config->adapter)) {
+ return (string) $config->adapter;
+ }
+ return false;
+ }
+
+ /**
+ * Create new connection adapter instance by connection type and config
+ *
+ * @param string $type the connection type
+ * @param Mage_Core_Model_Config_Element|array $config the connection configuration
+ * @return Varien_Db_Adapter_Interface|false
+ */
+ protected function _newConnection($type, $config)
+ {
+ if ($config instanceof Mage_Core_Model_Config_Element) {
+ $config = $config->asArray();
+ }
+ if (!is_array($config)) {
+ return false;
+ }
+
+ $connection = false;
+ // try to get adapter and create connection
+ $className = $this->_getConnectionAdapterClassName($type);
+ if ($className) {
+ // define profiler settings
+ $config['profiler'] = isset($config['profiler']) && $config['profiler'] != 'false';
+
+ $connection = new $className($config);
+ if ($connection instanceof Varien_Db_Adapter_Interface) {
+ // run after initialization statements
+ if (!empty($config['initStatements'])) {
+ $connection->query($config['initStatements']);
+ }
+ } else {
+ $connection = false;
+ }
+ }
+
+ // try to get connection from type
+ if (!$connection) {
+ $typeInstance = $this->getConnectionTypeInstance($type);
+ $connection = $typeInstance->getConnection($config);
+ if (!$connection instanceof Varien_Db_Adapter_Interface) {
+ $connection = false;
+ }
+ }
+
+ return $connection;
+ }
+
+ /**
+ * Retrieve default connection name by required connection name
+ *
+ * @param string $requiredConnectionName
+ * @return string
+ */
+ protected function _getDefaultConnection($requiredConnectionName)
+ {
+ if (str_contains($requiredConnectionName, 'read')) {
+ return $this->getConnection(self::DEFAULT_READ_RESOURCE);
+ }
+ return $this->getConnection(self::DEFAULT_WRITE_RESOURCE);
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Abstract.php b/app/code/core/Mage/Core/Model/Resource/Abstract.php
index 55497b83026..7347e5660f5 100644
--- a/app/code/core/Mage/Core/Model/Resource/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Resource/Abstract.php
@@ -22,6 +22,12 @@
*/
abstract class Mage_Core_Model_Resource_Abstract
{
+ /**
+ * Array of callbacks subscribed to commit transaction commit
+ *
+ * @var array
+ */
+ protected static $_commitCallbacks = [];
/**
* Main constructor
*/
@@ -33,27 +39,6 @@ public function __construct()
$this->_construct();
}
- /**
- * Array of callbacks subscribed to commit transaction commit
- *
- * @var array
- */
- protected static $_commitCallbacks = [];
-
- abstract protected function _construct();
-
- /**
- * Retrieve connection for read data
- * @return Varien_Db_Adapter_Interface
- */
- abstract protected function _getReadAdapter();
-
- /**
- * Retrieve connection for write data
- * @return Varien_Db_Adapter_Interface
- */
- abstract protected function _getWriteAdapter();
-
/**
* Start resource transaction
*
@@ -145,6 +130,25 @@ public function mktime($str)
return Varien_Date::toTimestamp($str);
}
+ public function isModuleEnabled(string $moduleName, string $helperAlias = 'core'): bool
+ {
+ return Mage::helper($helperAlias)->isModuleEnabled($moduleName);
+ }
+
+ abstract protected function _construct();
+
+ /**
+ * Retrieve connection for read data
+ * @return Varien_Db_Adapter_Interface
+ */
+ abstract protected function _getReadAdapter();
+
+ /**
+ * Retrieve connection for write data
+ * @return Varien_Db_Adapter_Interface
+ */
+ abstract protected function _getWriteAdapter();
+
/**
* Serialize specified field in an object
*
@@ -230,9 +234,4 @@ protected function _prepareTableValueForSave($value, $type)
}
return $value;
}
-
- public function isModuleEnabled(string $moduleName, string $helperAlias = 'core'): bool
- {
- return Mage::helper($helperAlias)->isModuleEnabled($moduleName);
- }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Cache.php b/app/code/core/Mage/Core/Model/Resource/Cache.php
index 12722fb3884..bafd49d8b06 100644
--- a/app/code/core/Mage/Core/Model/Resource/Cache.php
+++ b/app/code/core/Mage/Core/Model/Resource/Cache.php
@@ -22,11 +22,6 @@
*/
class Mage_Core_Model_Resource_Cache extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('core/cache_option', 'code');
- }
-
/**
* Get all cache options
*
@@ -81,4 +76,8 @@ public function saveAllOptions($options)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('core/cache_option', 'code');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Config.php b/app/code/core/Mage/Core/Model/Resource/Config.php
index 0c53f7d0890..300ff3241a8 100644
--- a/app/code/core/Mage/Core/Model/Resource/Config.php
+++ b/app/code/core/Mage/Core/Model/Resource/Config.php
@@ -22,11 +22,6 @@
*/
class Mage_Core_Model_Resource_Config extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('core/config_data', 'config_id');
- }
-
/**
* Load configuration values into xml config object
*
@@ -224,4 +219,8 @@ public function getConfig(string $path, string $scope, int $scopeId)
return $readAdapter->fetchOne($select);
}
+ protected function _construct()
+ {
+ $this->_init('core/config_data', 'config_id');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Config/Data/Collection.php b/app/code/core/Mage/Core/Model/Resource/Config/Data/Collection.php
index 4787f86074f..89ee48b8f06 100644
--- a/app/code/core/Mage/Core/Model/Resource/Config/Data/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Config/Data/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Core_Model_Resource_Config_Data_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- $this->_init('core/config_data');
- }
-
/**
* Add scope filter to collection
*
@@ -70,4 +61,12 @@ public function addValueFilter($value)
$this->addFieldToFilter('value', ['like' => $value]);
return $this;
}
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('core/config_data');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php b/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php
index de7998fe5b6..bc8ae1f1d0b 100644
--- a/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php
@@ -135,78 +135,6 @@ abstract class Mage_Core_Model_Resource_Db_Abstract extends Mage_Core_Model_Reso
*/
protected $_serializableFields = [];
- /**
- * Standard resource model initialization
- *
- * @param string $mainTable
- * @param string $idFieldName
- */
- protected function _init($mainTable, $idFieldName)
- {
- $this->_setMainTable($mainTable, $idFieldName);
- }
-
- /**
- * Initialize connections and tables for this resource model
- * If one or both arguments are string, will be used as prefix
- * If $tables is null and $connections is string, $tables will be the same
- *
- * @param string|array $connections
- * @param string|array|null $tables
- * @return Mage_Core_Model_Resource_Abstract
- */
- protected function _setResource($connections, $tables = null)
- {
- $this->_resources = Mage::getSingleton('core/resource');
-
- if (is_array($connections)) {
- foreach ($connections as $k => $v) {
- $this->_connections[$k] = $this->_resources->getConnection($v);
- }
- } elseif (is_string($connections)) {
- $this->_resourcePrefix = $connections;
- }
-
- if (is_null($tables) && is_string($connections)) {
- $this->_resourceModel = $this->_resourcePrefix;
- } elseif (is_array($tables)) {
- foreach ($tables as $k => $v) {
- $this->_tables[$k] = $this->_resources->getTableName($v);
- }
- } elseif (is_string($tables)) {
- $this->_resourceModel = $tables;
- }
- return $this;
- }
-
- /**
- * Set main entity table name and primary key field name
- * If field name is omitted {table_name}_id will be used
- *
- * @param string $mainTable
- * @param string|null $idFieldName
- * @return $this
- */
- protected function _setMainTable($mainTable, $idFieldName = null)
- {
- $mainTableArr = explode('/', $mainTable);
-
- if (!empty($mainTableArr[1])) {
- if (empty($this->_resourceModel)) {
- $this->_setResource($mainTableArr[0]);
- }
- $this->_setMainTable($mainTableArr[1], $idFieldName);
- } else {
- $this->_mainTable = $mainTable;
- if (is_null($idFieldName)) {
- $idFieldName = $mainTable . '_id';
- }
- $this->_idFieldName = $idFieldName;
- }
-
- return $this;
- }
-
/**
* Get primary key field name
*
@@ -290,28 +218,6 @@ public function getValueTable($entityName, $valueType)
return $this->getTable([$entityName, $valueType]);
}
- /**
- * Get connection by name or type
- *
- * @param string $connectionName
- * @return Magento_Db_Adapter_Pdo_Mysql
- */
- protected function _getConnection($connectionName)
- {
- if (isset($this->_connections[$connectionName])) {
- return $this->_connections[$connectionName];
- }
- if (!empty($this->_resourcePrefix)) {
- $this->_connections[$connectionName] = $this->_resources->getConnection(
- $this->_resourcePrefix . '_' . $connectionName,
- );
- } else {
- $this->_connections[$connectionName] = $this->_resources->getConnection($connectionName);
- }
-
- return $this->_connections[$connectionName];
- }
-
/**
* @param string $connectionName
* @return bool
@@ -321,34 +227,6 @@ public function hasConnection($connectionName)
return isset($this->_connections[$connectionName]);
}
- /**
- * Retrieve connection for read data
- *
- * @return Magento_Db_Adapter_Pdo_Mysql
- */
- protected function _getReadAdapter()
- {
- if ($this->hasConnection('write')) {
- $writeAdapter = $this->_getWriteAdapter();
- if ($writeAdapter && $writeAdapter->getTransactionLevel() > 0) {
- // if transaction is started we should use write connection for reading
- return $writeAdapter;
- }
- }
-
- return $this->_getConnection('read');
- }
-
- /**
- * Retrieve connection for write data
- *
- * @return Magento_Db_Adapter_Pdo_Mysql
- */
- protected function _getWriteAdapter()
- {
- return $this->_getConnection('write');
- }
-
/**
* Temporary resolving collection compatibility
*
@@ -388,30 +266,6 @@ public function load(Mage_Core_Model_Abstract $object, $value, $field = null)
return $this;
}
- /**
- * Retrieve select object for load object data
- *
- * @param string $field
- * @param mixed $value
- * @param Mage_Core_Model_Abstract $object
- * @return Varien_Db_Select
- * @throws Exception
- */
- protected function _getLoadSelect($field, $value, $object)
- {
- $fields = $this->_getReadAdapter()->describeTable($this->getMainTable());
-
- if (!isset($fields[$field])) {
- throw new Exception("Column \"{$field}\" does not exist in table \"{$this->getMainTable()}\"");
- }
-
- $value = $this->_getReadAdapter()->prepareColumnValue($fields[$field], $value);
- $field = $this->_getReadAdapter()->quoteIdentifier(sprintf('%s.%s', $this->getMainTable(), $field));
- return $this->_getReadAdapter()->select()
- ->from($this->getMainTable())
- ->where($field . '=?', $value);
- }
-
/**
* Save object object data
*
@@ -552,17 +406,6 @@ public function unserializeFields(Mage_Core_Model_Abstract $object)
}
}
- /**
- * Initialize unique fields
- *
- * @return $this
- */
- protected function _initUniqueFields()
- {
- $this->_uniqueFields = [];
- return $this;
- }
-
/**
* Get configuration of all unique fields
*
@@ -576,16 +419,6 @@ public function getUniqueFields()
return $this->_uniqueFields;
}
- /**
- * Prepare data for save
- *
- * @return array
- */
- protected function _prepareDataForSave(Mage_Core_Model_Abstract $object)
- {
- return $this->_prepareDataForTable($object, $this->getMainTable());
- }
-
/**
* Check that model data fields that can be saved
* has really changed comparing with origData
@@ -609,6 +442,199 @@ public function hasDataChanged($object)
return false;
}
+ /**
+ * After load
+ */
+ public function afterLoad(Mage_Core_Model_Abstract $object)
+ {
+ $this->_afterLoad($object);
+ }
+
+ /**
+ * Retrieve table checksum
+ *
+ * @param string|array $table
+ * @return array|false
+ */
+ public function getChecksum($table)
+ {
+ if (!$this->_getReadAdapter()) {
+ return false;
+ }
+ $checksum = $this->_getReadAdapter()->getTablesChecksum($table);
+ if (count($checksum) == 1) {
+ return $checksum[$table];
+ }
+ return $checksum;
+ }
+
+ /**
+ * Standard resource model initialization
+ *
+ * @param string $mainTable
+ * @param string $idFieldName
+ */
+ protected function _init($mainTable, $idFieldName)
+ {
+ $this->_setMainTable($mainTable, $idFieldName);
+ }
+
+ /**
+ * Initialize connections and tables for this resource model
+ * If one or both arguments are string, will be used as prefix
+ * If $tables is null and $connections is string, $tables will be the same
+ *
+ * @param string|array $connections
+ * @param string|array|null $tables
+ * @return Mage_Core_Model_Resource_Abstract
+ */
+ protected function _setResource($connections, $tables = null)
+ {
+ $this->_resources = Mage::getSingleton('core/resource');
+
+ if (is_array($connections)) {
+ foreach ($connections as $k => $v) {
+ $this->_connections[$k] = $this->_resources->getConnection($v);
+ }
+ } elseif (is_string($connections)) {
+ $this->_resourcePrefix = $connections;
+ }
+
+ if (is_null($tables) && is_string($connections)) {
+ $this->_resourceModel = $this->_resourcePrefix;
+ } elseif (is_array($tables)) {
+ foreach ($tables as $k => $v) {
+ $this->_tables[$k] = $this->_resources->getTableName($v);
+ }
+ } elseif (is_string($tables)) {
+ $this->_resourceModel = $tables;
+ }
+ return $this;
+ }
+
+ /**
+ * Set main entity table name and primary key field name
+ * If field name is omitted {table_name}_id will be used
+ *
+ * @param string $mainTable
+ * @param string|null $idFieldName
+ * @return $this
+ */
+ protected function _setMainTable($mainTable, $idFieldName = null)
+ {
+ $mainTableArr = explode('/', $mainTable);
+
+ if (!empty($mainTableArr[1])) {
+ if (empty($this->_resourceModel)) {
+ $this->_setResource($mainTableArr[0]);
+ }
+ $this->_setMainTable($mainTableArr[1], $idFieldName);
+ } else {
+ $this->_mainTable = $mainTable;
+ if (is_null($idFieldName)) {
+ $idFieldName = $mainTable . '_id';
+ }
+ $this->_idFieldName = $idFieldName;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get connection by name or type
+ *
+ * @param string $connectionName
+ * @return Magento_Db_Adapter_Pdo_Mysql
+ */
+ protected function _getConnection($connectionName)
+ {
+ if (isset($this->_connections[$connectionName])) {
+ return $this->_connections[$connectionName];
+ }
+ if (!empty($this->_resourcePrefix)) {
+ $this->_connections[$connectionName] = $this->_resources->getConnection(
+ $this->_resourcePrefix . '_' . $connectionName,
+ );
+ } else {
+ $this->_connections[$connectionName] = $this->_resources->getConnection($connectionName);
+ }
+
+ return $this->_connections[$connectionName];
+ }
+
+ /**
+ * Retrieve connection for read data
+ *
+ * @return Magento_Db_Adapter_Pdo_Mysql
+ */
+ protected function _getReadAdapter()
+ {
+ if ($this->hasConnection('write')) {
+ $writeAdapter = $this->_getWriteAdapter();
+ if ($writeAdapter && $writeAdapter->getTransactionLevel() > 0) {
+ // if transaction is started we should use write connection for reading
+ return $writeAdapter;
+ }
+ }
+
+ return $this->_getConnection('read');
+ }
+
+ /**
+ * Retrieve connection for write data
+ *
+ * @return Magento_Db_Adapter_Pdo_Mysql
+ */
+ protected function _getWriteAdapter()
+ {
+ return $this->_getConnection('write');
+ }
+
+ /**
+ * Retrieve select object for load object data
+ *
+ * @param string $field
+ * @param mixed $value
+ * @param Mage_Core_Model_Abstract $object
+ * @return Varien_Db_Select
+ * @throws Exception
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ $fields = $this->_getReadAdapter()->describeTable($this->getMainTable());
+
+ if (!isset($fields[$field])) {
+ throw new Exception("Column \"{$field}\" does not exist in table \"{$this->getMainTable()}\"");
+ }
+
+ $value = $this->_getReadAdapter()->prepareColumnValue($fields[$field], $value);
+ $field = $this->_getReadAdapter()->quoteIdentifier(sprintf('%s.%s', $this->getMainTable(), $field));
+ return $this->_getReadAdapter()->select()
+ ->from($this->getMainTable())
+ ->where($field . '=?', $value);
+ }
+
+ /**
+ * Initialize unique fields
+ *
+ * @return $this
+ */
+ protected function _initUniqueFields()
+ {
+ $this->_uniqueFields = [];
+ return $this;
+ }
+
+ /**
+ * Prepare data for save
+ *
+ * @return array
+ */
+ protected function _prepareDataForSave(Mage_Core_Model_Abstract $object)
+ {
+ return $this->_prepareDataForTable($object, $this->getMainTable());
+ }
+
/**
* Prepare value for save
*
@@ -678,14 +704,6 @@ protected function _checkUnique(Mage_Core_Model_Abstract $object)
return $this;
}
- /**
- * After load
- */
- public function afterLoad(Mage_Core_Model_Abstract $object)
- {
- $this->_afterLoad($object);
- }
-
/**
* Perform actions after object load
*
@@ -746,22 +764,4 @@ protected function _serializeFields(Mage_Core_Model_Abstract $object)
$this->_serializeField($object, $field, $serializeDefault, isset($parameters[2]));
}
}
-
- /**
- * Retrieve table checksum
- *
- * @param string|array $table
- * @return array|false
- */
- public function getChecksum($table)
- {
- if (!$this->_getReadAdapter()) {
- return false;
- }
- $checksum = $this->_getReadAdapter()->getTablesChecksum($table);
- if (count($checksum) == 1) {
- return $checksum[$table];
- }
- return $checksum;
- }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php b/app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php
index f2c8f74a8a0..207c6a2a8ac 100644
--- a/app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php
@@ -123,13 +123,6 @@ public function __construct($resource = null)
$this->_initSelect();
}
- /**
- * Initialization here
- *
- * @return void
- */
- protected function _construct() {}
-
/**
* Retrieve main table
*
@@ -168,17 +161,6 @@ public function setMainTable($table)
return $this;
}
- /**
- * Init collection select
- *
- * @return $this
- */
- protected function _initSelect()
- {
- $this->getSelect()->from(['main_table' => $this->getMainTable()]);
- return $this;
- }
-
/**
* Get Zend_Db_Select instance and applies fields to select if needed
*
@@ -193,92 +175,6 @@ public function getSelect()
return parent::getSelect();
}
- /**
- * Init fields for select
- *
- * @return $this
- */
- protected function _initSelectFields()
- {
- $columns = $this->_select->getPart(Zend_Db_Select::COLUMNS);
- $columnsToSelect = [];
- foreach ($columns as $columnEntry) {
- list($correlationName, $column, $alias) = $columnEntry;
- if ($correlationName !== 'main_table') { // Add joined fields to select
- if ($column instanceof Zend_Db_Expr) {
- $column = $column->__toString();
- }
- $key = $alias ?? $column;
- $columnsToSelect[$key] = $columnEntry;
- }
- }
-
- $columns = $columnsToSelect;
-
- $columnsToSelect = array_keys($columnsToSelect);
-
- if ($this->_fieldsToSelect !== null) {
- $insertIndex = 0;
- foreach ($this->_fieldsToSelect as $alias => $field) {
- if (!is_string($alias)) {
- $alias = null;
- }
-
- if ($field instanceof Zend_Db_Expr) {
- $column = $field->__toString();
- } else {
- $column = $field;
- }
-
- if (($alias !== null && in_array($alias, $columnsToSelect)) ||
- // If field already joined from another table
- ($alias === null && isset($alias, $columnsToSelect))
- ) {
- continue;
- }
-
- $columnEntry = ['main_table', $field, $alias];
- array_splice($columns, $insertIndex, 0, [$columnEntry]); // Insert column
- $insertIndex++;
- }
- } else {
- array_unshift($columns, ['main_table', '*', null]);
- }
-
- $this->_select->setPart(Zend_Db_Select::COLUMNS, $columns);
-
- return $this;
- }
-
- /**
- * Retrieve initial fields to select like id field
- *
- * @return array
- */
- protected function _getInitialFieldsToSelect()
- {
- if ($this->_initialFieldsToSelect === null) {
- $this->_initialFieldsToSelect = [];
- $this->_initInitialFieldsToSelect();
- }
-
- return $this->_initialFieldsToSelect;
- }
-
- /**
- * Initialize initial fields to select like id field
- *
- * @return $this
- */
- protected function _initInitialFieldsToSelect()
- {
- $idFieldName = $this->getResource()->getIdFieldName();
- if ($idFieldName) {
- $this->_initialFieldsToSelect[] = $idFieldName;
- }
- return $this;
- }
-
/**
* Add field to select
*
@@ -386,23 +282,6 @@ public function removeAllFieldsFromSelect()
return $this;
}
- /**
- * Standard resource collection initialization
- *
- * @param string $model
- * @param Mage_Core_Model_Resource_Db_Abstract $resourceModel
- * @return $this
- */
- protected function _init($model, $resourceModel = null)
- {
- $this->setModel($model);
- if (is_null($resourceModel)) {
- $resourceModel = $model;
- }
- $this->setResourceModel($resourceModel);
- return $this;
- }
-
/**
* Set model name for collection items
*
@@ -509,29 +388,6 @@ public function getData()
}
return $this->_data;
}
-
- /**
- * Prepare select for load
- *
- * @return string
- * @throws Zend_Db_Select_Exception
- */
- protected function _prepareSelect(Varien_Db_Select $select)
- {
- /** @var Mage_Core_Model_Resource_Helper_Mysql4 $helper */
- $helper = Mage::getResourceHelper('core');
-
- $unionParts = $select->getPart(Zend_Db_Select::UNION);
- if (!empty($unionParts)) {
- $select = $helper->limitUnion($select);
- }
-
- if ($this->_useAnalyticFunction) {
- return $helper->getQueryUsingAnalyticFunction($select);
- }
-
- return (string) $select;
- }
/**
* Join table to collection select
*
@@ -563,23 +419,6 @@ public function join($table, $cond, $cols = '*')
return $this;
}
- /**
- * Redeclare before load method for adding event
- *
- * @return $this
- */
- protected function _beforeLoad()
- {
- parent::_beforeLoad();
- Mage::dispatchEvent('core_collection_abstract_load_before', ['collection' => $this]);
- if ($this->_eventPrefix && $this->_eventObject) {
- Mage::dispatchEvent($this->_eventPrefix . '_load_before', [
- $this->_eventObject => $this,
- ]);
- }
- return $this;
- }
-
/**
* Set reset items data changed flag
*
@@ -607,6 +446,192 @@ public function resetItemsDataChanged()
return $this;
}
+ /**
+ * Save all the entities in the collection
+ *
+ * @return $this
+ */
+ public function save()
+ {
+ foreach ($this->getItems() as $item) {
+ $item->save();
+ }
+ return $this;
+ }
+
+ /**
+ * Format Date to internal database date format
+ *
+ * @param int|string|Zend_Date $date
+ * @param bool $includeTime
+ * @return string
+ */
+ public function formatDate($date, $includeTime = true)
+ {
+ return Varien_Date::formatDate($date, $includeTime);
+ }
+
+ /**
+ * Initialization here
+ *
+ * @return void
+ */
+ protected function _construct() {}
+
+ /**
+ * Init collection select
+ *
+ * @return $this
+ */
+ protected function _initSelect()
+ {
+ $this->getSelect()->from(['main_table' => $this->getMainTable()]);
+ return $this;
+ }
+
+ /**
+ * Init fields for select
+ *
+ * @return $this
+ */
+ protected function _initSelectFields()
+ {
+ $columns = $this->_select->getPart(Zend_Db_Select::COLUMNS);
+ $columnsToSelect = [];
+ foreach ($columns as $columnEntry) {
+ list($correlationName, $column, $alias) = $columnEntry;
+ if ($correlationName !== 'main_table') { // Add joined fields to select
+ if ($column instanceof Zend_Db_Expr) {
+ $column = $column->__toString();
+ }
+ $key = $alias ?? $column;
+ $columnsToSelect[$key] = $columnEntry;
+ }
+ }
+
+ $columns = $columnsToSelect;
+
+ $columnsToSelect = array_keys($columnsToSelect);
+
+ if ($this->_fieldsToSelect !== null) {
+ $insertIndex = 0;
+ foreach ($this->_fieldsToSelect as $alias => $field) {
+ if (!is_string($alias)) {
+ $alias = null;
+ }
+
+ if ($field instanceof Zend_Db_Expr) {
+ $column = $field->__toString();
+ } else {
+ $column = $field;
+ }
+
+ if (($alias !== null && in_array($alias, $columnsToSelect)) ||
+ // If field already joined from another table
+ ($alias === null && isset($alias, $columnsToSelect))
+ ) {
+ continue;
+ }
+
+ $columnEntry = ['main_table', $field, $alias];
+ array_splice($columns, $insertIndex, 0, [$columnEntry]); // Insert column
+ $insertIndex++;
+ }
+ } else {
+ array_unshift($columns, ['main_table', '*', null]);
+ }
+
+ $this->_select->setPart(Zend_Db_Select::COLUMNS, $columns);
+
+ return $this;
+ }
+
+ /**
+ * Retrieve initial fields to select like id field
+ *
+ * @return array
+ */
+ protected function _getInitialFieldsToSelect()
+ {
+ if ($this->_initialFieldsToSelect === null) {
+ $this->_initialFieldsToSelect = [];
+ $this->_initInitialFieldsToSelect();
+ }
+
+ return $this->_initialFieldsToSelect;
+ }
+
+ /**
+ * Initialize initial fields to select like id field
+ *
+ * @return $this
+ */
+ protected function _initInitialFieldsToSelect()
+ {
+ $idFieldName = $this->getResource()->getIdFieldName();
+ if ($idFieldName) {
+ $this->_initialFieldsToSelect[] = $idFieldName;
+ }
+ return $this;
+ }
+
+ /**
+ * Standard resource collection initialization
+ *
+ * @param string $model
+ * @param Mage_Core_Model_Resource_Db_Abstract $resourceModel
+ * @return $this
+ */
+ protected function _init($model, $resourceModel = null)
+ {
+ $this->setModel($model);
+ if (is_null($resourceModel)) {
+ $resourceModel = $model;
+ }
+ $this->setResourceModel($resourceModel);
+ return $this;
+ }
+
+ /**
+ * Prepare select for load
+ *
+ * @return string
+ * @throws Zend_Db_Select_Exception
+ */
+ protected function _prepareSelect(Varien_Db_Select $select)
+ {
+ /** @var Mage_Core_Model_Resource_Helper_Mysql4 $helper */
+ $helper = Mage::getResourceHelper('core');
+
+ $unionParts = $select->getPart(Zend_Db_Select::UNION);
+ if (!empty($unionParts)) {
+ $select = $helper->limitUnion($select);
+ }
+
+ if ($this->_useAnalyticFunction) {
+ return $helper->getQueryUsingAnalyticFunction($select);
+ }
+
+ return (string) $select;
+ }
+
+ /**
+ * Redeclare before load method for adding event
+ *
+ * @return $this
+ */
+ protected function _beforeLoad()
+ {
+ parent::_beforeLoad();
+ Mage::dispatchEvent('core_collection_abstract_load_before', ['collection' => $this]);
+ if ($this->_eventPrefix && $this->_eventObject) {
+ Mage::dispatchEvent($this->_eventPrefix . '_load_before', [
+ $this->_eventObject => $this,
+ ]);
+ }
+ return $this;
+ }
+
/**
* Redeclare after load method for specifying collection items original data
*
@@ -631,19 +656,6 @@ protected function _afterLoad()
return $this;
}
- /**
- * Save all the entities in the collection
- *
- * @return $this
- */
- public function save()
- {
- foreach ($this->getItems() as $item) {
- $item->save();
- }
- return $this;
- }
-
/**
* Check if cache can be used for collection
*
@@ -689,16 +701,4 @@ protected function _getCacheTags()
$tags[] = self::CACHE_TAG;
return $tags;
}
-
- /**
- * Format Date to internal database date format
- *
- * @param int|string|Zend_Date $date
- * @param bool $includeTime
- * @return string
- */
- public function formatDate($date, $includeTime = true)
- {
- return Varien_Date::formatDate($date, $includeTime);
- }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Design.php b/app/code/core/Mage/Core/Model/Resource/Design.php
index 0a295233ecc..6f716076928 100644
--- a/app/code/core/Mage/Core/Model/Resource/Design.php
+++ b/app/code/core/Mage/Core/Model/Resource/Design.php
@@ -22,11 +22,6 @@
*/
class Mage_Core_Model_Resource_Design extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('core/design_change', 'design_change_id');
- }
-
/**
* @param Mage_Core_Model_Design $object
* @inheritDoc
@@ -61,6 +56,37 @@ public function _beforeSave(Mage_Core_Model_Abstract $object)
return parent::_beforeSave($object);
}
+ /**
+ * Load changes for specific store and date
+ *
+ * @param int $storeId
+ * @param string $date
+ * @return array
+ */
+ public function loadChange($storeId, $date = null)
+ {
+ if (is_null($date)) {
+ $date = Varien_Date::now();
+ }
+
+ $select = $this->_getReadAdapter()->select()
+ ->from(['main_table' => $this->getTable('design_change')])
+ ->where('store_id = :store_id')
+ ->where('date_from <= :required_date or date_from IS NULL')
+ ->where('date_to >= :required_date or date_to IS NULL');
+
+ $bind = [
+ 'store_id' => (int) $storeId,
+ 'required_date' => $date,
+ ];
+
+ return $this->_getReadAdapter()->fetchRow($select, $bind);
+ }
+ protected function _construct()
+ {
+ $this->_init('core/design_change', 'design_change_id');
+ }
+
/**
* Check intersections
*
@@ -131,31 +157,4 @@ protected function _checkIntersection($storeId, $dateFrom, $dateTo, $currentId)
return $adapter->fetchOne($select, $bind);
}
-
- /**
- * Load changes for specific store and date
- *
- * @param int $storeId
- * @param string $date
- * @return array
- */
- public function loadChange($storeId, $date = null)
- {
- if (is_null($date)) {
- $date = Varien_Date::now();
- }
-
- $select = $this->_getReadAdapter()->select()
- ->from(['main_table' => $this->getTable('design_change')])
- ->where('store_id = :store_id')
- ->where('date_from <= :required_date or date_from IS NULL')
- ->where('date_to >= :required_date or date_to IS NULL');
-
- $bind = [
- 'store_id' => (int) $storeId,
- 'required_date' => $date,
- ];
-
- return $this->_getReadAdapter()->fetchRow($select, $bind);
- }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Design/Collection.php b/app/code/core/Mage/Core/Model/Resource/Design/Collection.php
index 80d8b5bba3e..bc8aabed815 100644
--- a/app/code/core/Mage/Core/Model/Resource/Design/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Design/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Core_Model_Resource_Design_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Core Design resource collection
- *
- */
- protected function _construct()
- {
- $this->_init('core/design');
- }
-
/**
* Join store data to collection
*
@@ -74,4 +65,12 @@ public function addStoreFilter($storeId)
{
return $this->addFieldToFilter('store_id', ['in' => $storeId]);
}
+ /**
+ * Core Design resource collection
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('core/design');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Email/Queue.php b/app/code/core/Mage/Core/Model/Resource/Email/Queue.php
index 70340dc91fc..528fb672419 100644
--- a/app/code/core/Mage/Core/Model/Resource/Email/Queue.php
+++ b/app/code/core/Mage/Core/Model/Resource/Email/Queue.php
@@ -20,45 +20,6 @@
*/
class Mage_Core_Model_Resource_Email_Queue extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Initialize email queue resource model
- *
- */
- protected function _construct()
- {
- $this->_init('core/email_queue', 'message_id');
- }
-
- /**
- * Load recipients, unserialize message parameters
- *
- * @param Mage_Core_Model_Email_Queue $object
- * @inheritDoc
- */
- protected function _afterLoad(Mage_Core_Model_Abstract $object)
- {
- $object->setRecipients($this->getRecipients($object->getId()));
- $object->setMessageParameters(unserialize($object->getMessageParameters(), ['allowed_classes' => false]));
- return $this;
- }
-
- /**
- * Prepare object data for saving
- *
- * @param Mage_Core_Model_Email_Queue $object
- * @inheritDoc
- */
- protected function _beforeSave(Mage_Core_Model_Abstract $object)
- {
- if ($object->isObjectNew()) {
- $object->setCreatedAt($this->formatDate(true));
- }
- $object->setMessageBodyHash(md5($object->getMessageBody()));
- $object->setMessageParameters(serialize($object->getMessageParameters()));
-
- return parent::_beforeSave($object);
- }
-
/**
* Check if email was added to queue for requested recipients
*
@@ -185,4 +146,42 @@ public function removeSentMessages()
$this->_getWriteAdapter()->delete($this->getMainTable(), 'processed_at IS NOT NULL');
return $this;
}
+ /**
+ * Initialize email queue resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('core/email_queue', 'message_id');
+ }
+
+ /**
+ * Load recipients, unserialize message parameters
+ *
+ * @param Mage_Core_Model_Email_Queue $object
+ * @inheritDoc
+ */
+ protected function _afterLoad(Mage_Core_Model_Abstract $object)
+ {
+ $object->setRecipients($this->getRecipients($object->getId()));
+ $object->setMessageParameters(unserialize($object->getMessageParameters(), ['allowed_classes' => false]));
+ return $this;
+ }
+
+ /**
+ * Prepare object data for saving
+ *
+ * @param Mage_Core_Model_Email_Queue $object
+ * @inheritDoc
+ */
+ protected function _beforeSave(Mage_Core_Model_Abstract $object)
+ {
+ if ($object->isObjectNew()) {
+ $object->setCreatedAt($this->formatDate(true));
+ }
+ $object->setMessageBodyHash(md5($object->getMessageBody()));
+ $object->setMessageParameters(serialize($object->getMessageParameters()));
+
+ return parent::_beforeSave($object);
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Email/Queue/Collection.php b/app/code/core/Mage/Core/Model/Resource/Email/Queue/Collection.php
index 33e6d6ca7e7..a7a6d30c148 100644
--- a/app/code/core/Mage/Core/Model/Resource/Email/Queue/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Email/Queue/Collection.php
@@ -22,6 +22,16 @@
*/
class Mage_Core_Model_Resource_Email_Queue_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
+ /**
+ * Add filter by only ready for sending item
+ *
+ * @return $this
+ */
+ public function addOnlyForSendingFilter()
+ {
+ $this->getSelect()->where('main_table.processed_at IS NULL');
+ return $this;
+ }
/**
* Internal constructor
*/
@@ -40,15 +50,4 @@ protected function _afterLoad()
$this->walk('afterLoad');
return $this;
}
-
- /**
- * Add filter by only ready for sending item
- *
- * @return $this
- */
- public function addOnlyForSendingFilter()
- {
- $this->getSelect()->where('main_table.processed_at IS NULL');
- return $this;
- }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Email/Template.php b/app/code/core/Mage/Core/Model/Resource/Email/Template.php
index 8143abf0a25..3cbf6b342bc 100644
--- a/app/code/core/Mage/Core/Model/Resource/Email/Template.php
+++ b/app/code/core/Mage/Core/Model/Resource/Email/Template.php
@@ -22,11 +22,6 @@
*/
class Mage_Core_Model_Resource_Email_Template extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('core/email_template', 'template_id');
- }
-
/**
* Load by template code from DB.
*
@@ -75,23 +70,6 @@ public function checkCodeUsage(Mage_Core_Model_Email_Template $template)
return false;
}
- /**
- * Set template type, added at and modified at time
- *
- * @param Mage_Core_Model_Email_Template $object
- * @inheritDoc
- */
- protected function _beforeSave(Mage_Core_Model_Abstract $object)
- {
- if ($object->isObjectNew()) {
- $object->setCreatedAt($this->formatDate(true));
- }
- $object->setModifiedAt($this->formatDate(true));
- $object->setTemplateType((int) $object->getTemplateType());
-
- return parent::_beforeSave($object);
- }
-
/**
* Retrieve config scope and scope id of specified email template by email paths
*
@@ -118,4 +96,25 @@ public function getSystemConfigByPathsAndTemplateId($paths, $templateId)
return $this->_getReadAdapter()->fetchAll($select, $bind);
}
+ protected function _construct()
+ {
+ $this->_init('core/email_template', 'template_id');
+ }
+
+ /**
+ * Set template type, added at and modified at time
+ *
+ * @param Mage_Core_Model_Email_Template $object
+ * @inheritDoc
+ */
+ protected function _beforeSave(Mage_Core_Model_Abstract $object)
+ {
+ if ($object->isObjectNew()) {
+ $object->setCreatedAt($this->formatDate(true));
+ }
+ $object->setModifiedAt($this->formatDate(true));
+ $object->setTemplateType((int) $object->getTemplateType());
+
+ return parent::_beforeSave($object);
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/File/Storage/Database.php b/app/code/core/Mage/Core/Model/Resource/File/Storage/Database.php
index 38db5cef139..a96dde3d82f 100644
--- a/app/code/core/Mage/Core/Model/Resource/File/Storage/Database.php
+++ b/app/code/core/Mage/Core/Model/Resource/File/Storage/Database.php
@@ -22,14 +22,6 @@
*/
class Mage_Core_Model_Resource_File_Storage_Database extends Mage_Core_Model_Resource_File_Storage_Abstract
{
- /**
- * Define table name and id field for resource
- */
- protected function _construct()
- {
- $this->_init('core/file_storage', 'file_id');
- }
-
/**
* Create database scheme for storing files
*
@@ -93,32 +85,6 @@ public function createDatabaseScheme()
return $this;
}
- /**
- * Decodes blob content retrieved by DB driver
- *
- * @param array $row Table row with 'content' key in it
- * @return array
- */
- protected function _decodeFileContent($row)
- {
- $row['content'] = $this->_getReadAdapter()->decodeVarbinary($row['content']);
- return $row;
- }
-
- /**
- * Decodes blob content retrieved by Database driver
- *
- * @param array $rows Array of table rows (files), each containing 'content' key
- * @return array
- */
- protected function _decodeAllFilesContent($rows)
- {
- foreach ($rows as $key => $row) {
- $rows[$key] = $this->_decodeFileContent($row);
- }
- return $rows;
- }
-
/**
* Load entity by filename
*
@@ -345,4 +311,37 @@ public function getDirectoryFiles($directory)
$rows = $adapter->fetchAll($select);
return $this->_decodeAllFilesContent($rows);
}
+ /**
+ * Define table name and id field for resource
+ */
+ protected function _construct()
+ {
+ $this->_init('core/file_storage', 'file_id');
+ }
+
+ /**
+ * Decodes blob content retrieved by DB driver
+ *
+ * @param array $row Table row with 'content' key in it
+ * @return array
+ */
+ protected function _decodeFileContent($row)
+ {
+ $row['content'] = $this->_getReadAdapter()->decodeVarbinary($row['content']);
+ return $row;
+ }
+
+ /**
+ * Decodes blob content retrieved by Database driver
+ *
+ * @param array $rows Array of table rows (files), each containing 'content' key
+ * @return array
+ */
+ protected function _decodeAllFilesContent($rows)
+ {
+ foreach ($rows as $key => $row) {
+ $rows[$key] = $this->_decodeFileContent($row);
+ }
+ return $rows;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/File/Storage/Directory/Database.php b/app/code/core/Mage/Core/Model/Resource/File/Storage/Directory/Database.php
index 917548c1406..7a5440fbb1c 100644
--- a/app/code/core/Mage/Core/Model/Resource/File/Storage/Directory/Database.php
+++ b/app/code/core/Mage/Core/Model/Resource/File/Storage/Directory/Database.php
@@ -22,14 +22,6 @@
*/
class Mage_Core_Model_Resource_File_Storage_Directory_Database extends Mage_Core_Model_Resource_File_Storage_Abstract
{
- /**
- * Define table name and id field for resource
- */
- protected function _construct()
- {
- $this->_init('core/directory_storage', 'directory_id');
- }
-
/**
* Create database scheme for storing files
*
@@ -217,4 +209,11 @@ public function deleteDirectory($name, $path)
$adapter->delete($this->getMainTable(), $where);
}
+ /**
+ * Define table name and id field for resource
+ */
+ protected function _construct()
+ {
+ $this->_init('core/directory_storage', 'directory_id');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/File/Storage/File.php b/app/code/core/Mage/Core/Model/Resource/File/Storage/File.php
index 82ac159b713..ad75135b29f 100644
--- a/app/code/core/Mage/Core/Model/Resource/File/Storage/File.php
+++ b/app/code/core/Mage/Core/Model/Resource/File/Storage/File.php
@@ -138,20 +138,6 @@ public function clear($dir = '')
return $this;
}
- /**
- * Returns list of files/directories that should be ignored when cleaning and reading files from the filesystem
- * @return array
- */
- protected function _getIgnoredFiles()
- {
- if ($this->_ignoredFiles === null) {
- $ignored = (string) Mage::app()->getConfig()
- ->getNode(Mage_Core_Model_File_Storage::XML_PATH_MEDIA_RESOURCE_IGNORED);
- $this->_ignoredFiles = $ignored ? explode(',', $ignored) : [];
- }
- return $this->_ignoredFiles;
- }
-
/**
* Save directory to storage
*
@@ -310,4 +296,18 @@ public function removeLockedFile($filePath)
@exec("find {$this->getMediaBaseDirectory()} -empty -type d -delete"); // TODO - replace with native PHP?
}
}
+
+ /**
+ * Returns list of files/directories that should be ignored when cleaning and reading files from the filesystem
+ * @return array
+ */
+ protected function _getIgnoredFiles()
+ {
+ if ($this->_ignoredFiles === null) {
+ $ignored = (string) Mage::app()->getConfig()
+ ->getNode(Mage_Core_Model_File_Storage::XML_PATH_MEDIA_RESOURCE_IGNORED);
+ $this->_ignoredFiles = $ignored ? explode(',', $ignored) : [];
+ }
+ return $this->_ignoredFiles;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Helper/Abstract.php b/app/code/core/Mage/Core/Model/Resource/Helper/Abstract.php
index 716e047fc73..42e27d3fc99 100644
--- a/app/code/core/Mage/Core/Model/Resource/Helper/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Resource/Helper/Abstract.php
@@ -53,49 +53,6 @@ public function __construct($module)
$this->_modulePrefix = (string) $module;
}
- /**
- * Retrieve connection for read data
- *
- * @return Varien_Db_Adapter_Interface
- */
- protected function _getReadAdapter()
- {
- if ($this->_readAdapter === null) {
- $this->_readAdapter = $this->_getConnection('read');
- }
-
- return $this->_readAdapter;
- }
-
- /**
- * Retrieve connection for write data
- *
- * @return Varien_Db_Adapter_Interface
- */
- protected function _getWriteAdapter()
- {
- if ($this->_writeAdapter === null) {
- $this->_writeAdapter = $this->_getConnection('write');
- }
-
- return $this->_writeAdapter;
- }
-
- /**
- * Retrieves connection to the resource
- *
- * @param string $name
- * @return Varien_Db_Adapter_Interface
- */
- protected function _getConnection($name)
- {
- $connection = sprintf('%s_%s', $this->_modulePrefix, $name);
- /** @var Mage_Core_Model_Resource $resource */
- $resource = Mage::getSingleton('core/resource');
-
- return $resource->getConnection($connection);
- }
-
/**
* Escapes value, that participates in LIKE, with '\' symbol.
* Note: this func cannot be used on its own, because different RDBMS may use different default escape symbols,
@@ -313,4 +270,47 @@ public function convertOldColumnDefinition($column)
return $result;
}
+
+ /**
+ * Retrieve connection for read data
+ *
+ * @return Varien_Db_Adapter_Interface
+ */
+ protected function _getReadAdapter()
+ {
+ if ($this->_readAdapter === null) {
+ $this->_readAdapter = $this->_getConnection('read');
+ }
+
+ return $this->_readAdapter;
+ }
+
+ /**
+ * Retrieve connection for write data
+ *
+ * @return Varien_Db_Adapter_Interface
+ */
+ protected function _getWriteAdapter()
+ {
+ if ($this->_writeAdapter === null) {
+ $this->_writeAdapter = $this->_getConnection('write');
+ }
+
+ return $this->_writeAdapter;
+ }
+
+ /**
+ * Retrieves connection to the resource
+ *
+ * @param string $name
+ * @return Varien_Db_Adapter_Interface
+ */
+ protected function _getConnection($name)
+ {
+ $connection = sprintf('%s_%s', $this->_modulePrefix, $name);
+ /** @var Mage_Core_Model_Resource $resource */
+ $resource = Mage::getSingleton('core/resource');
+
+ return $resource->getConnection($connection);
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Helper/Mysql4.php b/app/code/core/Mage/Core/Model/Resource/Helper/Mysql4.php
index dd134f40aa9..e5b3df05af7 100644
--- a/app/code/core/Mage/Core/Model/Resource/Helper/Mysql4.php
+++ b/app/code/core/Mage/Core/Model/Resource/Helper/Mysql4.php
@@ -80,6 +80,114 @@ public function limitUnion($select)
return $select;
}
+ /**
+ * Prepare select column list
+ *
+ * @param string $groupByCondition
+ * @return array
+ * @throws Zend_Db_Exception
+ */
+ public function prepareColumnsList(Varien_Db_Select $select, $groupByCondition = null)
+ {
+ if (!count($select->getPart(Zend_Db_Select::FROM))) {
+ return $select->getPart(Zend_Db_Select::COLUMNS);
+ }
+
+ $columns = $select->getPart(Zend_Db_Select::COLUMNS);
+ $tables = $select->getPart(Zend_Db_Select::FROM);
+ $preparedColumns = [];
+
+ foreach ($columns as $columnEntry) {
+ list($correlationName, $column, $alias) = $columnEntry;
+ if ($column instanceof Zend_Db_Expr) {
+ if ($alias !== null) {
+ if (preg_match('/(^|[^a-zA-Z_])^(SELECT)?(SUM|MIN|MAX|AVG|COUNT)\s*\(/i', (string) $column, $matches)) {
+ $column = $this->prepareColumn($column, $groupByCondition);
+ }
+ $preparedColumns[strtoupper($alias)] = [null, $column, $alias];
+ } else {
+ throw new Zend_Db_Exception("Can't prepare expression without alias");
+ }
+ } else {
+ if ($column == Zend_Db_Select::SQL_WILDCARD) {
+ if ($tables[$correlationName]['tableName'] instanceof Zend_Db_Expr) {
+ throw new Zend_Db_Exception("Can't prepare expression when tableName is instance of Zend_Db_Expr");
+ }
+ $tableColumns = $this->_getReadAdapter()->describeTable($tables[$correlationName]['tableName']);
+ foreach (array_keys($tableColumns) as $col) {
+ $preparedColumns[strtoupper($col)] = [$correlationName, $col, null];
+ }
+ } else {
+ $columnKey = is_null($alias) ? $column : $alias;
+ $preparedColumns[strtoupper($columnKey)] = [$correlationName, $column, $alias];
+ }
+ }
+ }
+
+ return $preparedColumns;
+ }
+
+ /**
+ * Add prepared column group_concat expression
+ *
+ * @param Varien_Db_Select $select
+ * @param string $fieldAlias Field alias which will be added with column group_concat expression
+ * @param string $fields
+ * @param string $groupConcatDelimiter
+ * @param string $fieldsDelimiter
+ * @param string $additionalWhere
+ * @return Varien_Db_Select
+ */
+ public function addGroupConcatColumn($select, $fieldAlias, $fields, $groupConcatDelimiter = ',', $fieldsDelimiter = '', $additionalWhere = '')
+ {
+ if (is_array($fields)) {
+ $fieldExpr = $this->_getReadAdapter()->getConcatSql($fields, $fieldsDelimiter);
+ } else {
+ $fieldExpr = $fields;
+ }
+ if ($additionalWhere) {
+ $fieldExpr = $this->_getReadAdapter()->getCheckSql($additionalWhere, $fieldExpr, "''");
+ }
+ $separator = '';
+ if ($groupConcatDelimiter) {
+ $separator = sprintf(" SEPARATOR '%s'", $groupConcatDelimiter);
+ }
+
+ $select->columns([$fieldAlias => new Zend_Db_Expr(sprintf('GROUP_CONCAT(%s%s)', $fieldExpr, $separator))]);
+
+ return $select;
+ }
+
+ /**
+ * Returns expression of days passed from $startDate to $endDate
+ *
+ * @param string|Zend_Db_Expr $startDate
+ * @param string|Zend_Db_Expr $endDate
+ * @return Zend_Db_Expr
+ */
+ public function getDateDiff($startDate, $endDate)
+ {
+ $dateDiff = '(TO_DAYS(' . $endDate . ') - TO_DAYS(' . $startDate . '))';
+ return new Zend_Db_Expr($dateDiff);
+ }
+
+ /**
+ * Escapes and quotes LIKE value.
+ * Stating escape symbol in expression is not required, because we use standard MySQL escape symbol.
+ * For options and escaping see escapeLikeValue().
+ *
+ * @param string $value
+ * @param array $options
+ * @return Zend_Db_Expr
+ *
+ * @see escapeLikeValue()
+ */
+ public function addLikeEscape($value, $options = [])
+ {
+ $value = $this->escapeLikeValue($value, $options);
+ return new Zend_Db_Expr($this->_getReadAdapter()->quote($value));
+ }
+
/**
* Returns array of quoted orders with direction
*
@@ -233,112 +341,4 @@ protected function _assembleLimit($query, $limitCount, $limitOffset, $columnList
return $query;
}
-
- /**
- * Prepare select column list
- *
- * @param string $groupByCondition
- * @return array
- * @throws Zend_Db_Exception
- */
- public function prepareColumnsList(Varien_Db_Select $select, $groupByCondition = null)
- {
- if (!count($select->getPart(Zend_Db_Select::FROM))) {
- return $select->getPart(Zend_Db_Select::COLUMNS);
- }
-
- $columns = $select->getPart(Zend_Db_Select::COLUMNS);
- $tables = $select->getPart(Zend_Db_Select::FROM);
- $preparedColumns = [];
-
- foreach ($columns as $columnEntry) {
- list($correlationName, $column, $alias) = $columnEntry;
- if ($column instanceof Zend_Db_Expr) {
- if ($alias !== null) {
- if (preg_match('/(^|[^a-zA-Z_])^(SELECT)?(SUM|MIN|MAX|AVG|COUNT)\s*\(/i', (string) $column, $matches)) {
- $column = $this->prepareColumn($column, $groupByCondition);
- }
- $preparedColumns[strtoupper($alias)] = [null, $column, $alias];
- } else {
- throw new Zend_Db_Exception("Can't prepare expression without alias");
- }
- } else {
- if ($column == Zend_Db_Select::SQL_WILDCARD) {
- if ($tables[$correlationName]['tableName'] instanceof Zend_Db_Expr) {
- throw new Zend_Db_Exception("Can't prepare expression when tableName is instance of Zend_Db_Expr");
- }
- $tableColumns = $this->_getReadAdapter()->describeTable($tables[$correlationName]['tableName']);
- foreach (array_keys($tableColumns) as $col) {
- $preparedColumns[strtoupper($col)] = [$correlationName, $col, null];
- }
- } else {
- $columnKey = is_null($alias) ? $column : $alias;
- $preparedColumns[strtoupper($columnKey)] = [$correlationName, $column, $alias];
- }
- }
- }
-
- return $preparedColumns;
- }
-
- /**
- * Add prepared column group_concat expression
- *
- * @param Varien_Db_Select $select
- * @param string $fieldAlias Field alias which will be added with column group_concat expression
- * @param string $fields
- * @param string $groupConcatDelimiter
- * @param string $fieldsDelimiter
- * @param string $additionalWhere
- * @return Varien_Db_Select
- */
- public function addGroupConcatColumn($select, $fieldAlias, $fields, $groupConcatDelimiter = ',', $fieldsDelimiter = '', $additionalWhere = '')
- {
- if (is_array($fields)) {
- $fieldExpr = $this->_getReadAdapter()->getConcatSql($fields, $fieldsDelimiter);
- } else {
- $fieldExpr = $fields;
- }
- if ($additionalWhere) {
- $fieldExpr = $this->_getReadAdapter()->getCheckSql($additionalWhere, $fieldExpr, "''");
- }
- $separator = '';
- if ($groupConcatDelimiter) {
- $separator = sprintf(" SEPARATOR '%s'", $groupConcatDelimiter);
- }
-
- $select->columns([$fieldAlias => new Zend_Db_Expr(sprintf('GROUP_CONCAT(%s%s)', $fieldExpr, $separator))]);
-
- return $select;
- }
-
- /**
- * Returns expression of days passed from $startDate to $endDate
- *
- * @param string|Zend_Db_Expr $startDate
- * @param string|Zend_Db_Expr $endDate
- * @return Zend_Db_Expr
- */
- public function getDateDiff($startDate, $endDate)
- {
- $dateDiff = '(TO_DAYS(' . $endDate . ') - TO_DAYS(' . $startDate . '))';
- return new Zend_Db_Expr($dateDiff);
- }
-
- /**
- * Escapes and quotes LIKE value.
- * Stating escape symbol in expression is not required, because we use standard MySQL escape symbol.
- * For options and escaping see escapeLikeValue().
- *
- * @param string $value
- * @param array $options
- * @return Zend_Db_Expr
- *
- * @see escapeLikeValue()
- */
- public function addLikeEscape($value, $options = [])
- {
- $value = $this->escapeLikeValue($value, $options);
- return new Zend_Db_Expr($this->_getReadAdapter()->quote($value));
- }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Language/Collection.php b/app/code/core/Mage/Core/Model/Resource/Language/Collection.php
index e22b4d78d44..b75929a3641 100644
--- a/app/code/core/Mage/Core/Model/Resource/Language/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Language/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Core_Model_Resource_Language_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- $this->_init('core/language');
- }
-
/**
* Convert collection items to array of select options
*
@@ -50,4 +41,12 @@ public function toOptionHash()
{
return $this->_toOptionHash('language_code', 'language_title');
}
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('core/language');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Layout.php b/app/code/core/Mage/Core/Model/Resource/Layout.php
index 64e72a59575..7a8063994e8 100644
--- a/app/code/core/Mage/Core/Model/Resource/Layout.php
+++ b/app/code/core/Mage/Core/Model/Resource/Layout.php
@@ -22,11 +22,6 @@
*/
class Mage_Core_Model_Resource_Layout extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('core/layout_update', 'layout_update_id');
- }
-
/**
* Retrieve layout updates by handle
*
@@ -71,4 +66,8 @@ public function fetchUpdatesByHandle($handle, $params = [])
}
return $result;
}
+ protected function _construct()
+ {
+ $this->_init('core/layout_update', 'layout_update_id');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Resource.php b/app/code/core/Mage/Core/Model/Resource/Resource.php
index 711611cd9ee..5853d1d7a45 100644
--- a/app/code/core/Mage/Core/Model/Resource/Resource.php
+++ b/app/code/core/Mage/Core/Model/Resource/Resource.php
@@ -36,50 +36,6 @@ class Mage_Core_Model_Resource_Resource extends Mage_Core_Model_Resource_Db_Abst
*/
protected static $_dataVersions = null;
- protected function _construct()
- {
- $this->_init('core/resource', 'store_id');
- }
-
- /**
- * Fill static versions arrays.
- * This routine fetches Db and Data versions of at once to optimize sql requests. However, when upgrading, it's
- * possible that 'data' column will be created only after all Db installs are passed. So $neededType contains
- * information on main purpose of calling this routine, and even when 'data' column is absent - it won't require
- * reissuing new sql just to get 'db' version of module.
- *
- * @param string $needType Can be 'db' or 'data'
- * @return $this
- * @SuppressWarnings("PHPMD.CamelCaseVariableName")
- */
- protected function _loadVersionData($needType)
- {
- if ((($needType == 'db') && is_null(self::$_versions))
- || (($needType == 'data') && is_null(self::$_dataVersions))
- ) {
- self::$_versions = []; // Db version column always exists
- self::$_dataVersions = null; // Data version array will be filled only if Data column exist
-
- if ($this->_getReadAdapter()->isTableExists($this->getMainTable())) {
- $select = $this->_getReadAdapter()->select()
- ->from($this->getMainTable(), '*');
- // phpcs:ignore Ecg.Performance.FetchAll.Found
- $rowSet = $this->_getReadAdapter()->fetchAll($select);
- foreach ($rowSet as $row) {
- self::$_versions[$row['code']] = $row['version'];
- if (array_key_exists('data_version', $row)) {
- if (is_null(self::$_dataVersions)) {
- self::$_dataVersions = [];
- }
- self::$_dataVersions[$row['code']] = $row['data_version'];
- }
- }
- }
- }
-
- return $this;
- }
-
/**
* Get Module version from DB
*
@@ -166,4 +122,48 @@ public function setDataVersion($resName, $version)
}
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('core/resource', 'store_id');
+ }
+
+ /**
+ * Fill static versions arrays.
+ * This routine fetches Db and Data versions of at once to optimize sql requests. However, when upgrading, it's
+ * possible that 'data' column will be created only after all Db installs are passed. So $neededType contains
+ * information on main purpose of calling this routine, and even when 'data' column is absent - it won't require
+ * reissuing new sql just to get 'db' version of module.
+ *
+ * @param string $needType Can be 'db' or 'data'
+ * @return $this
+ * @SuppressWarnings("PHPMD.CamelCaseVariableName")
+ */
+ protected function _loadVersionData($needType)
+ {
+ if ((($needType == 'db') && is_null(self::$_versions))
+ || (($needType == 'data') && is_null(self::$_dataVersions))
+ ) {
+ self::$_versions = []; // Db version column always exists
+ self::$_dataVersions = null; // Data version array will be filled only if Data column exist
+
+ if ($this->_getReadAdapter()->isTableExists($this->getMainTable())) {
+ $select = $this->_getReadAdapter()->select()
+ ->from($this->getMainTable(), '*');
+ // phpcs:ignore Ecg.Performance.FetchAll.Found
+ $rowSet = $this->_getReadAdapter()->fetchAll($select);
+ foreach ($rowSet as $row) {
+ self::$_versions[$row['code']] = $row['version'];
+ if (array_key_exists('data_version', $row)) {
+ if (is_null(self::$_dataVersions)) {
+ self::$_dataVersions = [];
+ }
+ self::$_dataVersions[$row['code']] = $row['data_version'];
+ }
+ }
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Setup.php b/app/code/core/Mage/Core/Model/Resource/Setup.php
index 96a7dd1d32a..978e51e4d1f 100644
--- a/app/code/core/Mage/Core/Model/Resource/Setup.php
+++ b/app/code/core/Mage/Core/Model/Resource/Setup.php
@@ -175,30 +175,6 @@ public function getTable($tableName)
return $this->_tables[$cacheKey];
}
- /**
- * Retrieve table name for cache
- *
- * @param string|array $tableName
- * @return string
- */
- protected function _getTableCacheName($tableName)
- {
- if (is_array($tableName)) {
- return implode('_', $tableName);
- }
- return $tableName;
- }
-
- /**
- * Get core resource resource model
- *
- * @return Mage_Core_Model_Resource_Resource
- */
- protected function _getResource()
- {
- return Mage::getResourceSingleton('core/resource');
- }
-
/**
* Apply database updates whenever needed
*
@@ -321,150 +297,466 @@ public function applyUpdates()
}
/**
- * Hooks queries to strengthen backwards compatibility in MySQL.
- * Currently - dynamically updates column types for foreign keys, when their targets were changed
- * during MMDB development.
+ * Callback function, called on every query adapter processes.
+ * Modifies SQL or tables, so that foreign keys will be set successfully
*
+ * @param string $sql
+ * @param array $bind
* @return $this
*/
- protected function _hookQueries()
+ public function callbackQueryHook(&$sql, &$bind)
{
- $this->_queriesHooked = true;
- /** @var Varien_Db_Adapter_Pdo_Mysql $adapter */
- $adapter = $this->getConnection();
- $adapter->setQueryHook(['object' => $this, 'method' => 'callbackQueryHook']);
+ Mage::getSingleton('core/resource_setup_query_modifier', [$this->getConnection()])
+ ->processQuery($sql, $bind);
return $this;
}
+ /******************* UTILITY METHODS *****************/
+
/**
- * Removes query hook
+ * Retrieve row or field from table by id or string and parent id
*
- * @return $this
+ * @param string $table
+ * @param string $idField
+ * @param string|int $id
+ * @param string $field
+ * @param string $parentField
+ * @param string|int $parentId
+ * @return mixed|boolean
*/
- protected function _unhookQueries()
+ public function getTableRow($table, $idField, $id, $field = null, $parentField = null, $parentId = 0)
{
- if (!$this->_queriesHooked) {
- return $this;
+ if (str_contains($table, '/')) {
+ $table = $this->getTable($table);
}
- /** @var Varien_Db_Adapter_Pdo_Mysql $adapter */
+
+ if (empty($this->_setupCache[$table][$parentId][$id])) {
+ $adapter = $this->getConnection();
+ $bind = ['id_field' => $id];
+ $select = $adapter->select()
+ ->from($table)
+ ->where($adapter->quoteIdentifier($idField) . '= :id_field');
+ if (!is_null($parentField)) {
+ $select->where($adapter->quoteIdentifier($parentField) . '= :parent_id');
+ $bind['parent_id'] = $parentId;
+ }
+ $this->_setupCache[$table][$parentId][$id] = $adapter->fetchRow($select, $bind);
+ }
+
+ if (is_null($field)) {
+ return $this->_setupCache[$table][$parentId][$id];
+ }
+ return $this->_setupCache[$table][$parentId][$id][$field] ?? false;
+ }
+
+ /**
+ * Delete table row
+ *
+ * @param string $table
+ * @param string $idField
+ * @param int|string $id
+ * @param null|string $parentField
+ * @param int|string $parentId
+ * @return $this
+ */
+ public function deleteTableRow($table, $idField, $id, $parentField = null, $parentId = 0)
+ {
+ if (str_contains($table, '/')) {
+ $table = $this->getTable($table);
+ }
+
$adapter = $this->getConnection();
- $adapter->setQueryHook(null);
- $this->_queriesHooked = false;
+ $where = [$adapter->quoteIdentifier($idField) . '=?' => $id];
+ if (!is_null($parentField)) {
+ $where[$adapter->quoteIdentifier($parentField) . '=?'] = $parentId;
+ }
+
+ $adapter->delete($table, $where);
+
+ if (isset($this->_setupCache[$table][$parentId][$id])) {
+ unset($this->_setupCache[$table][$parentId][$id]);
+ }
+
return $this;
}
/**
- * Callback function, called on every query adapter processes.
- * Modifies SQL or tables, so that foreign keys will be set successfully
+ * Update one or more fields of table row
*
- * @param string $sql
- * @param array $bind
+ * @param string $table
+ * @param string $idField
+ * @param string|int $id
+ * @param string|array $field
+ * @param mixed|null $value
+ * @param string $parentField
+ * @param string|int $parentId
* @return $this
*/
- public function callbackQueryHook(&$sql, &$bind)
+ public function updateTableRow($table, $idField, $id, $field, $value = null, $parentField = null, $parentId = 0)
{
- Mage::getSingleton('core/resource_setup_query_modifier', [$this->getConnection()])
- ->processQuery($sql, $bind);
+ if (str_contains($table, '/')) {
+ $table = $this->getTable($table);
+ }
+
+ if (is_array($field)) {
+ $data = $field;
+ } else {
+ $data = [$field => $value];
+ }
+
+ $adapter = $this->getConnection();
+ $where = [$adapter->quoteIdentifier($idField) . '=?' => $id];
+ $adapter->update($table, $data, $where);
+
+ if (isset($this->_setupCache[$table][$parentId][$id])) {
+ if (is_array($field)) {
+ $this->_setupCache[$table][$parentId][$id] =
+ array_merge($this->_setupCache[$table][$parentId][$id], $field);
+ } else {
+ $this->_setupCache[$table][$parentId][$id][$field] = $value;
+ }
+ }
+
return $this;
}
/**
- * Run data install scripts
+ * Update table data
*
- * @param string $newVersion
+ * @param string $table
+ * @param Zend_Db_Expr $conditionExpr
+ * @param Zend_Db_Expr $valueExpr
* @return $this
+ *
+ * @deprecated since 1.4.0.1
*/
- protected function _installData($newVersion)
+ public function updateTable($table, $conditionExpr, $valueExpr)
{
- $oldVersion = $this->_modifyResourceDb(self::TYPE_DATA_INSTALL, '', $newVersion);
- $this->_modifyResourceDb(self::TYPE_DATA_UPGRADE, $oldVersion, $newVersion);
- $this->_getResource()->setDataVersion($this->_resourceName, $newVersion);
+ if (str_contains($table, '/')) {
+ $table = $this->getTable($table);
+ }
+ $query = sprintf(
+ 'UPDATE %s SET %s WHERE %s',
+ $this->getConnection()->quoteIdentifier($table),
+ $conditionExpr,
+ $valueExpr,
+ );
+
+ $this->getConnection()->query($query);
return $this;
}
/**
- * Run data upgrade scripts
+ * Check is table exists
*
- * @param string $oldVersion
- * @param string $newVersion
- * @return $this
+ * @param string $table
+ * @return bool
*/
- protected function _upgradeData($oldVersion, $newVersion)
+ public function tableExists($table)
{
- $this->_modifyResourceDb('data-upgrade', $oldVersion, $newVersion);
- $this->_getResource()->setDataVersion($this->_resourceName, $newVersion);
+ if (str_contains($table, '/')) {
+ $table = $this->getTable($table);
+ }
- return $this;
+ return $this->getConnection()->isTableExists($table);
}
+ /******************* CONFIG *****************/
/**
- * Run resource installation file
+ * Undefined
*
- * @param string $newVersion
+ * @param string $path
+ * @param string $label
+ * @param string $default
* @return $this
+ * @deprecated since 1.4.0.1
*/
- protected function _installResourceDb($newVersion)
+ public function addConfigField($path, $label, array $data = [], $default = null)
{
- $oldVersion = $this->_modifyResourceDb(self::TYPE_DB_INSTALL, '', $newVersion);
- $this->_modifyResourceDb(self::TYPE_DB_UPGRADE, $oldVersion, $newVersion);
- $this->_getResource()->setDbVersion($this->_resourceName, $newVersion);
-
return $this;
}
/**
- * Run resource upgrade files from $oldVersion to $newVersion
+ * Save configuration data
*
- * @param string $oldVersion
- * @param string $newVersion
+ * @param string $path
+ * @param string $value
+ * @param int|string $scope
+ * @param int $scopeId
+ * @param int $inherit
* @return $this
*/
- protected function _upgradeResourceDb($oldVersion, $newVersion)
+ public function setConfigData($path, $value, $scope = 'default', $scopeId = 0, $inherit = 0)
{
- $this->_modifyResourceDb(self::TYPE_DB_UPGRADE, $oldVersion, $newVersion);
- $this->_getResource()->setDbVersion($this->_resourceName, $newVersion);
+ $table = $this->getTable('core/config_data');
+ // this is a fix for mysql 4.1
+ $this->getConnection()->showTableStatus($table);
+ $data = [
+ 'scope' => $scope,
+ 'scope_id' => $scopeId,
+ 'path' => $path,
+ 'value' => $value,
+ ];
+ $this->getConnection()->insertOnDuplicate($table, $data, ['value']);
return $this;
}
/**
- * Roll back resource
+ * Delete config field values
*
- * @param string $newVersion
- * @param string $oldVersion
+ * @param string $path
+ * @param string $scope (default|stores|websites|config)
* @return $this
*/
- protected function _rollbackResourceDb($newVersion, $oldVersion)
+ public function deleteConfigData($path, $scope = null)
{
- $this->_modifyResourceDb(self::TYPE_DB_ROLLBACK, $newVersion, $oldVersion);
+ $where = ['path = ?' => $path];
+ if (!is_null($scope)) {
+ $where['scope = ?'] = $scope;
+ }
+ $this->getConnection()->delete($this->getTable('core/config_data'), $where);
return $this;
}
/**
- * Uninstall resource
+ * Run plain SQL query(ies)
*
- * @param string $version existing resource version
+ * @param string $sql
* @return $this
*/
- protected function _uninstallResourceDb($version)
+ public function run($sql)
{
- $this->_modifyResourceDb(self::TYPE_DB_UNINSTALL, $version, '');
+ $this->getConnection()->multiQuery($sql);
return $this;
}
/**
- * Retrieve available Database install/upgrade files for current module
+ * Prepare database before install/upgrade
*
- * @param string $actionType
- * @param string $fromVersion
- * @param string $toVersion
- * @return array
+ * @return $this
*/
- protected function _getAvailableDbFiles($actionType, $fromVersion, $toVersion)
+ public function startSetup()
{
- $resModel = (string) $this->_connectionConfig->model;
- $modName = (string) $this->_moduleConfig[0]->getName();
+ $this->getConnection()->startSetup();
+ return $this;
+ }
+
+ /**
+ * Prepare database after install/upgrade
+ *
+ * @return $this
+ */
+ public function endSetup()
+ {
+ $this->getConnection()->endSetup();
+ return $this;
+ }
+
+ /**
+ * Retrieve 32bit UNIQUE HASH for a Table index
+ *
+ * @param string $tableName
+ * @param array|string $fields
+ * @param string $indexType
+ * @return string
+ */
+ public function getIdxName($tableName, $fields, $indexType = '')
+ {
+ return Mage::getSingleton('core/resource')->getIdxName($tableName, $fields, $indexType);
+ }
+
+ /**
+ * Retrieve 32bit UNIQUE HASH for a Table foreign key
+ *
+ * @param string $priTableName the target table name
+ * @param string $priColumnName the target table column name
+ * @param string $refTableName the reference table name
+ * @param string $refColumnName the reference table column name
+ * @return string
+ */
+ public function getFkName($priTableName, $priColumnName, $refTableName, $refColumnName)
+ {
+ return Mage::getSingleton('core/resource')
+ ->getFkName($priTableName, $priColumnName, $refTableName, $refColumnName);
+ }
+
+ /**
+ * Check call afterApplyAllUpdates method for setup class
+ *
+ * @return bool
+ */
+ public function getCallAfterApplyAllUpdates()
+ {
+ return $this->_callAfterApplyAllUpdates;
+ }
+
+ /**
+ * Run each time after applying of all updates,
+ * if setup model set $_callAfterApplyAllUpdates flag to true
+ *
+ * @return $this
+ */
+ public function afterApplyAllUpdates()
+ {
+ return $this;
+ }
+
+ /**
+ * Retrieve table name for cache
+ *
+ * @param string|array $tableName
+ * @return string
+ */
+ protected function _getTableCacheName($tableName)
+ {
+ if (is_array($tableName)) {
+ return implode('_', $tableName);
+ }
+ return $tableName;
+ }
+
+ /**
+ * Get core resource resource model
+ *
+ * @return Mage_Core_Model_Resource_Resource
+ */
+ protected function _getResource()
+ {
+ return Mage::getResourceSingleton('core/resource');
+ }
+
+ /**
+ * Hooks queries to strengthen backwards compatibility in MySQL.
+ * Currently - dynamically updates column types for foreign keys, when their targets were changed
+ * during MMDB development.
+ *
+ * @return $this
+ */
+ protected function _hookQueries()
+ {
+ $this->_queriesHooked = true;
+ /** @var Varien_Db_Adapter_Pdo_Mysql $adapter */
+ $adapter = $this->getConnection();
+ $adapter->setQueryHook(['object' => $this, 'method' => 'callbackQueryHook']);
+ return $this;
+ }
+
+ /**
+ * Removes query hook
+ *
+ * @return $this
+ */
+ protected function _unhookQueries()
+ {
+ if (!$this->_queriesHooked) {
+ return $this;
+ }
+ /** @var Varien_Db_Adapter_Pdo_Mysql $adapter */
+ $adapter = $this->getConnection();
+ $adapter->setQueryHook(null);
+ $this->_queriesHooked = false;
+ return $this;
+ }
+
+ /**
+ * Run data install scripts
+ *
+ * @param string $newVersion
+ * @return $this
+ */
+ protected function _installData($newVersion)
+ {
+ $oldVersion = $this->_modifyResourceDb(self::TYPE_DATA_INSTALL, '', $newVersion);
+ $this->_modifyResourceDb(self::TYPE_DATA_UPGRADE, $oldVersion, $newVersion);
+ $this->_getResource()->setDataVersion($this->_resourceName, $newVersion);
+
+ return $this;
+ }
+
+ /**
+ * Run data upgrade scripts
+ *
+ * @param string $oldVersion
+ * @param string $newVersion
+ * @return $this
+ */
+ protected function _upgradeData($oldVersion, $newVersion)
+ {
+ $this->_modifyResourceDb('data-upgrade', $oldVersion, $newVersion);
+ $this->_getResource()->setDataVersion($this->_resourceName, $newVersion);
+
+ return $this;
+ }
+
+ /**
+ * Run resource installation file
+ *
+ * @param string $newVersion
+ * @return $this
+ */
+ protected function _installResourceDb($newVersion)
+ {
+ $oldVersion = $this->_modifyResourceDb(self::TYPE_DB_INSTALL, '', $newVersion);
+ $this->_modifyResourceDb(self::TYPE_DB_UPGRADE, $oldVersion, $newVersion);
+ $this->_getResource()->setDbVersion($this->_resourceName, $newVersion);
+
+ return $this;
+ }
+
+ /**
+ * Run resource upgrade files from $oldVersion to $newVersion
+ *
+ * @param string $oldVersion
+ * @param string $newVersion
+ * @return $this
+ */
+ protected function _upgradeResourceDb($oldVersion, $newVersion)
+ {
+ $this->_modifyResourceDb(self::TYPE_DB_UPGRADE, $oldVersion, $newVersion);
+ $this->_getResource()->setDbVersion($this->_resourceName, $newVersion);
+
+ return $this;
+ }
+
+ /**
+ * Roll back resource
+ *
+ * @param string $newVersion
+ * @param string $oldVersion
+ * @return $this
+ */
+ protected function _rollbackResourceDb($newVersion, $oldVersion)
+ {
+ $this->_modifyResourceDb(self::TYPE_DB_ROLLBACK, $newVersion, $oldVersion);
+ return $this;
+ }
+
+ /**
+ * Uninstall resource
+ *
+ * @param string $version existing resource version
+ * @return $this
+ */
+ protected function _uninstallResourceDb($version)
+ {
+ $this->_modifyResourceDb(self::TYPE_DB_UNINSTALL, $version, '');
+ return $this;
+ }
+
+ /**
+ * Retrieve available Database install/upgrade files for current module
+ *
+ * @param string $actionType
+ * @param string $fromVersion
+ * @param string $toVersion
+ * @return array
+ */
+ protected function _getAvailableDbFiles($actionType, $fromVersion, $toVersion)
+ {
+ $resModel = (string) $this->_connectionConfig->model;
+ $modName = (string) $this->_moduleConfig[0]->getName();
$filesDir = Mage::getModuleDir('sql', $modName) . DS . $this->_resourceName;
if (!is_dir($filesDir) || !is_readable($filesDir)) {
@@ -692,296 +984,4 @@ protected function _getModifySqlFiles($actionType, $fromVersion, $toVersion, $ar
}
return $arrRes;
}
-
- /******************* UTILITY METHODS *****************/
-
- /**
- * Retrieve row or field from table by id or string and parent id
- *
- * @param string $table
- * @param string $idField
- * @param string|int $id
- * @param string $field
- * @param string $parentField
- * @param string|int $parentId
- * @return mixed|boolean
- */
- public function getTableRow($table, $idField, $id, $field = null, $parentField = null, $parentId = 0)
- {
- if (str_contains($table, '/')) {
- $table = $this->getTable($table);
- }
-
- if (empty($this->_setupCache[$table][$parentId][$id])) {
- $adapter = $this->getConnection();
- $bind = ['id_field' => $id];
- $select = $adapter->select()
- ->from($table)
- ->where($adapter->quoteIdentifier($idField) . '= :id_field');
- if (!is_null($parentField)) {
- $select->where($adapter->quoteIdentifier($parentField) . '= :parent_id');
- $bind['parent_id'] = $parentId;
- }
- $this->_setupCache[$table][$parentId][$id] = $adapter->fetchRow($select, $bind);
- }
-
- if (is_null($field)) {
- return $this->_setupCache[$table][$parentId][$id];
- }
- return $this->_setupCache[$table][$parentId][$id][$field] ?? false;
- }
-
- /**
- * Delete table row
- *
- * @param string $table
- * @param string $idField
- * @param int|string $id
- * @param null|string $parentField
- * @param int|string $parentId
- * @return $this
- */
- public function deleteTableRow($table, $idField, $id, $parentField = null, $parentId = 0)
- {
- if (str_contains($table, '/')) {
- $table = $this->getTable($table);
- }
-
- $adapter = $this->getConnection();
- $where = [$adapter->quoteIdentifier($idField) . '=?' => $id];
- if (!is_null($parentField)) {
- $where[$adapter->quoteIdentifier($parentField) . '=?'] = $parentId;
- }
-
- $adapter->delete($table, $where);
-
- if (isset($this->_setupCache[$table][$parentId][$id])) {
- unset($this->_setupCache[$table][$parentId][$id]);
- }
-
- return $this;
- }
-
- /**
- * Update one or more fields of table row
- *
- * @param string $table
- * @param string $idField
- * @param string|int $id
- * @param string|array $field
- * @param mixed|null $value
- * @param string $parentField
- * @param string|int $parentId
- * @return $this
- */
- public function updateTableRow($table, $idField, $id, $field, $value = null, $parentField = null, $parentId = 0)
- {
- if (str_contains($table, '/')) {
- $table = $this->getTable($table);
- }
-
- if (is_array($field)) {
- $data = $field;
- } else {
- $data = [$field => $value];
- }
-
- $adapter = $this->getConnection();
- $where = [$adapter->quoteIdentifier($idField) . '=?' => $id];
- $adapter->update($table, $data, $where);
-
- if (isset($this->_setupCache[$table][$parentId][$id])) {
- if (is_array($field)) {
- $this->_setupCache[$table][$parentId][$id] =
- array_merge($this->_setupCache[$table][$parentId][$id], $field);
- } else {
- $this->_setupCache[$table][$parentId][$id][$field] = $value;
- }
- }
-
- return $this;
- }
-
- /**
- * Update table data
- *
- * @param string $table
- * @param Zend_Db_Expr $conditionExpr
- * @param Zend_Db_Expr $valueExpr
- * @return $this
- *
- * @deprecated since 1.4.0.1
- */
- public function updateTable($table, $conditionExpr, $valueExpr)
- {
- if (str_contains($table, '/')) {
- $table = $this->getTable($table);
- }
- $query = sprintf(
- 'UPDATE %s SET %s WHERE %s',
- $this->getConnection()->quoteIdentifier($table),
- $conditionExpr,
- $valueExpr,
- );
-
- $this->getConnection()->query($query);
-
- return $this;
- }
-
- /**
- * Check is table exists
- *
- * @param string $table
- * @return bool
- */
- public function tableExists($table)
- {
- if (str_contains($table, '/')) {
- $table = $this->getTable($table);
- }
-
- return $this->getConnection()->isTableExists($table);
- }
-
- /******************* CONFIG *****************/
- /**
- * Undefined
- *
- * @param string $path
- * @param string $label
- * @param string $default
- * @return $this
- * @deprecated since 1.4.0.1
- */
- public function addConfigField($path, $label, array $data = [], $default = null)
- {
- return $this;
- }
-
- /**
- * Save configuration data
- *
- * @param string $path
- * @param string $value
- * @param int|string $scope
- * @param int $scopeId
- * @param int $inherit
- * @return $this
- */
- public function setConfigData($path, $value, $scope = 'default', $scopeId = 0, $inherit = 0)
- {
- $table = $this->getTable('core/config_data');
- // this is a fix for mysql 4.1
- $this->getConnection()->showTableStatus($table);
-
- $data = [
- 'scope' => $scope,
- 'scope_id' => $scopeId,
- 'path' => $path,
- 'value' => $value,
- ];
- $this->getConnection()->insertOnDuplicate($table, $data, ['value']);
- return $this;
- }
-
- /**
- * Delete config field values
- *
- * @param string $path
- * @param string $scope (default|stores|websites|config)
- * @return $this
- */
- public function deleteConfigData($path, $scope = null)
- {
- $where = ['path = ?' => $path];
- if (!is_null($scope)) {
- $where['scope = ?'] = $scope;
- }
- $this->getConnection()->delete($this->getTable('core/config_data'), $where);
- return $this;
- }
-
- /**
- * Run plain SQL query(ies)
- *
- * @param string $sql
- * @return $this
- */
- public function run($sql)
- {
- $this->getConnection()->multiQuery($sql);
- return $this;
- }
-
- /**
- * Prepare database before install/upgrade
- *
- * @return $this
- */
- public function startSetup()
- {
- $this->getConnection()->startSetup();
- return $this;
- }
-
- /**
- * Prepare database after install/upgrade
- *
- * @return $this
- */
- public function endSetup()
- {
- $this->getConnection()->endSetup();
- return $this;
- }
-
- /**
- * Retrieve 32bit UNIQUE HASH for a Table index
- *
- * @param string $tableName
- * @param array|string $fields
- * @param string $indexType
- * @return string
- */
- public function getIdxName($tableName, $fields, $indexType = '')
- {
- return Mage::getSingleton('core/resource')->getIdxName($tableName, $fields, $indexType);
- }
-
- /**
- * Retrieve 32bit UNIQUE HASH for a Table foreign key
- *
- * @param string $priTableName the target table name
- * @param string $priColumnName the target table column name
- * @param string $refTableName the reference table name
- * @param string $refColumnName the reference table column name
- * @return string
- */
- public function getFkName($priTableName, $priColumnName, $refTableName, $refColumnName)
- {
- return Mage::getSingleton('core/resource')
- ->getFkName($priTableName, $priColumnName, $refTableName, $refColumnName);
- }
-
- /**
- * Check call afterApplyAllUpdates method for setup class
- *
- * @return bool
- */
- public function getCallAfterApplyAllUpdates()
- {
- return $this->_callAfterApplyAllUpdates;
- }
-
- /**
- * Run each time after applying of all updates,
- * if setup model set $_callAfterApplyAllUpdates flag to true
- *
- * @return $this
- */
- public function afterApplyAllUpdates()
- {
- return $this;
- }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Setup/Query/Modifier.php b/app/code/core/Mage/Core/Model/Resource/Setup/Query/Modifier.php
index 79b181c519a..d99e0a99071 100644
--- a/app/code/core/Mage/Core/Model/Resource/Setup/Query/Modifier.php
+++ b/app/code/core/Mage/Core/Model/Resource/Setup/Query/Modifier.php
@@ -47,6 +47,92 @@ public function __construct($args)
$this->_adapter = $args[0];
}
+ /**
+ * Processes query, modifies targeted columns to fit foreign keys restrictions
+ *
+ * @param string $sql
+ * @param array $bind
+ * @return $this
+ */
+ public function processQuery(&$sql, &$bind)
+ {
+ // Quick test to skip queries without foreign keys
+ if (!stripos($sql, 'foreign')) {
+ return $this;
+ }
+
+ // Find foreign keys set
+ $pattern = '/CONSTRAINT\s+[^\s]+\s+FOREIGN\s+KEY[^(]+\\(([^),]+)\\)\s+REFERENCES\s+([^\s.]+)\s+\\(([^)]+)\\)/i';
+ if (!preg_match_all($pattern, $sql, $matchesFk, PREG_SET_ORDER)) {
+ return $this;
+ }
+
+ // Get current table name
+ if (!preg_match('/\s*(CREATE|ALTER)\s+TABLE\s+([^\s.]+)/i', $sql, $match)) {
+ return $this;
+ }
+
+ $operation = $this->_prepareIdentifier($match[1]);
+ $table = $this->_prepareIdentifier($match[2]);
+
+ // Process all
+ foreach ($matchesFk as $match) {
+ $column = $this->_prepareIdentifier($match[1]);
+ $refTable = $this->_prepareIdentifier($match[2]);
+ $refColumn = $this->_prepareIdentifier($match[3]);
+
+ // Check tables existence
+ if (($operation != 'create') && !($this->_tableExists($table))) {
+ continue;
+ }
+ if (!$this->_tableExists($refTable)) {
+ continue;
+ }
+
+ // Self references are out of our fix scope
+ if ($refTable == $table) {
+ continue;
+ }
+
+ // Extract column type
+ if ($operation == 'create') {
+ $columnDefinition = $this->_getColumnDefinitionFromSql($sql, $column);
+ } else {
+ $columnDefinition = $this->_getColumnDefinitionFromTable($table, $column);
+ }
+
+ // We fix only int columns
+ if (!$columnDefinition || !in_array($columnDefinition['type'], $this->_processedTypes)) {
+ continue;
+ }
+
+ // Extract referenced column type
+ $refColumnDefinition = $this->_getColumnDefinitionFromTable($refTable, $refColumn);
+ if (!$refColumnDefinition) {
+ continue;
+ }
+
+ // We fix only int columns
+ if (!$refColumnDefinition || !in_array($refColumnDefinition['type'], $this->_processedTypes)) {
+ continue;
+ }
+
+ // Whether we need to fix
+ if ($refColumnDefinition == $columnDefinition) {
+ continue;
+ }
+
+ // Fix column to be the same type as referenced one
+ if ($operation == 'create') {
+ $this->_fixColumnDefinitionInSql($sql, $column, $refColumnDefinition);
+ } else {
+ $this->_fixColumnDefinitionInTable($table, $column, $refColumnDefinition);
+ }
+ }
+
+ return $this;
+ }
+
/**
* Returns column definition from CREATE TABLE sql
*
@@ -248,90 +334,4 @@ protected function _prepareIdentifier($identifier)
{
return strtolower(trim($identifier, "`\n\r\t"));
}
-
- /**
- * Processes query, modifies targeted columns to fit foreign keys restrictions
- *
- * @param string $sql
- * @param array $bind
- * @return $this
- */
- public function processQuery(&$sql, &$bind)
- {
- // Quick test to skip queries without foreign keys
- if (!stripos($sql, 'foreign')) {
- return $this;
- }
-
- // Find foreign keys set
- $pattern = '/CONSTRAINT\s+[^\s]+\s+FOREIGN\s+KEY[^(]+\\(([^),]+)\\)\s+REFERENCES\s+([^\s.]+)\s+\\(([^)]+)\\)/i';
- if (!preg_match_all($pattern, $sql, $matchesFk, PREG_SET_ORDER)) {
- return $this;
- }
-
- // Get current table name
- if (!preg_match('/\s*(CREATE|ALTER)\s+TABLE\s+([^\s.]+)/i', $sql, $match)) {
- return $this;
- }
-
- $operation = $this->_prepareIdentifier($match[1]);
- $table = $this->_prepareIdentifier($match[2]);
-
- // Process all
- foreach ($matchesFk as $match) {
- $column = $this->_prepareIdentifier($match[1]);
- $refTable = $this->_prepareIdentifier($match[2]);
- $refColumn = $this->_prepareIdentifier($match[3]);
-
- // Check tables existence
- if (($operation != 'create') && !($this->_tableExists($table))) {
- continue;
- }
- if (!$this->_tableExists($refTable)) {
- continue;
- }
-
- // Self references are out of our fix scope
- if ($refTable == $table) {
- continue;
- }
-
- // Extract column type
- if ($operation == 'create') {
- $columnDefinition = $this->_getColumnDefinitionFromSql($sql, $column);
- } else {
- $columnDefinition = $this->_getColumnDefinitionFromTable($table, $column);
- }
-
- // We fix only int columns
- if (!$columnDefinition || !in_array($columnDefinition['type'], $this->_processedTypes)) {
- continue;
- }
-
- // Extract referenced column type
- $refColumnDefinition = $this->_getColumnDefinitionFromTable($refTable, $refColumn);
- if (!$refColumnDefinition) {
- continue;
- }
-
- // We fix only int columns
- if (!$refColumnDefinition || !in_array($refColumnDefinition['type'], $this->_processedTypes)) {
- continue;
- }
-
- // Whether we need to fix
- if ($refColumnDefinition == $columnDefinition) {
- continue;
- }
-
- // Fix column to be the same type as referenced one
- if ($operation == 'create') {
- $this->_fixColumnDefinitionInSql($sql, $column, $refColumnDefinition);
- } else {
- $this->_fixColumnDefinitionInTable($table, $column, $refColumnDefinition);
- }
- }
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Store/Collection.php b/app/code/core/Mage/Core/Model/Resource/Store/Collection.php
index 9e1675b1b8c..b95fbabcb23 100644
--- a/app/code/core/Mage/Core/Model/Resource/Store/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Store/Collection.php
@@ -33,16 +33,6 @@ class Mage_Core_Model_Resource_Store_Collection extends Mage_Core_Model_Resource
*/
protected $_loadDefault = false;
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- $this->setFlag('load_default_store', false);
- $this->_init('core/store');
- }
-
/**
* Set flag for load default (admin) store
*
@@ -241,4 +231,14 @@ public function initConfigCache()
return $this;
}
+
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->setFlag('load_default_store', false);
+ $this->_init('core/store');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Store/Group/Collection.php b/app/code/core/Mage/Core/Model/Resource/Store/Group/Collection.php
index 7160f24f549..bf2106ca2a6 100644
--- a/app/code/core/Mage/Core/Model/Resource/Store/Group/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Store/Group/Collection.php
@@ -33,16 +33,6 @@ class Mage_Core_Model_Resource_Store_Group_Collection extends Mage_Core_Model_Re
*/
protected $_loadDefault = false;
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- $this->setFlag('load_default_store_group', false);
- $this->_init('core/store_group');
- }
-
/**
* Set flag for load default (admin) store
*
@@ -118,4 +108,14 @@ public function addWebsiteFilter($website)
{
return $this->addFieldToFilter('main_table.website_id', ['in' => $website]);
}
+
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->setFlag('load_default_store_group', false);
+ $this->_init('core/store_group');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Transaction.php b/app/code/core/Mage/Core/Model/Resource/Transaction.php
index c052ee799a9..f14e1eb0e38 100644
--- a/app/code/core/Mage/Core/Model/Resource/Transaction.php
+++ b/app/code/core/Mage/Core/Model/Resource/Transaction.php
@@ -43,57 +43,6 @@ class Mage_Core_Model_Resource_Transaction
* @var array
*/
protected $_beforeCommitCallbacks = [];
- /**
- * Begin transaction for all involved object resources
- *
- * @return $this
- */
- protected function _startTransaction()
- {
- foreach ($this->_objects as $object) {
- $object->getResource()->beginTransaction();
- }
- return $this;
- }
-
- /**
- * Commit transaction for all resources
- *
- * @return $this
- */
- protected function _commitTransaction()
- {
- foreach ($this->_objects as $object) {
- $object->getResource()->commit();
- }
- return $this;
- }
-
- /**
- * Rollback transaction
- *
- * @return $this
- */
- protected function _rollbackTransaction()
- {
- foreach ($this->_objects as $object) {
- $object->getResource()->rollBack();
- }
- return $this;
- }
-
- /**
- * Run all configured object callbacks
- *
- * @return $this
- */
- protected function _runCallbacks()
- {
- foreach ($this->_beforeCommitCallbacks as $callback) {
- call_user_func($callback);
- }
- return $this;
- }
/**
* Adding object for using in transaction
@@ -194,4 +143,55 @@ public function delete()
}
return $this;
}
+ /**
+ * Begin transaction for all involved object resources
+ *
+ * @return $this
+ */
+ protected function _startTransaction()
+ {
+ foreach ($this->_objects as $object) {
+ $object->getResource()->beginTransaction();
+ }
+ return $this;
+ }
+
+ /**
+ * Commit transaction for all resources
+ *
+ * @return $this
+ */
+ protected function _commitTransaction()
+ {
+ foreach ($this->_objects as $object) {
+ $object->getResource()->commit();
+ }
+ return $this;
+ }
+
+ /**
+ * Rollback transaction
+ *
+ * @return $this
+ */
+ protected function _rollbackTransaction()
+ {
+ foreach ($this->_objects as $object) {
+ $object->getResource()->rollBack();
+ }
+ return $this;
+ }
+
+ /**
+ * Run all configured object callbacks
+ *
+ * @return $this
+ */
+ protected function _runCallbacks()
+ {
+ foreach ($this->_beforeCommitCallbacks as $callback) {
+ call_user_func($callback);
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Translate.php b/app/code/core/Mage/Core/Model/Resource/Translate.php
index b408976cc76..e1667ef8ad9 100644
--- a/app/code/core/Mage/Core/Model/Resource/Translate.php
+++ b/app/code/core/Mage/Core/Model/Resource/Translate.php
@@ -22,11 +22,6 @@
*/
class Mage_Core_Model_Resource_Translate extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('core/translate', 'key_id');
- }
-
/**
* Retrieve translation array for store / locale code
*
@@ -108,4 +103,8 @@ public function getMainChecksum()
{
return $this->getChecksum($this->getMainTable());
}
+ protected function _construct()
+ {
+ $this->_init('core/translate', 'key_id');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Translate/String.php b/app/code/core/Mage/Core/Model/Resource/Translate/String.php
index 3eba6f4e62f..f2eb1a52e39 100644
--- a/app/code/core/Mage/Core/Model/Resource/Translate/String.php
+++ b/app/code/core/Mage/Core/Model/Resource/Translate/String.php
@@ -22,11 +22,6 @@
*/
class Mage_Core_Model_Resource_Translate_String extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('core/translate', 'key_id');
- }
-
/**
* @param Mage_Core_Model_Translate_String $object
* @inheritDoc
@@ -46,21 +41,6 @@ public function load(Mage_Core_Model_Abstract $object, $value, $field = null)
}
}
- /**
- * Retrieve select for load
- *
- * @param String $field
- * @param String $value
- * @param Mage_Core_Model_Abstract $object
- * @return Varien_Db_Select
- */
- protected function _getLoadSelect($field, $value, $object)
- {
- $select = parent::_getLoadSelect($field, $value, $object);
- $select->where('store_id = ?', Mage_Core_Model_App::ADMIN_STORE_ID);
- return $select;
- }
-
/**
* After translation loading
*
@@ -78,71 +58,6 @@ public function _afterLoad(Mage_Core_Model_Abstract $object)
return parent::_afterLoad($object);
}
- /**
- * @param Mage_Core_Model_Translate_String $object
- * @inheritDoc
- */
- protected function _beforeSave(Mage_Core_Model_Abstract $object)
- {
- $adapter = $this->_getWriteAdapter();
- $select = $adapter->select()
- ->from($this->getMainTable(), 'key_id')
- ->where('string = :string')
- ->where('store_id = :store_id');
-
- $bind = [
- 'string' => $object->getString(),
- 'store_id' => Mage_Core_Model_App::ADMIN_STORE_ID,
- ];
-
- $object->setId($adapter->fetchOne($select, $bind));
- return parent::_beforeSave($object);
- }
-
- /**
- * @param Mage_Core_Model_Translate_String $object
- * @inheritDoc
- */
- protected function _afterSave(Mage_Core_Model_Abstract $object)
- {
- $adapter = $this->_getWriteAdapter();
- $select = $adapter->select()
- ->from($this->getMainTable(), ['store_id', 'key_id'])
- ->where('string = :string');
- $stores = $adapter->fetchPairs($select, ['string' => $object->getString()]);
-
- $translations = $object->getStoreTranslations();
-
- if (is_array($translations)) {
- foreach ($translations as $storeId => $translate) {
- if (is_null($translate) || $translate == '') {
- $where = [
- 'store_id = ?' => $storeId,
- 'string = ?' => $object->getString(),
- ];
- $adapter->delete($this->getMainTable(), $where);
- } else {
- $data = [
- 'store_id' => $storeId,
- 'string' => $object->getString(),
- 'translate' => $translate,
- ];
-
- if (isset($stores[$storeId])) {
- $adapter->update(
- $this->getMainTable(),
- $data,
- ['key_id = ?' => $stores[$storeId]],
- );
- } else {
- $adapter->insert($this->getMainTable(), $data);
- }
- }
- }
- }
- return parent::_afterSave($object);
- }
-
/**
* Delete translates
*
@@ -230,4 +145,88 @@ public function saveTranslate($string, $translate, $locale = null, $storeId = nu
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('core/translate', 'key_id');
+ }
+
+ /**
+ * Retrieve select for load
+ *
+ * @param String $field
+ * @param String $value
+ * @param Mage_Core_Model_Abstract $object
+ * @return Varien_Db_Select
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ $select = parent::_getLoadSelect($field, $value, $object);
+ $select->where('store_id = ?', Mage_Core_Model_App::ADMIN_STORE_ID);
+ return $select;
+ }
+
+ /**
+ * @param Mage_Core_Model_Translate_String $object
+ * @inheritDoc
+ */
+ protected function _beforeSave(Mage_Core_Model_Abstract $object)
+ {
+ $adapter = $this->_getWriteAdapter();
+ $select = $adapter->select()
+ ->from($this->getMainTable(), 'key_id')
+ ->where('string = :string')
+ ->where('store_id = :store_id');
+
+ $bind = [
+ 'string' => $object->getString(),
+ 'store_id' => Mage_Core_Model_App::ADMIN_STORE_ID,
+ ];
+
+ $object->setId($adapter->fetchOne($select, $bind));
+ return parent::_beforeSave($object);
+ }
+
+ /**
+ * @param Mage_Core_Model_Translate_String $object
+ * @inheritDoc
+ */
+ protected function _afterSave(Mage_Core_Model_Abstract $object)
+ {
+ $adapter = $this->_getWriteAdapter();
+ $select = $adapter->select()
+ ->from($this->getMainTable(), ['store_id', 'key_id'])
+ ->where('string = :string');
+ $stores = $adapter->fetchPairs($select, ['string' => $object->getString()]);
+
+ $translations = $object->getStoreTranslations();
+
+ if (is_array($translations)) {
+ foreach ($translations as $storeId => $translate) {
+ if (is_null($translate) || $translate == '') {
+ $where = [
+ 'store_id = ?' => $storeId,
+ 'string = ?' => $object->getString(),
+ ];
+ $adapter->delete($this->getMainTable(), $where);
+ } else {
+ $data = [
+ 'store_id' => $storeId,
+ 'string' => $object->getString(),
+ 'translate' => $translate,
+ ];
+
+ if (isset($stores[$storeId])) {
+ $adapter->update(
+ $this->getMainTable(),
+ $data,
+ ['key_id = ?' => $stores[$storeId]],
+ );
+ } else {
+ $adapter->insert($this->getMainTable(), $data);
+ }
+ }
+ }
+ }
+ return parent::_afterSave($object);
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php b/app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php
index cdce6f9a846..449582cd864 100644
--- a/app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php
+++ b/app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php
@@ -29,53 +29,6 @@ class Mage_Core_Model_Resource_Url_Rewrite extends Mage_Core_Model_Resource_Db_A
*/
protected $_tagTable;
- protected function _construct()
- {
- $this->_init('core/url_rewrite', 'url_rewrite_id');
- $this->_tagTable = $this->getTable('url_rewrite_tag');
- }
-
- /**
- * Initialize array fields
- *
- * @return $this
- */
- protected function _initUniqueFields()
- {
- $this->_uniqueFields = [
- [
- 'field' => ['id_path','store_id','is_system'],
- 'title' => Mage::helper('core')->__('ID Path for Specified Store'),
- ],
- [
- 'field' => ['request_path','store_id'],
- 'title' => Mage::helper('core')->__('Request Path for Specified Store'),
- ],
- ];
- return $this;
- }
-
- /**
- * Retrieve select object for load object data
- *
- * @param string $field
- * @param mixed $value
- * @param Mage_Core_Model_Url_Rewrite $object
- * @return Zend_Db_Select
- */
- protected function _getLoadSelect($field, $value, $object)
- {
- $select = parent::_getLoadSelect($field, $value, $object);
-
- if (!is_null($object->getStoreId())) {
- $select->where('store_id = ?', $object->getStoreId());
- $select->order('is_system ' . Varien_Db_Select::SQL_DESC);
- $select->limit(1);
- }
-
- return $select;
- }
-
/**
* Retrieve request_path using id_path and current store's id.
*
@@ -160,4 +113,51 @@ public function loadByRequestPath(Mage_Core_Model_Url_Rewrite $object, $path)
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('core/url_rewrite', 'url_rewrite_id');
+ $this->_tagTable = $this->getTable('url_rewrite_tag');
+ }
+
+ /**
+ * Initialize array fields
+ *
+ * @return $this
+ */
+ protected function _initUniqueFields()
+ {
+ $this->_uniqueFields = [
+ [
+ 'field' => ['id_path','store_id','is_system'],
+ 'title' => Mage::helper('core')->__('ID Path for Specified Store'),
+ ],
+ [
+ 'field' => ['request_path','store_id'],
+ 'title' => Mage::helper('core')->__('Request Path for Specified Store'),
+ ],
+ ];
+ return $this;
+ }
+
+ /**
+ * Retrieve select object for load object data
+ *
+ * @param string $field
+ * @param mixed $value
+ * @param Mage_Core_Model_Url_Rewrite $object
+ * @return Zend_Db_Select
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ $select = parent::_getLoadSelect($field, $value, $object);
+
+ if (!is_null($object->getStoreId())) {
+ $select->where('store_id = ?', $object->getStoreId());
+ $select->order('is_system ' . Varien_Db_Select::SQL_DESC);
+ $select->limit(1);
+ }
+
+ return $select;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Url/Rewrite/Collection.php b/app/code/core/Mage/Core/Model/Resource/Url/Rewrite/Collection.php
index d66ac723572..ba4e3304202 100644
--- a/app/code/core/Mage/Core/Model/Resource/Url/Rewrite/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Url/Rewrite/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Core_Model_Resource_Url_Rewrite_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- $this->_init('core/url_rewrite');
- }
-
/**
* Add filter for tags (combined by OR)
*
@@ -101,4 +92,12 @@ public function filterAllByCategory()
->where('id_path LIKE ?', 'category/%');
return $this;
}
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('core/url_rewrite');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Variable.php b/app/code/core/Mage/Core/Model/Resource/Variable.php
index 49ed0f85525..867bb763835 100644
--- a/app/code/core/Mage/Core/Model/Resource/Variable.php
+++ b/app/code/core/Mage/Core/Model/Resource/Variable.php
@@ -22,11 +22,6 @@
*/
class Mage_Core_Model_Resource_Variable extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('core/variable', 'variable_id');
- }
-
/**
* Load variable by code
*
@@ -59,6 +54,10 @@ public function getVariableByCode($code, $withValue = false, $storeId = 0)
}
return $this->_getReadAdapter()->fetchRow($select);
}
+ protected function _construct()
+ {
+ $this->_init('core/variable', 'variable_id');
+ }
/**
* @param Mage_Core_Model_Variable $object
diff --git a/app/code/core/Mage/Core/Model/Resource/Variable/Collection.php b/app/code/core/Mage/Core/Model/Resource/Variable/Collection.php
index 5e163bd5825..d40523fbee4 100644
--- a/app/code/core/Mage/Core/Model/Resource/Variable/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Variable/Collection.php
@@ -29,16 +29,6 @@ class Mage_Core_Model_Resource_Variable_Collection extends Mage_Core_Model_Resou
*/
protected $_storeId = 0;
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_init('core/variable');
- }
-
/**
* Setter
*
@@ -87,4 +77,14 @@ public function toOptionArray()
{
return $this->_toOptionArray('code', 'name');
}
+
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('core/variable');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Website.php b/app/code/core/Mage/Core/Model/Resource/Website.php
index 56864e2da34..243771a2a97 100644
--- a/app/code/core/Mage/Core/Model/Resource/Website.php
+++ b/app/code/core/Mage/Core/Model/Resource/Website.php
@@ -22,6 +22,33 @@
*/
class Mage_Core_Model_Resource_Website extends Mage_Core_Model_Resource_Db_Abstract
{
+ /**
+ * Retrieve default stores select object
+ * Select fields website_id, store_id
+ *
+ * @param bool $withDefault include/exclude default admin website
+ * @return Varien_Db_Select
+ */
+ public function getDefaultStoresSelect($withDefault = false)
+ {
+ $ifNull = $this->_getReadAdapter()
+ ->getCheckSql('store_group_table.default_store_id IS NULL', '0', 'store_group_table.default_store_id');
+ $select = $this->_getReadAdapter()->select()
+ ->from(
+ ['website_table' => $this->getTable('core/website')],
+ ['website_id'],
+ )
+ ->joinLeft(
+ ['store_group_table' => $this->getTable('core/store_group')],
+ 'website_table.website_id=store_group_table.website_id'
+ . ' AND website_table.default_group_id = store_group_table.group_id',
+ ['store_id' => $ifNull],
+ );
+ if (!$withDefault) {
+ $select->where('website_table.website_id <> ?', 0);
+ }
+ return $select;
+ }
protected function _construct()
{
$this->_init('core/website', 'website_id');
@@ -87,32 +114,4 @@ protected function _afterDelete(Mage_Core_Model_Abstract $model)
return $this;
}
-
- /**
- * Retrieve default stores select object
- * Select fields website_id, store_id
- *
- * @param bool $withDefault include/exclude default admin website
- * @return Varien_Db_Select
- */
- public function getDefaultStoresSelect($withDefault = false)
- {
- $ifNull = $this->_getReadAdapter()
- ->getCheckSql('store_group_table.default_store_id IS NULL', '0', 'store_group_table.default_store_id');
- $select = $this->_getReadAdapter()->select()
- ->from(
- ['website_table' => $this->getTable('core/website')],
- ['website_id'],
- )
- ->joinLeft(
- ['store_group_table' => $this->getTable('core/store_group')],
- 'website_table.website_id=store_group_table.website_id'
- . ' AND website_table.default_group_id = store_group_table.group_id',
- ['store_id' => $ifNull],
- );
- if (!$withDefault) {
- $select->where('website_table.website_id <> ?', 0);
- }
- return $select;
- }
}
diff --git a/app/code/core/Mage/Core/Model/Resource/Website/Collection.php b/app/code/core/Mage/Core/Model/Resource/Website/Collection.php
index f1da08c4fed..945b38ecef7 100644
--- a/app/code/core/Mage/Core/Model/Resource/Website/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Website/Collection.php
@@ -37,16 +37,6 @@ class Mage_Core_Model_Resource_Website_Collection extends Mage_Core_Model_Resour
*/
protected $_map = ['fields' => ['website_id' => 'main_table.website_id']];
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- $this->setFlag('load_default_website', false);
- $this->_init('core/website');
- }
-
/**
* Set flag for load default (admin) website
*
@@ -169,4 +159,14 @@ public function addFilterByGroupIds($groupIds)
}
return $this;
}
+
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->setFlag('load_default_website', false);
+ $this->_init('core/website');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php b/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php
index efaabb063b9..3c5c0b3191c 100644
--- a/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php
+++ b/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php
@@ -509,66 +509,6 @@ public function setValidatorSessionRenewTimestamp($timestamp)
$_SESSION[self::VALIDATOR_KEY][self::VALIDATOR_SESSION_RENEW_TIMESTAMP] = $timestamp;
}
- /**
- * Validate data
- *
- * @return bool
- * @SuppressWarnings("PHPMD.Superglobals")
- */
- protected function _validate()
- {
- $sessionData = $_SESSION[self::VALIDATOR_KEY];
- $validatorData = $this->getValidatorData();
- self::$isValidated = true; // Only validate once since the validator data is the same for every namespace
-
- if ($this->useValidateRemoteAddr()
- && $sessionData[self::VALIDATOR_REMOTE_ADDR_KEY] != $validatorData[self::VALIDATOR_REMOTE_ADDR_KEY]
- ) {
- return false;
- }
- if ($this->useValidateHttpVia()
- && $sessionData[self::VALIDATOR_HTTP_VIA_KEY] != $validatorData[self::VALIDATOR_HTTP_VIA_KEY]
- ) {
- return false;
- }
-
- if ($this->useValidateHttpXForwardedFor()
- && $sessionData[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY] != $validatorData[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY]
- ) {
- return false;
- }
- if ($this->useValidateHttpUserAgent()
- && $sessionData[self::VALIDATOR_HTTP_USER_AGENT_KEY] != $validatorData[self::VALIDATOR_HTTP_USER_AGENT_KEY]
- ) {
- $userAgentValidated = $this->getValidateHttpUserAgentSkip();
- foreach ($userAgentValidated as $agent) {
- if (preg_match('/' . $agent . '/iu', $validatorData[self::VALIDATOR_HTTP_USER_AGENT_KEY])) {
- return true;
- }
- }
- return false;
- }
-
- if ($this->useValidateSessionExpire()
- && isset($sessionData[self::VALIDATOR_SESSION_RENEW_TIMESTAMP])
- && isset($sessionData[self::VALIDATOR_SESSION_LIFETIME])
- && ((int) $sessionData[self::VALIDATOR_SESSION_RENEW_TIMESTAMP] + (int) $sessionData[self::VALIDATOR_SESSION_LIFETIME])
- < time()
- ) {
- return false;
- }
- if ($this->useValidateSessionPasswordTimestamp()
- && isset($validatorData[self::VALIDATOR_PASSWORD_CREATE_TIMESTAMP])
- && isset($sessionData[self::VALIDATOR_SESSION_RENEW_TIMESTAMP])
- && $validatorData[self::VALIDATOR_PASSWORD_CREATE_TIMESTAMP]
- > $sessionData[self::VALIDATOR_SESSION_RENEW_TIMESTAMP]
- ) {
- return false;
- }
-
- return true;
- }
-
/**
* Retrieve unique user data for validator
*
@@ -628,4 +568,64 @@ public function regenerateSessionId()
session_regenerate_id(true);
return $this;
}
+
+ /**
+ * Validate data
+ *
+ * @return bool
+ * @SuppressWarnings("PHPMD.Superglobals")
+ */
+ protected function _validate()
+ {
+ $sessionData = $_SESSION[self::VALIDATOR_KEY];
+ $validatorData = $this->getValidatorData();
+ self::$isValidated = true; // Only validate once since the validator data is the same for every namespace
+
+ if ($this->useValidateRemoteAddr()
+ && $sessionData[self::VALIDATOR_REMOTE_ADDR_KEY] != $validatorData[self::VALIDATOR_REMOTE_ADDR_KEY]
+ ) {
+ return false;
+ }
+ if ($this->useValidateHttpVia()
+ && $sessionData[self::VALIDATOR_HTTP_VIA_KEY] != $validatorData[self::VALIDATOR_HTTP_VIA_KEY]
+ ) {
+ return false;
+ }
+
+ if ($this->useValidateHttpXForwardedFor()
+ && $sessionData[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY] != $validatorData[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY]
+ ) {
+ return false;
+ }
+ if ($this->useValidateHttpUserAgent()
+ && $sessionData[self::VALIDATOR_HTTP_USER_AGENT_KEY] != $validatorData[self::VALIDATOR_HTTP_USER_AGENT_KEY]
+ ) {
+ $userAgentValidated = $this->getValidateHttpUserAgentSkip();
+ foreach ($userAgentValidated as $agent) {
+ if (preg_match('/' . $agent . '/iu', $validatorData[self::VALIDATOR_HTTP_USER_AGENT_KEY])) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ if ($this->useValidateSessionExpire()
+ && isset($sessionData[self::VALIDATOR_SESSION_RENEW_TIMESTAMP])
+ && isset($sessionData[self::VALIDATOR_SESSION_LIFETIME])
+ && ((int) $sessionData[self::VALIDATOR_SESSION_RENEW_TIMESTAMP] + (int) $sessionData[self::VALIDATOR_SESSION_LIFETIME])
+ < time()
+ ) {
+ return false;
+ }
+ if ($this->useValidateSessionPasswordTimestamp()
+ && isset($validatorData[self::VALIDATOR_PASSWORD_CREATE_TIMESTAMP])
+ && isset($sessionData[self::VALIDATOR_SESSION_RENEW_TIMESTAMP])
+ && $validatorData[self::VALIDATOR_PASSWORD_CREATE_TIMESTAMP]
+ > $sessionData[self::VALIDATOR_SESSION_RENEW_TIMESTAMP]
+ ) {
+ return false;
+ }
+
+ return true;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Store.php b/app/code/core/Mage/Core/Model/Store.php
index 6ceb63b02a0..85123ffda04 100644
--- a/app/code/core/Mage/Core/Model/Store.php
+++ b/app/code/core/Mage/Core/Model/Store.php
@@ -248,40 +248,6 @@ class Mage_Core_Model_Store extends Mage_Core_Model_Abstract
// phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
private $_isReadOnly = false;
- /**
- * Initialize object
- */
- protected function _construct()
- {
- $this->_init('core/store');
- $this->_configCacheBaseNodes = [
- self::XML_PATH_PRICE_SCOPE,
- self::XML_PATH_SECURE_BASE_URL,
- self::XML_PATH_SECURE_IN_ADMINHTML,
- self::XML_PATH_SECURE_IN_FRONTEND,
- self::XML_PATH_STORE_IN_URL,
- self::XML_PATH_UNSECURE_BASE_URL,
- self::XML_PATH_USE_REWRITES,
- self::XML_PATH_UNSECURE_BASE_LINK_URL,
- self::XML_PATH_SECURE_BASE_LINK_URL,
- 'general/locale/code',
- ];
- }
-
- /**
- * Retrieve store session object
- *
- * @return Mage_Core_Model_Session
- */
- protected function _getSession()
- {
- if (!$this->_session) {
- $this->_session = Mage::getModel('core/session')
- ->init('store_' . $this->getCode());
- }
- return $this->_session;
- }
-
/**
* @inheritDoc
*/
@@ -463,53 +429,6 @@ public function getWebsite()
return $this->_website;
}
- /**
- * Process config value
- *
- * @param string $fullPath
- * @param string $path
- * @param Varien_Simplexml_Element $node
- * @return array|string
- */
- protected function _processConfigValue($fullPath, $path, $node)
- {
- if (isset($this->_configCache[$path])) {
- return $this->_configCache[$path];
- }
-
- if ($node->hasChildren()) {
- $aValue = [];
- foreach ($node->children() as $k => $v) {
- $aValue[$k] = $this->_processConfigValue($fullPath . '/' . $k, $path . '/' . $k, $v);
- }
- $this->_configCache[$path] = $aValue;
- return $aValue;
- }
-
- $sValue = (string) $node;
- if (!empty($node['backend_model']) && !empty($sValue)) {
- $backend = Mage::getModel((string) $node['backend_model']);
- $backend->setPath($path)->setValue($sValue)->afterLoad();
- $sValue = $backend->getValue();
- }
-
- if (is_string($sValue) && strpos($sValue, '{{') !== false) {
- if (strpos($sValue, '{{unsecure_base_url}}') !== false) {
- $unsecureBaseUrl = $this->getConfig(self::XML_PATH_UNSECURE_BASE_URL);
- $sValue = str_replace('{{unsecure_base_url}}', $unsecureBaseUrl, $sValue);
- } elseif (strpos($sValue, '{{secure_base_url}}') !== false) {
- $secureBaseUrl = $this->getConfig(self::XML_PATH_SECURE_BASE_URL);
- $sValue = str_replace('{{secure_base_url}}', $secureBaseUrl, $sValue);
- } elseif (strpos($sValue, '{{base_url}}') !== false) {
- $sValue = Mage::getConfig()->substDistroServerVars($sValue);
- }
- }
-
- $this->_configCache[$path] = $sValue;
-
- return $sValue;
- }
-
/**
* Convert config values for url paths
*
@@ -624,71 +543,6 @@ public function getBaseUrl($type = self::URL_TYPE_LINK, $secure = null)
return $this->_baseUrlCache[$cacheKey];
}
- /**
- * Remove script file name from url in case when server rewrites are enabled
- *
- * @param string $url
- * @return string
- * @SuppressWarnings("PHPMD.Superglobals")
- */
- protected function _updatePathUseRewrites($url)
- {
- if ($this->isAdmin() || !$this->getConfig(self::XML_PATH_USE_REWRITES) || !Mage::isInstalled()) {
- // phpcs:ignore Ecg.Security.ForbiddenFunction.Found,Ecg.Security.Superglobal.SuperglobalUsageWarning
- $indexFileName = $this->_isCustomEntryPoint() ? 'index.php' : basename($_SERVER['SCRIPT_FILENAME']);
- $url .= $indexFileName . '/';
- }
- return $url;
- }
-
- /**
- * Check if used entry point is custom
- *
- * @return bool
- */
- protected function _isCustomEntryPoint()
- {
- return (bool) Mage::registry('custom_entry_point');
- }
-
- /**
- * Retrieve URL for media catalog
- *
- * If we use Database file storage and server doesn't support rewrites (.htaccess in media folder)
- * we have to put name of fetching media script exactly into URL
- *
- * @param null|bool $secure
- * @param string $type
- * @return string
- */
- protected function _updateMediaPathUseRewrites($secure = null, $type = self::URL_TYPE_MEDIA)
- {
- $secure = is_null($secure) ? $this->isCurrentlySecure() : (bool) $secure;
- $secureStringFlag = $secure ? 'secure' : 'unsecure';
- $url = $this->getConfig('web/' . $secureStringFlag . '/base_' . $type . '_url');
- if (!$this->getConfig(self::XML_PATH_USE_REWRITES)
- && Mage::helper('core/file_storage_database')->checkDbUsage()
- ) {
- $urlStart = $this->getConfig('web/' . $secureStringFlag . '/base_url');
- $url = str_replace($urlStart, $urlStart . self::MEDIA_REWRITE_SCRIPT, $url);
- }
- return $url;
- }
-
- /**
- * Add store code to url in case if it is enabled in configuration
- *
- * @param string $url
- * @return string
- */
- protected function _updatePathUseStoreView($url)
- {
- if ($this->getStoreInUrl()) {
- $url .= $this->getCode() . '/';
- }
- return $url;
- }
-
/**
* Returns whether url forming scheme prepends url path with store view code
*
@@ -1156,44 +1010,6 @@ public function getName()
return $this->_getData('name');
}
- /**
- * Protect delete from non admin area
- *
- * Register indexing event before delete store
- *
- * {@inheritDoc}
- */
- protected function _beforeDelete()
- {
- $this->_protectFromNonAdmin();
- Mage::getSingleton('index/indexer')->logEvent($this, self::ENTITY, Mage_Index_Model_Event::TYPE_DELETE);
- return parent::_beforeDelete();
- }
-
- /**
- * rewrite in order to clear configuration cache
- *
- * @return $this
- */
- protected function _afterDelete()
- {
- parent::_afterDelete();
- Mage::getConfig()->removeCache();
- return $this;
- }
-
- /**
- * Init indexing process after store delete commit
- *
- * @return $this
- */
- protected function _afterDeleteCommit()
- {
- parent::_afterDeleteCommit();
- Mage::getSingleton('index/indexer')->indexEvents(self::ENTITY, Mage_Index_Model_Event::TYPE_DELETE);
- return $this;
- }
-
/**
* Reinit and reset Config Data
*
@@ -1237,4 +1053,188 @@ public function getFrontendName()
}
return $this->_frontendName;
}
+
+ /**
+ * Initialize object
+ */
+ protected function _construct()
+ {
+ $this->_init('core/store');
+ $this->_configCacheBaseNodes = [
+ self::XML_PATH_PRICE_SCOPE,
+ self::XML_PATH_SECURE_BASE_URL,
+ self::XML_PATH_SECURE_IN_ADMINHTML,
+ self::XML_PATH_SECURE_IN_FRONTEND,
+ self::XML_PATH_STORE_IN_URL,
+ self::XML_PATH_UNSECURE_BASE_URL,
+ self::XML_PATH_USE_REWRITES,
+ self::XML_PATH_UNSECURE_BASE_LINK_URL,
+ self::XML_PATH_SECURE_BASE_LINK_URL,
+ 'general/locale/code',
+ ];
+ }
+
+ /**
+ * Retrieve store session object
+ *
+ * @return Mage_Core_Model_Session
+ */
+ protected function _getSession()
+ {
+ if (!$this->_session) {
+ $this->_session = Mage::getModel('core/session')
+ ->init('store_' . $this->getCode());
+ }
+ return $this->_session;
+ }
+
+ /**
+ * Process config value
+ *
+ * @param string $fullPath
+ * @param string $path
+ * @param Varien_Simplexml_Element $node
+ * @return array|string
+ */
+ protected function _processConfigValue($fullPath, $path, $node)
+ {
+ if (isset($this->_configCache[$path])) {
+ return $this->_configCache[$path];
+ }
+
+ if ($node->hasChildren()) {
+ $aValue = [];
+ foreach ($node->children() as $k => $v) {
+ $aValue[$k] = $this->_processConfigValue($fullPath . '/' . $k, $path . '/' . $k, $v);
+ }
+ $this->_configCache[$path] = $aValue;
+ return $aValue;
+ }
+
+ $sValue = (string) $node;
+ if (!empty($node['backend_model']) && !empty($sValue)) {
+ $backend = Mage::getModel((string) $node['backend_model']);
+ $backend->setPath($path)->setValue($sValue)->afterLoad();
+ $sValue = $backend->getValue();
+ }
+
+ if (is_string($sValue) && strpos($sValue, '{{') !== false) {
+ if (strpos($sValue, '{{unsecure_base_url}}') !== false) {
+ $unsecureBaseUrl = $this->getConfig(self::XML_PATH_UNSECURE_BASE_URL);
+ $sValue = str_replace('{{unsecure_base_url}}', $unsecureBaseUrl, $sValue);
+ } elseif (strpos($sValue, '{{secure_base_url}}') !== false) {
+ $secureBaseUrl = $this->getConfig(self::XML_PATH_SECURE_BASE_URL);
+ $sValue = str_replace('{{secure_base_url}}', $secureBaseUrl, $sValue);
+ } elseif (strpos($sValue, '{{base_url}}') !== false) {
+ $sValue = Mage::getConfig()->substDistroServerVars($sValue);
+ }
+ }
+
+ $this->_configCache[$path] = $sValue;
+
+ return $sValue;
+ }
+
+ /**
+ * Remove script file name from url in case when server rewrites are enabled
+ *
+ * @param string $url
+ * @return string
+ * @SuppressWarnings("PHPMD.Superglobals")
+ */
+ protected function _updatePathUseRewrites($url)
+ {
+ if ($this->isAdmin() || !$this->getConfig(self::XML_PATH_USE_REWRITES) || !Mage::isInstalled()) {
+ // phpcs:ignore Ecg.Security.ForbiddenFunction.Found,Ecg.Security.Superglobal.SuperglobalUsageWarning
+ $indexFileName = $this->_isCustomEntryPoint() ? 'index.php' : basename($_SERVER['SCRIPT_FILENAME']);
+ $url .= $indexFileName . '/';
+ }
+ return $url;
+ }
+
+ /**
+ * Check if used entry point is custom
+ *
+ * @return bool
+ */
+ protected function _isCustomEntryPoint()
+ {
+ return (bool) Mage::registry('custom_entry_point');
+ }
+
+ /**
+ * Retrieve URL for media catalog
+ *
+ * If we use Database file storage and server doesn't support rewrites (.htaccess in media folder)
+ * we have to put name of fetching media script exactly into URL
+ *
+ * @param null|bool $secure
+ * @param string $type
+ * @return string
+ */
+ protected function _updateMediaPathUseRewrites($secure = null, $type = self::URL_TYPE_MEDIA)
+ {
+ $secure = is_null($secure) ? $this->isCurrentlySecure() : (bool) $secure;
+ $secureStringFlag = $secure ? 'secure' : 'unsecure';
+ $url = $this->getConfig('web/' . $secureStringFlag . '/base_' . $type . '_url');
+ if (!$this->getConfig(self::XML_PATH_USE_REWRITES)
+ && Mage::helper('core/file_storage_database')->checkDbUsage()
+ ) {
+ $urlStart = $this->getConfig('web/' . $secureStringFlag . '/base_url');
+ $url = str_replace($urlStart, $urlStart . self::MEDIA_REWRITE_SCRIPT, $url);
+ }
+ return $url;
+ }
+
+ /**
+ * Add store code to url in case if it is enabled in configuration
+ *
+ * @param string $url
+ * @return string
+ */
+ protected function _updatePathUseStoreView($url)
+ {
+ if ($this->getStoreInUrl()) {
+ $url .= $this->getCode() . '/';
+ }
+ return $url;
+ }
+
+ /**
+ * Protect delete from non admin area
+ *
+ * Register indexing event before delete store
+ *
+ * {@inheritDoc}
+ */
+ protected function _beforeDelete()
+ {
+ $this->_protectFromNonAdmin();
+ Mage::getSingleton('index/indexer')->logEvent($this, self::ENTITY, Mage_Index_Model_Event::TYPE_DELETE);
+ return parent::_beforeDelete();
+ }
+
+ /**
+ * rewrite in order to clear configuration cache
+ *
+ * @return $this
+ */
+ protected function _afterDelete()
+ {
+ parent::_afterDelete();
+ Mage::getConfig()->removeCache();
+ return $this;
+ }
+
+ /**
+ * Init indexing process after store delete commit
+ *
+ * @return $this
+ */
+ protected function _afterDeleteCommit()
+ {
+ parent::_afterDeleteCommit();
+ Mage::getSingleton('index/indexer')->indexEvents(self::ENTITY, Mage_Index_Model_Event::TYPE_DELETE);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Store/Group.php b/app/code/core/Mage/Core/Model/Store/Group.php
index 13be4da75b7..8dea8a3441f 100644
--- a/app/code/core/Mage/Core/Model/Store/Group.php
+++ b/app/code/core/Mage/Core/Model/Store/Group.php
@@ -101,35 +101,6 @@ class Mage_Core_Model_Store_Group extends Mage_Core_Model_Abstract
// phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
private $_isReadOnly = false;
- /**
- * init model
- *
- */
- protected function _construct()
- {
- $this->_init('core/store_group');
- }
-
- /**
- * Load store collection and set internal data
- */
- protected function _loadStores()
- {
- $this->_stores = [];
- $this->_storesCount = 0;
- /** @var Mage_Core_Model_Store $store */
- foreach ($this->getStoreCollection() as $store) {
- $storeId = $store->getId();
- $this->_stores[$storeId] = $store;
- $this->_storeIds[$storeId] = $storeId;
- $this->_storeCodes[$storeId] = $store->getCode();
- if ($this->getDefaultStoreId() == $storeId) {
- $this->_defaultStore = $store;
- }
- $this->_storesCount++;
- }
- }
-
/**
* Set website stores
*
@@ -330,15 +301,6 @@ public function getWebsiteId()
return $this->_getData('website_id');
}
- /**
- * @inheritDoc
- */
- protected function _beforeDelete()
- {
- $this->_protectFromNonAdmin();
- return parent::_beforeDelete();
- }
-
/**
* Get/Set isReadOnly flag
*
@@ -352,4 +314,42 @@ public function isReadOnly($value = null)
}
return $this->_isReadOnly;
}
+
+ /**
+ * init model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('core/store_group');
+ }
+
+ /**
+ * Load store collection and set internal data
+ */
+ protected function _loadStores()
+ {
+ $this->_stores = [];
+ $this->_storesCount = 0;
+ /** @var Mage_Core_Model_Store $store */
+ foreach ($this->getStoreCollection() as $store) {
+ $storeId = $store->getId();
+ $this->_stores[$storeId] = $store;
+ $this->_storeIds[$storeId] = $storeId;
+ $this->_storeCodes[$storeId] = $store->getCode();
+ if ($this->getDefaultStoreId() == $storeId) {
+ $this->_defaultStore = $store;
+ }
+ $this->_storesCount++;
+ }
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _beforeDelete()
+ {
+ $this->_protectFromNonAdmin();
+ return parent::_beforeDelete();
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Template.php b/app/code/core/Mage/Core/Model/Template.php
index 17131c4f787..104d614e2e3 100644
--- a/app/code/core/Mage/Core/Model/Template.php
+++ b/app/code/core/Mage/Core/Model/Template.php
@@ -55,57 +55,6 @@ abstract class Mage_Core_Model_Template extends Mage_Core_Model_Abstract
*/
protected $_initialEnvironmentInfo = null;
- /**
- * Applying of design config
- *
- * @return $this
- */
- protected function _applyDesignConfig()
- {
- $designConfig = $this->getDesignConfig();
- $store = $designConfig->getStore();
- $storeId = is_object($store) ? $store->getId() : $store;
- $area = $designConfig->getArea();
- if (!is_null($storeId) && ($storeId != Mage::app()->getStore()->getId())) {
- $appEmulation = Mage::getSingleton('core/app_emulation');
- $this->_initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId, $area);
- }
- return $this;
- }
-
- /**
- * Revert design settings to previous
- *
- * @return $this
- */
- protected function _cancelDesignConfig()
- {
- if (!empty($this->_initialEnvironmentInfo)) {
- $appEmulation = Mage::getSingleton('core/app_emulation');
- $appEmulation->stopEnvironmentEmulation($this->_initialEnvironmentInfo);
- $this->_initialEnvironmentInfo = null;
- }
- return $this;
- }
-
- /**
- * Get design configuration data
- *
- * @return Varien_Object
- */
- protected function getDesignConfig()
- {
- if (is_null($this->_designConfig)) {
- $store = Mage::getDesign()->getStore();
- $storeId = is_object($store) ? $store->getId() : $store;
- $this->_designConfig = new Varien_Object([
- 'area' => Mage::getDesign()->getArea(),
- 'store' => $storeId,
- ]);
- }
- return $this->_designConfig;
- }
-
/**
* Initialize design information for template processing
*
@@ -166,4 +115,55 @@ public function isPlain()
* @return int|string
*/
abstract public function getType();
+
+ /**
+ * Applying of design config
+ *
+ * @return $this
+ */
+ protected function _applyDesignConfig()
+ {
+ $designConfig = $this->getDesignConfig();
+ $store = $designConfig->getStore();
+ $storeId = is_object($store) ? $store->getId() : $store;
+ $area = $designConfig->getArea();
+ if (!is_null($storeId) && ($storeId != Mage::app()->getStore()->getId())) {
+ $appEmulation = Mage::getSingleton('core/app_emulation');
+ $this->_initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId, $area);
+ }
+ return $this;
+ }
+
+ /**
+ * Revert design settings to previous
+ *
+ * @return $this
+ */
+ protected function _cancelDesignConfig()
+ {
+ if (!empty($this->_initialEnvironmentInfo)) {
+ $appEmulation = Mage::getSingleton('core/app_emulation');
+ $appEmulation->stopEnvironmentEmulation($this->_initialEnvironmentInfo);
+ $this->_initialEnvironmentInfo = null;
+ }
+ return $this;
+ }
+
+ /**
+ * Get design configuration data
+ *
+ * @return Varien_Object
+ */
+ protected function getDesignConfig()
+ {
+ if (is_null($this->_designConfig)) {
+ $store = Mage::getDesign()->getStore();
+ $storeId = is_object($store) ? $store->getId() : $store;
+ $this->_designConfig = new Varien_Object([
+ 'area' => Mage::getDesign()->getArea(),
+ 'store' => $storeId,
+ ]);
+ }
+ return $this->_designConfig;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Translate.php b/app/code/core/Mage/Core/Model/Translate.php
index 35fda12c0cf..be93ffec6d4 100644
--- a/app/code/core/Mage/Core/Model/Translate.php
+++ b/app/code/core/Mage/Core/Model/Translate.php
@@ -191,131 +191,6 @@ public function getConfig($key)
return $this->_config[$key] ?? null;
}
- /**
- * Loading data from module translation files
- *
- * @param string $moduleName
- * @param array $files
- * @param bool $forceReload
- * @return $this
- */
- protected function _loadModuleTranslation($moduleName, $files, $forceReload = false)
- {
- foreach ($files as $file) {
- $file = $this->_getModuleFilePath($moduleName, $file);
- $this->_addData($this->_getFileData($file), $moduleName, $forceReload);
- }
- return $this;
- }
-
- /**
- * Adding translation data
- *
- * @param array $data
- * @param string $scope
- * @param bool $forceReload
- * @return $this
- */
- protected function _addData($data, $scope, $forceReload = false)
- {
- foreach ($data as $key => $value) {
- if ($key === $value) {
- continue;
- }
- $key = $this->_prepareDataString($key);
- $value = $value === null ? '' : $this->_prepareDataString($value);
- if ($scope && isset($this->_dataScope[$key]) && !$forceReload) {
- /**
- * Checking previous value
- */
- $scopeKey = $this->_dataScope[$key] . self::SCOPE_SEPARATOR . $key;
- if (!isset($this->_data[$scopeKey])) {
- if (isset($this->_data[$key])) {
- $this->_data[$scopeKey] = $this->_data[$key];
- /**
- * Not allow use translation not related to module
- */
- if (Mage::getIsDeveloperMode()) {
- unset($this->_data[$key]);
- }
- }
- }
- $scopeKey = $scope . self::SCOPE_SEPARATOR . $key;
- $this->_data[$scopeKey] = $value;
- } else {
- $this->_data[$key] = $value;
- $this->_dataScope[$key] = $scope;
- }
- }
- return $this;
- }
-
- /**
- * @param string $string
- * @return string
- */
- protected function _prepareDataString($string)
- {
- return str_replace('""', '"', $string);
- }
-
- /**
- * Loading current theme translation
- *
- * @param bool $forceReload
- * @return $this
- */
- protected function _loadThemeTranslation($forceReload = false)
- {
- $file = Mage::getDesign()->getLocaleFileName('translate.csv');
- $this->_addData($this->_getFileData($file), false, $forceReload);
- return $this;
- }
-
- /**
- * Loading current store translation from DB
- *
- * @param bool $forceReload
- * @return $this
- */
- protected function _loadDbTranslation($forceReload = false)
- {
- $arr = $this->getResource()->getTranslationArray(null, $this->getLocale());
- $this->_addData($arr, $this->getConfig(self::CONFIG_KEY_STORE), $forceReload);
- return $this;
- }
-
- /**
- * Retrieve translation file for module
- *
- * @param string $module
- * @param string $fileName
- * @return string
- */
- protected function _getModuleFilePath($module, $fileName)
- {
- //$file = Mage::getConfig()->getModuleDir('locale', $module);
- $file = Mage::getBaseDir('locale');
- return $file . (DS . $this->getLocale() . DS . $fileName);
- }
-
- /**
- * Retrieve data from file
- *
- * @param string $file
- * @return array
- */
- protected function _getFileData($file)
- {
- $data = [];
- if (file_exists($file)) {
- $parser = new Varien_File_Csv();
- $parser->setDelimiter(self::CSV_SEPARATOR);
- $data = $parser->getDataPairs($file);
- }
- return $data;
- }
-
/**
* Retrieve translation data
*
@@ -515,6 +390,131 @@ public function getCacheId()
return $this->_cacheId;
}
+ /**
+ * Loading data from module translation files
+ *
+ * @param string $moduleName
+ * @param array $files
+ * @param bool $forceReload
+ * @return $this
+ */
+ protected function _loadModuleTranslation($moduleName, $files, $forceReload = false)
+ {
+ foreach ($files as $file) {
+ $file = $this->_getModuleFilePath($moduleName, $file);
+ $this->_addData($this->_getFileData($file), $moduleName, $forceReload);
+ }
+ return $this;
+ }
+
+ /**
+ * Adding translation data
+ *
+ * @param array $data
+ * @param string $scope
+ * @param bool $forceReload
+ * @return $this
+ */
+ protected function _addData($data, $scope, $forceReload = false)
+ {
+ foreach ($data as $key => $value) {
+ if ($key === $value) {
+ continue;
+ }
+ $key = $this->_prepareDataString($key);
+ $value = $value === null ? '' : $this->_prepareDataString($value);
+ if ($scope && isset($this->_dataScope[$key]) && !$forceReload) {
+ /**
+ * Checking previous value
+ */
+ $scopeKey = $this->_dataScope[$key] . self::SCOPE_SEPARATOR . $key;
+ if (!isset($this->_data[$scopeKey])) {
+ if (isset($this->_data[$key])) {
+ $this->_data[$scopeKey] = $this->_data[$key];
+ /**
+ * Not allow use translation not related to module
+ */
+ if (Mage::getIsDeveloperMode()) {
+ unset($this->_data[$key]);
+ }
+ }
+ }
+ $scopeKey = $scope . self::SCOPE_SEPARATOR . $key;
+ $this->_data[$scopeKey] = $value;
+ } else {
+ $this->_data[$key] = $value;
+ $this->_dataScope[$key] = $scope;
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * @param string $string
+ * @return string
+ */
+ protected function _prepareDataString($string)
+ {
+ return str_replace('""', '"', $string);
+ }
+
+ /**
+ * Loading current theme translation
+ *
+ * @param bool $forceReload
+ * @return $this
+ */
+ protected function _loadThemeTranslation($forceReload = false)
+ {
+ $file = Mage::getDesign()->getLocaleFileName('translate.csv');
+ $this->_addData($this->_getFileData($file), false, $forceReload);
+ return $this;
+ }
+
+ /**
+ * Loading current store translation from DB
+ *
+ * @param bool $forceReload
+ * @return $this
+ */
+ protected function _loadDbTranslation($forceReload = false)
+ {
+ $arr = $this->getResource()->getTranslationArray(null, $this->getLocale());
+ $this->_addData($arr, $this->getConfig(self::CONFIG_KEY_STORE), $forceReload);
+ return $this;
+ }
+
+ /**
+ * Retrieve translation file for module
+ *
+ * @param string $module
+ * @param string $fileName
+ * @return string
+ */
+ protected function _getModuleFilePath($module, $fileName)
+ {
+ //$file = Mage::getConfig()->getModuleDir('locale', $module);
+ $file = Mage::getBaseDir('locale');
+ return $file . (DS . $this->getLocale() . DS . $fileName);
+ }
+
+ /**
+ * Retrieve data from file
+ *
+ * @param string $file
+ * @return array
+ */
+ protected function _getFileData($file)
+ {
+ $data = [];
+ if (file_exists($file)) {
+ $parser = new Varien_File_Csv();
+ $parser->setDelimiter(self::CSV_SEPARATOR);
+ $data = $parser->getDataPairs($file);
+ }
+ return $data;
+ }
+
/**
* Loading data cache
*
diff --git a/app/code/core/Mage/Core/Model/Translate/Inline.php b/app/code/core/Mage/Core/Model/Translate/Inline.php
index d9a98071b4c..2fd50096906 100644
--- a/app/code/core/Mage/Core/Model/Translate/Inline.php
+++ b/app/code/core/Mage/Core/Model/Translate/Inline.php
@@ -231,6 +231,52 @@ public function processResponseBody(&$body)
return $this;
}
+ /**
+ * Check is a Request contain Json flag
+ *
+ * @deprecated 1.3.2.2
+ * @return bool
+ */
+ public function getIsAjaxRequest()
+ {
+ return (bool) Mage::app()->getRequest()->getQuery('isAjax');
+ }
+
+ /**
+ * Set is a Request contain Json flag
+ *
+ * @param bool $flag
+ * @deprecated 1.3.2.2
+ * @return $this
+ */
+ public function setIsAjaxRequest($flag)
+ {
+ Mage::app()->getRequest()->setQuery('isAjax', (int) (bool) $flag);
+ return $this;
+ }
+
+ /**
+ * Retrieve flag about parsed content is Json
+ *
+ * @return bool
+ */
+ public function getIsJson()
+ {
+ return $this->_isJson;
+ }
+
+ /**
+ * Set flag about parsed content is Json
+ *
+ * @param bool $flag
+ * @return $this
+ */
+ public function setIsJson($flag)
+ {
+ $this->_isJson = (bool) $flag;
+ return $this;
+ }
+
/**
* Add translate js to body
*/
@@ -496,36 +542,6 @@ protected function _translateTags(&$content, $tagsList, $formatCallback, $isNeed
}
}
- /**
- * Find end of tag
- *
- * @param string $body
- * @param string $tagName
- * @param int $from
- * @return false|int return false if end of tag is not found
- */
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private function findEndOfTag($body, $tagName, $from)
- {
- $openTag = '<' . $tagName;
- $closeTag = ($this->getIsJson() ? '<\\/' : '') . $tagName;
- $tagLength = strlen($tagName);
- $length = $tagLength + 1;
- $end = $from + 1;
- while (substr_count($body, $openTag, $from, $length) != substr_count($body, $closeTag, $from, $length)) {
- $end = strpos($body, $closeTag, $end + $tagLength + 1);
- if ($end === false) {
- return false;
- }
- $length = $end - $from + $tagLength + 3;
- }
- if (preg_match('#<\\\\?\/' . $tagName . '\s*?>#i', $body, $tagMatch, 0, $end)) {
- return $end + strlen($tagMatch[0]);
- } else {
- return false;
- }
- }
-
/**
* Prepare other text inline translates
*/
@@ -556,48 +572,32 @@ protected function _otherText()
}
/**
- * Check is a Request contain Json flag
- *
- * @deprecated 1.3.2.2
- * @return bool
- */
- public function getIsAjaxRequest()
- {
- return (bool) Mage::app()->getRequest()->getQuery('isAjax');
- }
-
- /**
- * Set is a Request contain Json flag
- *
- * @param bool $flag
- * @deprecated 1.3.2.2
- * @return $this
- */
- public function setIsAjaxRequest($flag)
- {
- Mage::app()->getRequest()->setQuery('isAjax', (int) (bool) $flag);
- return $this;
- }
-
- /**
- * Retrieve flag about parsed content is Json
- *
- * @return bool
- */
- public function getIsJson()
- {
- return $this->_isJson;
- }
-
- /**
- * Set flag about parsed content is Json
+ * Find end of tag
*
- * @param bool $flag
- * @return $this
+ * @param string $body
+ * @param string $tagName
+ * @param int $from
+ * @return false|int return false if end of tag is not found
*/
- public function setIsJson($flag)
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private function findEndOfTag($body, $tagName, $from)
{
- $this->_isJson = (bool) $flag;
- return $this;
+ $openTag = '<' . $tagName;
+ $closeTag = ($this->getIsJson() ? '<\\/' : '') . $tagName;
+ $tagLength = strlen($tagName);
+ $length = $tagLength + 1;
+ $end = $from + 1;
+ while (substr_count($body, $openTag, $from, $length) != substr_count($body, $closeTag, $from, $length)) {
+ $end = strpos($body, $closeTag, $end + $tagLength + 1);
+ if ($end === false) {
+ return false;
+ }
+ $length = $end - $from + $tagLength + 3;
+ }
+ if (preg_match('#<\\\\?\/' . $tagName . '\s*?>#i', $body, $tagMatch, 0, $end)) {
+ return $end + strlen($tagMatch[0]);
+ } else {
+ return false;
+ }
}
}
diff --git a/app/code/core/Mage/Core/Model/Translate/String.php b/app/code/core/Mage/Core/Model/Translate/String.php
index 65e67ffc4f8..35d18de28b7 100644
--- a/app/code/core/Mage/Core/Model/Translate/String.php
+++ b/app/code/core/Mage/Core/Model/Translate/String.php
@@ -33,11 +33,6 @@
*/
class Mage_Core_Model_Translate_String extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('core/translate_string');
- }
-
/**
* @param string $string
* @return $this
@@ -59,4 +54,8 @@ public function getString()
//return strtolower($this->getData('string'));
return $this->getData('string');
}
+ protected function _construct()
+ {
+ $this->_init('core/translate_string');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Url.php b/app/code/core/Mage/Core/Model/Url.php
index b1d357cfd34..5a3d5465196 100644
--- a/app/code/core/Mage/Core/Model/Url.php
+++ b/app/code/core/Mage/Core/Model/Url.php
@@ -149,14 +149,6 @@ class Mage_Core_Model_Url extends Varien_Object
*/
protected $_useSession;
- /**
- * Initialize object
- */
- protected function _construct()
- {
- $this->setStore(null);
- }
-
/**
* Initialize object data from retrieved url
*
@@ -1019,55 +1011,6 @@ public function getUrl($routePath = null, $routeParams = null)
return $this->escape($url);
}
- /**
- * Return singleton model instance
- *
- * @param string $name
- * @param array $arguments
- * @return Mage_Core_Model_Abstract
- */
- protected function _getSingletonModel($name, $arguments = [])
- {
- return Mage::getSingleton($name, $arguments);
- }
-
- /**
- * Check and add session id to URL
- *
- * @param string $url
- *
- * @return $this
- */
- protected function _prepareSessionUrl($url)
- {
- return $this->_prepareSessionUrlWithParams($url, []);
- }
-
- /**
- * Check and add session id to URL, session is obtained with parameters
- *
- * @param string $url
- *
- * @return $this
- */
- protected function _prepareSessionUrlWithParams($url, array $params)
- {
- if (!$this->getUseSession()) {
- return $this;
- }
-
- /** @var Mage_Core_Model_Session $session */
- $session = Mage::getSingleton('core/session', $params);
-
- $sessionId = $session->getSessionIdForHost($url);
- if (Mage::app()->getUseSessionVar() && !$sessionId) {
- $this->setQueryParam('___SID', $this->getSecure() ? 'S' : 'U'); // Secure/Unsecure
- } elseif ($sessionId) {
- $this->setQueryParam($session->getSessionIdQueryParam(), $sessionId);
- }
- return $this;
- }
-
/**
* Rebuild URL to handle the case when session ID was changed
*
@@ -1245,4 +1188,61 @@ public function getRedirectUrl($url)
return $url;
}
+
+ /**
+ * Initialize object
+ */
+ protected function _construct()
+ {
+ $this->setStore(null);
+ }
+
+ /**
+ * Return singleton model instance
+ *
+ * @param string $name
+ * @param array $arguments
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _getSingletonModel($name, $arguments = [])
+ {
+ return Mage::getSingleton($name, $arguments);
+ }
+
+ /**
+ * Check and add session id to URL
+ *
+ * @param string $url
+ *
+ * @return $this
+ */
+ protected function _prepareSessionUrl($url)
+ {
+ return $this->_prepareSessionUrlWithParams($url, []);
+ }
+
+ /**
+ * Check and add session id to URL, session is obtained with parameters
+ *
+ * @param string $url
+ *
+ * @return $this
+ */
+ protected function _prepareSessionUrlWithParams($url, array $params)
+ {
+ if (!$this->getUseSession()) {
+ return $this;
+ }
+
+ /** @var Mage_Core_Model_Session $session */
+ $session = Mage::getSingleton('core/session', $params);
+
+ $sessionId = $session->getSessionIdForHost($url);
+ if (Mage::app()->getUseSessionVar() && !$sessionId) {
+ $this->setQueryParam('___SID', $this->getSecure() ? 'S' : 'U'); // Secure/Unsecure
+ } elseif ($sessionId) {
+ $this->setQueryParam($session->getSessionIdQueryParam(), $sessionId);
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Url/Rewrite.php b/app/code/core/Mage/Core/Model/Url/Rewrite.php
index 662451d2d77..4569aa53b4d 100644
--- a/app/code/core/Mage/Core/Model/Url/Rewrite.php
+++ b/app/code/core/Mage/Core/Model/Url/Rewrite.php
@@ -59,27 +59,6 @@ class Mage_Core_Model_Url_Rewrite extends Mage_Core_Model_Abstract implements Ma
*/
protected $_cacheTag = false;
- protected function _construct()
- {
- $this->_init('core/url_rewrite');
- }
-
- /**
- * Clean cache for front-end menu
- *
- * @return Mage_Core_Model_Url_Rewrite
- */
- protected function _afterSave()
- {
- if ($this->hasCategoryId()) {
- $this->_cacheTag = [Mage_Catalog_Model_Category::CACHE_TAG, Mage_Core_Model_Store_Group::CACHE_TAG];
- }
-
- parent::_afterSave();
-
- return $this;
- }
-
/**
* Load rewrite information for request
* If $path is array - we must load possible records and choose one matching earlier record in array
@@ -307,6 +286,35 @@ public function rewrite(?Zend_Controller_Request_Http $request = null, ?Zend_Con
return true;
}
+ /**
+ * @return int|null
+ */
+ public function getStoreId()
+ {
+ return $this->_getData('store_id');
+ }
+
+ protected function _construct()
+ {
+ $this->_init('core/url_rewrite');
+ }
+
+ /**
+ * Clean cache for front-end menu
+ *
+ * @return Mage_Core_Model_Url_Rewrite
+ */
+ protected function _afterSave()
+ {
+ if ($this->hasCategoryId()) {
+ $this->_cacheTag = [Mage_Catalog_Model_Category::CACHE_TAG, Mage_Core_Model_Store_Group::CACHE_TAG];
+ }
+
+ parent::_afterSave();
+
+ return $this;
+ }
+
/**
* Prepare and return QUERY_STRING
*
@@ -335,14 +343,6 @@ protected function _getQueryString()
return false;
}
- /**
- * @return int|null
- */
- public function getStoreId()
- {
- return $this->_getData('store_id');
- }
-
/**
* Add location header and disable browser page caching
*
diff --git a/app/code/core/Mage/Core/Model/Url/Validator.php b/app/code/core/Mage/Core/Model/Url/Validator.php
index cd96cf2f720..ebd856c545c 100644
--- a/app/code/core/Mage/Core/Model/Url/Validator.php
+++ b/app/code/core/Mage/Core/Model/Url/Validator.php
@@ -27,15 +27,6 @@ class Mage_Core_Model_Url_Validator extends Zend_Validate_Abstract
*/
public const INVALID_URL = 'invalidUrl';
- /**
- * Object constructor
- */
- public function __construct()
- {
- // set translated message template
- $this->setMessage(Mage::helper('core')->__("Invalid URL '%value%'."), self::INVALID_URL);
- }
-
/**
* Validation failure message template definitions
*
@@ -45,6 +36,15 @@ public function __construct()
self::INVALID_URL => "Invalid URL '%value%'.",
];
+ /**
+ * Object constructor
+ */
+ public function __construct()
+ {
+ // set translated message template
+ $this->setMessage(Mage::helper('core')->__("Invalid URL '%value%'."), self::INVALID_URL);
+ }
+
/**
* Validate value
*
diff --git a/app/code/core/Mage/Core/Model/Variable.php b/app/code/core/Mage/Core/Model/Variable.php
index aafe18fb243..7a0e1e74725 100644
--- a/app/code/core/Mage/Core/Model/Variable.php
+++ b/app/code/core/Mage/Core/Model/Variable.php
@@ -37,15 +37,6 @@ class Mage_Core_Model_Variable extends Mage_Core_Model_Abstract
protected $_storeId = 0;
- /**
- * Internal Constructor
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_init('core/variable');
- }
-
/**
* Setter
*
@@ -147,4 +138,13 @@ public function getVariablesOptionArray($withGroup = false)
}
return $variables;
}
+
+ /**
+ * Internal Constructor
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('core/variable');
+ }
}
diff --git a/app/code/core/Mage/Core/Model/Website.php b/app/code/core/Mage/Core/Model/Website.php
index d52646d70a8..dd7f31139b8 100644
--- a/app/code/core/Mage/Core/Model/Website.php
+++ b/app/code/core/Mage/Core/Model/Website.php
@@ -140,15 +140,6 @@ class Mage_Core_Model_Website extends Mage_Core_Model_Abstract
// phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
private $_isReadOnly = false;
- /**
- * init model
- *
- */
- protected function _construct()
- {
- $this->_init('core/website');
- }
-
/**
* @inheritDoc
*/
@@ -217,25 +208,6 @@ public function getConfig($path)
return $this->_configCache[$path];
}
- /**
- * Load group collection and set internal data
- *
- */
- protected function _loadGroups()
- {
- $this->_groups = [];
- $this->_groupsCount = 0;
- foreach ($this->getGroupCollection() as $group) {
- $groupId = $group->getId();
- $this->_groups[$groupId] = $group;
- $this->_groupIds[$groupId] = $groupId;
- if ($this->getDefaultGroupId() == $groupId) {
- $this->_defaultGroup = $group;
- }
- $this->_groupsCount++;
- }
- }
-
/**
* Set website groups
*
@@ -325,26 +297,6 @@ public function getDefaultGroup()
return $this->_defaultGroup;
}
- /**
- * Load store collection and set internal data
- *
- */
- protected function _loadStores()
- {
- $this->_stores = [];
- $this->_storesCount = 0;
- foreach ($this->getStoreCollection() as $store) {
- $storeId = $store->getId();
- $this->_stores[$storeId] = $store;
- $this->_storeIds[$storeId] = $storeId;
- $this->_storeCodes[$storeId] = $store->getCode();
- if ($this->getDefaultGroup() && $this->getDefaultGroup()->getDefaultStoreId() == $storeId) {
- $this->_defaultStore = $store;
- }
- $this->_storesCount++;
- }
- }
-
/**
* Set website stores
*
@@ -473,29 +425,6 @@ public function getCode()
return $this->_getData('code');
}
- /**
- * @inheritDoc
- */
- protected function _beforeDelete()
- {
- $this->_protectFromNonAdmin();
- return parent::_beforeDelete();
- }
-
- /**
- * rewrite in order to clear configuration cache
- *
- * @return $this
- */
- protected function _afterDelete()
- {
- Mage::app()->clearWebsiteCache($this->getId());
-
- parent::_afterDelete();
- Mage::getConfig()->removeCache();
- return $this;
- }
-
/**
* Retrieve website base currency code
*
@@ -564,4 +493,75 @@ public function isReadOnly($value = null)
}
return $this->_isReadOnly;
}
+
+ /**
+ * init model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('core/website');
+ }
+
+ /**
+ * Load group collection and set internal data
+ *
+ */
+ protected function _loadGroups()
+ {
+ $this->_groups = [];
+ $this->_groupsCount = 0;
+ foreach ($this->getGroupCollection() as $group) {
+ $groupId = $group->getId();
+ $this->_groups[$groupId] = $group;
+ $this->_groupIds[$groupId] = $groupId;
+ if ($this->getDefaultGroupId() == $groupId) {
+ $this->_defaultGroup = $group;
+ }
+ $this->_groupsCount++;
+ }
+ }
+
+ /**
+ * Load store collection and set internal data
+ *
+ */
+ protected function _loadStores()
+ {
+ $this->_stores = [];
+ $this->_storesCount = 0;
+ foreach ($this->getStoreCollection() as $store) {
+ $storeId = $store->getId();
+ $this->_stores[$storeId] = $store;
+ $this->_storeIds[$storeId] = $storeId;
+ $this->_storeCodes[$storeId] = $store->getCode();
+ if ($this->getDefaultGroup() && $this->getDefaultGroup()->getDefaultStoreId() == $storeId) {
+ $this->_defaultStore = $store;
+ }
+ $this->_storesCount++;
+ }
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _beforeDelete()
+ {
+ $this->_protectFromNonAdmin();
+ return parent::_beforeDelete();
+ }
+
+ /**
+ * rewrite in order to clear configuration cache
+ *
+ * @return $this
+ */
+ protected function _afterDelete()
+ {
+ Mage::app()->clearWebsiteCache($this->getId());
+
+ parent::_afterDelete();
+ Mage::getConfig()->removeCache();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Cron/Model/Observer.php b/app/code/core/Mage/Cron/Model/Observer.php
index 66b374e1bd6..d00543d0ae7 100644
--- a/app/code/core/Mage/Cron/Model/Observer.php
+++ b/app/code/core/Mage/Cron/Model/Observer.php
@@ -146,6 +146,48 @@ public function generate()
return $this;
}
+ /**
+ * Clean up the history of tasks
+ *
+ * @return $this
+ */
+ public function cleanup()
+ {
+ // check if history cleanup is needed
+ $lastCleanup = Mage::app()->loadCache(self::CACHE_KEY_LAST_HISTORY_CLEANUP_AT);
+ if ($lastCleanup > time() - Mage::getStoreConfig(self::XML_PATH_HISTORY_CLEANUP_EVERY) * 60) {
+ return $this;
+ }
+
+ $history = Mage::getModel('cron/schedule')->getCollection()
+ ->addFieldToFilter('status', ['in' => [
+ Mage_Cron_Model_Schedule::STATUS_SUCCESS,
+ Mage_Cron_Model_Schedule::STATUS_MISSED,
+ Mage_Cron_Model_Schedule::STATUS_ERROR,
+ ]])
+ ->load();
+
+ $historyLifetimes = [
+ Mage_Cron_Model_Schedule::STATUS_SUCCESS => Mage::getStoreConfig(self::XML_PATH_HISTORY_SUCCESS) * 60,
+ Mage_Cron_Model_Schedule::STATUS_MISSED => Mage::getStoreConfig(self::XML_PATH_HISTORY_FAILURE) * 60,
+ Mage_Cron_Model_Schedule::STATUS_ERROR => Mage::getStoreConfig(self::XML_PATH_HISTORY_FAILURE) * 60,
+ ];
+
+ $now = time();
+ foreach ($history->getIterator() as $record) {
+ if (empty($record->getExecutedAt())
+ || (strtotime($record->getExecutedAt()) < $now - $historyLifetimes[$record->getStatus()])
+ ) {
+ $record->delete();
+ }
+ }
+
+ // save time history cleanup was ran with no expiration
+ Mage::app()->saveCache(time(), self::CACHE_KEY_LAST_HISTORY_CLEANUP_AT, ['crontab'], null);
+
+ return $this;
+ }
+
/**
* Generate jobs for config information
*
@@ -192,48 +234,6 @@ protected function _generateJobs($jobs, $exists)
return $this;
}
- /**
- * Clean up the history of tasks
- *
- * @return $this
- */
- public function cleanup()
- {
- // check if history cleanup is needed
- $lastCleanup = Mage::app()->loadCache(self::CACHE_KEY_LAST_HISTORY_CLEANUP_AT);
- if ($lastCleanup > time() - Mage::getStoreConfig(self::XML_PATH_HISTORY_CLEANUP_EVERY) * 60) {
- return $this;
- }
-
- $history = Mage::getModel('cron/schedule')->getCollection()
- ->addFieldToFilter('status', ['in' => [
- Mage_Cron_Model_Schedule::STATUS_SUCCESS,
- Mage_Cron_Model_Schedule::STATUS_MISSED,
- Mage_Cron_Model_Schedule::STATUS_ERROR,
- ]])
- ->load();
-
- $historyLifetimes = [
- Mage_Cron_Model_Schedule::STATUS_SUCCESS => Mage::getStoreConfig(self::XML_PATH_HISTORY_SUCCESS) * 60,
- Mage_Cron_Model_Schedule::STATUS_MISSED => Mage::getStoreConfig(self::XML_PATH_HISTORY_FAILURE) * 60,
- Mage_Cron_Model_Schedule::STATUS_ERROR => Mage::getStoreConfig(self::XML_PATH_HISTORY_FAILURE) * 60,
- ];
-
- $now = time();
- foreach ($history->getIterator() as $record) {
- if (empty($record->getExecutedAt())
- || (strtotime($record->getExecutedAt()) < $now - $historyLifetimes[$record->getStatus()])
- ) {
- $record->delete();
- }
- }
-
- // save time history cleanup was ran with no expiration
- Mage::app()->saveCache(time(), self::CACHE_KEY_LAST_HISTORY_CLEANUP_AT, ['crontab'], null);
-
- return $this;
- }
-
/**
* Processing cron task which is marked as always
*
diff --git a/app/code/core/Mage/CurrencySymbol/Block/Adminhtml/System/Currencysymbol.php b/app/code/core/Mage/CurrencySymbol/Block/Adminhtml/System/Currencysymbol.php
index 0afc70fbc88..d2942c05c30 100644
--- a/app/code/core/Mage/CurrencySymbol/Block/Adminhtml/System/Currencysymbol.php
+++ b/app/code/core/Mage/CurrencySymbol/Block/Adminhtml/System/Currencysymbol.php
@@ -29,16 +29,6 @@ class Mage_CurrencySymbol_Block_Adminhtml_System_Currencysymbol extends Mage_Adm
*/
protected $_symbolsData = [];
- /**
- * Prepares layout
- *
- * @return Mage_Core_Block_Abstract
- */
- protected function _prepareLayout()
- {
- return parent::_prepareLayout();
- }
-
/**
* Returns page header
*
@@ -120,4 +110,14 @@ public function getInheritText()
{
return Mage::helper('currencysymbol')->__('Use Standard');
}
+
+ /**
+ * Prepares layout
+ *
+ * @return Mage_Core_Block_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/CurrencySymbol/Model/System/Currencysymbol.php b/app/code/core/Mage/CurrencySymbol/Model/System/Currencysymbol.php
index 2169dc0188f..2c8003dc144 100644
--- a/app/code/core/Mage/CurrencySymbol/Model/System/Currencysymbol.php
+++ b/app/code/core/Mage/CurrencySymbol/Model/System/Currencysymbol.php
@@ -24,6 +24,21 @@
*/
class Mage_CurrencySymbol_Model_System_Currencysymbol
{
+ /**
+ * Config path to custom currency symbol value
+ */
+ public const XML_PATH_CUSTOM_CURRENCY_SYMBOL = 'currency/options/customsymbol';
+ public const XML_PATH_ALLOWED_CURRENCIES = 'currency/options/allow';
+
+ /**
+ * Separator used in config in allowed currencies list
+ */
+ public const ALLOWED_CURRENCIES_CONFIG_SEPARATOR = ',';
+
+ /**
+ * Config currency section
+ */
+ public const CONFIG_SECTION = 'currency';
/**
* Custom currency symbol properties
*
@@ -55,22 +70,6 @@ class Mage_CurrencySymbol_Model_System_Currencysymbol
'layout',
];
- /**
- * Config path to custom currency symbol value
- */
- public const XML_PATH_CUSTOM_CURRENCY_SYMBOL = 'currency/options/customsymbol';
- public const XML_PATH_ALLOWED_CURRENCIES = 'currency/options/allow';
-
- /**
- * Separator used in config in allowed currencies list
- */
- public const ALLOWED_CURRENCIES_CONFIG_SEPARATOR = ',';
-
- /**
- * Config currency section
- */
- public const CONFIG_SECTION = 'currency';
-
/**
* Sets store Id
*
diff --git a/app/code/core/Mage/Customer/Block/Address/Book.php b/app/code/core/Mage/Customer/Block/Address/Book.php
index d783ac808a0..1c344f7cf40 100644
--- a/app/code/core/Mage/Customer/Block/Address/Book.php
+++ b/app/code/core/Mage/Customer/Block/Address/Book.php
@@ -25,17 +25,6 @@
*/
class Mage_Customer_Block_Address_Book extends Mage_Core_Block_Template
{
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->getLayout()->getBlock('head')
- ->setTitle(Mage::helper('customer')->__('Address Book'));
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -130,4 +119,14 @@ public function getCustomer()
}
return $customer;
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->getLayout()->getBlock('head')
+ ->setTitle(Mage::helper('customer')->__('Address Book'));
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Customer/Block/Address/Edit.php b/app/code/core/Mage/Customer/Block/Address/Edit.php
index bdc350ebfb3..a23fbab0422 100644
--- a/app/code/core/Mage/Customer/Block/Address/Edit.php
+++ b/app/code/core/Mage/Customer/Block/Address/Edit.php
@@ -31,40 +31,6 @@ class Mage_Customer_Block_Address_Edit extends Mage_Directory_Block_Data
protected $_countryCollection;
protected $_regionCollection;
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
- $this->_address = Mage::getModel('customer/address');
-
- // Init address object
- if ($id = $this->getRequest()->getParam('id')) {
- $this->_address->load($id);
- if ($this->_address->getCustomerId() != Mage::getSingleton('customer/session')->getCustomerId()) {
- $this->_address->setData([]);
- }
- }
-
- if (!$this->_address->getId()) {
- $this->_address->setPrefix($this->getCustomer()->getPrefix())
- ->setFirstname($this->getCustomer()->getFirstname())
- ->setMiddlename($this->getCustomer()->getMiddlename())
- ->setLastname($this->getCustomer()->getLastname())
- ->setSuffix($this->getCustomer()->getSuffix());
- }
-
- if ($headBlock = $this->getLayout()->getBlock('head')) {
- $headBlock->setTitle($this->getTitle());
- }
-
- if ($postedData = Mage::getSingleton('customer/session')->getAddressFormData(true)) {
- $this->_address->addData($postedData);
- }
- return $this;
- }
-
/**
* Generate name block html
*
@@ -213,4 +179,38 @@ public function getBackButtonUrl()
return $this->getUrl('customer/account/');
}
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+ $this->_address = Mage::getModel('customer/address');
+
+ // Init address object
+ if ($id = $this->getRequest()->getParam('id')) {
+ $this->_address->load($id);
+ if ($this->_address->getCustomerId() != Mage::getSingleton('customer/session')->getCustomerId()) {
+ $this->_address->setData([]);
+ }
+ }
+
+ if (!$this->_address->getId()) {
+ $this->_address->setPrefix($this->getCustomer()->getPrefix())
+ ->setFirstname($this->getCustomer()->getFirstname())
+ ->setMiddlename($this->getCustomer()->getMiddlename())
+ ->setLastname($this->getCustomer()->getLastname())
+ ->setSuffix($this->getCustomer()->getSuffix());
+ }
+
+ if ($headBlock = $this->getLayout()->getBlock('head')) {
+ $headBlock->setTitle($this->getTitle());
+ }
+
+ if ($postedData = Mage::getSingleton('customer/session')->getAddressFormData(true)) {
+ $this->_address->addData($postedData);
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Customer/Block/Form/Register.php b/app/code/core/Mage/Customer/Block/Form/Register.php
index 79adfb2243f..2d88f014764 100644
--- a/app/code/core/Mage/Customer/Block/Form/Register.php
+++ b/app/code/core/Mage/Customer/Block/Form/Register.php
@@ -34,15 +34,6 @@ class Mage_Customer_Block_Form_Register extends Mage_Directory_Block_Data
*/
protected $_address;
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->getLayout()->getBlock('head')->setTitle(Mage::helper('customer')->__('Create New Customer Account'));
- return parent::_prepareLayout();
- }
-
/**
* Retrieve form posting url
*
@@ -180,4 +171,13 @@ public function getMinPasswordLength()
{
return Mage::getModel('customer/customer')->getMinPasswordLength();
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->getLayout()->getBlock('head')->setTitle(Mage::helper('customer')->__('Create New Customer Account'));
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Customer/Block/Widget/Name.php b/app/code/core/Mage/Customer/Block/Widget/Name.php
index 2f6d70291ad..2b3fcd5734c 100644
--- a/app/code/core/Mage/Customer/Block/Widget/Name.php
+++ b/app/code/core/Mage/Customer/Block/Widget/Name.php
@@ -33,17 +33,6 @@ public function _construct()
$this->setTemplate('customer/widget/name.phtml');
}
- /**
- * Can show config value
- *
- * @param string $key
- * @return bool
- */
- protected function _showConfig($key)
- {
- return (bool) $this->getConfig($key);
- }
-
/**
* Can show prefix
*
@@ -164,6 +153,30 @@ public function getContainerClassName()
return $class . ($this->showSuffix() ? '-suffix' : '');
}
+ /**
+ * Retrieve store attribute label
+ *
+ * @param string $attributeCode
+ * @return string
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ public function getStoreLabel($attributeCode)
+ {
+ $attribute = $this->_getAttribute($attributeCode);
+ return $attribute ? $this->__($attribute->getStoreLabel()) : '';
+ }
+
+ /**
+ * Can show config value
+ *
+ * @param string $key
+ * @return bool
+ */
+ protected function _showConfig($key)
+ {
+ return (bool) $this->getConfig($key);
+ }
+
/**
* Retrieve customer or customer address attribute instance
*
@@ -187,17 +200,4 @@ protected function _getAttribute($attributeCode)
return $attribute;
}
-
- /**
- * Retrieve store attribute label
- *
- * @param string $attributeCode
- * @return string
- * @throws Mage_Core_Model_Store_Exception
- */
- public function getStoreLabel($attributeCode)
- {
- $attribute = $this->_getAttribute($attributeCode);
- return $attribute ? $this->__($attribute->getStoreLabel()) : '';
- }
}
diff --git a/app/code/core/Mage/Customer/Helper/Data.php b/app/code/core/Mage/Customer/Helper/Data.php
index 1a4a741f5f2..97e438d2f0e 100644
--- a/app/code/core/Mage/Customer/Helper/Data.php
+++ b/app/code/core/Mage/Customer/Helper/Data.php
@@ -403,27 +403,6 @@ public function getNameSuffixOptions($store = null)
);
}
- /**
- * Unserialize and clear name prefix or suffix options
- *
- * @param string $options
- * @return array|bool
- */
- protected function _prepareNamePrefixSuffixOptions($options)
- {
- $options = trim($options);
- if (empty($options)) {
- return false;
- }
- $result = [];
- $options = explode(';', $options);
- foreach ($options as $value) {
- $value = $this->escapeHtml(trim($value));
- $result[$value] = $value;
- }
- return $result;
- }
-
/**
* Generate unique token for reset password confirmation link
*
@@ -725,6 +704,27 @@ public function getPasswordTimestamp($customerId)
return Mage::getResourceModel('customer/customer')->getPasswordTimestamp($customerId);
}
+ /**
+ * Unserialize and clear name prefix or suffix options
+ *
+ * @param string $options
+ * @return array|bool
+ */
+ protected function _prepareNamePrefixSuffixOptions($options)
+ {
+ $options = trim($options);
+ if (empty($options)) {
+ return false;
+ }
+ $result = [];
+ $options = explode(';', $options);
+ foreach ($options as $value) {
+ $value = $this->escapeHtml(trim($value));
+ $result[$value] = $value;
+ }
+ return $result;
+ }
+
/**
* Create SOAP client based on VAT validation service WSDL
*
diff --git a/app/code/core/Mage/Customer/Model/Address.php b/app/code/core/Mage/Customer/Model/Address.php
index 189489d211c..b343ce4c105 100644
--- a/app/code/core/Mage/Customer/Model/Address.php
+++ b/app/code/core/Mage/Customer/Model/Address.php
@@ -32,9 +32,9 @@ class Mage_Customer_Model_Address extends Mage_Customer_Model_Address_Abstract
{
protected $_customer;
- protected function _construct()
+ public function __clone()
{
- $this->_init('customer/address');
+ $this->setId(null);
}
/**
@@ -120,11 +120,6 @@ public function getAttributes()
return $attributes;
}
- public function __clone()
- {
- $this->setId(null);
- }
-
/**
* Return Entity Type instance
*
@@ -171,4 +166,9 @@ public function setRegionId($regionId)
$this->setData('region_id', (int) $regionId);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('customer/address');
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Address/Abstract.php b/app/code/core/Mage/Customer/Model/Address/Abstract.php
index 9dfe5085969..1a0b252571f 100644
--- a/app/code/core/Mage/Customer/Model/Address/Abstract.php
+++ b/app/code/core/Mage/Customer/Model/Address/Abstract.php
@@ -410,16 +410,6 @@ public function getConfig()
return Mage::getSingleton('customer/address_config');
}
- /**
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
- $this->getRegion();
- return $this;
- }
-
/**
* Validate address attribute values
*
@@ -445,6 +435,28 @@ public function validate()
return $errors;
}
+ /**
+ * Add error
+ *
+ * @param string $error
+ * @return $this
+ */
+ public function addError($error)
+ {
+ $this->_errors[] = $error;
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ $this->getRegion();
+ return $this;
+ }
+
/**
* Perform basic validation
*/
@@ -489,18 +501,6 @@ protected function _basicCheck()
}
}
- /**
- * Add error
- *
- * @param string $error
- * @return $this
- */
- public function addError($error)
- {
- $this->_errors[] = $error;
- return $this;
- }
-
/**
* Retrieve errors
*
diff --git a/app/code/core/Mage/Customer/Model/Address/Config.php b/app/code/core/Mage/Customer/Model/Address/Config.php
index 5ece70a4c4a..f38f7f50a0e 100644
--- a/app/code/core/Mage/Customer/Model/Address/Config.php
+++ b/app/code/core/Mage/Customer/Model/Address/Config.php
@@ -53,6 +53,15 @@ class Mage_Customer_Model_Address_Config extends Mage_Core_Model_Config_Base
*/
private $_defaultType = [];
+ /**
+ * Define node
+ *
+ */
+ public function __construct()
+ {
+ parent::__construct(Mage::getConfig()->getNode()->global->customer->address);
+ }
+
/**
* @param null|string|bool|int|Mage_Core_Model_Store $store
* @return $this
@@ -77,15 +86,6 @@ public function getStore()
return $this->_store;
}
- /**
- * Define node
- *
- */
- public function __construct()
- {
- parent::__construct(Mage::getConfig()->getNode()->global->customer->address);
- }
-
/**
* Retrieve address formats
*
@@ -124,6 +124,22 @@ public function getFormats()
return $this->_types[$storeId];
}
+ /**
+ * Retrieve address format by code
+ *
+ * @param string $typeCode
+ * @return Varien_Object
+ */
+ public function getFormatByCode($typeCode)
+ {
+ foreach ($this->getFormats() as $type) {
+ if ($type->getCode() == $typeCode) {
+ return $type;
+ }
+ }
+ return $this->_getDefaultFormat();
+ }
+
/**
* Retrieve default address format
*
@@ -147,20 +163,4 @@ protected function _getDefaultFormat()
}
return $this->_defaultType[$storeId];
}
-
- /**
- * Retrieve address format by code
- *
- * @param string $typeCode
- * @return Varien_Object
- */
- public function getFormatByCode($typeCode)
- {
- foreach ($this->getFormats() as $type) {
- if ($type->getCode() == $typeCode) {
- return $type;
- }
- }
- return $this->_getDefaultFormat();
- }
}
diff --git a/app/code/core/Mage/Customer/Model/Api/Resource.php b/app/code/core/Mage/Customer/Model/Api/Resource.php
index 45f6d00fe94..f16afcabfa5 100644
--- a/app/code/core/Mage/Customer/Model/Api/Resource.php
+++ b/app/code/core/Mage/Customer/Model/Api/Resource.php
@@ -36,25 +36,6 @@ class Mage_Customer_Model_Api_Resource extends Mage_Api_Model_Resource_Abstract
*/
protected $_ignoredAttributeTypes = [];
- /**
- * Check is attribute allowed
- *
- * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute
- * @return bool
- */
- protected function _isAllowedAttribute($attribute, ?array $filter = null)
- {
- if (!is_null($filter)
- && !(in_array($attribute->getAttributeCode(), $filter)
- || in_array($attribute->getAttributeId(), $filter))
- ) {
- return false;
- }
-
- return !in_array($attribute->getFrontendInput(), $this->_ignoredAttributeTypes)
- && !in_array($attribute->getAttributeCode(), $this->_ignoredAttributeCodes);
- }
-
/**
* Return list of allowed attributes
*
@@ -75,4 +56,23 @@ public function getAllowedAttributes($entity, ?array $filter = null)
return $result;
}
+
+ /**
+ * Check is attribute allowed
+ *
+ * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute
+ * @return bool
+ */
+ protected function _isAllowedAttribute($attribute, ?array $filter = null)
+ {
+ if (!is_null($filter)
+ && !(in_array($attribute->getAttributeCode(), $filter)
+ || in_array($attribute->getAttributeId(), $filter))
+ ) {
+ return false;
+ }
+
+ return !in_array($attribute->getFrontendInput(), $this->_ignoredAttributeTypes)
+ && !in_array($attribute->getAttributeCode(), $this->_ignoredAttributeCodes);
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Convert/Adapter/Customer.php b/app/code/core/Mage/Customer/Model/Convert/Adapter/Customer.php
index de0c015fa6a..4e1e0d1092b 100644
--- a/app/code/core/Mage/Customer/Model/Convert/Adapter/Customer.php
+++ b/app/code/core/Mage/Customer/Model/Convert/Adapter/Customer.php
@@ -66,6 +66,56 @@ class Mage_Customer_Model_Convert_Adapter_Customer extends Mage_Eav_Model_Conver
protected $_customerId = '';
+ public function __construct()
+ {
+ $this->setVar('entity_type', 'customer/customer');
+
+ if (!Mage::registry('Object_Cache_Customer')) {
+ $this->setCustomer(Mage::getModel('customer/customer'));
+ }
+ //$this->setAddress(Mage::getModel('catalog/'))
+
+ /**
+ * @var string $code
+ * @var Mage_Core_Model_Config_Element $node
+ */
+ foreach (Mage::getConfig()->getFieldset('customer_dataflow', 'admin') as $code => $node) {
+ if ($node->is('ignore')) {
+ $this->_ignoreFields[] = $code;
+ }
+ if ($node->is('billing')) {
+ $this->_billingFields[] = 'billing_' . $code;
+ }
+ if ($node->is('shipping')) {
+ $this->_shippingFields[] = 'shipping_' . $code;
+ }
+
+ if ($node->is('billing') && $node->is('shipping')) {
+ $this->_addressFields[] = $code;
+ }
+
+ if ($node->is('mapped') || $node->is('billing_mapped')) {
+ $this->_billingMappedFields['billing_' . $code] = $code;
+ }
+ if ($node->is('mapped') || $node->is('shipping_mapped')) {
+ $this->_shippingMappedFields['shipping_' . $code] = $code;
+ }
+ if ($node->is('street')) {
+ $this->_billingStreetFields[] = 'billing_' . $code;
+ $this->_shippingStreetFields[] = 'shipping_' . $code;
+ }
+ if ($node->is('required')) {
+ $this->_requiredFields[] = $code;
+ }
+ if ($node->is('billing_required')) {
+ $this->_billingRequiredFields[] = 'billing_' . $code;
+ }
+ if ($node->is('shipping_required')) {
+ $this->_shippingRequiredFields[] = 'shipping_' . $code;
+ }
+ }
+ }
+
/**
* Retrieve customer model cache
*
@@ -213,56 +263,6 @@ public function getCustomerGoups()
return $this->getCustomerGroups();
}
- public function __construct()
- {
- $this->setVar('entity_type', 'customer/customer');
-
- if (!Mage::registry('Object_Cache_Customer')) {
- $this->setCustomer(Mage::getModel('customer/customer'));
- }
- //$this->setAddress(Mage::getModel('catalog/'))
-
- /**
- * @var string $code
- * @var Mage_Core_Model_Config_Element $node
- */
- foreach (Mage::getConfig()->getFieldset('customer_dataflow', 'admin') as $code => $node) {
- if ($node->is('ignore')) {
- $this->_ignoreFields[] = $code;
- }
- if ($node->is('billing')) {
- $this->_billingFields[] = 'billing_' . $code;
- }
- if ($node->is('shipping')) {
- $this->_shippingFields[] = 'shipping_' . $code;
- }
-
- if ($node->is('billing') && $node->is('shipping')) {
- $this->_addressFields[] = $code;
- }
-
- if ($node->is('mapped') || $node->is('billing_mapped')) {
- $this->_billingMappedFields['billing_' . $code] = $code;
- }
- if ($node->is('mapped') || $node->is('shipping_mapped')) {
- $this->_shippingMappedFields['shipping_' . $code] = $code;
- }
- if ($node->is('street')) {
- $this->_billingStreetFields[] = 'billing_' . $code;
- $this->_shippingStreetFields[] = 'shipping_' . $code;
- }
- if ($node->is('required')) {
- $this->_requiredFields[] = $code;
- }
- if ($node->is('billing_required')) {
- $this->_billingRequiredFields[] = 'billing_' . $code;
- }
- if ($node->is('shipping_required')) {
- $this->_shippingRequiredFields[] = 'shipping_' . $code;
- }
- }
- }
-
/**
* @return Mage_Eav_Model_Convert_Adapter_Entity
* @throws Mage_Core_Model_Store_Exception
diff --git a/app/code/core/Mage/Customer/Model/Convert/Parser/Customer.php b/app/code/core/Mage/Customer/Model/Convert/Parser/Customer.php
index 143e945ab8d..c91cd7702f2 100644
--- a/app/code/core/Mage/Customer/Model/Convert/Parser/Customer.php
+++ b/app/code/core/Mage/Customer/Model/Convert/Parser/Customer.php
@@ -420,27 +420,6 @@ public function getExternalAttributes()
return $attributes;
}
- /**
- * Gets group code by customer's groupId
- *
- * @param Mage_Customer_Model_Customer $customer
- * @return string|null
- */
- protected function _getCustomerGroupCode($customer)
- {
- if (is_null($this->_customerGroups)) {
- $groups = Mage::getResourceModel('customer/group_collection')
- ->load();
-
- /** @var Mage_Customer_Model_Group $group */
- foreach ($groups as $group) {
- $this->_customerGroups[$group->getId()] = $group->getData('customer_group_code');
- }
- }
-
- return $this->_customerGroups[$customer->getGroupId()] ?? null;
- }
-
/**
* @deprecated not used anymore
*/
@@ -633,4 +612,25 @@ public function parse()
$this->setData($this->_collections);
return $this;
}
+
+ /**
+ * Gets group code by customer's groupId
+ *
+ * @param Mage_Customer_Model_Customer $customer
+ * @return string|null
+ */
+ protected function _getCustomerGroupCode($customer)
+ {
+ if (is_null($this->_customerGroups)) {
+ $groups = Mage::getResourceModel('customer/group_collection')
+ ->load();
+
+ /** @var Mage_Customer_Model_Group $group */
+ foreach ($groups as $group) {
+ $this->_customerGroups[$group->getId()] = $group->getData('customer_group_code');
+ }
+ }
+
+ return $this->_customerGroups[$customer->getGroupId()] ?? null;
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Customer.php b/app/code/core/Mage/Customer/Model/Customer.php
index 4dcf9b2c926..0d39c5ad21f 100644
--- a/app/code/core/Mage/Customer/Model/Customer.php
+++ b/app/code/core/Mage/Customer/Model/Customer.php
@@ -233,6 +233,20 @@ class Mage_Customer_Model_Customer extends Mage_Core_Model_Abstract
// phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
private static $_isConfirmationRequired;
+ /**
+ * Clone current object
+ */
+ public function __clone()
+ {
+ $newAddressCollection = $this->getPrimaryAddresses();
+ $newAddressCollection = array_merge($newAddressCollection, $this->getAdditionalAddresses());
+ $this->setId(null);
+ $this->cleanAllAddresses();
+ foreach ($newAddressCollection as $address) {
+ $this->addAddress(clone $address);
+ }
+ }
+
/**
* Initialize customer model
*/
@@ -297,25 +311,6 @@ public function loadByEmail($customerEmail)
return $this;
}
- /**
- * Processing object before save data
- *
- * @return $this
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
-
- $storeId = $this->getStoreId();
- if ($storeId === null) {
- $this->setStoreId(Mage::app()->getStore()->getId());
- }
-
- $this->getGroupId();
- return $this;
- }
-
/**
* Change customer password
*
@@ -513,17 +508,6 @@ public function hashPassword($password, $salt = null)
return $helper->getHash(trim($password), (bool) $salt ? $salt : Mage_Admin_Model_User::HASH_SALT_LENGTH);
}
- /**
- * Get helper instance
- *
- * @param string $helperName
- * @return Mage_Core_Helper_Abstract
- */
- protected function _getHelper($helperName)
- {
- return Mage::helper($helperName);
- }
-
/**
* Retrieve random password
*
@@ -829,34 +813,6 @@ public function sendChangedPasswordOrEmail()
return $this;
}
- /**
- * Send corresponding email template
- *
- * @param string $template configuration path of email template
- * @param string $sender configuration path of email identity
- * @param array $templateParams
- * @param int|null $storeId
- * @param string|null $customerEmail
- * @return $this
- */
- protected function _sendEmailTemplate($template, $sender, $templateParams = [], $storeId = null, $customerEmail = null)
- {
- $customerEmail = ($customerEmail) ? $customerEmail : $this->getEmail();
- /** @var Mage_Core_Model_Email_Template_Mailer $mailer */
- $mailer = Mage::getModel('core/email_template_mailer');
- $emailInfo = Mage::getModel('core/email_info');
- $emailInfo->addTo($customerEmail, $this->getName());
- $mailer->addEmailInfo($emailInfo);
-
- // Set all required params and send emails
- $mailer->setSender(Mage::getStoreConfig($sender, $storeId));
- $mailer->setStoreId($storeId);
- $mailer->setTemplateId(Mage::getStoreConfig($template, $storeId));
- $mailer->setTemplateParams($templateParams);
- $mailer->send();
- return $this;
- }
-
/**
* Send email with reset password confirmation link
*
@@ -1425,15 +1381,6 @@ public function validateAddress(array $data, $type = 'billing')
return false;
}
- /**
- * Prepare customer for delete
- */
- protected function _beforeDelete()
- {
- $this->_protectFromNonAdmin();
- return parent::_beforeDelete();
- }
-
/**
* Get customer created at date timestamp
*
@@ -1517,20 +1464,6 @@ public function canSkipConfirmation()
&& strtolower($this->getSkipConfirmationIfEmail()) === strtolower($this->getEmail());
}
- /**
- * Clone current object
- */
- public function __clone()
- {
- $newAddressCollection = $this->getPrimaryAddresses();
- $newAddressCollection = array_merge($newAddressCollection, $this->getAdditionalAddresses());
- $this->setId(null);
- $this->cleanAllAddresses();
- foreach ($newAddressCollection as $address) {
- $this->addAddress(clone $address);
- }
- }
-
/**
* Return Entity Type instance
*
@@ -1558,23 +1491,6 @@ public function getEntityTypeId()
return $entityTypeId;
}
- /**
- * Get either first store ID from a set website or the provided as default
- *
- * @param int|string|null $defaultStoreId
- * @return int
- * @throws Mage_Core_Exception
- */
- protected function _getWebsiteStoreId($defaultStoreId = null)
- {
- if ($this->getWebsiteId() != 0 && empty($defaultStoreId)) {
- $storeIds = Mage::app()->getWebsite($this->getWebsiteId())->getStoreIds();
- reset($storeIds);
- $defaultStoreId = current($storeIds);
- }
- return $defaultStoreId;
- }
-
/**
* Change reset password link token
*
@@ -1670,4 +1586,88 @@ public function getMinPasswordLength()
$absoluteMinLength = Mage_Core_Model_App::ABSOLUTE_MIN_PASSWORD_LENGTH;
return ($minLength < $absoluteMinLength) ? $absoluteMinLength : $minLength;
}
+
+ /**
+ * Processing object before save data
+ *
+ * @return $this
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+
+ $storeId = $this->getStoreId();
+ if ($storeId === null) {
+ $this->setStoreId(Mage::app()->getStore()->getId());
+ }
+
+ $this->getGroupId();
+ return $this;
+ }
+
+ /**
+ * Get helper instance
+ *
+ * @param string $helperName
+ * @return Mage_Core_Helper_Abstract
+ */
+ protected function _getHelper($helperName)
+ {
+ return Mage::helper($helperName);
+ }
+
+ /**
+ * Send corresponding email template
+ *
+ * @param string $template configuration path of email template
+ * @param string $sender configuration path of email identity
+ * @param array $templateParams
+ * @param int|null $storeId
+ * @param string|null $customerEmail
+ * @return $this
+ */
+ protected function _sendEmailTemplate($template, $sender, $templateParams = [], $storeId = null, $customerEmail = null)
+ {
+ $customerEmail = ($customerEmail) ? $customerEmail : $this->getEmail();
+ /** @var Mage_Core_Model_Email_Template_Mailer $mailer */
+ $mailer = Mage::getModel('core/email_template_mailer');
+ $emailInfo = Mage::getModel('core/email_info');
+ $emailInfo->addTo($customerEmail, $this->getName());
+ $mailer->addEmailInfo($emailInfo);
+
+ // Set all required params and send emails
+ $mailer->setSender(Mage::getStoreConfig($sender, $storeId));
+ $mailer->setStoreId($storeId);
+ $mailer->setTemplateId(Mage::getStoreConfig($template, $storeId));
+ $mailer->setTemplateParams($templateParams);
+ $mailer->send();
+ return $this;
+ }
+
+ /**
+ * Prepare customer for delete
+ */
+ protected function _beforeDelete()
+ {
+ $this->_protectFromNonAdmin();
+ return parent::_beforeDelete();
+ }
+
+ /**
+ * Get either first store ID from a set website or the provided as default
+ *
+ * @param int|string|null $defaultStoreId
+ * @return int
+ * @throws Mage_Core_Exception
+ */
+ protected function _getWebsiteStoreId($defaultStoreId = null)
+ {
+ if ($this->getWebsiteId() != 0 && empty($defaultStoreId)) {
+ $storeIds = Mage::app()->getWebsite($this->getWebsiteId())->getStoreIds();
+ reset($storeIds);
+ $defaultStoreId = current($storeIds);
+ }
+ return $defaultStoreId;
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Customer/Api.php b/app/code/core/Mage/Customer/Model/Customer/Api.php
index 8d706fea7a7..24b941bc886 100644
--- a/app/code/core/Mage/Customer/Model/Customer/Api.php
+++ b/app/code/core/Mage/Customer/Model/Customer/Api.php
@@ -25,23 +25,6 @@ class Mage_Customer_Model_Customer_Api extends Mage_Customer_Model_Api_Resource
protected $_mapAttributes = [
'customer_id' => 'entity_id',
];
- /**
- * Prepare data to insert/update.
- * Creating array for stdClass Object
- *
- * @param array $data
- * @return array
- */
- protected function _prepareData($data)
- {
- foreach ($this->_mapAttributes as $attributeAlias => $attributeCode) {
- if (isset($data[$attributeAlias])) {
- $data[$attributeCode] = $data[$attributeAlias];
- unset($data[$attributeAlias]);
- }
- }
- return $data;
- }
/**
* Create new customer
@@ -182,4 +165,21 @@ public function delete($customerId)
return true;
}
+ /**
+ * Prepare data to insert/update.
+ * Creating array for stdClass Object
+ *
+ * @param array $data
+ * @return array
+ */
+ protected function _prepareData($data)
+ {
+ foreach ($this->_mapAttributes as $attributeAlias => $attributeCode) {
+ if (isset($data[$attributeAlias])) {
+ $data[$attributeCode] = $data[$attributeAlias];
+ unset($data[$attributeAlias]);
+ }
+ }
+ return $data;
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Flowpassword.php b/app/code/core/Mage/Customer/Model/Flowpassword.php
index 394489bf16f..f7886e574cd 100644
--- a/app/code/core/Mage/Customer/Model/Flowpassword.php
+++ b/app/code/core/Mage/Customer/Model/Flowpassword.php
@@ -27,33 +27,6 @@
*/
class Mage_Customer_Model_Flowpassword extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('customer/flowpassword');
- }
-
- /**
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- $this->_prepareData();
- return parent::_beforeSave();
- }
-
- /**
- * Prepare customer flow password data
- *
- * @return $this
- */
- protected function _prepareData()
- {
- $validatorData = Mage::getSingleton('customer/session')->getValidatorData();
- $this->setIp($validatorData[Mage_Customer_Model_Session::VALIDATOR_REMOTE_ADDR_KEY])
- ->setRequestedDate(Mage::getModel('core/date')->date());
- return $this;
- }
-
/**
* Check forgot password requests to times per 24 hours from 1 e-mail
*
@@ -112,4 +85,30 @@ public function checkCustomerForgotPasswordFlowIp()
}
return true;
}
+ protected function _construct()
+ {
+ $this->_init('customer/flowpassword');
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ $this->_prepareData();
+ return parent::_beforeSave();
+ }
+
+ /**
+ * Prepare customer flow password data
+ *
+ * @return $this
+ */
+ protected function _prepareData()
+ {
+ $validatorData = Mage::getSingleton('customer/session')->getValidatorData();
+ $this->setIp($validatorData[Mage_Customer_Model_Session::VALIDATOR_REMOTE_ADDR_KEY])
+ ->setRequestedDate(Mage::getModel('core/date')->date());
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Group.php b/app/code/core/Mage/Customer/Model/Group.php
index f7d4ec3f522..82fc3f3d296 100644
--- a/app/code/core/Mage/Customer/Model/Group.php
+++ b/app/code/core/Mage/Customer/Model/Group.php
@@ -61,11 +61,6 @@ class Mage_Customer_Model_Group extends Mage_Core_Model_Abstract
protected static $_taxClassIds = [];
- protected function _construct()
- {
- $this->_init('customer/group');
- }
-
/**
* Alias for setCustomerGroupCode
*
@@ -132,6 +127,11 @@ public function afterCommitCallback()
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('customer/group');
+ }
+
/**
* @inheritDoc
*/
diff --git a/app/code/core/Mage/Customer/Model/Observer.php b/app/code/core/Mage/Customer/Model/Observer.php
index ac863e1950b..b0d7d04261a 100644
--- a/app/code/core/Mage/Customer/Model/Observer.php
+++ b/app/code/core/Mage/Customer/Model/Observer.php
@@ -32,53 +32,6 @@ class Mage_Customer_Model_Observer
*/
public const VIV_CURRENTLY_SAVED_ADDRESS = 'currently_saved_address';
- /**
- * Check whether specified billing address is default for its customer
- *
- * @param Mage_Customer_Model_Address $address
- * @return bool
- */
- protected function _isDefaultBilling($address)
- {
- return ($address->getId() && $address->getId() == $address->getCustomer()->getDefaultBilling())
- || $address->getIsPrimaryBilling() || $address->getIsDefaultBilling();
- }
-
- /**
- * Check whether specified shipping address is default for its customer
- *
- * @param Mage_Customer_Model_Address $address
- * @return bool
- */
- protected function _isDefaultShipping($address)
- {
- return ($address->getId() && $address->getId() == $address->getCustomer()->getDefaultShipping())
- || $address->getIsPrimaryShipping() || $address->getIsDefaultShipping();
- }
-
- /**
- * Check whether specified address should be processed in after_save event handler
- *
- * @param Mage_Customer_Model_Address $address
- * @return bool
- */
- protected function _canProcessAddress($address)
- {
- if ($address->getForceProcess()) {
- return true;
- }
-
- if (Mage::registry(self::VIV_CURRENTLY_SAVED_ADDRESS) != $address->getId()) {
- return false;
- }
-
- $configAddressType = Mage::helper('customer/address')->getTaxCalculationAddressType();
- if ($configAddressType == Mage_Customer_Model_Address_Abstract::TYPE_SHIPPING) {
- return $this->_isDefaultShipping($address);
- }
- return $this->_isDefaultBilling($address);
- }
-
/**
* Before load layout event handler
*
@@ -255,4 +208,51 @@ public function actionUpgradeCustomerPassword($observer)
$model->changePassword($password, false);
}
}
+
+ /**
+ * Check whether specified billing address is default for its customer
+ *
+ * @param Mage_Customer_Model_Address $address
+ * @return bool
+ */
+ protected function _isDefaultBilling($address)
+ {
+ return ($address->getId() && $address->getId() == $address->getCustomer()->getDefaultBilling())
+ || $address->getIsPrimaryBilling() || $address->getIsDefaultBilling();
+ }
+
+ /**
+ * Check whether specified shipping address is default for its customer
+ *
+ * @param Mage_Customer_Model_Address $address
+ * @return bool
+ */
+ protected function _isDefaultShipping($address)
+ {
+ return ($address->getId() && $address->getId() == $address->getCustomer()->getDefaultShipping())
+ || $address->getIsPrimaryShipping() || $address->getIsDefaultShipping();
+ }
+
+ /**
+ * Check whether specified address should be processed in after_save event handler
+ *
+ * @param Mage_Customer_Model_Address $address
+ * @return bool
+ */
+ protected function _canProcessAddress($address)
+ {
+ if ($address->getForceProcess()) {
+ return true;
+ }
+
+ if (Mage::registry(self::VIV_CURRENTLY_SAVED_ADDRESS) != $address->getId()) {
+ return false;
+ }
+
+ $configAddressType = Mage::helper('customer/address')->getTaxCalculationAddressType();
+ if ($configAddressType == Mage_Customer_Model_Address_Abstract::TYPE_SHIPPING) {
+ return $this->_isDefaultShipping($address);
+ }
+ return $this->_isDefaultBilling($address);
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Resource/Address.php b/app/code/core/Mage/Customer/Model/Resource/Address.php
index ab28aee7274..70170f62ecf 100644
--- a/app/code/core/Mage/Customer/Model/Resource/Address.php
+++ b/app/code/core/Mage/Customer/Model/Resource/Address.php
@@ -22,6 +22,30 @@
*/
class Mage_Customer_Model_Resource_Address extends Mage_Eav_Model_Entity_Abstract
{
+ /**
+ * Return customer id
+ * @deprecated
+ *
+ * @param Mage_Customer_Model_Address $object
+ * @return int
+ */
+ public function getCustomerId($object)
+ {
+ return $object->getData('customer_id') ? $object->getData('customer_id') : $object->getParentId();
+ }
+
+ /**
+ * Set customer id
+ * @deprecated
+ *
+ * @param Mage_Customer_Model_Address $object
+ * @param int $id
+ * @return $this
+ */
+ public function setCustomerId($object, $id)
+ {
+ return $this;
+ }
protected function _construct()
{
$resource = Mage::getSingleton('core/resource');
@@ -55,29 +79,4 @@ protected function _afterSave(Varien_Object $address)
}
return $this;
}
-
- /**
- * Return customer id
- * @deprecated
- *
- * @param Mage_Customer_Model_Address $object
- * @return int
- */
- public function getCustomerId($object)
- {
- return $object->getData('customer_id') ? $object->getData('customer_id') : $object->getParentId();
- }
-
- /**
- * Set customer id
- * @deprecated
- *
- * @param Mage_Customer_Model_Address $object
- * @param int $id
- * @return $this
- */
- public function setCustomerId($object, $id)
- {
- return $this;
- }
}
diff --git a/app/code/core/Mage/Customer/Model/Resource/Address/Collection.php b/app/code/core/Mage/Customer/Model/Resource/Address/Collection.php
index 37f97b6b09c..86a0e779751 100644
--- a/app/code/core/Mage/Customer/Model/Resource/Address/Collection.php
+++ b/app/code/core/Mage/Customer/Model/Resource/Address/Collection.php
@@ -25,11 +25,6 @@
*/
class Mage_Customer_Model_Resource_Address_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('customer/address');
- }
-
/**
* Set customer filter
*
@@ -45,4 +40,8 @@ public function setCustomerFilter($customer)
}
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('customer/address');
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Resource/Customer.php b/app/code/core/Mage/Customer/Model/Resource/Customer.php
index 05afecc9299..2bcfa99a60f 100644
--- a/app/code/core/Mage/Customer/Model/Resource/Customer.php
+++ b/app/code/core/Mage/Customer/Model/Resource/Customer.php
@@ -28,159 +28,6 @@ public function __construct()
$this->setConnection('customer_read', 'customer_write');
}
- /**
- * Retrieve customer entity default attributes
- *
- * @return array
- */
- protected function _getDefaultAttributes()
- {
- return [
- 'entity_type_id',
- 'attribute_set_id',
- 'created_at',
- 'updated_at',
- 'increment_id',
- 'store_id',
- 'website_id',
- ];
- }
-
- /**
- * Check customer scope, email and confirmation key before saving
- *
- * @param Mage_Customer_Model_Customer $customer
- * @return $this
- * @throws Mage_Core_Exception
- */
- protected function _beforeSave(Varien_Object $customer)
- {
- parent::_beforeSave($customer);
-
- if (!$customer->getEmail()) {
- throw Mage::exception('Mage_Customer', Mage::helper('customer')->__('Customer email is required'));
- }
-
- $adapter = $this->_getWriteAdapter();
- $bind = ['email' => $customer->getEmail()];
-
- $select = $adapter->select()
- ->from($this->getEntityTable(), [$this->getEntityIdField()])
- ->where('email = :email');
- if ($customer->getSharingConfig()->isWebsiteScope()) {
- $bind['website_id'] = (int) $customer->getWebsiteId();
- $select->where('website_id = :website_id');
- }
- if ($customer->getId()) {
- $bind['entity_id'] = (int) $customer->getId();
- $select->where('entity_id != :entity_id');
- }
-
- $result = $adapter->fetchOne($select, $bind);
- if ($result) {
- throw Mage::exception(
- 'Mage_Customer',
- Mage::helper('customer')->__('This customer email already exists'),
- Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS,
- );
- }
-
- // set confirmation key logic
- if ($customer->getForceConfirmed()) {
- $customer->setConfirmation(null);
- } elseif (!$customer->getId() && $customer->isConfirmationRequired()) {
- $customer->setConfirmation($customer->getRandomConfirmationKey());
- }
- // remove customer confirmation key from database, if empty
- if (!$customer->getConfirmation()) {
- $customer->setConfirmation(null);
- }
-
- return $this;
- }
-
- /**
- * Save customer addresses and set default addresses in attributes backend
- *
- * @return Mage_Eav_Model_Entity_Abstract
- */
- protected function _afterSave(Varien_Object $customer)
- {
- $this->_saveAddresses($customer);
- return parent::_afterSave($customer);
- }
-
- /**
- * Save/delete customer address
- *
- * @return $this
- */
- protected function _saveAddresses(Mage_Customer_Model_Customer $customer)
- {
- $defaultBillingId = $customer->getData('default_billing');
- $defaultShippingId = $customer->getData('default_shipping');
- foreach ($customer->getAddresses() as $address) {
- if ($address->getData('_deleted')) {
- if ($address->getId() == $defaultBillingId) {
- $customer->setData('default_billing', null);
- }
- if ($address->getId() == $defaultShippingId) {
- $customer->setData('default_shipping', null);
- }
- $address->delete();
- } else {
- if ($address->getParentId() != $customer->getId()) {
- $address->setParentId($customer->getId());
- }
-
- if ($address->hasDataChanges()) {
- $address->setStoreId($customer->getStoreId())
- ->setIsCustomerSaveTransaction(true)
- ->save();
- } else {
- $address->setStoreId($customer->getStoreId())
- ->setIsCustomerSaveTransaction(true);
- }
-
- if (($address->getIsPrimaryBilling() || $address->getIsDefaultBilling())
- && $address->getId() != $defaultBillingId
- ) {
- $customer->setData('default_billing', $address->getId());
- }
- if (($address->getIsPrimaryShipping() || $address->getIsDefaultShipping())
- && $address->getId() != $defaultShippingId
- ) {
- $customer->setData('default_shipping', $address->getId());
- }
- }
- }
- if ($customer->dataHasChangedFor('default_billing')) {
- $this->saveAttribute($customer, 'default_billing');
- }
- if ($customer->dataHasChangedFor('default_shipping')) {
- $this->saveAttribute($customer, 'default_shipping');
- }
-
- return $this;
- }
-
- /**
- * Retrieve select object for loading base entity row
- *
- * @param Mage_Customer_Model_Customer $object
- * @param mixed $rowId
- * @return Zend_Db_Select
- */
- protected function _getLoadRowSelect($object, $rowId)
- {
- $select = parent::_getLoadRowSelect($object, $rowId);
- if ($object->getWebsiteId() && $object->getSharingConfig()->isWebsiteScope()) {
- $select->where('website_id =?', (int) $object->getWebsiteId());
- }
-
- return $select;
- }
-
/**
* Load customer by email
*
@@ -390,4 +237,157 @@ public function getEmail($customerId)
return $this->_getReadAdapter()->fetchOne($select);
}
+
+ /**
+ * Retrieve customer entity default attributes
+ *
+ * @return array
+ */
+ protected function _getDefaultAttributes()
+ {
+ return [
+ 'entity_type_id',
+ 'attribute_set_id',
+ 'created_at',
+ 'updated_at',
+ 'increment_id',
+ 'store_id',
+ 'website_id',
+ ];
+ }
+
+ /**
+ * Check customer scope, email and confirmation key before saving
+ *
+ * @param Mage_Customer_Model_Customer $customer
+ * @return $this
+ * @throws Mage_Core_Exception
+ */
+ protected function _beforeSave(Varien_Object $customer)
+ {
+ parent::_beforeSave($customer);
+
+ if (!$customer->getEmail()) {
+ throw Mage::exception('Mage_Customer', Mage::helper('customer')->__('Customer email is required'));
+ }
+
+ $adapter = $this->_getWriteAdapter();
+ $bind = ['email' => $customer->getEmail()];
+
+ $select = $adapter->select()
+ ->from($this->getEntityTable(), [$this->getEntityIdField()])
+ ->where('email = :email');
+ if ($customer->getSharingConfig()->isWebsiteScope()) {
+ $bind['website_id'] = (int) $customer->getWebsiteId();
+ $select->where('website_id = :website_id');
+ }
+ if ($customer->getId()) {
+ $bind['entity_id'] = (int) $customer->getId();
+ $select->where('entity_id != :entity_id');
+ }
+
+ $result = $adapter->fetchOne($select, $bind);
+ if ($result) {
+ throw Mage::exception(
+ 'Mage_Customer',
+ Mage::helper('customer')->__('This customer email already exists'),
+ Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS,
+ );
+ }
+
+ // set confirmation key logic
+ if ($customer->getForceConfirmed()) {
+ $customer->setConfirmation(null);
+ } elseif (!$customer->getId() && $customer->isConfirmationRequired()) {
+ $customer->setConfirmation($customer->getRandomConfirmationKey());
+ }
+ // remove customer confirmation key from database, if empty
+ if (!$customer->getConfirmation()) {
+ $customer->setConfirmation(null);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Save customer addresses and set default addresses in attributes backend
+ *
+ * @return Mage_Eav_Model_Entity_Abstract
+ */
+ protected function _afterSave(Varien_Object $customer)
+ {
+ $this->_saveAddresses($customer);
+ return parent::_afterSave($customer);
+ }
+
+ /**
+ * Save/delete customer address
+ *
+ * @return $this
+ */
+ protected function _saveAddresses(Mage_Customer_Model_Customer $customer)
+ {
+ $defaultBillingId = $customer->getData('default_billing');
+ $defaultShippingId = $customer->getData('default_shipping');
+ foreach ($customer->getAddresses() as $address) {
+ if ($address->getData('_deleted')) {
+ if ($address->getId() == $defaultBillingId) {
+ $customer->setData('default_billing', null);
+ }
+ if ($address->getId() == $defaultShippingId) {
+ $customer->setData('default_shipping', null);
+ }
+ $address->delete();
+ } else {
+ if ($address->getParentId() != $customer->getId()) {
+ $address->setParentId($customer->getId());
+ }
+
+ if ($address->hasDataChanges()) {
+ $address->setStoreId($customer->getStoreId())
+ ->setIsCustomerSaveTransaction(true)
+ ->save();
+ } else {
+ $address->setStoreId($customer->getStoreId())
+ ->setIsCustomerSaveTransaction(true);
+ }
+
+ if (($address->getIsPrimaryBilling() || $address->getIsDefaultBilling())
+ && $address->getId() != $defaultBillingId
+ ) {
+ $customer->setData('default_billing', $address->getId());
+ }
+ if (($address->getIsPrimaryShipping() || $address->getIsDefaultShipping())
+ && $address->getId() != $defaultShippingId
+ ) {
+ $customer->setData('default_shipping', $address->getId());
+ }
+ }
+ }
+ if ($customer->dataHasChangedFor('default_billing')) {
+ $this->saveAttribute($customer, 'default_billing');
+ }
+ if ($customer->dataHasChangedFor('default_shipping')) {
+ $this->saveAttribute($customer, 'default_shipping');
+ }
+
+ return $this;
+ }
+
+ /**
+ * Retrieve select object for loading base entity row
+ *
+ * @param Mage_Customer_Model_Customer $object
+ * @param mixed $rowId
+ * @return Zend_Db_Select
+ */
+ protected function _getLoadRowSelect($object, $rowId)
+ {
+ $select = parent::_getLoadRowSelect($object, $rowId);
+ if ($object->getWebsiteId() && $object->getSharingConfig()->isWebsiteScope()) {
+ $select->where('website_id =?', (int) $object->getWebsiteId());
+ }
+
+ return $select;
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Resource/Customer/Collection.php b/app/code/core/Mage/Customer/Model/Resource/Customer/Collection.php
index b92a48d1f55..1e92e49bdde 100644
--- a/app/code/core/Mage/Customer/Model/Resource/Customer/Collection.php
+++ b/app/code/core/Mage/Customer/Model/Resource/Customer/Collection.php
@@ -24,11 +24,6 @@
*/
class Mage_Customer_Model_Resource_Customer_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('customer/customer');
- }
-
/**
* Group result by customer email
*
@@ -109,6 +104,10 @@ public function getSelectCountSql()
return $select;
}
+ protected function _construct()
+ {
+ $this->_init('customer/customer');
+ }
/**
* Reset left join
diff --git a/app/code/core/Mage/Customer/Model/Resource/Group/Collection.php b/app/code/core/Mage/Customer/Model/Resource/Group/Collection.php
index da8c925c279..933d3b37337 100644
--- a/app/code/core/Mage/Customer/Model/Resource/Group/Collection.php
+++ b/app/code/core/Mage/Customer/Model/Resource/Group/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Customer_Model_Resource_Group_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('customer/group');
- }
-
/**
* Set tax group filter
*
@@ -100,4 +95,8 @@ public function toOptionHash()
{
return parent::_toOptionHash('customer_group_id', 'customer_group_code');
}
+ protected function _construct()
+ {
+ $this->_init('customer/group');
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Resource/Setup.php b/app/code/core/Mage/Customer/Model/Resource/Setup.php
index 4d25b1180d5..5418dac21cc 100644
--- a/app/code/core/Mage/Customer/Model/Resource/Setup.php
+++ b/app/code/core/Mage/Customer/Model/Resource/Setup.php
@@ -22,27 +22,6 @@
*/
class Mage_Customer_Model_Resource_Setup extends Mage_Eav_Model_Entity_Setup
{
- /**
- * Prepare customer attribute values to save in additional table
- *
- * @param array $attr
- * @return array
- */
- protected function _prepareValues($attr)
- {
- $data = parent::_prepareValues($attr);
-
- return array_merge($data, [
- 'is_visible' => $this->_getValue($attr, 'visible', 1),
- 'is_system' => $this->_getValue($attr, 'system', 1),
- 'input_filter' => $this->_getValue($attr, 'input_filter', null),
- 'multiline_count' => $this->_getValue($attr, 'multiline_count', 0),
- 'validate_rules' => $this->_getValue($attr, 'validate_rules', null),
- 'data_model' => $this->_getValue($attr, 'data', null),
- 'sort_order' => $this->_getValue($attr, 'position', 0),
- ]);
- }
-
/**
* Add customer attributes to customer forms
*/
@@ -450,4 +429,24 @@ public function getDefaultEntities()
],
];
}
+ /**
+ * Prepare customer attribute values to save in additional table
+ *
+ * @param array $attr
+ * @return array
+ */
+ protected function _prepareValues($attr)
+ {
+ $data = parent::_prepareValues($attr);
+
+ return array_merge($data, [
+ 'is_visible' => $this->_getValue($attr, 'visible', 1),
+ 'is_system' => $this->_getValue($attr, 'system', 1),
+ 'input_filter' => $this->_getValue($attr, 'input_filter', null),
+ 'multiline_count' => $this->_getValue($attr, 'multiline_count', 0),
+ 'validate_rules' => $this->_getValue($attr, 'validate_rules', null),
+ 'data_model' => $this->_getValue($attr, 'data', null),
+ 'sort_order' => $this->_getValue($attr, 'position', 0),
+ ]);
+ }
}
diff --git a/app/code/core/Mage/Customer/Model/Session.php b/app/code/core/Mage/Customer/Model/Session.php
index 7bb9b6add30..a6e007f68be 100644
--- a/app/code/core/Mage/Customer/Model/Session.php
+++ b/app/code/core/Mage/Customer/Model/Session.php
@@ -75,16 +75,6 @@ class Mage_Customer_Model_Session extends Mage_Core_Model_Session_Abstract
*/
protected $_persistentCustomerGroupId = null;
- /**
- * Retrieve customer sharing configuration model
- *
- * @return Mage_Customer_Model_Config_Share
- */
- public function getCustomerConfigShare()
- {
- return Mage::getSingleton('customer/config_share');
- }
-
public function __construct()
{
$namespace = 'customer';
@@ -96,6 +86,16 @@ public function __construct()
Mage::dispatchEvent('customer_session_init', ['customer_session' => $this]);
}
+ /**
+ * Retrieve customer sharing configuration model
+ *
+ * @return Mage_Customer_Model_Config_Share
+ */
+ public function getCustomerConfigShare()
+ {
+ return Mage::getSingleton('customer/config_share');
+ }
+
/**
* Set customer object and setting customer id in session
*
@@ -310,67 +310,67 @@ public function authenticate(Mage_Core_Controller_Varien_Action $action, $loginU
}
/**
- * Set auth url
+ * Set Before auth url
*
- * @param string $key
* @param string $url
* @return $this
*/
- protected function _setAuthUrl($key, $url)
+ public function setBeforeAuthUrl($url)
{
- $url = Mage::helper('core/url')
- ->removeRequestParam($url, Mage::getSingleton('core/session')->getSessionIdQueryParam());
- // Add correct session ID to URL if needed
- $url = Mage::getModel('core/url')->getRebuiltUrl($url);
- return $this->setData($key, $url);
+ return $this->_setAuthUrl('before_auth_url', $url);
}
/**
- * Logout without dispatching event
+ * Set After auth url
*
+ * @param string $url
* @return $this
*/
- protected function _logout()
+ public function setAfterAuthUrl($url)
{
- $this->setId(null);
- $this->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
- $this->getCookie()->delete($this->getSessionName());
- Mage::getSingleton('core/session')->renewFormKey();
- return $this;
+ return $this->_setAuthUrl('after_auth_url', $url);
}
/**
- * Set Before auth url
+ * Reset core session hosts after resetting session ID
*
- * @param string $url
* @return $this
*/
- public function setBeforeAuthUrl($url)
+ public function renewSession()
{
- return $this->_setAuthUrl('before_auth_url', $url);
+ parent::renewSession();
+ Mage::getSingleton('core/session')->unsSessionHosts();
+
+ return $this;
}
/**
- * Set After auth url
+ * Set auth url
*
+ * @param string $key
* @param string $url
* @return $this
*/
- public function setAfterAuthUrl($url)
+ protected function _setAuthUrl($key, $url)
{
- return $this->_setAuthUrl('after_auth_url', $url);
+ $url = Mage::helper('core/url')
+ ->removeRequestParam($url, Mage::getSingleton('core/session')->getSessionIdQueryParam());
+ // Add correct session ID to URL if needed
+ $url = Mage::getModel('core/url')->getRebuiltUrl($url);
+ return $this->setData($key, $url);
}
/**
- * Reset core session hosts after resetting session ID
+ * Logout without dispatching event
*
* @return $this
*/
- public function renewSession()
+ protected function _logout()
{
- parent::renewSession();
- Mage::getSingleton('core/session')->unsSessionHosts();
-
+ $this->setId(null);
+ $this->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
+ $this->getCookie()->delete($this->getSessionName());
+ Mage::getSingleton('core/session')->renewFormKey();
return $this;
}
}
diff --git a/app/code/core/Mage/Customer/controllers/AccountController.php b/app/code/core/Mage/Customer/controllers/AccountController.php
index 09737e0a1cf..70f980879a3 100644
--- a/app/code/core/Mage/Customer/controllers/AccountController.php
+++ b/app/code/core/Mage/Customer/controllers/AccountController.php
@@ -34,16 +34,6 @@ class Mage_Customer_AccountController extends Mage_Core_Controller_Front_Action
*/
protected $_cookieCheckActions = ['loginPost', 'createpost'];
- /**
- * Retrieve customer session model object
- *
- * @return Mage_Customer_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('customer/session');
- }
-
/**
* Action predispatch
*
@@ -180,51 +170,6 @@ public function loginPostAction()
$this->_loginPostRedirect();
}
- /**
- * Define target URL and redirect customer after logging in
- */
- protected function _loginPostRedirect()
- {
- Mage::dispatchEvent('customer_controller_account_login_post_redirect_before', ['controller' => $this]);
- /** @var Helper $helper */
- $helper = $this->_getHelper('customer');
-
- $session = $this->_getSession();
-
- if (!$session->getBeforeAuthUrl() || $session->getBeforeAuthUrl() === Mage::getBaseUrl()) {
- // Set default URL to redirect customer to
- $session->setBeforeAuthUrl($helper->getAccountUrl());
- // Redirect customer to the last page visited after logging in
- if ($session->isLoggedIn()) {
- if (!Mage::getStoreConfigFlag(Helper::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD)) {
- $referer = $this->getRequest()->getParam(Helper::REFERER_QUERY_PARAM_NAME);
- if ($referer) {
- // Rebuild referer URL to handle the case when SID was changed
- $referer = Mage::getModel('core/url')
- ->getRebuiltUrl($this->_getHelper('core')->urlDecodeAndEscape($referer));
- if ($this->_isUrlInternal($referer)) {
- $session->setBeforeAuthUrl($referer);
- }
- }
- } elseif ($session->getAfterAuthUrl()) {
- $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
- }
- } else {
- $session->setBeforeAuthUrl($helper->getLoginUrl());
- }
- } elseif ($session->getBeforeAuthUrl() === $helper->getLogoutUrl()) {
- $session->setBeforeAuthUrl($helper->getDashboardUrl());
- } else {
- if (!$session->getAfterAuthUrl()) {
- $session->setAfterAuthUrl($session->getBeforeAuthUrl());
- }
- if ($session->isLoggedIn()) {
- $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
- }
- }
- $this->_redirectUrl($session->getBeforeAuthUrl(true));
- }
-
/**
* Customer logout action
*/
@@ -321,573 +266,761 @@ public function createPostAction()
}
/**
- * Success Registration
+ * @deprecated Use Mage::getModel() instead for PHPStan and IDE type hinting.
+ * Get model by path
*
- * @return $this
- * @throws Mage_Core_Exception
+ * @param string $path
+ * @param array|null $arguments
+ * @return false|Mage_Core_Model_Abstract
*/
- protected function _successProcessRegistration(Mage_Customer_Model_Customer $customer)
+ public function _getModel($path, $arguments = [])
{
- $session = $this->_getSession();
- if ($customer->isConfirmationRequired()) {
- $app = $this->_getApp();
- $store = $app->getStore();
- $customer->sendNewAccountEmail(
- 'confirmation',
- $session->getBeforeAuthUrl(),
- $store->getId(),
- $this->getRequest()->getPost('password'),
- );
- /** @var Helper $customerHelper */
- $customerHelper = $this->_getHelper('customer');
- $session->addSuccess($this->__(
- 'Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.',
- $customerHelper->getEmailConfirmationUrl($customer->getEmail()),
- ));
- $url = $this->_getUrl('*/*/index', ['_secure' => true]);
- } else {
- $session->setCustomerAsLoggedIn($customer);
- $url = $this->_welcomeCustomer($customer);
- }
- $this->_redirectSuccess($url);
- return $this;
+ return Mage::getModel($path, $arguments);
}
/**
- * Get Customer Model
- *
- * @return Mage_Customer_Model_Customer
+ * Confirm customer account by id and confirmation key
*/
- protected function _getCustomer()
+ public function confirmAction()
{
- $customer = $this->_getFromRegistry('current_customer');
- if (!$customer) {
- $customer = Mage::getModel('customer/customer')->setId(null);
- }
- if ($this->getRequest()->getParam('is_subscribed', false)) {
- $customer->setIsSubscribed(1);
+ $session = $this->_getSession();
+ if ($session->isLoggedIn()) {
+ $this->_getSession()->logout()->regenerateSessionId();
}
- /**
- * Initialize customer group id
- */
- $customer->getGroupId();
+ try {
+ $id = $this->getRequest()->getParam('id', false);
+ $key = $this->getRequest()->getParam('key', false);
+ $backUrl = $this->getRequest()->getParam('back_url', false);
+ if (empty($id) || empty($key)) {
+ throw new Exception($this->__('Bad request.'));
+ }
- return $customer;
+ // load customer by id (try/catch in case if it throws exceptions)
+ try {
+ $customer = Mage::getModel('customer/customer')->load($id);
+ if (!$customer->getId()) {
+ throw new Exception('Failed to load customer by id.');
+ }
+ } catch (Exception $e) {
+ throw new Exception($this->__('Wrong customer account specified.'));
+ }
+
+ // check if it is inactive
+ if ($customer->getConfirmation()) {
+ if ($customer->getConfirmation() !== $key) {
+ throw new Exception($this->__('Wrong confirmation key.'));
+ }
+
+ // activate customer
+ try {
+ $customer->setConfirmation(null);
+ $customer->save();
+ } catch (Exception $e) {
+ throw new Exception($this->__('Failed to confirm customer account.'));
+ }
+
+ // log in and send greeting email, then die happy
+ $session->setCustomerAsLoggedIn($customer);
+ $successUrl = $this->_welcomeCustomer($customer, true);
+ $this->_redirectSuccess($backUrl ?: $successUrl);
+ return;
+ }
+
+ // die happy
+ $this->_redirectSuccess($this->_getUrl('*/*/index', ['_secure' => true]));
+ return;
+ } catch (Exception $e) {
+ // die unhappy
+ $this->_getSession()->addError($e->getMessage());
+ $this->_redirectError($this->_getUrl('*/*/index', ['_secure' => true]));
+ return;
+ }
}
/**
- * Add session error method
- *
- * @param string|array $errors
+ * Send confirmation link to specified email
*/
- protected function _addSessionError($errors)
+ public function confirmationAction()
{
- $session = $this->_getSession();
- $session->setCustomerFormData($this->getRequest()->getPost());
- if (is_array($errors)) {
- foreach ($errors as $errorMessage) {
- $session->addError($this->_escapeHtml($errorMessage));
+ $customer = Mage::getModel('customer/customer');
+ if ($this->_getSession()->isLoggedIn()) {
+ $this->_redirect('*/*/');
+ return;
+ }
+
+ // try to confirm by email
+ $email = $this->getRequest()->getPost('email');
+ if ($email) {
+ try {
+ $customer->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($email);
+ if (!$customer->getId()) {
+ throw new Exception('');
+ }
+ if ($customer->getConfirmation()) {
+ $customer->sendNewAccountEmail('confirmation', '', Mage::app()->getStore()->getId());
+ $this->_getSession()->addSuccess($this->__('Please, check your email for confirmation key.'));
+ } else {
+ $this->_getSession()->addSuccess($this->__('This email does not require confirmation.'));
+ }
+ $this->_getSession()->setUsername($email);
+ $this->_redirectSuccess($this->_getUrl('*/*/index', ['_secure' => true]));
+ } catch (Exception $e) {
+ $this->_getSession()->addException($e, $this->__('Wrong email.'));
+ $this->_redirectError($this->_getUrl('*/*/*', ['email' => $email, '_secure' => true]));
}
- } else {
- $session->addError($this->__('Invalid customer data'));
+ return;
}
+
+ // output form
+ $this->loadLayout();
+
+ $this->getLayout()->getBlock('accountConfirmation')
+ ->setEmail($this->getRequest()->getParam('email', $email));
+
+ $this->_initLayoutMessages('customer/session');
+ $this->renderLayout();
}
/**
- * Escape message text HTML.
- *
- * @param string $text
- * @return string
+ * Forgot customer password page
*/
- protected function _escapeHtml($text)
+ public function forgotPasswordAction()
{
- return Mage::helper('core')->escapeHtml($text);
+ $this->loadLayout();
+
+ $this->getLayout()->getBlock('forgotPassword')->setEmailValue(
+ $this->_getSession()->getForgottenEmail(),
+ );
+ $this->_getSession()->unsForgottenEmail();
+
+ $this->_initLayoutMessages('customer/session');
+ $this->renderLayout();
}
/**
- * Validate customer data and return errors if they are
- *
- * @param Mage_Customer_Model_Customer $customer
- * @return array
+ * Forgot customer password action
+ * @throws Mage_Core_Model_Store_Exception
*/
- protected function _getCustomerErrors($customer)
+ public function forgotPasswordPostAction()
{
- $errors = [];
- $request = $this->getRequest();
- if ($request->getPost('create_address')) {
- $errors = $this->_getErrorsOnCustomerAddress($customer);
- }
- $customerForm = $this->_getCustomerForm($customer);
- $customerData = $customerForm->extractData($request);
- $customerErrors = $customerForm->validateData($customerData);
- if ($customerErrors !== true) {
- $errors = array_merge($customerErrors, $errors);
- } else {
- $customerForm->compactData($customerData);
- $customer->setPassword($request->getPost('password'));
- $customer->setPasswordConfirmation($request->getPost('confirmation'));
- $customerErrors = $customer->validate();
- if (is_array($customerErrors)) {
- $errors = array_merge($customerErrors, $errors);
- }
- }
- return $errors;
- }
+ $email = (string) $this->getRequest()->getPost('email');
+ if ($email) {
+ $flowPassword = Mage::getModel('customer/flowpassword');
+ $flowPassword->setEmail($email)->save();
- /**
- * Get Customer Form Initialized Model
- *
- * @param Mage_Customer_Model_Customer $customer
- * @return Mage_Customer_Model_Form
- */
- protected function _getCustomerForm($customer)
- {
- $customerForm = Mage::getModel('customer/form');
- $customerForm->setFormCode('customer_account_create');
- $customerForm->setEntity($customer);
- return $customerForm;
+ if (!$flowPassword->checkCustomerForgotPasswordFlowEmail($email)) {
+ $this->_getSession()
+ ->addError($this->__('You have exceeded requests to times per 24 hours from 1 e-mail.'));
+ $this->_redirect('*/*/forgotpassword');
+ return;
+ }
+
+ if (!$flowPassword->checkCustomerForgotPasswordFlowIp()) {
+ $this->_getSession()->addError($this->__('You have exceeded requests to times per hour from 1 IP.'));
+ $this->_redirect('*/*/forgotpassword');
+ return;
+ }
+
+ if (!Zend_Validate::is($email, 'EmailAddress')) {
+ $this->_getSession()->setForgottenEmail($email);
+ $this->_getSession()->addError($this->__('Invalid email address.'));
+ $this->_redirect('*/*/forgotpassword');
+ return;
+ }
+
+ $customer = Mage::getModel('customer/customer')
+ ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
+ ->loadByEmail($email);
+
+ $customerId = $customer->getId();
+ if ($customerId) {
+ try {
+ /** @var Helper $helper */
+ $helper = $this->_getHelper('customer');
+ $newResetPasswordLinkToken = $helper->generateResetPasswordLinkToken();
+ $newResetPasswordLinkCustomerId = $helper->generateResetPasswordLinkCustomerId($customerId);
+ $customer->changeResetPasswordLinkCustomerId($newResetPasswordLinkCustomerId);
+ $customer->changeResetPasswordLinkToken($newResetPasswordLinkToken);
+ $customer->sendPasswordResetConfirmationEmail();
+ } catch (Exception $exception) {
+ $this->_getSession()->addError($exception->getMessage());
+ $this->_redirect('*/*/forgotpassword');
+ return;
+ }
+ }
+ $this->_getSession()
+ ->addSuccess($this->_getHelper('customer')
+ ->__(
+ 'If there is an account associated with %s you will receive an email with a link to reset your password.',
+ $this->_getHelper('customer')->escapeHtml($email),
+ ));
+ $this->_redirect('*/*/');
+ return;
+ } else {
+ $this->_getSession()->addError($this->__('Please enter your email.'));
+ $this->_redirect('*/*/forgotpassword');
+ return;
+ }
}
/**
- * Get Helper
+ * Display reset forgotten password form
*
- * @param string $path
- * @return Mage_Core_Helper_Abstract
*/
- protected function _getHelper($path)
+ public function changeForgottenAction()
{
- return Mage::helper($path);
+ try {
+ list($customerId, $resetPasswordLinkToken) = $this->_getRestorePasswordParameters($this->_getSession());
+ $this->_validateResetPasswordLinkToken($customerId, $resetPasswordLinkToken);
+ $this->loadLayout();
+ $this->renderLayout();
+ } catch (Exception $exception) {
+ $this->_getSession()->addError($this->_getHelper('customer')->__('Your password reset link has expired.'));
+ $this->_redirect('*/*/forgotpassword');
+ }
}
/**
- * Get App
+ * Checks reset forgotten password token
+ *
+ * User is redirected on this action when he clicks on the corresponding link in password reset confirmation email.
*
- * @return Mage_Core_Model_App
*/
- protected function _getApp()
+ public function resetPasswordAction()
{
- return Mage::app();
+ try {
+ $customerId = (int) $this->getCustomerId();
+ $resetPasswordLinkToken = (string) $this->getRequest()->getQuery('token');
+
+ $this->_validateResetPasswordLinkToken($customerId, $resetPasswordLinkToken);
+ $this->_saveRestorePasswordParameters($customerId, $resetPasswordLinkToken)
+ ->_redirect('*/*/changeforgotten');
+ } catch (Exception $exception) {
+ $this->_getSession()->addError($this->_getHelper('customer')->__('Your password reset link has expired.'));
+ $this->_redirect('*/*/forgotpassword');
+ }
}
/**
- * Dispatch Event
- *
- * @param Mage_Customer_Model_Customer $customer
+ * Reset forgotten password
+ * Used to handle data received from reset forgotten password form
*/
- protected function _dispatchRegisterSuccess($customer)
+ public function resetPasswordPostAction()
{
- Mage::dispatchEvent(
- 'customer_register_success',
- ['account_controller' => $this, 'customer' => $customer],
- );
+ if (!$this->_validateFormKey()) {
+ $this->_redirect('*/*/');
+ return;
+ }
+
+ list($customerId, $resetPasswordLinkToken) = $this->_getRestorePasswordParameters($this->_getSession());
+ $password = (string) $this->getRequest()->getPost('password');
+ $passwordConfirmation = (string) $this->getRequest()->getPost('confirmation');
+
+ try {
+ $this->_validateResetPasswordLinkToken($customerId, $resetPasswordLinkToken);
+ } catch (Exception $exception) {
+ $this->_getSession()->addError($this->_getHelper('customer')->__('Your password reset link has expired.'));
+ $this->_redirect('*/*/');
+ return;
+ }
+
+ $errorMessages = [];
+ if (iconv_strlen($password) <= 0) {
+ $errorMessages[] = $this->_getHelper('customer')->__('New password field cannot be empty.');
+ }
+ $customer = Mage::getModel('customer/customer')->load($customerId);
+
+ $customer->setPassword($password);
+ $customer->setPasswordConfirmation($passwordConfirmation);
+ $validationErrorMessages = $customer->validateResetPassword();
+ if (is_array($validationErrorMessages)) {
+ $errorMessages = array_merge($errorMessages, $validationErrorMessages);
+ }
+
+ if (!empty($errorMessages)) {
+ $this->_getSession()->setCustomerFormData($this->getRequest()->getPost());
+ foreach ($errorMessages as $errorMessage) {
+ $this->_getSession()->addError($errorMessage);
+ }
+ $this->_redirect('*/*/changeforgotten');
+ return;
+ }
+
+ try {
+ // Empty current reset password token i.e. invalidate it
+ $customer->setRpToken(null);
+ $customer->setRpTokenCreatedAt(null);
+ $customer->cleanPasswordsValidationData();
+ $customer->setPasswordCreatedAt(time());
+ $customer->setRpCustomerId(null);
+ $customer->setConfirmation(null); // Set email is confirmed.
+ $customer->save();
+
+ $this->_getSession()->unsetData(self::TOKEN_SESSION_NAME);
+ $this->_getSession()->unsetData(self::CUSTOMER_ID_SESSION_NAME);
+
+ $this->_getSession()->addSuccess($this->_getHelper('customer')->__('Your password has been updated.'));
+ $this->_redirect('*/*/login');
+ } catch (Exception $exception) {
+ $this->_getSession()->addException($exception, $this->__('Cannot save a new password.'));
+ $this->_redirect('*/*/changeforgotten');
+ return;
+ }
}
/**
- * Gets customer address
- *
- * @param Mage_Customer_Model_Customer $customer
- * @return array $errors
+ * Forgot customer account information page
*/
- protected function _getErrorsOnCustomerAddress($customer)
+ public function editAction()
{
- $errors = [];
- $address = Mage::getModel('customer/address');
- $addressForm = Mage::getModel('customer/form');
- $addressForm->setFormCode('customer_register_address')
- ->setEntity($address);
+ $this->loadLayout();
+ $this->_initLayoutMessages('customer/session');
+ $this->_initLayoutMessages('catalog/session');
- $addressData = $addressForm->extractData($this->getRequest(), 'address', false);
- $addressErrors = $addressForm->validateData($addressData);
- if (is_array($addressErrors)) {
- $errors = array_merge($errors, $addressErrors);
+ $block = $this->getLayout()->getBlock('customer_edit');
+ if ($block) {
+ $block->setRefererUrl($this->_getRefererUrl());
}
- $address->setId(null)
- ->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
- ->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
- $addressForm->compactData($addressData);
- $customer->addAddress($address);
-
- $addressErrors = $address->validate();
- if (is_array($addressErrors)) {
- $errors = array_merge($errors, $addressErrors);
+ $data = $this->_getSession()->getCustomerFormData(true);
+ $customer = $this->_getSession()->getCustomer();
+ if (!empty($data)) {
+ $customer->addData($data);
}
- return $errors;
+ if ($this->getRequest()->getParam('changepass') == 1) {
+ $customer->setChangePassword(1);
+ }
+
+ $this->getLayout()->getBlock('head')->setTitle($this->__('Account Information'));
+ $this->getLayout()->getBlock('messages')->setEscapeMessageFlag(true);
+ $this->renderLayout();
}
/**
- * @deprecated Use Mage::getModel() instead for PHPStan and IDE type hinting.
- * Get model by path
- *
- * @param string $path
- * @param array|null $arguments
- * @return false|Mage_Core_Model_Abstract
+ * Change customer password action
*/
- public function _getModel($path, $arguments = [])
+ public function editPostAction()
{
- return Mage::getModel($path, $arguments);
+ if (!$this->_validateFormKey()) {
+ return $this->_redirect('*/*/edit');
+ }
+
+ if ($this->getRequest()->isPost()) {
+ $customer = $this->_getSession()->getCustomer();
+ $customer->setOldEmail($customer->getEmail());
+ $customerForm = Mage::getModel('customer/form');
+ $customerForm->setFormCode('customer_account_edit')
+ ->setEntity($customer);
+
+ $customerData = $customerForm->extractData($this->getRequest());
+
+ $errors = [];
+ $customerErrors = $customerForm->validateData($customerData);
+ if ($customerErrors !== true) {
+ $errors = array_merge($customerErrors, $errors);
+ } else {
+ $customerForm->compactData($customerData);
+ $errors = [];
+
+ if (!$customer->validatePassword($this->getRequest()->getPost('current_password'))) {
+ $errors[] = $this->__('Invalid current password');
+ }
+
+ // If email change was requested then set flag
+ $isChangeEmail = $customer->getOldEmail() !== $customer->getEmail();
+ $customer->setIsChangeEmail($isChangeEmail);
+
+ // If password change was requested then add it to common validation scheme
+ $customer->setIsChangePassword($this->getRequest()->getParam('change_password'));
+
+ if ($customer->getIsChangePassword()) {
+ $newPass = $this->getRequest()->getPost('password');
+ $confPass = $this->getRequest()->getPost('confirmation');
+
+ if (strlen($newPass)) {
+ /**
+ * Set entered password and its confirmation - they
+ * will be validated later to match each other and be of right length
+ */
+ $customer->setPassword($newPass);
+ $customer->setPasswordConfirmation($confPass);
+
+ // Invalidate reset password token when user changes password
+ $customer->setRpToken(null);
+ $customer->setRpTokenCreatedAt(null);
+ $customer->setRpCustomerId(null);
+ } else {
+ $errors[] = $this->__('New password field cannot be empty.');
+ }
+ }
+
+ // Validate account and compose list of errors if any
+ $customerErrors = $customer->validate();
+ if (is_array($customerErrors)) {
+ $errors = array_merge($errors, $customerErrors);
+ }
+ }
+
+ if (!empty($errors)) {
+ $this->_getSession()->setCustomerFormData($this->getRequest()->getPost());
+ foreach ($errors as $message) {
+ $this->_getSession()->addError($message);
+ }
+ $this->_redirect('*/*/edit');
+ return $this;
+ }
+
+ try {
+ $customer->cleanPasswordsValidationData();
+ $customer->setPasswordCreatedAt(time());
+
+ // Reset all password reset tokens if all data was sufficient and correct on email change
+ if ($customer->getIsChangeEmail()) {
+ $customer->setRpToken(null);
+ $customer->setRpTokenCreatedAt(null);
+ }
+
+ $customer->save();
+ $this->_getSession()->setCustomer($customer)
+ ->addSuccess($this->__('The account information has been saved.'));
+
+ if ($customer->getIsChangeEmail() || $customer->getIsChangePassword()) {
+ $customer->sendChangedPasswordOrEmail();
+ }
+
+ $this->_redirect('customer/account');
+ return;
+ } catch (Mage_Core_Exception $e) {
+ $this->_getSession()->setCustomerFormData($this->getRequest()->getPost())
+ ->addError($e->getMessage());
+ } catch (Exception $e) {
+ $this->_getSession()->setCustomerFormData($this->getRequest()->getPost())
+ ->addException($e, $this->__('Cannot save the customer.'));
+ }
+ }
+
+ $this->_redirect('*/*/edit');
}
/**
- * Get model from registry by path
+ * Retrieve customer session model object
*
- * @param string $path
- * @return mixed
+ * @return Mage_Customer_Model_Session
*/
- protected function _getFromRegistry($path)
+ protected function _getSession()
{
- return Mage::registry($path);
+ return Mage::getSingleton('customer/session');
}
/**
- * Add welcome message and send new account email.
- * Returns success URL
- *
- * @param bool $isJustConfirmed
- * @return string
- * @throws Mage_Core_Model_Store_Exception
- * @throws Mage_Core_Exception
+ * Define target URL and redirect customer after logging in
*/
- protected function _welcomeCustomer(Mage_Customer_Model_Customer $customer, $isJustConfirmed = false)
+ protected function _loginPostRedirect()
{
- $this->_getSession()->addSuccess(
- $this->__('Thank you for registering with %s.', Mage::app()->getStore()->getFrontendName()),
- );
- if ($this->_isVatValidationEnabled()) {
- // Show corresponding VAT message to customer
- /** @var Mage_Customer_Helper_Address $helper */
- $helper = $this->_getHelper('customer/address');
- $configAddressType = $helper->getTaxCalculationAddressType();
- $userPrompt = '';
- switch ($configAddressType) {
- case Mage_Customer_Model_Address_Abstract::TYPE_SHIPPING:
- $userPrompt = $this->__(
- 'If you are a registered VAT customer, please click here to enter you shipping address for proper VAT calculation',
- $this->_getUrl('customer/address/edit'),
- );
- break;
- default:
- $userPrompt = $this->__(
- 'If you are a registered VAT customer, please click here to enter you billing address for proper VAT calculation',
- $this->_getUrl('customer/address/edit'),
- );
- }
- $this->_getSession()->addSuccess($userPrompt);
- }
+ Mage::dispatchEvent('customer_controller_account_login_post_redirect_before', ['controller' => $this]);
+ /** @var Helper $helper */
+ $helper = $this->_getHelper('customer');
- $customer->sendNewAccountEmail(
- $isJustConfirmed ? 'confirmed' : 'registered',
- '',
- Mage::app()->getStore()->getId(),
- $this->getRequest()->getPost('password'),
- );
+ $session = $this->_getSession();
- $successUrl = $this->_getUrl('*/*/index', ['_secure' => true]);
- if ($this->_getSession()->getBeforeAuthUrl()) {
- $successUrl = $this->_getSession()->getBeforeAuthUrl(true);
+ if (!$session->getBeforeAuthUrl() || $session->getBeforeAuthUrl() === Mage::getBaseUrl()) {
+ // Set default URL to redirect customer to
+ $session->setBeforeAuthUrl($helper->getAccountUrl());
+ // Redirect customer to the last page visited after logging in
+ if ($session->isLoggedIn()) {
+ if (!Mage::getStoreConfigFlag(Helper::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD)) {
+ $referer = $this->getRequest()->getParam(Helper::REFERER_QUERY_PARAM_NAME);
+ if ($referer) {
+ // Rebuild referer URL to handle the case when SID was changed
+ $referer = Mage::getModel('core/url')
+ ->getRebuiltUrl($this->_getHelper('core')->urlDecodeAndEscape($referer));
+ if ($this->_isUrlInternal($referer)) {
+ $session->setBeforeAuthUrl($referer);
+ }
+ }
+ } elseif ($session->getAfterAuthUrl()) {
+ $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
+ }
+ } else {
+ $session->setBeforeAuthUrl($helper->getLoginUrl());
+ }
+ } elseif ($session->getBeforeAuthUrl() === $helper->getLogoutUrl()) {
+ $session->setBeforeAuthUrl($helper->getDashboardUrl());
+ } else {
+ if (!$session->getAfterAuthUrl()) {
+ $session->setAfterAuthUrl($session->getBeforeAuthUrl());
+ }
+ if ($session->isLoggedIn()) {
+ $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
+ }
}
- return $successUrl;
+ $this->_redirectUrl($session->getBeforeAuthUrl(true));
}
/**
- * Confirm customer account by id and confirmation key
+ * Success Registration
+ *
+ * @return $this
+ * @throws Mage_Core_Exception
*/
- public function confirmAction()
+ protected function _successProcessRegistration(Mage_Customer_Model_Customer $customer)
{
$session = $this->_getSession();
- if ($session->isLoggedIn()) {
- $this->_getSession()->logout()->regenerateSessionId();
- }
- try {
- $id = $this->getRequest()->getParam('id', false);
- $key = $this->getRequest()->getParam('key', false);
- $backUrl = $this->getRequest()->getParam('back_url', false);
- if (empty($id) || empty($key)) {
- throw new Exception($this->__('Bad request.'));
- }
-
- // load customer by id (try/catch in case if it throws exceptions)
- try {
- $customer = Mage::getModel('customer/customer')->load($id);
- if (!$customer->getId()) {
- throw new Exception('Failed to load customer by id.');
- }
- } catch (Exception $e) {
- throw new Exception($this->__('Wrong customer account specified.'));
- }
-
- // check if it is inactive
- if ($customer->getConfirmation()) {
- if ($customer->getConfirmation() !== $key) {
- throw new Exception($this->__('Wrong confirmation key.'));
- }
-
- // activate customer
- try {
- $customer->setConfirmation(null);
- $customer->save();
- } catch (Exception $e) {
- throw new Exception($this->__('Failed to confirm customer account.'));
- }
-
- // log in and send greeting email, then die happy
- $session->setCustomerAsLoggedIn($customer);
- $successUrl = $this->_welcomeCustomer($customer, true);
- $this->_redirectSuccess($backUrl ?: $successUrl);
- return;
- }
-
- // die happy
- $this->_redirectSuccess($this->_getUrl('*/*/index', ['_secure' => true]));
- return;
- } catch (Exception $e) {
- // die unhappy
- $this->_getSession()->addError($e->getMessage());
- $this->_redirectError($this->_getUrl('*/*/index', ['_secure' => true]));
- return;
+ if ($customer->isConfirmationRequired()) {
+ $app = $this->_getApp();
+ $store = $app->getStore();
+ $customer->sendNewAccountEmail(
+ 'confirmation',
+ $session->getBeforeAuthUrl(),
+ $store->getId(),
+ $this->getRequest()->getPost('password'),
+ );
+ /** @var Helper $customerHelper */
+ $customerHelper = $this->_getHelper('customer');
+ $session->addSuccess($this->__(
+ 'Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.',
+ $customerHelper->getEmailConfirmationUrl($customer->getEmail()),
+ ));
+ $url = $this->_getUrl('*/*/index', ['_secure' => true]);
+ } else {
+ $session->setCustomerAsLoggedIn($customer);
+ $url = $this->_welcomeCustomer($customer);
}
+ $this->_redirectSuccess($url);
+ return $this;
}
/**
- * Send confirmation link to specified email
+ * Get Customer Model
+ *
+ * @return Mage_Customer_Model_Customer
*/
- public function confirmationAction()
+ protected function _getCustomer()
{
- $customer = Mage::getModel('customer/customer');
- if ($this->_getSession()->isLoggedIn()) {
- $this->_redirect('*/*/');
- return;
+ $customer = $this->_getFromRegistry('current_customer');
+ if (!$customer) {
+ $customer = Mage::getModel('customer/customer')->setId(null);
}
-
- // try to confirm by email
- $email = $this->getRequest()->getPost('email');
- if ($email) {
- try {
- $customer->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($email);
- if (!$customer->getId()) {
- throw new Exception('');
- }
- if ($customer->getConfirmation()) {
- $customer->sendNewAccountEmail('confirmation', '', Mage::app()->getStore()->getId());
- $this->_getSession()->addSuccess($this->__('Please, check your email for confirmation key.'));
- } else {
- $this->_getSession()->addSuccess($this->__('This email does not require confirmation.'));
- }
- $this->_getSession()->setUsername($email);
- $this->_redirectSuccess($this->_getUrl('*/*/index', ['_secure' => true]));
- } catch (Exception $e) {
- $this->_getSession()->addException($e, $this->__('Wrong email.'));
- $this->_redirectError($this->_getUrl('*/*/*', ['email' => $email, '_secure' => true]));
- }
- return;
+ if ($this->getRequest()->getParam('is_subscribed', false)) {
+ $customer->setIsSubscribed(1);
}
+ /**
+ * Initialize customer group id
+ */
+ $customer->getGroupId();
- // output form
- $this->loadLayout();
-
- $this->getLayout()->getBlock('accountConfirmation')
- ->setEmail($this->getRequest()->getParam('email', $email));
-
- $this->_initLayoutMessages('customer/session');
- $this->renderLayout();
+ return $customer;
}
/**
- * Get Url method
+ * Add session error method
*
- * @param string $url
- * @param array $params
- * @return string
+ * @param string|array $errors
*/
- protected function _getUrl($url, $params = [])
+ protected function _addSessionError($errors)
{
- return Mage::getUrl($url, $params);
+ $session = $this->_getSession();
+ $session->setCustomerFormData($this->getRequest()->getPost());
+ if (is_array($errors)) {
+ foreach ($errors as $errorMessage) {
+ $session->addError($this->_escapeHtml($errorMessage));
+ }
+ } else {
+ $session->addError($this->__('Invalid customer data'));
+ }
}
/**
- * Forgot customer password page
+ * Escape message text HTML.
+ *
+ * @param string $text
+ * @return string
*/
- public function forgotPasswordAction()
+ protected function _escapeHtml($text)
{
- $this->loadLayout();
-
- $this->getLayout()->getBlock('forgotPassword')->setEmailValue(
- $this->_getSession()->getForgottenEmail(),
- );
- $this->_getSession()->unsForgottenEmail();
-
- $this->_initLayoutMessages('customer/session');
- $this->renderLayout();
+ return Mage::helper('core')->escapeHtml($text);
}
/**
- * Forgot customer password action
- * @throws Mage_Core_Model_Store_Exception
+ * Validate customer data and return errors if they are
+ *
+ * @param Mage_Customer_Model_Customer $customer
+ * @return array
*/
- public function forgotPasswordPostAction()
+ protected function _getCustomerErrors($customer)
{
- $email = (string) $this->getRequest()->getPost('email');
- if ($email) {
- $flowPassword = Mage::getModel('customer/flowpassword');
- $flowPassword->setEmail($email)->save();
-
- if (!$flowPassword->checkCustomerForgotPasswordFlowEmail($email)) {
- $this->_getSession()
- ->addError($this->__('You have exceeded requests to times per 24 hours from 1 e-mail.'));
- $this->_redirect('*/*/forgotpassword');
- return;
- }
-
- if (!$flowPassword->checkCustomerForgotPasswordFlowIp()) {
- $this->_getSession()->addError($this->__('You have exceeded requests to times per hour from 1 IP.'));
- $this->_redirect('*/*/forgotpassword');
- return;
- }
-
- if (!Zend_Validate::is($email, 'EmailAddress')) {
- $this->_getSession()->setForgottenEmail($email);
- $this->_getSession()->addError($this->__('Invalid email address.'));
- $this->_redirect('*/*/forgotpassword');
- return;
+ $errors = [];
+ $request = $this->getRequest();
+ if ($request->getPost('create_address')) {
+ $errors = $this->_getErrorsOnCustomerAddress($customer);
+ }
+ $customerForm = $this->_getCustomerForm($customer);
+ $customerData = $customerForm->extractData($request);
+ $customerErrors = $customerForm->validateData($customerData);
+ if ($customerErrors !== true) {
+ $errors = array_merge($customerErrors, $errors);
+ } else {
+ $customerForm->compactData($customerData);
+ $customer->setPassword($request->getPost('password'));
+ $customer->setPasswordConfirmation($request->getPost('confirmation'));
+ $customerErrors = $customer->validate();
+ if (is_array($customerErrors)) {
+ $errors = array_merge($customerErrors, $errors);
}
+ }
+ return $errors;
+ }
- $customer = Mage::getModel('customer/customer')
- ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
- ->loadByEmail($email);
+ /**
+ * Get Customer Form Initialized Model
+ *
+ * @param Mage_Customer_Model_Customer $customer
+ * @return Mage_Customer_Model_Form
+ */
+ protected function _getCustomerForm($customer)
+ {
+ $customerForm = Mage::getModel('customer/form');
+ $customerForm->setFormCode('customer_account_create');
+ $customerForm->setEntity($customer);
+ return $customerForm;
+ }
- $customerId = $customer->getId();
- if ($customerId) {
- try {
- /** @var Helper $helper */
- $helper = $this->_getHelper('customer');
- $newResetPasswordLinkToken = $helper->generateResetPasswordLinkToken();
- $newResetPasswordLinkCustomerId = $helper->generateResetPasswordLinkCustomerId($customerId);
- $customer->changeResetPasswordLinkCustomerId($newResetPasswordLinkCustomerId);
- $customer->changeResetPasswordLinkToken($newResetPasswordLinkToken);
- $customer->sendPasswordResetConfirmationEmail();
- } catch (Exception $exception) {
- $this->_getSession()->addError($exception->getMessage());
- $this->_redirect('*/*/forgotpassword');
- return;
- }
- }
- $this->_getSession()
- ->addSuccess($this->_getHelper('customer')
- ->__(
- 'If there is an account associated with %s you will receive an email with a link to reset your password.',
- $this->_getHelper('customer')->escapeHtml($email),
- ));
- $this->_redirect('*/*/');
- return;
- } else {
- $this->_getSession()->addError($this->__('Please enter your email.'));
- $this->_redirect('*/*/forgotpassword');
- return;
- }
+ /**
+ * Get Helper
+ *
+ * @param string $path
+ * @return Mage_Core_Helper_Abstract
+ */
+ protected function _getHelper($path)
+ {
+ return Mage::helper($path);
}
/**
- * Display reset forgotten password form
+ * Get App
*
+ * @return Mage_Core_Model_App
*/
- public function changeForgottenAction()
+ protected function _getApp()
{
- try {
- list($customerId, $resetPasswordLinkToken) = $this->_getRestorePasswordParameters($this->_getSession());
- $this->_validateResetPasswordLinkToken($customerId, $resetPasswordLinkToken);
- $this->loadLayout();
- $this->renderLayout();
- } catch (Exception $exception) {
- $this->_getSession()->addError($this->_getHelper('customer')->__('Your password reset link has expired.'));
- $this->_redirect('*/*/forgotpassword');
- }
+ return Mage::app();
}
/**
- * Checks reset forgotten password token
+ * Dispatch Event
*
- * User is redirected on this action when he clicks on the corresponding link in password reset confirmation email.
+ * @param Mage_Customer_Model_Customer $customer
+ */
+ protected function _dispatchRegisterSuccess($customer)
+ {
+ Mage::dispatchEvent(
+ 'customer_register_success',
+ ['account_controller' => $this, 'customer' => $customer],
+ );
+ }
+
+ /**
+ * Gets customer address
*
+ * @param Mage_Customer_Model_Customer $customer
+ * @return array $errors
*/
- public function resetPasswordAction()
+ protected function _getErrorsOnCustomerAddress($customer)
{
- try {
- $customerId = (int) $this->getCustomerId();
- $resetPasswordLinkToken = (string) $this->getRequest()->getQuery('token');
+ $errors = [];
+ $address = Mage::getModel('customer/address');
+ $addressForm = Mage::getModel('customer/form');
+ $addressForm->setFormCode('customer_register_address')
+ ->setEntity($address);
- $this->_validateResetPasswordLinkToken($customerId, $resetPasswordLinkToken);
- $this->_saveRestorePasswordParameters($customerId, $resetPasswordLinkToken)
- ->_redirect('*/*/changeforgotten');
- } catch (Exception $exception) {
- $this->_getSession()->addError($this->_getHelper('customer')->__('Your password reset link has expired.'));
- $this->_redirect('*/*/forgotpassword');
+ $addressData = $addressForm->extractData($this->getRequest(), 'address', false);
+ $addressErrors = $addressForm->validateData($addressData);
+ if (is_array($addressErrors)) {
+ $errors = array_merge($errors, $addressErrors);
+ }
+ $address->setId(null)
+ ->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
+ ->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
+ $addressForm->compactData($addressData);
+ $customer->addAddress($address);
+
+ $addressErrors = $address->validate();
+ if (is_array($addressErrors)) {
+ $errors = array_merge($errors, $addressErrors);
}
+ return $errors;
}
/**
- * Reset forgotten password
- * Used to handle data received from reset forgotten password form
+ * Get model from registry by path
+ *
+ * @param string $path
+ * @return mixed
*/
- public function resetPasswordPostAction()
+ protected function _getFromRegistry($path)
{
- if (!$this->_validateFormKey()) {
- $this->_redirect('*/*/');
- return;
- }
-
- list($customerId, $resetPasswordLinkToken) = $this->_getRestorePasswordParameters($this->_getSession());
- $password = (string) $this->getRequest()->getPost('password');
- $passwordConfirmation = (string) $this->getRequest()->getPost('confirmation');
-
- try {
- $this->_validateResetPasswordLinkToken($customerId, $resetPasswordLinkToken);
- } catch (Exception $exception) {
- $this->_getSession()->addError($this->_getHelper('customer')->__('Your password reset link has expired.'));
- $this->_redirect('*/*/');
- return;
- }
-
- $errorMessages = [];
- if (iconv_strlen($password) <= 0) {
- $errorMessages[] = $this->_getHelper('customer')->__('New password field cannot be empty.');
- }
- $customer = Mage::getModel('customer/customer')->load($customerId);
-
- $customer->setPassword($password);
- $customer->setPasswordConfirmation($passwordConfirmation);
- $validationErrorMessages = $customer->validateResetPassword();
- if (is_array($validationErrorMessages)) {
- $errorMessages = array_merge($errorMessages, $validationErrorMessages);
- }
+ return Mage::registry($path);
+ }
- if (!empty($errorMessages)) {
- $this->_getSession()->setCustomerFormData($this->getRequest()->getPost());
- foreach ($errorMessages as $errorMessage) {
- $this->_getSession()->addError($errorMessage);
+ /**
+ * Add welcome message and send new account email.
+ * Returns success URL
+ *
+ * @param bool $isJustConfirmed
+ * @return string
+ * @throws Mage_Core_Model_Store_Exception
+ * @throws Mage_Core_Exception
+ */
+ protected function _welcomeCustomer(Mage_Customer_Model_Customer $customer, $isJustConfirmed = false)
+ {
+ $this->_getSession()->addSuccess(
+ $this->__('Thank you for registering with %s.', Mage::app()->getStore()->getFrontendName()),
+ );
+ if ($this->_isVatValidationEnabled()) {
+ // Show corresponding VAT message to customer
+ /** @var Mage_Customer_Helper_Address $helper */
+ $helper = $this->_getHelper('customer/address');
+ $configAddressType = $helper->getTaxCalculationAddressType();
+ $userPrompt = '';
+ switch ($configAddressType) {
+ case Mage_Customer_Model_Address_Abstract::TYPE_SHIPPING:
+ $userPrompt = $this->__(
+ 'If you are a registered VAT customer, please click here to enter you shipping address for proper VAT calculation',
+ $this->_getUrl('customer/address/edit'),
+ );
+ break;
+ default:
+ $userPrompt = $this->__(
+ 'If you are a registered VAT customer, please click here to enter you billing address for proper VAT calculation',
+ $this->_getUrl('customer/address/edit'),
+ );
}
- $this->_redirect('*/*/changeforgotten');
- return;
+ $this->_getSession()->addSuccess($userPrompt);
}
- try {
- // Empty current reset password token i.e. invalidate it
- $customer->setRpToken(null);
- $customer->setRpTokenCreatedAt(null);
- $customer->cleanPasswordsValidationData();
- $customer->setPasswordCreatedAt(time());
- $customer->setRpCustomerId(null);
- $customer->setConfirmation(null); // Set email is confirmed.
- $customer->save();
-
- $this->_getSession()->unsetData(self::TOKEN_SESSION_NAME);
- $this->_getSession()->unsetData(self::CUSTOMER_ID_SESSION_NAME);
+ $customer->sendNewAccountEmail(
+ $isJustConfirmed ? 'confirmed' : 'registered',
+ '',
+ Mage::app()->getStore()->getId(),
+ $this->getRequest()->getPost('password'),
+ );
- $this->_getSession()->addSuccess($this->_getHelper('customer')->__('Your password has been updated.'));
- $this->_redirect('*/*/login');
- } catch (Exception $exception) {
- $this->_getSession()->addException($exception, $this->__('Cannot save a new password.'));
- $this->_redirect('*/*/changeforgotten');
- return;
+ $successUrl = $this->_getUrl('*/*/index', ['_secure' => true]);
+ if ($this->_getSession()->getBeforeAuthUrl()) {
+ $successUrl = $this->_getSession()->getBeforeAuthUrl(true);
}
+ return $successUrl;
+ }
+
+ /**
+ * Get Url method
+ *
+ * @param string $url
+ * @param array $params
+ * @return string
+ */
+ protected function _getUrl($url, $params = [])
+ {
+ return Mage::getUrl($url, $params);
}
/**
@@ -938,139 +1071,6 @@ protected function _validateResetPasswordLinkToken($customerId, $resetPasswordLi
}
}
- /**
- * Forgot customer account information page
- */
- public function editAction()
- {
- $this->loadLayout();
- $this->_initLayoutMessages('customer/session');
- $this->_initLayoutMessages('catalog/session');
-
- $block = $this->getLayout()->getBlock('customer_edit');
- if ($block) {
- $block->setRefererUrl($this->_getRefererUrl());
- }
- $data = $this->_getSession()->getCustomerFormData(true);
- $customer = $this->_getSession()->getCustomer();
- if (!empty($data)) {
- $customer->addData($data);
- }
- if ($this->getRequest()->getParam('changepass') == 1) {
- $customer->setChangePassword(1);
- }
-
- $this->getLayout()->getBlock('head')->setTitle($this->__('Account Information'));
- $this->getLayout()->getBlock('messages')->setEscapeMessageFlag(true);
- $this->renderLayout();
- }
-
- /**
- * Change customer password action
- */
- public function editPostAction()
- {
- if (!$this->_validateFormKey()) {
- return $this->_redirect('*/*/edit');
- }
-
- if ($this->getRequest()->isPost()) {
- $customer = $this->_getSession()->getCustomer();
- $customer->setOldEmail($customer->getEmail());
- $customerForm = Mage::getModel('customer/form');
- $customerForm->setFormCode('customer_account_edit')
- ->setEntity($customer);
-
- $customerData = $customerForm->extractData($this->getRequest());
-
- $errors = [];
- $customerErrors = $customerForm->validateData($customerData);
- if ($customerErrors !== true) {
- $errors = array_merge($customerErrors, $errors);
- } else {
- $customerForm->compactData($customerData);
- $errors = [];
-
- if (!$customer->validatePassword($this->getRequest()->getPost('current_password'))) {
- $errors[] = $this->__('Invalid current password');
- }
-
- // If email change was requested then set flag
- $isChangeEmail = $customer->getOldEmail() !== $customer->getEmail();
- $customer->setIsChangeEmail($isChangeEmail);
-
- // If password change was requested then add it to common validation scheme
- $customer->setIsChangePassword($this->getRequest()->getParam('change_password'));
-
- if ($customer->getIsChangePassword()) {
- $newPass = $this->getRequest()->getPost('password');
- $confPass = $this->getRequest()->getPost('confirmation');
-
- if (strlen($newPass)) {
- /**
- * Set entered password and its confirmation - they
- * will be validated later to match each other and be of right length
- */
- $customer->setPassword($newPass);
- $customer->setPasswordConfirmation($confPass);
-
- // Invalidate reset password token when user changes password
- $customer->setRpToken(null);
- $customer->setRpTokenCreatedAt(null);
- $customer->setRpCustomerId(null);
- } else {
- $errors[] = $this->__('New password field cannot be empty.');
- }
- }
-
- // Validate account and compose list of errors if any
- $customerErrors = $customer->validate();
- if (is_array($customerErrors)) {
- $errors = array_merge($errors, $customerErrors);
- }
- }
-
- if (!empty($errors)) {
- $this->_getSession()->setCustomerFormData($this->getRequest()->getPost());
- foreach ($errors as $message) {
- $this->_getSession()->addError($message);
- }
- $this->_redirect('*/*/edit');
- return $this;
- }
-
- try {
- $customer->cleanPasswordsValidationData();
- $customer->setPasswordCreatedAt(time());
-
- // Reset all password reset tokens if all data was sufficient and correct on email change
- if ($customer->getIsChangeEmail()) {
- $customer->setRpToken(null);
- $customer->setRpTokenCreatedAt(null);
- }
-
- $customer->save();
- $this->_getSession()->setCustomer($customer)
- ->addSuccess($this->__('The account information has been saved.'));
-
- if ($customer->getIsChangeEmail() || $customer->getIsChangePassword()) {
- $customer->sendChangedPasswordOrEmail();
- }
-
- $this->_redirect('customer/account');
- return;
- } catch (Mage_Core_Exception $e) {
- $this->_getSession()->setCustomerFormData($this->getRequest()->getPost())
- ->addError($e->getMessage());
- } catch (Exception $e) {
- $this->_getSession()->setCustomerFormData($this->getRequest()->getPost())
- ->addException($e, $this->__('Cannot save the customer.'));
- }
- }
-
- $this->_redirect('*/*/edit');
- }
-
/**
* Filtering posted data. Converting localized data if needed
*
diff --git a/app/code/core/Mage/Customer/controllers/AddressController.php b/app/code/core/Mage/Customer/controllers/AddressController.php
index 272b707ac02..bfd5c9a1f90 100644
--- a/app/code/core/Mage/Customer/controllers/AddressController.php
+++ b/app/code/core/Mage/Customer/controllers/AddressController.php
@@ -22,16 +22,6 @@
*/
class Mage_Customer_AddressController extends Mage_Core_Controller_Front_Action
{
- /**
- * Retrieve customer session object
- *
- * @return Mage_Customer_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('customer/session');
- }
-
/**
* @inheritDoc
*/
@@ -188,4 +178,13 @@ public function deleteAction()
}
$this->getResponse()->setRedirect(Mage::getUrl('*/*/index'));
}
+ /**
+ * Retrieve customer session object
+ *
+ * @return Mage_Customer_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('customer/session');
+ }
}
diff --git a/app/code/core/Mage/Dataflow/Model/Batch.php b/app/code/core/Mage/Dataflow/Model/Batch.php
index 8a3dab70997..70051e28743 100644
--- a/app/code/core/Mage/Dataflow/Model/Batch.php
+++ b/app/code/core/Mage/Dataflow/Model/Batch.php
@@ -67,15 +67,6 @@ class Mage_Dataflow_Model_Batch extends Mage_Core_Model_Abstract
*/
protected $_batchImport;
- /**
- * Init model
- *
- */
- protected function _construct()
- {
- $this->_init('dataflow/batch');
- }
-
/**
* Retrieve prepared field list
*
@@ -115,20 +106,6 @@ public function getIoAdapter()
return $this->_ioAdapter;
}
- protected function _beforeSave()
- {
- if (is_null($this->getData('created_at'))) {
- $this->setData('created_at', Mage::getSingleton('core/date')->gmtDate());
- }
- return $this;
- }
-
- protected function _afterDelete()
- {
- $this->getIoAdapter()->clear();
- return $this;
- }
-
/**
* Retrieve Batch export model
*
@@ -197,4 +174,27 @@ public function getParams()
$data = $this->_data['params'];
return unserialize($data, ['allowed_classes' => false]);
}
+
+ /**
+ * Init model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('dataflow/batch');
+ }
+
+ protected function _beforeSave()
+ {
+ if (is_null($this->getData('created_at'))) {
+ $this->setData('created_at', Mage::getSingleton('core/date')->gmtDate());
+ }
+ return $this;
+ }
+
+ protected function _afterDelete()
+ {
+ $this->getIoAdapter()->clear();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Dataflow/Model/Convert/Container/Abstract.php b/app/code/core/Mage/Dataflow/Model/Convert/Container/Abstract.php
index 528fc554ac7..2bd5612838e 100644
--- a/app/code/core/Mage/Dataflow/Model/Convert/Container/Abstract.php
+++ b/app/code/core/Mage/Dataflow/Model/Convert/Container/Abstract.php
@@ -34,17 +34,6 @@ abstract class Mage_Dataflow_Model_Convert_Container_Abstract implements Mage_Da
protected $_position;
- /**
- * Detect serialization of data
- *
- * @param mixed $data
- * @return bool
- */
- protected function isSerialized($data)
- {
- return Mage::helper('core/string')->isSerializedArrayOrObject($data);
- }
-
public function getVar($key, $default = null)
{
if (!isset($this->_vars[$key]) || (!is_array($this->_vars[$key]) && strlen($this->_vars[$key]) == 0)) {
@@ -231,4 +220,15 @@ public function getBatchParams($key = null)
}
return $this->_batchParams;
}
+
+ /**
+ * Detect serialization of data
+ *
+ * @param mixed $data
+ * @return bool
+ */
+ protected function isSerialized($data)
+ {
+ return Mage::helper('core/string')->isSerializedArrayOrObject($data);
+ }
}
diff --git a/app/code/core/Mage/Dataflow/Model/Convert/Iterator.php b/app/code/core/Mage/Dataflow/Model/Convert/Iterator.php
index 1e7135e00b8..88b8b2ff98e 100644
--- a/app/code/core/Mage/Dataflow/Model/Convert/Iterator.php
+++ b/app/code/core/Mage/Dataflow/Model/Convert/Iterator.php
@@ -41,6 +41,16 @@ public function walk()
->walk($import->select($sessionId), $callbacks);
}
+ public function updateProgress($args)
+ {
+ $memory = !empty($args['memory']) ? $args['memory'] : '';
+ echo '';
+ echo '' . $memory . '';
+
+ return [];
+ }
+
protected function _getProgressBarHtml($sessionId, $totalRows)
{
return '
@@ -94,16 +104,6 @@ function updateProgress(sessionId, idx, time, memory) {
';
}
- public function updateProgress($args)
- {
- $memory = !empty($args['memory']) ? $args['memory'] : '';
- echo '';
- echo '' . $memory . '';
-
- return [];
- }
-
protected function _parseCallback($callback, $defaultMethod = null)
{
if (!preg_match('#^([a-z0-9_/]+)(::([a-z0-9_]+))?$#i', $callback, $match)) {
diff --git a/app/code/core/Mage/Dataflow/Model/Convert/Parser/Xml/Excel.php b/app/code/core/Mage/Dataflow/Model/Convert/Parser/Xml/Excel.php
index 372a218ef02..dd66babfd82 100644
--- a/app/code/core/Mage/Dataflow/Model/Convert/Parser/Xml/Excel.php
+++ b/app/code/core/Mage/Dataflow/Model/Convert/Parser/Xml/Excel.php
@@ -150,6 +150,66 @@ public function parse()
return $this;
}
+ public function unparse()
+ {
+ $batchExport = $this->getBatchExportModel()
+ ->setBatchId($this->getBatchModel()->getId());
+ $fieldList = $this->getBatchModel()->getFieldList();
+ $batchExportIds = $batchExport->getIdCollection();
+
+ if (!is_array($batchExportIds)) {
+ return $this;
+ }
+
+ $io = $this->getBatchModel()->getIoAdapter();
+ $io->open();
+
+ $xml = '<' . '?xml version="1.0"?' . '><' . '?mso-application progid="Excel.Sheet"?'
+ . '>'
+ . ''
+ . ''
+ . ''
+ . '';
+ $io->write($xml);
+
+ $wsName = htmlspecialchars($this->getVar('single_sheet'));
+ $wsName = !empty($wsName) ? $wsName : Mage::helper('dataflow')->__('Sheet 1');
+
+ $xml = '';
+ $io->write($xml);
+
+ if ($this->getVar('fieldnames')) {
+ $xml = $this->_getXmlString($fieldList);
+ $io->write($xml);
+ }
+
+ foreach ($batchExportIds as $batchExportId) {
+ $xmlData = [];
+ $batchExport->load($batchExportId);
+ $row = $batchExport->getBatchData();
+
+ foreach ($fieldList as $field) {
+ $xmlData[] = $row[$field] ?? '';
+ }
+ $xmlData = $this->_getXmlString($xmlData);
+ $io->write($xmlData);
+ }
+
+ $xml = '
';
+ $io->write($xml);
+ $io->close();
+
+ return $this;
+ }
+
/**
* Parse MS Excel XML string
*
@@ -247,66 +307,6 @@ protected function _saveParsedRow($xmlString)
return $this;
}
- public function unparse()
- {
- $batchExport = $this->getBatchExportModel()
- ->setBatchId($this->getBatchModel()->getId());
- $fieldList = $this->getBatchModel()->getFieldList();
- $batchExportIds = $batchExport->getIdCollection();
-
- if (!is_array($batchExportIds)) {
- return $this;
- }
-
- $io = $this->getBatchModel()->getIoAdapter();
- $io->open();
-
- $xml = '<' . '?xml version="1.0"?' . '><' . '?mso-application progid="Excel.Sheet"?'
- . '>'
- . ''
- . ''
- . ''
- . '';
- $io->write($xml);
-
- $wsName = htmlspecialchars($this->getVar('single_sheet'));
- $wsName = !empty($wsName) ? $wsName : Mage::helper('dataflow')->__('Sheet 1');
-
- $xml = '';
- $io->write($xml);
-
- if ($this->getVar('fieldnames')) {
- $xml = $this->_getXmlString($fieldList);
- $io->write($xml);
- }
-
- foreach ($batchExportIds as $batchExportId) {
- $xmlData = [];
- $batchExport->load($batchExportId);
- $row = $batchExport->getBatchData();
-
- foreach ($fieldList as $field) {
- $xmlData[] = $row[$field] ?? '';
- }
- $xmlData = $this->_getXmlString($xmlData);
- $io->write($xmlData);
- }
-
- $xml = '
';
- $io->write($xml);
- $io->close();
-
- return $this;
- }
-
/**
* Prepare and return XML string for MS Excel XML from array
*
diff --git a/app/code/core/Mage/Dataflow/Model/Profile.php b/app/code/core/Mage/Dataflow/Model/Profile.php
index 1163196d315..8a05f93f26b 100644
--- a/app/code/core/Mage/Dataflow/Model/Profile.php
+++ b/app/code/core/Mage/Dataflow/Model/Profile.php
@@ -62,198 +62,6 @@ class Mage_Dataflow_Model_Profile extends Mage_Core_Model_Abstract
*/
protected $_customerTablePermanentAttributes = ['email', 'website'];
- protected function _construct()
- {
- $this->_init('dataflow/profile');
- }
-
- protected function _afterLoad()
- {
- $guiData = '';
- if (is_string($this->getGuiData())) {
- try {
- $guiData = Mage::helper('core/unserializeArray')
- ->unserialize($this->getGuiData());
- } catch (Exception $e) {
- Mage::logException($e);
- }
- }
- $this->setGuiData($guiData);
-
- return parent::_afterLoad();
- }
-
- /**
- * @SuppressWarnings("PHPMD.ErrorControlOperator")
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
- $actionsXML = $this->getData('actions_xml');
- // @phpstan-ignore-next-line because of https://github.com/phpstan/phpstan/issues/10570
- if ($actionsXML !== null && strlen($actionsXML) < 0 &&
- @simplexml_load_string('' . $actionsXML . '', null, LIBXML_NOERROR) === false
- ) {
- Mage::throwException(Mage::helper('dataflow')->__('Actions XML is not valid.'));
- }
-
- if (is_array($this->getGuiData())) {
- $data = $this->getData();
- $guiData = $this->getGuiData();
- $charSingleList = ['\\', '/', '.', '!', '@', '#', '$', '%', '&', '*', '~', '^'];
- if (isset($guiData['file']['type']) && $guiData['file']['type'] == 'file') {
- if (empty($guiData['file']['path'])
- || (strlen($guiData['file']['path']) == 1
- && in_array($guiData['file']['path'], $charSingleList))
- ) {
- $guiData['file']['path'] = self::DEFAULT_EXPORT_PATH;
- }
- if (empty($guiData['file']['filename'])) {
- $guiData['file']['filename'] = self::DEFAULT_EXPORT_FILENAME . $data['entity_type']
- . '.' . ($guiData['parse']['type'] == 'csv' ? $guiData['parse']['type'] : 'xml');
- }
-
- //validate export available path
- $path = rtrim($guiData['file']['path'], '\\/')
- . DS . $guiData['file']['filename'];
- /** @var Mage_Core_Model_File_Validator_AvailablePath $validator */
- $validator = Mage::getModel('core/file_validator_availablePath');
- /** @var Mage_ImportExport_Helper_Data $helperImportExport */
- $helperImportExport = Mage::helper('importexport');
- $validator->setPaths($helperImportExport->getLocalValidPaths());
- if (!$validator->isValid($path)) {
- foreach ($validator->getMessages() as $message) {
- Mage::throwException($message);
- }
- }
-
- $this->setGuiData($guiData);
- }
- $this->_parseGuiData();
-
- $this->setGuiData(serialize($this->getGuiData()));
- }
-
- if ($this->_getResource()->isProfileExists($this->getName(), $this->getId())) {
- Mage::throwException(Mage::helper('dataflow')->__('Profile with the same name already exists.'));
- }
- return $this;
- }
-
- /**
- * @SuppressWarnings("PHPMD.Superglobals")
- */
- protected function _afterSave()
- {
- if ($this->getGuiData() && is_string($this->getGuiData())) {
- try {
- $guiData = Mage::helper('core/unserializeArray')
- ->unserialize($this->getGuiData());
- $this->setGuiData($guiData);
- } catch (Exception $e) {
- Mage::logException($e);
- }
- }
-
- $profileHistory = Mage::getModel('dataflow/profile_history');
-
- $adminUserId = $this->getAdminUserId();
- if ($adminUserId) {
- $profileHistory->setUserId($adminUserId);
- }
-
- $profileHistory
- ->setProfileId($this->getId())
- ->setActionCode($this->getOrigData('profile_id') ? 'update' : 'create')
- ->save();
- $csvParser = new Varien_File_Csv();
- $delimiter = trim($this->getData('gui_data/parse/delimiter') ?? '');
- if ($delimiter) {
- $csvParser->setDelimiter($delimiter);
- }
- $xmlParser = new DOMDocument();
- $newUploadedFilenames = [];
-
- if (isset($_FILES['file_1']['tmp_name']) || isset($_FILES['file_2']['tmp_name'])
- || isset($_FILES['file_3']['tmp_name'])
- ) {
- for ($index = 0; $index < 3; $index++) {
- if ($file = $_FILES['file_' . ($index + 1)]['tmp_name']) {
- $uploader = Mage::getModel('core/file_uploader', 'file_' . ($index + 1));
- $uploader->setAllowedExtensions(['csv','xml']);
- $path = Mage::app()->getConfig()->getTempVarDir() . '/import/';
- $uploader->save($path);
- $uploadFile = $uploader->getUploadedFileName();
-
- if ($_FILES['file_' . ($index + 1)]['type'] == 'text/csv'
- || $_FILES['file_' . ($index + 1)]['type'] == 'application/vnd.ms-excel'
- ) {
- $fileData = $csvParser->getData($path . $uploadFile);
- $fileData = array_shift($fileData);
- } else {
- try {
- $xmlParser->loadXML(file_get_contents($path . $uploadFile));
- $cells = $this->getNode($xmlParser, 'Worksheet')->item(0);
- $cells = $this->getNode($cells, 'Row')->item(0);
- $cells = $this->getNode($cells, 'Cell');
- $fileData = [];
- foreach ($cells as $cell) {
- $fileData[] = $this->getNode($cell, 'Data')->item(0)->nodeValue;
- }
- } catch (Exception $e) {
- foreach ($newUploadedFilenames as $k => $v) {
- unlink($path . $v);
- }
- unlink($path . $uploadFile);
- Mage::throwException(
- Mage::helper('Dataflow')->__(
- 'Upload failed. Wrong data format in file: %s.',
- $uploadFile,
- ),
- );
- }
- }
-
- if ($this->_data['entity_type'] == 'customer') {
- $attributes = $this->_customerTablePermanentAttributes;
- } else {
- $attributes = $this->_productTablePermanentAttributes;
- }
- $colsAbsent = array_diff($attributes, $fileData);
- if ($colsAbsent) {
- foreach ($newUploadedFilenames as $v) {
- unlink($path . $v);
- }
- unlink($path . $uploadFile);
- Mage::throwException(
- Mage::helper('Dataflow')->__(
- 'Upload failed. Can not find required columns: %s in file %s.',
- implode(', ', $colsAbsent),
- $uploadFile,
- ),
- );
- }
- if ($uploadFile) {
- $newFilename = 'import-' . date('YmdHis') . '-' . ($index + 1) . '_' . $uploadFile;
- rename($path . $uploadFile, $path . $newFilename);
- $newUploadedFilenames[] = $newFilename;
- }
- }
- //BOM deleting for UTF files
- if (isset($newFilename) && $newFilename) {
- $contents = file_get_contents($path . $newFilename);
- if (ord($contents[0]) == 0xEF && ord($contents[1]) == 0xBB && ord($contents[2]) == 0xBF) {
- $contents = substr($contents, 3);
- file_put_contents($path . $newFilename, $contents);
- }
- unset($contents);
- }
- }
- }
- parent::_afterSave();
- return $this;
- }
-
/**
* Run profile
*
@@ -485,6 +293,198 @@ public function _parseGuiData()
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('dataflow/profile');
+ }
+
+ protected function _afterLoad()
+ {
+ $guiData = '';
+ if (is_string($this->getGuiData())) {
+ try {
+ $guiData = Mage::helper('core/unserializeArray')
+ ->unserialize($this->getGuiData());
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+ }
+ $this->setGuiData($guiData);
+
+ return parent::_afterLoad();
+ }
+
+ /**
+ * @SuppressWarnings("PHPMD.ErrorControlOperator")
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ $actionsXML = $this->getData('actions_xml');
+ // @phpstan-ignore-next-line because of https://github.com/phpstan/phpstan/issues/10570
+ if ($actionsXML !== null && strlen($actionsXML) < 0 &&
+ @simplexml_load_string('' . $actionsXML . '', null, LIBXML_NOERROR) === false
+ ) {
+ Mage::throwException(Mage::helper('dataflow')->__('Actions XML is not valid.'));
+ }
+
+ if (is_array($this->getGuiData())) {
+ $data = $this->getData();
+ $guiData = $this->getGuiData();
+ $charSingleList = ['\\', '/', '.', '!', '@', '#', '$', '%', '&', '*', '~', '^'];
+ if (isset($guiData['file']['type']) && $guiData['file']['type'] == 'file') {
+ if (empty($guiData['file']['path'])
+ || (strlen($guiData['file']['path']) == 1
+ && in_array($guiData['file']['path'], $charSingleList))
+ ) {
+ $guiData['file']['path'] = self::DEFAULT_EXPORT_PATH;
+ }
+ if (empty($guiData['file']['filename'])) {
+ $guiData['file']['filename'] = self::DEFAULT_EXPORT_FILENAME . $data['entity_type']
+ . '.' . ($guiData['parse']['type'] == 'csv' ? $guiData['parse']['type'] : 'xml');
+ }
+
+ //validate export available path
+ $path = rtrim($guiData['file']['path'], '\\/')
+ . DS . $guiData['file']['filename'];
+ /** @var Mage_Core_Model_File_Validator_AvailablePath $validator */
+ $validator = Mage::getModel('core/file_validator_availablePath');
+ /** @var Mage_ImportExport_Helper_Data $helperImportExport */
+ $helperImportExport = Mage::helper('importexport');
+ $validator->setPaths($helperImportExport->getLocalValidPaths());
+ if (!$validator->isValid($path)) {
+ foreach ($validator->getMessages() as $message) {
+ Mage::throwException($message);
+ }
+ }
+
+ $this->setGuiData($guiData);
+ }
+ $this->_parseGuiData();
+
+ $this->setGuiData(serialize($this->getGuiData()));
+ }
+
+ if ($this->_getResource()->isProfileExists($this->getName(), $this->getId())) {
+ Mage::throwException(Mage::helper('dataflow')->__('Profile with the same name already exists.'));
+ }
+ return $this;
+ }
+
+ /**
+ * @SuppressWarnings("PHPMD.Superglobals")
+ */
+ protected function _afterSave()
+ {
+ if ($this->getGuiData() && is_string($this->getGuiData())) {
+ try {
+ $guiData = Mage::helper('core/unserializeArray')
+ ->unserialize($this->getGuiData());
+ $this->setGuiData($guiData);
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+ }
+
+ $profileHistory = Mage::getModel('dataflow/profile_history');
+
+ $adminUserId = $this->getAdminUserId();
+ if ($adminUserId) {
+ $profileHistory->setUserId($adminUserId);
+ }
+
+ $profileHistory
+ ->setProfileId($this->getId())
+ ->setActionCode($this->getOrigData('profile_id') ? 'update' : 'create')
+ ->save();
+ $csvParser = new Varien_File_Csv();
+ $delimiter = trim($this->getData('gui_data/parse/delimiter') ?? '');
+ if ($delimiter) {
+ $csvParser->setDelimiter($delimiter);
+ }
+ $xmlParser = new DOMDocument();
+ $newUploadedFilenames = [];
+
+ if (isset($_FILES['file_1']['tmp_name']) || isset($_FILES['file_2']['tmp_name'])
+ || isset($_FILES['file_3']['tmp_name'])
+ ) {
+ for ($index = 0; $index < 3; $index++) {
+ if ($file = $_FILES['file_' . ($index + 1)]['tmp_name']) {
+ $uploader = Mage::getModel('core/file_uploader', 'file_' . ($index + 1));
+ $uploader->setAllowedExtensions(['csv','xml']);
+ $path = Mage::app()->getConfig()->getTempVarDir() . '/import/';
+ $uploader->save($path);
+ $uploadFile = $uploader->getUploadedFileName();
+
+ if ($_FILES['file_' . ($index + 1)]['type'] == 'text/csv'
+ || $_FILES['file_' . ($index + 1)]['type'] == 'application/vnd.ms-excel'
+ ) {
+ $fileData = $csvParser->getData($path . $uploadFile);
+ $fileData = array_shift($fileData);
+ } else {
+ try {
+ $xmlParser->loadXML(file_get_contents($path . $uploadFile));
+ $cells = $this->getNode($xmlParser, 'Worksheet')->item(0);
+ $cells = $this->getNode($cells, 'Row')->item(0);
+ $cells = $this->getNode($cells, 'Cell');
+ $fileData = [];
+ foreach ($cells as $cell) {
+ $fileData[] = $this->getNode($cell, 'Data')->item(0)->nodeValue;
+ }
+ } catch (Exception $e) {
+ foreach ($newUploadedFilenames as $k => $v) {
+ unlink($path . $v);
+ }
+ unlink($path . $uploadFile);
+ Mage::throwException(
+ Mage::helper('Dataflow')->__(
+ 'Upload failed. Wrong data format in file: %s.',
+ $uploadFile,
+ ),
+ );
+ }
+ }
+
+ if ($this->_data['entity_type'] == 'customer') {
+ $attributes = $this->_customerTablePermanentAttributes;
+ } else {
+ $attributes = $this->_productTablePermanentAttributes;
+ }
+ $colsAbsent = array_diff($attributes, $fileData);
+ if ($colsAbsent) {
+ foreach ($newUploadedFilenames as $v) {
+ unlink($path . $v);
+ }
+ unlink($path . $uploadFile);
+ Mage::throwException(
+ Mage::helper('Dataflow')->__(
+ 'Upload failed. Can not find required columns: %s in file %s.',
+ implode(', ', $colsAbsent),
+ $uploadFile,
+ ),
+ );
+ }
+ if ($uploadFile) {
+ $newFilename = 'import-' . date('YmdHis') . '-' . ($index + 1) . '_' . $uploadFile;
+ rename($path . $uploadFile, $path . $newFilename);
+ $newUploadedFilenames[] = $newFilename;
+ }
+ }
+ //BOM deleting for UTF files
+ if (isset($newFilename) && $newFilename) {
+ $contents = file_get_contents($path . $newFilename);
+ if (ord($contents[0]) == 0xEF && ord($contents[1]) == 0xBB && ord($contents[2]) == 0xBF) {
+ $contents = substr($contents, 3);
+ file_put_contents($path . $newFilename, $contents);
+ }
+ unset($contents);
+ }
+ }
+ }
+ parent::_afterSave();
+ return $this;
+ }
+
/**
* Get node from xml object
*
diff --git a/app/code/core/Mage/Dataflow/Model/Resource/Batch/Collection.php b/app/code/core/Mage/Dataflow/Model/Resource/Batch/Collection.php
index ddc1fe22621..a86e92b02be 100644
--- a/app/code/core/Mage/Dataflow/Model/Resource/Batch/Collection.php
+++ b/app/code/core/Mage/Dataflow/Model/Resource/Batch/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Dataflow_Model_Resource_Batch_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Init model
- *
- */
- protected function _construct()
- {
- $this->_init('dataflow/batch');
- }
-
/**
* Add expire filter (for abandoned batches)
*
@@ -44,4 +35,12 @@ public function addExpireFilter()
$this->getSelect()->where('created_at < ?', $expire);
}
+ /**
+ * Init model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('dataflow/batch');
+ }
}
diff --git a/app/code/core/Mage/Dataflow/Model/Resource/Import.php b/app/code/core/Mage/Dataflow/Model/Resource/Import.php
index 9aaa6f8d61a..dccb098e5b3 100644
--- a/app/code/core/Mage/Dataflow/Model/Resource/Import.php
+++ b/app/code/core/Mage/Dataflow/Model/Resource/Import.php
@@ -22,11 +22,6 @@
*/
class Mage_Dataflow_Model_Resource_Import extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('dataflow/import', 'import_id');
- }
-
/**
* Returns all import data select by session id
*
@@ -112,4 +107,8 @@ public function loadById($importId)
->where('import_id = :import_id');
return $read->fetchRow($select, $bind);
}
+ protected function _construct()
+ {
+ $this->_init('dataflow/import', 'import_id');
+ }
}
diff --git a/app/code/core/Mage/Dataflow/Model/Resource/Profile.php b/app/code/core/Mage/Dataflow/Model/Resource/Profile.php
index 1229df2a6bb..6d6d7621707 100644
--- a/app/code/core/Mage/Dataflow/Model/Resource/Profile.php
+++ b/app/code/core/Mage/Dataflow/Model/Resource/Profile.php
@@ -22,25 +22,6 @@
*/
class Mage_Dataflow_Model_Resource_Profile extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('dataflow/profile', 'profile_id');
- }
-
- /**
- * Setting up created_at and updarted_at
- *
- * @inheritDoc
- */
- protected function _beforeSave(Mage_Core_Model_Abstract $object)
- {
- if (!$object->getCreatedAt()) {
- $object->setCreatedAt($this->formatDate(time()));
- }
- $object->setUpdatedAt($this->formatDate(time()));
- return parent::_beforeSave($object);
- }
-
/**
* Returns true if profile with name exists
*
@@ -61,4 +42,22 @@ public function isProfileExists($name, $id = null)
}
return $this->_getReadAdapter()->fetchOne($select, $bind) ? true : false;
}
+ protected function _construct()
+ {
+ $this->_init('dataflow/profile', 'profile_id');
+ }
+
+ /**
+ * Setting up created_at and updarted_at
+ *
+ * @inheritDoc
+ */
+ protected function _beforeSave(Mage_Core_Model_Abstract $object)
+ {
+ if (!$object->getCreatedAt()) {
+ $object->setCreatedAt($this->formatDate(time()));
+ }
+ $object->setUpdatedAt($this->formatDate(time()));
+ return parent::_beforeSave($object);
+ }
}
diff --git a/app/code/core/Mage/Dataflow/Model/Resource/Profile/Collection.php b/app/code/core/Mage/Dataflow/Model/Resource/Profile/Collection.php
index 195848e0d72..fc0f7dbff15 100644
--- a/app/code/core/Mage/Dataflow/Model/Resource/Profile/Collection.php
+++ b/app/code/core/Mage/Dataflow/Model/Resource/Profile/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Dataflow_Model_Resource_Profile_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define resource model and model
- *
- */
- protected function _construct()
- {
- $this->_init('dataflow/profile');
- }
-
/**
* Filter collection by specified store ids
*
@@ -43,4 +34,12 @@ public function addStoreFilter($storeIds)
->where('main_table.store_id IN (?)', [0, $storeIds]);
return $this;
}
+ /**
+ * Define resource model and model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('dataflow/profile');
+ }
}
diff --git a/app/code/core/Mage/Dataflow/Model/Resource/Profile/History/Collection.php b/app/code/core/Mage/Dataflow/Model/Resource/Profile/History/Collection.php
index a0eff65bb05..528a6e41f27 100644
--- a/app/code/core/Mage/Dataflow/Model/Resource/Profile/History/Collection.php
+++ b/app/code/core/Mage/Dataflow/Model/Resource/Profile/History/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Dataflow_Model_Resource_Profile_History_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define resource model and model
- *
- */
- protected function _construct()
- {
- $this->_init('dataflow/profile_history');
- }
-
/**
* Joins admin data to select
*
@@ -45,4 +36,12 @@ public function joinAdminUser()
);
return $this;
}
+ /**
+ * Define resource model and model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('dataflow/profile_history');
+ }
}
diff --git a/app/code/core/Mage/Directory/Helper/Data.php b/app/code/core/Mage/Directory/Helper/Data.php
index d95f210826b..5de4f86fbf4 100644
--- a/app/code/core/Mage/Directory/Helper/Data.php
+++ b/app/code/core/Mage/Directory/Helper/Data.php
@@ -172,46 +172,6 @@ public function getRegionJsonByStore($storeId = null)
return $this->_regionJson;
}
- /**
- * Get Regions for specific Countries
- * @param string|int|null $storeId
- * @return array|null
- * @throws Mage_Core_Exception
- */
- protected function _getRegions($storeId)
- {
- $countryIds = [];
-
- $countryCollection = $this->getCountryCollection()->loadByStore($storeId);
- /** @var Mage_Directory_Model_Country $country */
- foreach ($countryCollection as $country) {
- $countryIds[] = $country->getCountryId();
- }
-
- /** @var Mage_Directory_Model_Region $regionModel */
- $regionModel = $this->_factory->getModel('directory/region');
- $collection = $regionModel->getResourceCollection()
- ->addCountryFilter($countryIds)
- ->load();
-
- $regions = [
- 'config' => [
- 'show_all_regions' => $this->getShowNonRequiredState(),
- 'regions_required' => $this->getCountriesWithStatesRequired(),
- ],
- ];
- foreach ($collection as $region) {
- if (!$region->getRegionId()) {
- continue;
- }
- $regions[$region->getCountryId()][$region->getRegionId()] = [
- 'code' => $region->getCode(),
- 'name' => $this->__($region->getName()),
- ];
- }
- return $regions;
- }
-
/**
* Convert currency
*
@@ -322,4 +282,44 @@ public function getTopCountryCodes(): array
return $transportObject->getData('top_countries');
}
+
+ /**
+ * Get Regions for specific Countries
+ * @param string|int|null $storeId
+ * @return array|null
+ * @throws Mage_Core_Exception
+ */
+ protected function _getRegions($storeId)
+ {
+ $countryIds = [];
+
+ $countryCollection = $this->getCountryCollection()->loadByStore($storeId);
+ /** @var Mage_Directory_Model_Country $country */
+ foreach ($countryCollection as $country) {
+ $countryIds[] = $country->getCountryId();
+ }
+
+ /** @var Mage_Directory_Model_Region $regionModel */
+ $regionModel = $this->_factory->getModel('directory/region');
+ $collection = $regionModel->getResourceCollection()
+ ->addCountryFilter($countryIds)
+ ->load();
+
+ $regions = [
+ 'config' => [
+ 'show_all_regions' => $this->getShowNonRequiredState(),
+ 'regions_required' => $this->getCountriesWithStatesRequired(),
+ ],
+ ];
+ foreach ($collection as $region) {
+ if (!$region->getRegionId()) {
+ continue;
+ }
+ $regions[$region->getCountryId()][$region->getRegionId()] = [
+ 'code' => $region->getCode(),
+ 'name' => $this->__($region->getName()),
+ ];
+ }
+ return $regions;
+ }
}
diff --git a/app/code/core/Mage/Directory/Model/Country.php b/app/code/core/Mage/Directory/Model/Country.php
index 65b65093d1f..d636de601df 100644
--- a/app/code/core/Mage/Directory/Model/Country.php
+++ b/app/code/core/Mage/Directory/Model/Country.php
@@ -35,11 +35,6 @@ class Mage_Directory_Model_Country extends Mage_Core_Model_Abstract
{
public static $_format = [];
- protected function _construct()
- {
- $this->_init('directory/country');
- }
-
/**
* @param string $code
* @return $this
@@ -167,4 +162,9 @@ public function getName()
}
return $this->getData('name');
}
+
+ protected function _construct()
+ {
+ $this->_init('directory/country');
+ }
}
diff --git a/app/code/core/Mage/Directory/Model/Currency.php b/app/code/core/Mage/Directory/Model/Currency.php
index a67e48e7dcb..936cba0ffa0 100644
--- a/app/code/core/Mage/Directory/Model/Currency.php
+++ b/app/code/core/Mage/Directory/Model/Currency.php
@@ -50,14 +50,6 @@ class Mage_Directory_Model_Currency extends Mage_Core_Model_Abstract
*/
protected $_rates;
- /**
- * Class constructor
- */
- protected function _construct()
- {
- $this->_init('directory/currency');
- }
-
/**
* Get currency code
*
@@ -348,4 +340,12 @@ public function saveRates($rates)
$this->_getResource()->saveRates($rates);
return $this;
}
+
+ /**
+ * Class constructor
+ */
+ protected function _construct()
+ {
+ $this->_init('directory/currency');
+ }
}
diff --git a/app/code/core/Mage/Directory/Model/Currency/Import/Abstract.php b/app/code/core/Mage/Directory/Model/Currency/Import/Abstract.php
index 4b0df235a29..e19ef07dbff 100644
--- a/app/code/core/Mage/Directory/Model/Currency/Import/Abstract.php
+++ b/app/code/core/Mage/Directory/Model/Currency/Import/Abstract.php
@@ -25,6 +25,53 @@
*/
abstract class Mage_Directory_Model_Currency_Import_Abstract
{
+ /**
+ * Import rates
+ *
+ * @return Mage_Directory_Model_Currency_Import_Abstract
+ */
+ public function importRates()
+ {
+ $data = $this->fetchRates();
+ $this->_saveRates($data);
+ return $this;
+ }
+
+ /**
+ * @return array
+ * @SuppressWarnings("PHPMD.ErrorControlOperator")
+ */
+ public function fetchRates()
+ {
+ $data = [];
+ $currencies = $this->_getCurrencyCodes();
+ $defaultCurrencies = $this->_getDefaultCurrencyCodes();
+ @set_time_limit(0);
+ foreach ($defaultCurrencies as $currencyFrom) {
+ if (!isset($data[$currencyFrom])) {
+ $data[$currencyFrom] = [];
+ }
+
+ foreach ($currencies as $currencyTo) {
+ if ($currencyFrom == $currencyTo) {
+ $data[$currencyFrom][$currencyTo] = $this->_numberFormat(1);
+ } else {
+ $data[$currencyFrom][$currencyTo] = $this->_numberFormat($this->_convert($currencyFrom, $currencyTo));
+ }
+ }
+ ksort($data[$currencyFrom]);
+ }
+
+ return $data;
+ }
+
+ /**
+ * @return array
+ */
+ public function getMessages()
+ {
+ return $this->_messages;
+ }
/**
* Retrieve currency codes
*
@@ -71,46 +118,6 @@ protected function _saveRates($rates)
return $this;
}
- /**
- * Import rates
- *
- * @return Mage_Directory_Model_Currency_Import_Abstract
- */
- public function importRates()
- {
- $data = $this->fetchRates();
- $this->_saveRates($data);
- return $this;
- }
-
- /**
- * @return array
- * @SuppressWarnings("PHPMD.ErrorControlOperator")
- */
- public function fetchRates()
- {
- $data = [];
- $currencies = $this->_getCurrencyCodes();
- $defaultCurrencies = $this->_getDefaultCurrencyCodes();
- @set_time_limit(0);
- foreach ($defaultCurrencies as $currencyFrom) {
- if (!isset($data[$currencyFrom])) {
- $data[$currencyFrom] = [];
- }
-
- foreach ($currencies as $currencyTo) {
- if ($currencyFrom == $currencyTo) {
- $data[$currencyFrom][$currencyTo] = $this->_numberFormat(1);
- } else {
- $data[$currencyFrom][$currencyTo] = $this->_numberFormat($this->_convert($currencyFrom, $currencyTo));
- }
- }
- ksort($data[$currencyFrom]);
- }
-
- return $data;
- }
-
/**
* @param float $number
* @return float
@@ -119,12 +126,4 @@ protected function _numberFormat($number)
{
return $number;
}
-
- /**
- * @return array
- */
- public function getMessages()
- {
- return $this->_messages;
- }
}
diff --git a/app/code/core/Mage/Directory/Model/Currency/Import/Currencyconverterapi.php b/app/code/core/Mage/Directory/Model/Currency/Import/Currencyconverterapi.php
index 92c9662b498..ef9916b80b0 100644
--- a/app/code/core/Mage/Directory/Model/Currency/Import/Currencyconverterapi.php
+++ b/app/code/core/Mage/Directory/Model/Currency/Import/Currencyconverterapi.php
@@ -61,14 +61,6 @@ public function __construct()
$this->_httpClient = new Varien_Http_Client();
}
- /**
- * @inheritdoc
- */
- protected function _convert($currencyFrom, $currencyTo)
- {
- return 1;
- }
-
/**
* Fetching of the currency rates data
*
@@ -92,6 +84,14 @@ public function fetchRates()
return $data;
}
+ /**
+ * @inheritdoc
+ */
+ protected function _convert($currencyFrom, $currencyTo)
+ {
+ return 1;
+ }
+
/**
* Batch import of currency rates
*
diff --git a/app/code/core/Mage/Directory/Model/Currency/Import/Fixerio.php b/app/code/core/Mage/Directory/Model/Currency/Import/Fixerio.php
index 04c5a53c35b..b8a8c9beb5e 100644
--- a/app/code/core/Mage/Directory/Model/Currency/Import/Fixerio.php
+++ b/app/code/core/Mage/Directory/Model/Currency/Import/Fixerio.php
@@ -61,14 +61,6 @@ public function __construct()
$this->_httpClient = new Varien_Http_Client();
}
- /**
- * @inheritdoc
- */
- protected function _convert($currencyFrom, $currencyTo)
- {
- return 1;
- }
-
/**
* Fetching of the currency rates data
*
@@ -92,6 +84,14 @@ public function fetchRates()
return $data;
}
+ /**
+ * @inheritdoc
+ */
+ protected function _convert($currencyFrom, $currencyTo)
+ {
+ return 1;
+ }
+
/**
* Batch import of currency rates
*
diff --git a/app/code/core/Mage/Directory/Model/Region.php b/app/code/core/Mage/Directory/Model/Region.php
index 7ef9c1e25f7..b140fc1d1b3 100644
--- a/app/code/core/Mage/Directory/Model/Region.php
+++ b/app/code/core/Mage/Directory/Model/Region.php
@@ -33,11 +33,6 @@
*/
class Mage_Directory_Model_Region extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('directory/region');
- }
-
/**
* Retrieve region name
*
@@ -77,4 +72,8 @@ public function loadByName($name, $countryId)
$this->_getResource()->loadByName($this, $name, $countryId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('directory/region');
+ }
}
diff --git a/app/code/core/Mage/Directory/Model/Resource/Country.php b/app/code/core/Mage/Directory/Model/Resource/Country.php
index 1d26daa1b40..5d1efb4668b 100644
--- a/app/code/core/Mage/Directory/Model/Resource/Country.php
+++ b/app/code/core/Mage/Directory/Model/Resource/Country.php
@@ -22,11 +22,6 @@
*/
class Mage_Directory_Model_Resource_Country extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('directory/country', 'country_id');
- }
-
/**
* Load country by ISO code
*
@@ -52,4 +47,8 @@ public function loadByCode(Mage_Directory_Model_Country $country, $code)
return $this->load($country, $code, $field);
}
+ protected function _construct()
+ {
+ $this->_init('directory/country', 'country_id');
+ }
}
diff --git a/app/code/core/Mage/Directory/Model/Resource/Country/Collection.php b/app/code/core/Mage/Directory/Model/Resource/Country/Collection.php
index d1af350080c..0f0884e3c9d 100644
--- a/app/code/core/Mage/Directory/Model/Resource/Country/Collection.php
+++ b/app/code/core/Mage/Directory/Model/Resource/Country/Collection.php
@@ -26,23 +26,6 @@
*/
class Mage_Directory_Model_Resource_Country_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('directory/country');
- }
-
- /**
- * Get Store Config
- *
- * @param string $path
- * @param mixed|null $store
- * @return string
- */
- protected function _getStoreConfig($path, $store = null)
- {
- return Mage::getStoreConfig($path, $store);
- }
-
/**
* Load allowed countries for specific store
*
@@ -163,4 +146,20 @@ public function toOptionArray($emptyLabel = ' ')
return $options;
}
+ protected function _construct()
+ {
+ $this->_init('directory/country');
+ }
+
+ /**
+ * Get Store Config
+ *
+ * @param string $path
+ * @param mixed|null $store
+ * @return string
+ */
+ protected function _getStoreConfig($path, $store = null)
+ {
+ return Mage::getStoreConfig($path, $store);
+ }
}
diff --git a/app/code/core/Mage/Directory/Model/Resource/Country/Format/Collection.php b/app/code/core/Mage/Directory/Model/Resource/Country/Format/Collection.php
index 36a10188460..98d6aa082a1 100644
--- a/app/code/core/Mage/Directory/Model/Resource/Country/Format/Collection.php
+++ b/app/code/core/Mage/Directory/Model/Resource/Country/Format/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Directory_Model_Resource_Country_Format_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('directory/country_format');
- }
-
/**
* Set country filter
*
@@ -43,4 +38,8 @@ public function setCountryFilter($country)
return $this->addFieldToFilter('country_id', $countryId);
}
+ protected function _construct()
+ {
+ $this->_init('directory/country_format');
+ }
}
diff --git a/app/code/core/Mage/Directory/Model/Resource/Currency.php b/app/code/core/Mage/Directory/Model/Resource/Currency.php
index e6b6cf855d4..2440a966e4d 100644
--- a/app/code/core/Mage/Directory/Model/Resource/Currency.php
+++ b/app/code/core/Mage/Directory/Model/Resource/Currency.php
@@ -36,16 +36,6 @@ class Mage_Directory_Model_Resource_Currency extends Mage_Core_Model_Resource_Db
*/
protected static $_rateCache;
- /**
- * Define main and currency rate tables
- *
- */
- protected function _construct()
- {
- $this->_init('directory/currency', 'currency_code');
- $this->_currencyRateTable = $this->getTable('directory/currency_rate');
- }
-
/**
* Retrieve currency rate (only base=>allowed)
*
@@ -214,6 +204,16 @@ public function getCurrencyRates($currency, $toCurrencies = null)
return $rates;
}
+ /**
+ * Define main and currency rate tables
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('directory/currency', 'currency_code');
+ $this->_currencyRateTable = $this->getTable('directory/currency_rate');
+ }
+
/**
* Protected method used by getCurrencyRates() method
*
diff --git a/app/code/core/Mage/Directory/Model/Resource/Currency/Collection.php b/app/code/core/Mage/Directory/Model/Resource/Currency/Collection.php
index f0b31bb9464..0494fead346 100644
--- a/app/code/core/Mage/Directory/Model/Resource/Currency/Collection.php
+++ b/app/code/core/Mage/Directory/Model/Resource/Currency/Collection.php
@@ -37,17 +37,6 @@ class Mage_Directory_Model_Resource_Currency_Collection extends Mage_Core_Model_
*/
protected $_currencyRateTable;
- /**
- * Define resource model and tables
- */
- protected function _construct()
- {
- $this->_init('directory/currency');
-
- $this->_currencyNameTable = $this->getTable('directory/currency_name');
- $this->_currencyRateTable = $this->getTable('directory/currency_rate');
- }
-
/**
* Join currency rates by currency
*
@@ -108,4 +97,15 @@ public function toOptionArray()
{
return $this->_toOptionArray('currency_code', 'currency_name');
}
+
+ /**
+ * Define resource model and tables
+ */
+ protected function _construct()
+ {
+ $this->_init('directory/currency');
+
+ $this->_currencyNameTable = $this->getTable('directory/currency_name');
+ $this->_currencyRateTable = $this->getTable('directory/currency_rate');
+ }
}
diff --git a/app/code/core/Mage/Directory/Model/Resource/Region.php b/app/code/core/Mage/Directory/Model/Resource/Region.php
index 658e54bac94..2a548d60d24 100644
--- a/app/code/core/Mage/Directory/Model/Resource/Region.php
+++ b/app/code/core/Mage/Directory/Model/Resource/Region.php
@@ -29,6 +29,30 @@ class Mage_Directory_Model_Resource_Region extends Mage_Core_Model_Resource_Db_A
*/
protected $_regionNameTable;
+ /**
+ * Loads region by region code and country id
+ *
+ * @param string $regionCode
+ * @param string $countryId
+ * @return $this
+ */
+ public function loadByCode(Mage_Directory_Model_Region $region, $regionCode, $countryId)
+ {
+ return $this->_loadByCountry($region, $countryId, (string) $regionCode, 'code');
+ }
+
+ /**
+ * Load data by country id and default region name
+ *
+ * @param string $regionName
+ * @param string $countryId
+ * @return $this
+ */
+ public function loadByName(Mage_Directory_Model_Region $region, $regionName, $countryId)
+ {
+ return $this->_loadByCountry($region, $countryId, (string) $regionName, 'default_name');
+ }
+
/**
* Define main and locale region name tables
*
@@ -114,28 +138,4 @@ protected function _loadByCountry($object, $countryId, $value, $field)
return $this;
}
-
- /**
- * Loads region by region code and country id
- *
- * @param string $regionCode
- * @param string $countryId
- * @return $this
- */
- public function loadByCode(Mage_Directory_Model_Region $region, $regionCode, $countryId)
- {
- return $this->_loadByCountry($region, $countryId, (string) $regionCode, 'code');
- }
-
- /**
- * Load data by country id and default region name
- *
- * @param string $regionName
- * @param string $countryId
- * @return $this
- */
- public function loadByName(Mage_Directory_Model_Region $region, $regionName, $countryId)
- {
- return $this->_loadByCountry($region, $countryId, (string) $regionName, 'default_name');
- }
}
diff --git a/app/code/core/Mage/Directory/Model/Resource/Region/Collection.php b/app/code/core/Mage/Directory/Model/Resource/Region/Collection.php
index 80ffc3d8f70..8f471c9f689 100644
--- a/app/code/core/Mage/Directory/Model/Resource/Region/Collection.php
+++ b/app/code/core/Mage/Directory/Model/Resource/Region/Collection.php
@@ -36,41 +36,6 @@ class Mage_Directory_Model_Resource_Region_Collection extends Mage_Core_Model_Re
*/
protected $_countryTable;
- /**
- * Define main, country, locale region name tables
- *
- */
- protected function _construct()
- {
- $this->_init('directory/region');
-
- $this->_countryTable = $this->getTable('directory/country');
- $this->_regionNameTable = $this->getTable('directory/country_region_name');
-
- $this->addOrder('name', Varien_Data_Collection::SORT_ORDER_ASC);
- $this->addOrder('default_name', Varien_Data_Collection::SORT_ORDER_ASC);
- }
-
- /**
- * Initialize select object
- *
- * @return $this
- */
- protected function _initSelect()
- {
- parent::_initSelect();
- $locale = Mage::app()->getLocale()->getLocaleCode();
-
- $this->addBindParam(':region_locale', $locale);
- $this->getSelect()->joinLeft(
- ['rname' => $this->_regionNameTable],
- 'main_table.region_id = rname.region_id AND rname.locale = :region_locale',
- ['name'],
- );
-
- return $this;
- }
-
/**
* Filter by country_id
*
@@ -175,4 +140,39 @@ public function toOptionArray()
}
return $options;
}
+
+ /**
+ * Define main, country, locale region name tables
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('directory/region');
+
+ $this->_countryTable = $this->getTable('directory/country');
+ $this->_regionNameTable = $this->getTable('directory/country_region_name');
+
+ $this->addOrder('name', Varien_Data_Collection::SORT_ORDER_ASC);
+ $this->addOrder('default_name', Varien_Data_Collection::SORT_ORDER_ASC);
+ }
+
+ /**
+ * Initialize select object
+ *
+ * @return $this
+ */
+ protected function _initSelect()
+ {
+ parent::_initSelect();
+ $locale = Mage::app()->getLocale()->getLocaleCode();
+
+ $this->addBindParam(':region_locale', $locale);
+ $this->getSelect()->joinLeft(
+ ['rname' => $this->_regionNameTable],
+ 'main_table.region_id = rname.region_id AND rname.locale = :region_locale',
+ ['name'],
+ );
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php b/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
index f95f58226f8..e1576784314 100644
--- a/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
+++ b/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
@@ -241,29 +241,6 @@ public function getConfigMaxDownloads()
return Mage::getStoreConfig(Mage_Downloadable_Model_Link::XML_PATH_DEFAULT_DOWNLOADS_NUMBER);
}
- /**
- * Prepare block Layout
- *
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
- $this->setChild(
- 'upload_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')->addData([
- 'id' => '',
- 'label' => Mage::helper('adminhtml')->__('Upload Files'),
- 'type' => 'button',
- 'onclick' => 'Downloadable.massUploadByType(\'links\');Downloadable.massUploadByType(\'linkssample\')',
- ]),
- );
- $this->_addElementIdsMapping([
- 'container' => $this->getHtmlId() . '-new',
- 'delete' => $this->getHtmlId() . '-delete',
- ]);
- return $this;
- }
-
/**
* Retrieve Upload button HTML
*
@@ -333,4 +310,27 @@ public function getConfig()
{
return $this;
}
+
+ /**
+ * Prepare block Layout
+ *
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+ $this->setChild(
+ 'upload_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')->addData([
+ 'id' => '',
+ 'label' => Mage::helper('adminhtml')->__('Upload Files'),
+ 'type' => 'button',
+ 'onclick' => 'Downloadable.massUploadByType(\'links\');Downloadable.massUploadByType(\'linkssample\')',
+ ]),
+ );
+ $this->_addElementIdsMapping([
+ 'container' => $this->getHtmlId() . '-new',
+ 'delete' => $this->getHtmlId() . '-delete',
+ ]);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php b/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php
index d48b38bec3d..cfb0bc89b79 100644
--- a/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php
+++ b/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php
@@ -132,31 +132,6 @@ public function getSamplesTitle()
return Mage::getStoreConfig(Mage_Downloadable_Model_Sample::XML_PATH_SAMPLES_TITLE);
}
- /**
- * Prepare layout
- *
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
- $this->setChild(
- 'upload_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->addData([
- 'id' => '',
- 'label' => Mage::helper('adminhtml')->__('Upload Files'),
- 'type' => 'button',
- 'onclick' => 'Downloadable.massUploadByType(\'samples\')',
- ]),
- );
-
- $this->_addElementIdsMapping([
- 'container' => $this->getHtmlId() . '-new',
- 'delete' => $this->getHtmlId() . '-delete',
- ]);
- return $this;
- }
-
/**
* Retrieve Upload button HTML
*
@@ -221,4 +196,29 @@ public function getConfig()
{
return $this;
}
+
+ /**
+ * Prepare layout
+ *
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+ $this->setChild(
+ 'upload_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->addData([
+ 'id' => '',
+ 'label' => Mage::helper('adminhtml')->__('Upload Files'),
+ 'type' => 'button',
+ 'onclick' => 'Downloadable.massUploadByType(\'samples\')',
+ ]),
+ );
+
+ $this->_addElementIdsMapping([
+ 'container' => $this->getHtmlId() . '-new',
+ 'delete' => $this->getHtmlId() . '-delete',
+ ]);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Block/Customer/Products/List.php b/app/code/core/Mage/Downloadable/Block/Customer/Products/List.php
index d4028d7a436..7c4de124d8a 100644
--- a/app/code/core/Mage/Downloadable/Block/Customer/Products/List.php
+++ b/app/code/core/Mage/Downloadable/Block/Customer/Products/List.php
@@ -63,24 +63,6 @@ public function __construct()
$this->setItems($purchasedItems);
}
- /**
- * @return $this
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
-
- $pager = $this->getLayout()->createBlock('page/html_pager', 'downloadable.customer.products.pager')
- ->setCollection($this->getItems());
- $this->setChild('pager', $pager);
- $this->getItems()->load();
- /** @var Mage_Downloadable_Model_Link_Purchased_Item $item */
- foreach ($this->getItems() as $item) {
- $item->setPurchased($this->getPurchased()->getItemById($item->getPurchasedId()));
- }
- return $this;
- }
-
/**
* Return order view url
*
@@ -137,4 +119,22 @@ public function getIsOpenInNewWindow()
{
return Mage::getStoreConfigFlag(Mage_Downloadable_Model_Link::XML_PATH_TARGET_NEW_WINDOW);
}
+
+ /**
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+
+ $pager = $this->getLayout()->createBlock('page/html_pager', 'downloadable.customer.products.pager')
+ ->setCollection($this->getItems());
+ $this->setChild('pager', $pager);
+ $this->getItems()->load();
+ /** @var Mage_Downloadable_Model_Link_Purchased_Item $item */
+ foreach ($this->getItems() as $item) {
+ $item->setPurchased($this->getPurchased()->getItemById($item->getPurchasedId()));
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Helper/Download.php b/app/code/core/Mage/Downloadable/Helper/Download.php
index c0898f68523..c95983ead96 100644
--- a/app/code/core/Mage/Downloadable/Helper/Download.php
+++ b/app/code/core/Mage/Downloadable/Helper/Download.php
@@ -71,109 +71,6 @@ class Mage_Downloadable_Helper_Download extends Mage_Core_Helper_Abstract
*/
protected $_fileName = 'download';
- /**
- * Retrieve Resource file handle (socket, file pointer etc)
- *
- * @return resource
- */
- protected function _getHandle()
- {
- if (!$this->_resourceFile) {
- Mage::throwException(Mage::helper('downloadable')->__('Please set resource file and link type.'));
- }
-
- if (is_null($this->_handle)) {
- if ($this->_linkType == self::LINK_TYPE_URL) {
- /**
- * Validate URL
- */
- $urlProp = parse_url($this->_resourceFile);
- if (!isset($urlProp['scheme'])
- || strtolower($urlProp['scheme'] != 'http') && strtolower($urlProp['scheme'] != 'https')
- ) {
- Mage::throwException(Mage::helper('downloadable')->__('Invalid download URL scheme.'));
- }
- if (!isset($urlProp['host'])) {
- Mage::throwException(Mage::helper('downloadable')->__('Invalid download URL host.'));
- }
- switch ($urlProp['scheme']) {
- case 'https':
- $scheme = 'ssl://';
- $port = 443;
- break;
- case 'http':
- default:
- $scheme = '';
- $port = 80;
- }
- $hostname = $scheme . $urlProp['host'];
-
- if (isset($urlProp['port'])) {
- $port = (int) $urlProp['port'];
- }
-
- $path = $urlProp['path'] ?? '/';
- $query = '';
- if (isset($urlProp['query'])) {
- $query = '?' . $urlProp['query'];
- }
-
- try {
- $this->_handle = fsockopen($hostname, $port, $errno, $errstr);
- } catch (Exception $e) {
- throw $e;
- }
-
- if ($this->_handle === false) {
- Mage::throwException(Mage::helper('downloadable')->__('Cannot connect to remote host, error: %s.', $errstr));
- }
-
- $headers = 'GET ' . $path . $query . ' HTTP/1.0' . "\r\n"
- . 'Host: ' . $urlProp['host'] . "\r\n"
- . 'User-Agent: Magento ver/' . Mage::getVersion() . "\r\n"
- . 'Connection: close' . "\r\n"
- . "\r\n";
- fwrite($this->_handle, $headers);
-
- while (!feof($this->_handle)) {
- $str = fgets($this->_handle, 1024);
- if ($str == "\r\n") {
- break;
- }
- $match = [];
- if (preg_match('#^([^:]+): (.*)\s+$#', $str, $match)) {
- $k = strtolower($match[1]);
- if ($k == 'set-cookie') {
- continue;
- } else {
- $this->_urlHeaders[$k] = trim($match[2]);
- }
- } elseif (preg_match('#^HTTP/[0-9\.]+ (\d+) (.*)\s$#', $str, $match)) {
- $this->_urlHeaders['code'] = $match[1];
- $this->_urlHeaders['code-string'] = trim($match[2]);
- }
- }
-
- if (!isset($this->_urlHeaders['code']) || $this->_urlHeaders['code'] != 200) {
- Mage::throwException(Mage::helper('downloadable')->__('An error occurred while getting the requested content. Please contact the store owner.'));
- }
- } elseif ($this->_linkType == self::LINK_TYPE_FILE) {
- $this->_handle = new Varien_Io_File();
- if (!is_file($this->_resourceFile)) {
- Mage::helper('core/file_storage_database')->saveFileToFilesystem($this->_resourceFile);
- }
- $this->_handle->open(['path' => Mage::getBaseDir('var')]);
- if (!$this->_handle->fileExists($this->_resourceFile, true)) {
- Mage::throwException(Mage::helper('downloadable')->__('The file does not exist.'));
- }
- $this->_handle->streamOpen($this->_resourceFile, 'r');
- } else {
- Mage::throwException(Mage::helper('downloadable')->__('Invalid download link type.'));
- }
- }
- return $this->_handle;
- }
-
/**
* Retrieve file size in bytes
*/
@@ -302,4 +199,107 @@ public function getContentDisposition($store = null)
{
return Mage::getStoreConfig(self::XML_PATH_CONTENT_DISPOSITION, $store);
}
+
+ /**
+ * Retrieve Resource file handle (socket, file pointer etc)
+ *
+ * @return resource
+ */
+ protected function _getHandle()
+ {
+ if (!$this->_resourceFile) {
+ Mage::throwException(Mage::helper('downloadable')->__('Please set resource file and link type.'));
+ }
+
+ if (is_null($this->_handle)) {
+ if ($this->_linkType == self::LINK_TYPE_URL) {
+ /**
+ * Validate URL
+ */
+ $urlProp = parse_url($this->_resourceFile);
+ if (!isset($urlProp['scheme'])
+ || strtolower($urlProp['scheme'] != 'http') && strtolower($urlProp['scheme'] != 'https')
+ ) {
+ Mage::throwException(Mage::helper('downloadable')->__('Invalid download URL scheme.'));
+ }
+ if (!isset($urlProp['host'])) {
+ Mage::throwException(Mage::helper('downloadable')->__('Invalid download URL host.'));
+ }
+ switch ($urlProp['scheme']) {
+ case 'https':
+ $scheme = 'ssl://';
+ $port = 443;
+ break;
+ case 'http':
+ default:
+ $scheme = '';
+ $port = 80;
+ }
+ $hostname = $scheme . $urlProp['host'];
+
+ if (isset($urlProp['port'])) {
+ $port = (int) $urlProp['port'];
+ }
+
+ $path = $urlProp['path'] ?? '/';
+ $query = '';
+ if (isset($urlProp['query'])) {
+ $query = '?' . $urlProp['query'];
+ }
+
+ try {
+ $this->_handle = fsockopen($hostname, $port, $errno, $errstr);
+ } catch (Exception $e) {
+ throw $e;
+ }
+
+ if ($this->_handle === false) {
+ Mage::throwException(Mage::helper('downloadable')->__('Cannot connect to remote host, error: %s.', $errstr));
+ }
+
+ $headers = 'GET ' . $path . $query . ' HTTP/1.0' . "\r\n"
+ . 'Host: ' . $urlProp['host'] . "\r\n"
+ . 'User-Agent: Magento ver/' . Mage::getVersion() . "\r\n"
+ . 'Connection: close' . "\r\n"
+ . "\r\n";
+ fwrite($this->_handle, $headers);
+
+ while (!feof($this->_handle)) {
+ $str = fgets($this->_handle, 1024);
+ if ($str == "\r\n") {
+ break;
+ }
+ $match = [];
+ if (preg_match('#^([^:]+): (.*)\s+$#', $str, $match)) {
+ $k = strtolower($match[1]);
+ if ($k == 'set-cookie') {
+ continue;
+ } else {
+ $this->_urlHeaders[$k] = trim($match[2]);
+ }
+ } elseif (preg_match('#^HTTP/[0-9\.]+ (\d+) (.*)\s$#', $str, $match)) {
+ $this->_urlHeaders['code'] = $match[1];
+ $this->_urlHeaders['code-string'] = trim($match[2]);
+ }
+ }
+
+ if (!isset($this->_urlHeaders['code']) || $this->_urlHeaders['code'] != 200) {
+ Mage::throwException(Mage::helper('downloadable')->__('An error occurred while getting the requested content. Please contact the store owner.'));
+ }
+ } elseif ($this->_linkType == self::LINK_TYPE_FILE) {
+ $this->_handle = new Varien_Io_File();
+ if (!is_file($this->_resourceFile)) {
+ Mage::helper('core/file_storage_database')->saveFileToFilesystem($this->_resourceFile);
+ }
+ $this->_handle->open(['path' => Mage::getBaseDir('var')]);
+ if (!$this->_handle->fileExists($this->_resourceFile, true)) {
+ Mage::throwException(Mage::helper('downloadable')->__('The file does not exist.'));
+ }
+ $this->_handle->streamOpen($this->_resourceFile, 'r');
+ } else {
+ Mage::throwException(Mage::helper('downloadable')->__('Invalid download link type.'));
+ }
+ }
+ return $this->_handle;
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Helper/File.php b/app/code/core/Mage/Downloadable/Helper/File.php
index 9bb3da9c969..a209ba6c160 100644
--- a/app/code/core/Mage/Downloadable/Helper/File.php
+++ b/app/code/core/Mage/Downloadable/Helper/File.php
@@ -43,18 +43,6 @@ public function __construct()
$this->_mimeTypes = $this->_getFileHelper()->getMimeTypes();
}
- /**
- * @return Mage_Uploader_Helper_File
- */
- protected function _getFileHelper()
- {
- if (!$this->_fileHelper) {
- $this->_fileHelper = Mage::helper('uploader/file');
- }
-
- return $this->_fileHelper;
- }
-
/**
* Checking file for moving and move it
*
@@ -83,44 +71,6 @@ public function moveFileFromTmp($baseTmpPath, $basePath, $file)
return '';
}
- /**
- * Move file from tmp path to base path
- *
- * @param string $baseTmpPath
- * @param string $basePath
- * @param string $file
- * @return string
- */
- protected function _moveFileFromTmp($baseTmpPath, $basePath, $file)
- {
- $ioObject = new Varien_Io_File();
- $destDirectory = dirname($this->getFilePath($basePath, $file));
- try {
- $ioObject->open(['path' => $destDirectory]);
- } catch (Exception $e) {
- $ioObject->mkdir($destDirectory, 0777, true);
- $ioObject->open(['path' => $destDirectory]);
- }
-
- if (strrpos($file, '.tmp') == strlen($file) - 4) {
- $file = substr($file, 0, -4);
- }
-
- $destFile = dirname($file) . $ioObject->dirsep()
- . Mage_Core_Model_File_Uploader::getNewFileName($this->getFilePath($basePath, $file));
-
- Mage::helper('core/file_storage_database')->copyFile(
- $this->getFilePath($baseTmpPath, $file),
- $this->getFilePath($basePath, $destFile),
- );
-
- $result = $ioObject->mv(
- $this->getFilePath($baseTmpPath, $file),
- $this->getFilePath($basePath, $destFile),
- );
- return str_replace($ioObject->dirsep(), '/', $destFile);
- }
-
/**
* Return full path to file
*
@@ -143,17 +93,6 @@ public function getFilePath($path, $file)
return $path . DS . $file;
}
- /**
- * Replace slashes with directory separator
- *
- * @param string $file
- * @return string
- */
- protected function _prepareFileForPath($file)
- {
- return str_replace('/', DS, $file);
- }
-
/**
* Return file name form file path
*
@@ -179,18 +118,6 @@ public function getFileType($filePath)
return $this->_getFileTypeByExt($ext);
}
- /**
- * Get MIME type by file extension
- *
- * @param string $ext
- * @return string
- * @deprecated
- */
- protected function _getFileTypeByExt($ext)
- {
- return $this->_getFileHelper()->getMimeTypeByExtension($ext);
- }
-
/**
* Get all MIME types
*
@@ -210,4 +137,77 @@ public function getAllMineTypes()
{
return $this->_mimeTypes;
}
+
+ /**
+ * @return Mage_Uploader_Helper_File
+ */
+ protected function _getFileHelper()
+ {
+ if (!$this->_fileHelper) {
+ $this->_fileHelper = Mage::helper('uploader/file');
+ }
+
+ return $this->_fileHelper;
+ }
+
+ /**
+ * Move file from tmp path to base path
+ *
+ * @param string $baseTmpPath
+ * @param string $basePath
+ * @param string $file
+ * @return string
+ */
+ protected function _moveFileFromTmp($baseTmpPath, $basePath, $file)
+ {
+ $ioObject = new Varien_Io_File();
+ $destDirectory = dirname($this->getFilePath($basePath, $file));
+ try {
+ $ioObject->open(['path' => $destDirectory]);
+ } catch (Exception $e) {
+ $ioObject->mkdir($destDirectory, 0777, true);
+ $ioObject->open(['path' => $destDirectory]);
+ }
+
+ if (strrpos($file, '.tmp') == strlen($file) - 4) {
+ $file = substr($file, 0, -4);
+ }
+
+ $destFile = dirname($file) . $ioObject->dirsep()
+ . Mage_Core_Model_File_Uploader::getNewFileName($this->getFilePath($basePath, $file));
+
+ Mage::helper('core/file_storage_database')->copyFile(
+ $this->getFilePath($baseTmpPath, $file),
+ $this->getFilePath($basePath, $destFile),
+ );
+
+ $result = $ioObject->mv(
+ $this->getFilePath($baseTmpPath, $file),
+ $this->getFilePath($basePath, $destFile),
+ );
+ return str_replace($ioObject->dirsep(), '/', $destFile);
+ }
+
+ /**
+ * Replace slashes with directory separator
+ *
+ * @param string $file
+ * @return string
+ */
+ protected function _prepareFileForPath($file)
+ {
+ return str_replace('/', DS, $file);
+ }
+
+ /**
+ * Get MIME type by file extension
+ *
+ * @param string $ext
+ * @return string
+ * @deprecated
+ */
+ protected function _getFileTypeByExt($ext)
+ {
+ return $this->_getFileHelper()->getMimeTypeByExtension($ext);
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Link.php b/app/code/core/Mage/Downloadable/Model/Link.php
index dc9bed99820..287834aeb64 100644
--- a/app/code/core/Mage/Downloadable/Model/Link.php
+++ b/app/code/core/Mage/Downloadable/Model/Link.php
@@ -73,12 +73,6 @@ class Mage_Downloadable_Model_Link extends Mage_Core_Model_Abstract
public const LINK_SHAREABLE_NO = 0;
public const LINK_SHAREABLE_CONFIG = 2;
- protected function _construct()
- {
- $this->_init('downloadable/link');
- parent::_construct();
- }
-
/**
* Return link files path
*
@@ -89,15 +83,6 @@ public static function getLinkDir()
return Mage::getBaseDir();
}
- /**
- * @inheritDoc
- */
- protected function _afterSave()
- {
- $this->getResource()->saveItemTitleAndPrice($this);
- return parent::_afterSave();
- }
-
/**
* Retrieve base temporary path
*
@@ -150,4 +135,19 @@ public function getSearchableData($productId, $storeId)
return $this->_getResource()
->getSearchableData($productId, $storeId);
}
+
+ protected function _construct()
+ {
+ $this->_init('downloadable/link');
+ parent::_construct();
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _afterSave()
+ {
+ $this->getResource()->saveItemTitleAndPrice($this);
+ return parent::_afterSave();
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Link/Api.php b/app/code/core/Mage/Downloadable/Model/Link/Api.php
index 43dd422b806..16c97f1b9de 100644
--- a/app/code/core/Mage/Downloadable/Model/Link/Api.php
+++ b/app/code/core/Mage/Downloadable/Model/Link/Api.php
@@ -22,59 +22,6 @@
*/
class Mage_Downloadable_Model_Link_Api extends Mage_Catalog_Model_Api_Resource
{
- /**
- * Return validator instance
- *
- * @return Mage_Downloadable_Model_Link_Api_Validator
- */
- protected function _getValidator()
- {
- return Mage::getSingleton('downloadable/link_api_validator');
- }
-
- /**
- * Decode file from base64 and upload it to donwloadable 'tmp' folder
- *
- * @param array $fileInfo
- * @param string $type
- * @return string
- */
- protected function _uploadFile($fileInfo, $type)
- {
- $tmpPath = '';
- if ($type == 'sample') {
- $tmpPath = Mage_Downloadable_Model_Sample::getBaseTmpPath();
- } elseif ($type == 'link') {
- $tmpPath = Mage_Downloadable_Model_Link::getBaseTmpPath();
- } elseif ($type == 'link_samples') {
- $tmpPath = Mage_Downloadable_Model_Link::getBaseSampleTmpPath();
- }
-
- $result = [];
- try {
- /** @var Mage_Downloadable_Model_Link_Api_Uploader $uploader */
- $uploader = Mage::getModel('downloadable/link_api_uploader', $fileInfo);
- $uploader->setAllowRenameFiles(true);
- $uploader->setFilesDispersion(true);
- $result = $uploader->save($tmpPath);
-
- if (isset($result['file'])) {
- $fullPath = rtrim($tmpPath, DS) . DS . ltrim($result['file'], DS);
- Mage::helper('core/file_storage_database')->saveFile($fullPath);
- }
- } catch (Exception $e) {
- if ($e->getMessage() != '') {
- $this->_fault('upload_failed', $e->getMessage());
- } else {
- $this->_fault($e->getCode());
- }
- }
-
- $result['status'] = 'new';
- $result['name'] = substr($result['file'], strrpos($result['file'], '/') + 1);
- return Mage::helper('core')->jsonEncode([$result]);
- }
-
/**
* Add downloadable content to product
*
@@ -249,6 +196,58 @@ public function remove($linkId, $resourceType)
return true;
}
+ /**
+ * Return validator instance
+ *
+ * @return Mage_Downloadable_Model_Link_Api_Validator
+ */
+ protected function _getValidator()
+ {
+ return Mage::getSingleton('downloadable/link_api_validator');
+ }
+
+ /**
+ * Decode file from base64 and upload it to donwloadable 'tmp' folder
+ *
+ * @param array $fileInfo
+ * @param string $type
+ * @return string
+ */
+ protected function _uploadFile($fileInfo, $type)
+ {
+ $tmpPath = '';
+ if ($type == 'sample') {
+ $tmpPath = Mage_Downloadable_Model_Sample::getBaseTmpPath();
+ } elseif ($type == 'link') {
+ $tmpPath = Mage_Downloadable_Model_Link::getBaseTmpPath();
+ } elseif ($type == 'link_samples') {
+ $tmpPath = Mage_Downloadable_Model_Link::getBaseSampleTmpPath();
+ }
+
+ $result = [];
+ try {
+ /** @var Mage_Downloadable_Model_Link_Api_Uploader $uploader */
+ $uploader = Mage::getModel('downloadable/link_api_uploader', $fileInfo);
+ $uploader->setAllowRenameFiles(true);
+ $uploader->setFilesDispersion(true);
+ $result = $uploader->save($tmpPath);
+
+ if (isset($result['file'])) {
+ $fullPath = rtrim($tmpPath, DS) . DS . ltrim($result['file'], DS);
+ Mage::helper('core/file_storage_database')->saveFile($fullPath);
+ }
+ } catch (Exception $e) {
+ if ($e->getMessage() != '') {
+ $this->_fault('upload_failed', $e->getMessage());
+ } else {
+ $this->_fault($e->getCode());
+ }
+ }
+
+ $result['status'] = 'new';
+ $result['name'] = substr($result['file'], strrpos($result['file'], '/') + 1);
+ return Mage::helper('core')->jsonEncode([$result]);
+ }
/**
* Return loaded downloadable product instance
diff --git a/app/code/core/Mage/Downloadable/Model/Link/Api/Uploader.php b/app/code/core/Mage/Downloadable/Model/Link/Api/Uploader.php
index ea2a038cf51..1d72ce50664 100644
--- a/app/code/core/Mage/Downloadable/Model/Link/Api/Uploader.php
+++ b/app/code/core/Mage/Downloadable/Model/Link/Api/Uploader.php
@@ -22,6 +22,10 @@
*/
class Mage_Downloadable_Model_Link_Api_Uploader extends Mage_Core_Model_File_Uploader
{
+ /**
+ * Default file type
+ */
+ public const DEFAULT_FILE_TYPE = 'application/octet-stream';
/**
* Filename prefix
*
@@ -29,11 +33,6 @@ class Mage_Downloadable_Model_Link_Api_Uploader extends Mage_Core_Model_File_Upl
*/
protected $_filePrefix = 'Api';
- /**
- * Default file type
- */
- public const DEFAULT_FILE_TYPE = 'application/octet-stream';
-
/**
* Check if the uploaded file exists
*
@@ -50,6 +49,18 @@ public function __construct($file)
}
}
+ /**
+ * Moves a file
+ *
+ * @param string $sourceFile
+ * @param string $destinationFile
+ * @return bool
+ */
+ protected function _moveFile($sourceFile, $destinationFile)
+ {
+ return rename($sourceFile, $destinationFile);
+ }
+
/**
* Sets uploaded file info and decodes the file
*
@@ -100,16 +111,4 @@ private function _getTmpFilePath()
{
return tempnam(sys_get_temp_dir(), $this->_filePrefix);
}
-
- /**
- * Moves a file
- *
- * @param string $sourceFile
- * @param string $destinationFile
- * @return bool
- */
- protected function _moveFile($sourceFile, $destinationFile)
- {
- return rename($sourceFile, $destinationFile);
- }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Link/Api/V2.php b/app/code/core/Mage/Downloadable/Model/Link/Api/V2.php
index 670f9a10905..7ffd99a7177 100644
--- a/app/code/core/Mage/Downloadable/Model/Link/Api/V2.php
+++ b/app/code/core/Mage/Downloadable/Model/Link/Api/V2.php
@@ -22,22 +22,6 @@
*/
class Mage_Downloadable_Model_Link_Api_V2 extends Mage_Downloadable_Model_Link_Api
{
- /**
- * Clean the object, leave only property values
- *
- * @param object $var
- * @param-out array $var
- */
- protected function _prepareData(&$var)
- {
- if (is_object($var)) {
- $var = get_object_vars($var);
- foreach ($var as $key => &$value) {
- $this->_prepareData($value);
- }
- }
- }
-
/**
* Add downloadable content to product
*
@@ -53,4 +37,19 @@ public function add($productId, $resource, $resourceType, $store = null, $identi
$this->_prepareData($resource);
return parent::add($productId, $resource, $resourceType, $store, $identifierType);
}
+ /**
+ * Clean the object, leave only property values
+ *
+ * @param object $var
+ * @param-out array $var
+ */
+ protected function _prepareData(&$var)
+ {
+ if (is_object($var)) {
+ $var = get_object_vars($var);
+ foreach ($var as $key => &$value) {
+ $this->_prepareData($value);
+ }
+ }
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Link/Api/Validator.php b/app/code/core/Mage/Downloadable/Model/Link/Api/Validator.php
index 49fdf943deb..d99d0d9b042 100644
--- a/app/code/core/Mage/Downloadable/Model/Link/Api/Validator.php
+++ b/app/code/core/Mage/Downloadable/Model/Link/Api/Validator.php
@@ -154,25 +154,6 @@ public function validateFileDetails(&$var)
}
}
- /**
- * Runs all checks.
- *
- * @param array $resource
- * @param array $fields
- */
- protected function _dispatch(&$resource, $fields)
- {
- foreach ($fields as $name => $validator) {
- if (is_string($validator) && strlen($validator) > 0 && array_key_exists($name, $resource)) {
- $call = 'validate' . $validator;
- $this->$call($resource[$name]);
- }
- if (is_array($validator)) {
- $this->_dispatch($resource[$name], $validator);
- }
- }
- }
-
/**
* Validate variable, in case of fault loads default entity.
*
@@ -272,4 +253,23 @@ public function validateUploadType(&$var)
{
$var = in_array($var, $this->_uploadTypes) ? $var : 'file';
}
+
+ /**
+ * Runs all checks.
+ *
+ * @param array $resource
+ * @param array $fields
+ */
+ protected function _dispatch(&$resource, $fields)
+ {
+ foreach ($fields as $name => $validator) {
+ if (is_string($validator) && strlen($validator) > 0 && array_key_exists($name, $resource)) {
+ $call = 'validate' . $validator;
+ $this->$call($resource[$name]);
+ }
+ if (is_array($validator)) {
+ $this->_dispatch($resource[$name], $validator);
+ }
+ }
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Link/Purchased.php b/app/code/core/Mage/Downloadable/Model/Link/Purchased.php
index adba75b6ed9..01543d09b31 100644
--- a/app/code/core/Mage/Downloadable/Model/Link/Purchased.php
+++ b/app/code/core/Mage/Downloadable/Model/Link/Purchased.php
@@ -44,12 +44,6 @@
*/
class Mage_Downloadable_Model_Link_Purchased extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('downloadable/link_purchased');
- parent::_construct();
- }
-
/**
* Check order id
*
@@ -64,4 +58,9 @@ public function _beforeSave()
}
return parent::_beforeSave();
}
+ protected function _construct()
+ {
+ $this->_init('downloadable/link_purchased');
+ parent::_construct();
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Link/Purchased/Item.php b/app/code/core/Mage/Downloadable/Model/Link/Purchased/Item.php
index f54daa71f29..a3f03f37173 100644
--- a/app/code/core/Mage/Downloadable/Model/Link/Purchased/Item.php
+++ b/app/code/core/Mage/Downloadable/Model/Link/Purchased/Item.php
@@ -66,12 +66,6 @@ class Mage_Downloadable_Model_Link_Purchased_Item extends Mage_Core_Model_Abstra
public const LINK_STATUS_PENDING_PAYMENT = 'pending_payment';
public const LINK_STATUS_PAYMENT_REVIEW = 'payment_review';
- protected function _construct()
- {
- $this->_init('downloadable/link_purchased_item');
- parent::_construct();
- }
-
/**
* Check order item id
*
@@ -86,4 +80,10 @@ public function _beforeSave()
}
return parent::_beforeSave();
}
+
+ protected function _construct()
+ {
+ $this->_init('downloadable/link_purchased_item');
+ parent::_construct();
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Product/Type.php b/app/code/core/Mage/Downloadable/Model/Product/Type.php
index f4aeab5a6af..808d564bef0 100644
--- a/app/code/core/Mage/Downloadable/Model/Product/Type.php
+++ b/app/code/core/Mage/Downloadable/Model/Product/Type.php
@@ -263,56 +263,6 @@ public function save($product = null)
return $this;
}
- /**
- * Prepare product and its configuration to be added to some products list.
- * Perform standard preparation process and then prepare options for downloadable links.
- *
- * @param Mage_Catalog_Model_Product $product
- * @param string $processMode
- * @return array|string
- */
- protected function _prepareProduct(Varien_Object $buyRequest, $product, $processMode)
- {
- $result = parent::_prepareProduct($buyRequest, $product, $processMode);
-
- if (is_string($result)) {
- return $result;
- }
- // if adding product from admin area we add all links to product
- $originalLinksPurchasedSeparately = null;
- if ($this->getProduct($product)->getSkipCheckRequiredOption()) {
- $originalLinksPurchasedSeparately = $this->getProduct($product)
- ->getLinksPurchasedSeparately();
- $this->getProduct($product)->setLinksPurchasedSeparately(false);
- }
- $preparedLinks = [];
- if ($this->getProduct($product)->getLinksPurchasedSeparately()) {
- if ($links = $buyRequest->getLinks()) {
- foreach ($this->getLinks($product) as $link) {
- if (in_array($link->getId(), $links)) {
- $preparedLinks[] = $link->getId();
- }
- }
- }
- } else {
- foreach ($this->getLinks($product) as $link) {
- $preparedLinks[] = $link->getId();
- }
- }
- if ($originalLinksPurchasedSeparately !== null) {
- $this->getProduct($product)
- ->setLinksPurchasedSeparately($originalLinksPurchasedSeparately);
- }
- if ($preparedLinks) {
- $this->getProduct($product)->addCustomOption('downloadable_link_ids', implode(',', $preparedLinks));
- return $result;
- }
- if ($this->getLinkSelectionRequired($product) && $this->_isStrictProcessMode($processMode)) {
- return Mage::helper('downloadable')->__('Please specify product link(s).');
- }
- return $result;
- }
-
/**
* Check if product can be bought
*
@@ -468,4 +418,54 @@ public function canConfigure($product = null)
{
return $this->hasLinks($product) && $this->getProduct($product)->getLinksPurchasedSeparately();
}
+
+ /**
+ * Prepare product and its configuration to be added to some products list.
+ * Perform standard preparation process and then prepare options for downloadable links.
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param string $processMode
+ * @return array|string
+ */
+ protected function _prepareProduct(Varien_Object $buyRequest, $product, $processMode)
+ {
+ $result = parent::_prepareProduct($buyRequest, $product, $processMode);
+
+ if (is_string($result)) {
+ return $result;
+ }
+ // if adding product from admin area we add all links to product
+ $originalLinksPurchasedSeparately = null;
+ if ($this->getProduct($product)->getSkipCheckRequiredOption()) {
+ $originalLinksPurchasedSeparately = $this->getProduct($product)
+ ->getLinksPurchasedSeparately();
+ $this->getProduct($product)->setLinksPurchasedSeparately(false);
+ }
+ $preparedLinks = [];
+ if ($this->getProduct($product)->getLinksPurchasedSeparately()) {
+ if ($links = $buyRequest->getLinks()) {
+ foreach ($this->getLinks($product) as $link) {
+ if (in_array($link->getId(), $links)) {
+ $preparedLinks[] = $link->getId();
+ }
+ }
+ }
+ } else {
+ foreach ($this->getLinks($product) as $link) {
+ $preparedLinks[] = $link->getId();
+ }
+ }
+ if ($originalLinksPurchasedSeparately !== null) {
+ $this->getProduct($product)
+ ->setLinksPurchasedSeparately($originalLinksPurchasedSeparately);
+ }
+ if ($preparedLinks) {
+ $this->getProduct($product)->addCustomOption('downloadable_link_ids', implode(',', $preparedLinks));
+ return $result;
+ }
+ if ($this->getLinkSelectionRequired($product) && $this->_isStrictProcessMode($processMode)) {
+ return Mage::helper('downloadable')->__('Please specify product link(s).');
+ }
+ return $result;
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Resource/Link.php b/app/code/core/Mage/Downloadable/Model/Resource/Link.php
index e50996fc895..3339550d05f 100644
--- a/app/code/core/Mage/Downloadable/Model/Resource/Link.php
+++ b/app/code/core/Mage/Downloadable/Model/Resource/Link.php
@@ -22,11 +22,6 @@
*/
class Mage_Downloadable_Model_Resource_Link extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('downloadable/link', 'link_id');
- }
-
/**
* Save title and price of link item
*
@@ -205,4 +200,8 @@ public function getSearchableData($productId, $storeId)
return $adapter->fetchCol($select, $bind);
}
+ protected function _construct()
+ {
+ $this->_init('downloadable/link', 'link_id');
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Resource/Link/Collection.php b/app/code/core/Mage/Downloadable/Model/Resource/Link/Collection.php
index e416d299824..6108719cd16 100644
--- a/app/code/core/Mage/Downloadable/Model/Resource/Link/Collection.php
+++ b/app/code/core/Mage/Downloadable/Model/Resource/Link/Collection.php
@@ -22,14 +22,6 @@
*/
class Mage_Downloadable_Model_Resource_Link_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Init resource model
- */
- protected function _construct()
- {
- $this->_init('downloadable/link');
- }
-
/**
* Method for product filter
*
@@ -100,4 +92,11 @@ public function addPriceToResult($websiteId)
return $this;
}
+ /**
+ * Init resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('downloadable/link');
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Resource/Link/Purchased/Collection.php b/app/code/core/Mage/Downloadable/Model/Resource/Link/Purchased/Collection.php
index 9b47d6b06e1..80c4e03ae29 100644
--- a/app/code/core/Mage/Downloadable/Model/Resource/Link/Purchased/Collection.php
+++ b/app/code/core/Mage/Downloadable/Model/Resource/Link/Purchased/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Downloadable_Model_Resource_Link_Purchased_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Init resource model
- *
- */
- protected function _construct()
- {
- $this->_init('downloadable/link_purchased');
- }
-
/**
* Add purchased items to collection
*
@@ -45,4 +36,12 @@ public function addPurchasedItemsToResult()
);
return $this;
}
+ /**
+ * Init resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('downloadable/link_purchased');
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Resource/Sample.php b/app/code/core/Mage/Downloadable/Model/Resource/Sample.php
index 35c0a548c00..583b1d3a679 100644
--- a/app/code/core/Mage/Downloadable/Model/Resource/Sample.php
+++ b/app/code/core/Mage/Downloadable/Model/Resource/Sample.php
@@ -22,11 +22,6 @@
*/
class Mage_Downloadable_Model_Resource_Sample extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('downloadable/sample', 'sample_id');
- }
-
/**
* Save title of sample item in store scope
*
@@ -135,4 +130,8 @@ public function getSearchableData($productId, $storeId)
return $adapter->fetchCol($select, $bind);
}
+ protected function _construct()
+ {
+ $this->_init('downloadable/sample', 'sample_id');
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Resource/Sample/Collection.php b/app/code/core/Mage/Downloadable/Model/Resource/Sample/Collection.php
index d4c9d61313c..db204562a19 100644
--- a/app/code/core/Mage/Downloadable/Model/Resource/Sample/Collection.php
+++ b/app/code/core/Mage/Downloadable/Model/Resource/Sample/Collection.php
@@ -22,14 +22,6 @@
*/
class Mage_Downloadable_Model_Resource_Sample_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Init resource model
- */
- protected function _construct()
- {
- $this->_init('downloadable/sample');
- }
-
/**
* Method for product filter
*
@@ -75,4 +67,11 @@ public function addTitleToResult($storeId = 0)
return $this;
}
+ /**
+ * Init resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('downloadable/sample');
+ }
}
diff --git a/app/code/core/Mage/Downloadable/Model/Sample.php b/app/code/core/Mage/Downloadable/Model/Sample.php
index 6f58d727b64..ae5aa586237 100644
--- a/app/code/core/Mage/Downloadable/Model/Sample.php
+++ b/app/code/core/Mage/Downloadable/Model/Sample.php
@@ -44,16 +44,6 @@ class Mage_Downloadable_Model_Sample extends Mage_Core_Model_Abstract
{
public const XML_PATH_SAMPLES_TITLE = 'catalog/downloadable/samples_title';
- /**
- * Initialize resource
- *
- */
- protected function _construct()
- {
- $this->_init('downloadable/sample');
- parent::_construct();
- }
-
/**
* Return sample files path
*
@@ -64,18 +54,6 @@ public static function getSampleDir()
return Mage::getBaseDir();
}
- /**
- * After save process
- *
- * @inheritDoc
- */
- protected function _afterSave()
- {
- $this->getResource()
- ->saveItemTitle($this);
- return parent::_afterSave();
- }
-
/**
* Retrieve sample URL
*
@@ -122,4 +100,26 @@ public function getSearchableData($productId, $storeId)
return $this->_getResource()
->getSearchableData($productId, $storeId);
}
+
+ /**
+ * Initialize resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('downloadable/sample');
+ parent::_construct();
+ }
+
+ /**
+ * After save process
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave()
+ {
+ $this->getResource()
+ ->saveItemTitle($this);
+ return parent::_afterSave();
+ }
}
diff --git a/app/code/core/Mage/Downloadable/controllers/Adminhtml/Downloadable/Product/EditController.php b/app/code/core/Mage/Downloadable/controllers/Adminhtml/Downloadable/Product/EditController.php
index 0ae79184d2f..e6541705c2f 100644
--- a/app/code/core/Mage/Downloadable/controllers/Adminhtml/Downloadable/Product/EditController.php
+++ b/app/code/core/Mage/Downloadable/controllers/Adminhtml/Downloadable/Product/EditController.php
@@ -24,11 +24,6 @@
*/
class Mage_Downloadable_Adminhtml_Downloadable_Product_EditController extends Mage_Adminhtml_Catalog_ProductController
{
- protected function _construct()
- {
- $this->setUsedModuleName('Mage_Downloadable');
- }
-
/**
* Load downloadable tab fieldsets
*
@@ -42,6 +37,41 @@ public function formAction()
);
}
+ /**
+ * Download link action
+ *
+ * @SuppressWarnings("PHPMD.ExitExpression")
+ */
+ public function linkAction()
+ {
+ $linkId = $this->getRequest()->getParam('id', 0);
+ $link = Mage::getModel('downloadable/link')->load($linkId);
+ if ($link->getId()) {
+ $resource = '';
+ $resourceType = '';
+ if ($link->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_URL) {
+ $resource = $link->getLinkUrl();
+ $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_URL;
+ } elseif ($link->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
+ $resource = Mage::helper('downloadable/file')->getFilePath(
+ Mage_Downloadable_Model_Link::getBasePath(),
+ $link->getLinkFile(),
+ );
+ $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_FILE;
+ }
+ try {
+ $this->_processDownload($resource, $resourceType);
+ } catch (Mage_Core_Exception $e) {
+ $this->_getSession()->addError(Mage::helper('downloadable')->__('An error occurred while getting the requested content.'));
+ }
+ }
+ exit(0);
+ }
+ protected function _construct()
+ {
+ $this->setUsedModuleName('Mage_Downloadable');
+ }
+
/**
* Download process
*
@@ -81,35 +111,4 @@ protected function _processDownload($resource, $resourceType)
$helper->output();
}
-
- /**
- * Download link action
- *
- * @SuppressWarnings("PHPMD.ExitExpression")
- */
- public function linkAction()
- {
- $linkId = $this->getRequest()->getParam('id', 0);
- $link = Mage::getModel('downloadable/link')->load($linkId);
- if ($link->getId()) {
- $resource = '';
- $resourceType = '';
- if ($link->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_URL) {
- $resource = $link->getLinkUrl();
- $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_URL;
- } elseif ($link->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
- $resource = Mage::helper('downloadable/file')->getFilePath(
- Mage_Downloadable_Model_Link::getBasePath(),
- $link->getLinkFile(),
- );
- $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_FILE;
- }
- try {
- $this->_processDownload($resource, $resourceType);
- } catch (Mage_Core_Exception $e) {
- $this->_getSession()->addError(Mage::helper('downloadable')->__('An error occurred while getting the requested content.'));
- }
- }
- exit(0);
- }
}
diff --git a/app/code/core/Mage/Downloadable/controllers/DownloadController.php b/app/code/core/Mage/Downloadable/controllers/DownloadController.php
index 2e969e3a32c..2f41c4b3f10 100644
--- a/app/code/core/Mage/Downloadable/controllers/DownloadController.php
+++ b/app/code/core/Mage/Downloadable/controllers/DownloadController.php
@@ -22,64 +22,6 @@
*/
class Mage_Downloadable_DownloadController extends Mage_Core_Controller_Front_Action
{
- /**
- * Return core session object
- *
- * @return Mage_Core_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('core/session');
- }
-
- /**
- * Return customer session object
- *
- * @return Mage_Customer_Model_Session
- */
- protected function _getCustomerSession()
- {
- return Mage::getSingleton('customer/session');
- }
-
- /**
- * @param string $resource
- * @param string $resourceType
- * @throws Zend_Controller_Response_Exception
- */
- protected function _processDownload($resource, $resourceType)
- {
- $helper = Mage::helper('downloadable/download');
- $helper->setResource($resource, $resourceType);
-
- $fileName = $helper->getFilename();
- $contentType = $helper->getContentType();
-
- $this->getResponse()
- ->setHttpResponseCode(200)
- ->setHeader('Pragma', 'public', true)
- ->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)
- ->setHeader('Content-type', $contentType, true);
-
- if ($fileSize = $helper->getFilesize()) {
- $this->getResponse()
- ->setHeader('Content-Length', $fileSize);
- }
-
- if ($contentDisposition = $helper->getContentDisposition()) {
- $this->getResponse()
- ->setHeader('Content-Disposition', $contentDisposition . '; filename=' . $fileName);
- }
-
- $this->getResponse()
- ->clearBody();
- $this->getResponse()
- ->sendHeaders();
-
- session_write_close();
- $helper->output();
- }
-
/**
* Download sample action
*
@@ -235,4 +177,61 @@ public function linkAction()
}
return $this->_redirect('*/customer/products');
}
+ /**
+ * Return core session object
+ *
+ * @return Mage_Core_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('core/session');
+ }
+
+ /**
+ * Return customer session object
+ *
+ * @return Mage_Customer_Model_Session
+ */
+ protected function _getCustomerSession()
+ {
+ return Mage::getSingleton('customer/session');
+ }
+
+ /**
+ * @param string $resource
+ * @param string $resourceType
+ * @throws Zend_Controller_Response_Exception
+ */
+ protected function _processDownload($resource, $resourceType)
+ {
+ $helper = Mage::helper('downloadable/download');
+ $helper->setResource($resource, $resourceType);
+
+ $fileName = $helper->getFilename();
+ $contentType = $helper->getContentType();
+
+ $this->getResponse()
+ ->setHttpResponseCode(200)
+ ->setHeader('Pragma', 'public', true)
+ ->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)
+ ->setHeader('Content-type', $contentType, true);
+
+ if ($fileSize = $helper->getFilesize()) {
+ $this->getResponse()
+ ->setHeader('Content-Length', $fileSize);
+ }
+
+ if ($contentDisposition = $helper->getContentDisposition()) {
+ $this->getResponse()
+ ->setHeader('Content-Disposition', $contentDisposition . '; filename=' . $fileName);
+ }
+
+ $this->getResponse()
+ ->clearBody();
+ $this->getResponse()
+ ->sendHeaders();
+
+ session_write_close();
+ $helper->output();
+ }
}
diff --git a/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Edit/Options/Abstract.php b/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Edit/Options/Abstract.php
index dc146442539..011128e99c0 100644
--- a/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Edit/Options/Abstract.php
+++ b/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Edit/Options/Abstract.php
@@ -28,34 +28,6 @@ public function __construct()
$this->setTemplate('eav/attribute/options.phtml');
}
- /**
- * Preparing layout, adding buttons
- *
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('eav')->__('Delete'),
- 'class' => 'delete delete-option',
- ]),
- );
-
- $this->setChild(
- 'add_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->setData([
- 'label' => Mage::helper('eav')->__('Add Option'),
- 'class' => 'add',
- 'id' => 'add_new_option_button',
- ]),
- );
- return parent::_prepareLayout();
- }
-
/**
* Retrieve HTML of delete button
*
@@ -221,4 +193,32 @@ public function isConfigurableSwatchesEnabled(): bool
return $this->isModuleEnabled('Mage_ConfigurableSwatches')
&& Mage::helper('configurableswatches')->attrIsSwatchType($this->getAttributeObject());
}
+
+ /**
+ * Preparing layout, adding buttons
+ *
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('eav')->__('Delete'),
+ 'class' => 'delete delete-option',
+ ]),
+ );
+
+ $this->setChild(
+ 'add_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->setData([
+ 'label' => Mage::helper('eav')->__('Add Option'),
+ 'class' => 'add',
+ 'id' => 'add_new_option_button',
+ ]),
+ );
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Grid/Abstract.php b/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Grid/Abstract.php
index 1e835b5e115..8f943c16e3b 100644
--- a/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Grid/Abstract.php
+++ b/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Grid/Abstract.php
@@ -30,6 +30,17 @@ public function __construct()
$this->setDefaultDir('ASC');
}
+ /**
+ * Return url of given row
+ *
+ * @param Mage_Catalog_Model_Resource_Eav_Attribute $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['attribute_id' => $row->getAttributeId()]);
+ }
+
/**
* Prepare default grid column
*
@@ -73,15 +84,4 @@ protected function _prepareColumns()
return $this;
}
-
- /**
- * Return url of given row
- *
- * @param Mage_Catalog_Model_Resource_Eav_Attribute $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['attribute_id' => $row->getAttributeId()]);
- }
}
diff --git a/app/code/core/Mage/Eav/Helper/Data.php b/app/code/core/Mage/Eav/Helper/Data.php
index 14cacd2647d..40ff76689dd 100644
--- a/app/code/core/Mage/Eav/Helper/Data.php
+++ b/app/code/core/Mage/Eav/Helper/Data.php
@@ -33,45 +33,6 @@ class Mage_Eav_Helper_Data extends Mage_Core_Helper_Abstract
protected $_entityTypeFrontendClasses = [];
- /**
- * Return default frontend classes value labal array
- *
- * @return array
- */
- protected function _getDefaultFrontendClasses()
- {
- return [
- [
- 'value' => '',
- 'label' => Mage::helper('eav')->__('None'),
- ],
- [
- 'value' => 'validate-number',
- 'label' => Mage::helper('eav')->__('Decimal Number'),
- ],
- [
- 'value' => 'validate-digits',
- 'label' => Mage::helper('eav')->__('Integer Number'),
- ],
- [
- 'value' => 'validate-email',
- 'label' => Mage::helper('eav')->__('Email'),
- ],
- [
- 'value' => 'validate-url',
- 'label' => Mage::helper('eav')->__('URL'),
- ],
- [
- 'value' => 'validate-alpha',
- 'label' => Mage::helper('eav')->__('Letters'),
- ],
- [
- 'value' => 'validate-alphanum',
- 'label' => Mage::helper('eav')->__('Letters (a-z, A-Z) or Numbers (0-9)'),
- ],
- ];
- }
-
/**
* Return merged default and entity type frontend classes value label array
*
@@ -138,4 +99,43 @@ public function getInputTypesValidatorData()
{
return Mage::getStoreConfig(self::XML_PATH_VALIDATOR_DATA_INPUT_TYPES);
}
+
+ /**
+ * Return default frontend classes value labal array
+ *
+ * @return array
+ */
+ protected function _getDefaultFrontendClasses()
+ {
+ return [
+ [
+ 'value' => '',
+ 'label' => Mage::helper('eav')->__('None'),
+ ],
+ [
+ 'value' => 'validate-number',
+ 'label' => Mage::helper('eav')->__('Decimal Number'),
+ ],
+ [
+ 'value' => 'validate-digits',
+ 'label' => Mage::helper('eav')->__('Integer Number'),
+ ],
+ [
+ 'value' => 'validate-email',
+ 'label' => Mage::helper('eav')->__('Email'),
+ ],
+ [
+ 'value' => 'validate-url',
+ 'label' => Mage::helper('eav')->__('URL'),
+ ],
+ [
+ 'value' => 'validate-alpha',
+ 'label' => Mage::helper('eav')->__('Letters'),
+ ],
+ [
+ 'value' => 'validate-alphanum',
+ 'label' => Mage::helper('eav')->__('Letters (a-z, A-Z) or Numbers (0-9)'),
+ ],
+ ];
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Adminhtml/System/Config/Source/Inputtype/Validator.php b/app/code/core/Mage/Eav/Model/Adminhtml/System/Config/Source/Inputtype/Validator.php
index eb6d0475441..a02ebe761b2 100644
--- a/app/code/core/Mage/Eav/Model/Adminhtml/System/Config/Source/Inputtype/Validator.php
+++ b/app/code/core/Mage/Eav/Model/Adminhtml/System/Config/Source/Inputtype/Validator.php
@@ -46,31 +46,31 @@ public function __construct()
}
/**
- * Initialize message templates with translating
+ * Add input type to haystack
*
+ * @param string $type
* @return $this
*/
- protected function _initMessageTemplates()
+ public function addInputType($type)
{
- if (!$this->_messageTemplates) {
- $this->_messageTemplates = [
- self::NOT_IN_ARRAY =>
- Mage::helper('core')->__('Input type "%value%" not found in the input types list.'),
- ];
+ if (!in_array((string) $type, $this->_haystack, true)) {
+ $this->_haystack[] = (string) $type;
}
return $this;
}
/**
- * Add input type to haystack
+ * Initialize message templates with translating
*
- * @param string $type
* @return $this
*/
- public function addInputType($type)
+ protected function _initMessageTemplates()
{
- if (!in_array((string) $type, $this->_haystack, true)) {
- $this->_haystack[] = (string) $type;
+ if (!$this->_messageTemplates) {
+ $this->_messageTemplates = [
+ self::NOT_IN_ARRAY =>
+ Mage::helper('core')->__('Input type "%value%" not found in the input types list.'),
+ ];
}
return $this;
}
diff --git a/app/code/core/Mage/Eav/Model/Attribute.php b/app/code/core/Mage/Eav/Model/Attribute.php
index e720377873e..b2b3cada91b 100644
--- a/app/code/core/Mage/Eav/Model/Attribute.php
+++ b/app/code/core/Mage/Eav/Model/Attribute.php
@@ -68,17 +68,6 @@ public function getWebsite()
return $this->_website;
}
- /**
- * Processing object after save data
- *
- * @inheritDoc
- */
- protected function _afterSave()
- {
- Mage::getSingleton('eav/config')->clear();
- return parent::_afterSave();
- }
-
/**
* Return forms in which the attribute
*
@@ -128,18 +117,6 @@ public function setValidateRules($rules)
return $this;
}
- /**
- * Return scope value by key
- *
- * @param string $key
- * @return mixed
- */
- protected function _getScopeValue($key)
- {
- $scopeKey = sprintf('scope_%s', $key);
- return $this->getData($scopeKey) ?? $this->getData($key);
- }
-
/**
* Return is attribute value required
*
@@ -179,4 +156,27 @@ public function getMultilineCount()
{
return $this->_getScopeValue('multiline_count');
}
+
+ /**
+ * Processing object after save data
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave()
+ {
+ Mage::getSingleton('eav/config')->clear();
+ return parent::_afterSave();
+ }
+
+ /**
+ * Return scope value by key
+ *
+ * @param string $key
+ * @return mixed
+ */
+ protected function _getScopeValue($key)
+ {
+ $scopeKey = sprintf('scope_%s', $key);
+ return $this->getData($scopeKey) ?? $this->getData($key);
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Attribute/Data/Abstract.php b/app/code/core/Mage/Eav/Model/Attribute/Data/Abstract.php
index b403a8b80e9..94ef1de113a 100644
--- a/app/code/core/Mage/Eav/Model/Attribute/Data/Abstract.php
+++ b/app/code/core/Mage/Eav/Model/Attribute/Data/Abstract.php
@@ -171,6 +171,68 @@ public function getExtractedData($index = null)
return $this->_extractedData;
}
+ /**
+ * Set is AJAX Request flag
+ *
+ * @param bool $flag
+ * @return Mage_Eav_Model_Attribute_Data_Abstract
+ */
+ public function setIsAjaxRequest($flag = true)
+ {
+ $this->_isAjax = (bool) $flag;
+ return $this;
+ }
+
+ /**
+ * Return is AJAX Request
+ *
+ * @return bool
+ */
+ public function getIsAjaxRequest()
+ {
+ return $this->_isAjax;
+ }
+
+ /**
+ * Extract data from request and return value
+ *
+ * @return array|string
+ */
+ abstract public function extractValue(Zend_Controller_Request_Http $request);
+
+ /**
+ * Validate data
+ *
+ * @param array|string $value
+ * @throws Mage_Core_Exception
+ * @return bool
+ */
+ abstract public function validateValue($value);
+
+ /**
+ * Export attribute value to entity model
+ *
+ * @param array|string $value
+ * @return Mage_Eav_Model_Attribute_Data_Abstract
+ */
+ abstract public function compactValue($value);
+
+ /**
+ * Restore attribute value from SESSION to entity model
+ *
+ * @param array|string $value
+ * @return Mage_Eav_Model_Attribute_Data_Abstract
+ */
+ abstract public function restoreValue($value);
+
+ /**
+ * Return formatted attribute value from entity model
+ *
+ * @param string $format
+ * @return string|array
+ */
+ abstract public function outputValue($format = Mage_Eav_Model_Attribute_Data::OUTPUT_FORMAT_TEXT);
+
/**
* Apply attribute input filter to value
*
@@ -444,28 +506,6 @@ protected function _validateInputRule($value)
return true;
}
- /**
- * Set is AJAX Request flag
- *
- * @param bool $flag
- * @return Mage_Eav_Model_Attribute_Data_Abstract
- */
- public function setIsAjaxRequest($flag = true)
- {
- $this->_isAjax = (bool) $flag;
- return $this;
- }
-
- /**
- * Return is AJAX Request
- *
- * @return bool
- */
- public function getIsAjaxRequest()
- {
- return $this->_isAjax;
- }
-
/**
* Return Original Attribute value from Request
*
@@ -495,44 +535,4 @@ protected function _getRequestValue(Zend_Controller_Request_Http $request)
}
return $value;
}
-
- /**
- * Extract data from request and return value
- *
- * @return array|string
- */
- abstract public function extractValue(Zend_Controller_Request_Http $request);
-
- /**
- * Validate data
- *
- * @param array|string $value
- * @throws Mage_Core_Exception
- * @return bool
- */
- abstract public function validateValue($value);
-
- /**
- * Export attribute value to entity model
- *
- * @param array|string $value
- * @return Mage_Eav_Model_Attribute_Data_Abstract
- */
- abstract public function compactValue($value);
-
- /**
- * Restore attribute value from SESSION to entity model
- *
- * @param array|string $value
- * @return Mage_Eav_Model_Attribute_Data_Abstract
- */
- abstract public function restoreValue($value);
-
- /**
- * Return formatted attribute value from entity model
- *
- * @param string $format
- * @return string|array
- */
- abstract public function outputValue($format = Mage_Eav_Model_Attribute_Data::OUTPUT_FORMAT_TEXT);
}
diff --git a/app/code/core/Mage/Eav/Model/Attribute/Data/File.php b/app/code/core/Mage/Eav/Model/Attribute/Data/File.php
index 049bd345d09..6967d3e40ed 100644
--- a/app/code/core/Mage/Eav/Model/Attribute/Data/File.php
+++ b/app/code/core/Mage/Eav/Model/Attribute/Data/File.php
@@ -86,56 +86,6 @@ public function extractValue(Zend_Controller_Request_Http $request)
return $value;
}
- /**
- * Validate file by attribute validate rules
- * Return array of errors
- *
- * @param array $value
- * @return array
- */
- protected function _validateByRules($value)
- {
- $label = $this->getAttribute()->getStoreLabel();
- $rules = $this->getAttribute()->getValidateRules();
- $extension = pathinfo($value['name'], PATHINFO_EXTENSION);
-
- if (!empty($rules['file_extensions'])) {
- $extensions = explode(',', $rules['file_extensions']);
- $extensions = array_map('trim', $extensions);
- if (!in_array($extension, $extensions)) {
- return [
- Mage::helper('eav')->__('"%s" is not a valid file extension.', $label),
- ];
- }
- }
-
- /**
- * Check protected file extension
- */
- /** @var Mage_Core_Model_File_Validator_NotProtectedExtension $validator */
- $validator = Mage::getSingleton('core/file_validator_notProtectedExtension');
- if (!$validator->isValid($extension)) {
- return $validator->getMessages();
- }
-
- if (!is_uploaded_file($value['tmp_name'])) {
- return [
- Mage::helper('eav')->__('"%s" is not a valid file.', $label),
- ];
- }
-
- if (!empty($rules['max_file_size'])) {
- $size = $value['size'];
- if ($rules['max_file_size'] < $size) {
- return [
- Mage::helper('eav')->__('"%s" exceeds the allowed file size.', $label),
- ];
- }
- }
-
- return [];
- }
-
/**
* Validate data
*
@@ -276,4 +226,54 @@ public function outputValue($format = Mage_Eav_Model_Attribute_Data::OUTPUT_FORM
return $output;
}
+
+ /**
+ * Validate file by attribute validate rules
+ * Return array of errors
+ *
+ * @param array $value
+ * @return array
+ */
+ protected function _validateByRules($value)
+ {
+ $label = $this->getAttribute()->getStoreLabel();
+ $rules = $this->getAttribute()->getValidateRules();
+ $extension = pathinfo($value['name'], PATHINFO_EXTENSION);
+
+ if (!empty($rules['file_extensions'])) {
+ $extensions = explode(',', $rules['file_extensions']);
+ $extensions = array_map('trim', $extensions);
+ if (!in_array($extension, $extensions)) {
+ return [
+ Mage::helper('eav')->__('"%s" is not a valid file extension.', $label),
+ ];
+ }
+ }
+
+ /**
+ * Check protected file extension
+ */
+ /** @var Mage_Core_Model_File_Validator_NotProtectedExtension $validator */
+ $validator = Mage::getSingleton('core/file_validator_notProtectedExtension');
+ if (!$validator->isValid($extension)) {
+ return $validator->getMessages();
+ }
+
+ if (!is_uploaded_file($value['tmp_name'])) {
+ return [
+ Mage::helper('eav')->__('"%s" is not a valid file.', $label),
+ ];
+ }
+
+ if (!empty($rules['max_file_size'])) {
+ $size = $value['size'];
+ if ($rules['max_file_size'] < $size) {
+ return [
+ Mage::helper('eav')->__('"%s" exceeds the allowed file size.', $label),
+ ];
+ }
+ }
+
+ return [];
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Attribute/Data/Select.php b/app/code/core/Mage/Eav/Model/Attribute/Data/Select.php
index b3ffa253e7c..a480cc39d2e 100644
--- a/app/code/core/Mage/Eav/Model/Attribute/Data/Select.php
+++ b/app/code/core/Mage/Eav/Model/Attribute/Data/Select.php
@@ -90,17 +90,6 @@ public function restoreValue($value)
return $this->compactValue($value);
}
- /**
- * Return a text for option value
- *
- * @param int $value
- * @return string
- */
- protected function _getOptionText($value)
- {
- return $this->getAttribute()->getSource()->getOptionText($value);
- }
-
/**
* Return formatted attribute value from entity model
*
@@ -126,4 +115,15 @@ public function outputValue($format = Mage_Eav_Model_Attribute_Data::OUTPUT_FORM
return $output;
}
+
+ /**
+ * Return a text for option value
+ *
+ * @param int $value
+ * @return string
+ */
+ protected function _getOptionText($value)
+ {
+ return $this->getAttribute()->getSource()->getOptionText($value);
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Config.php b/app/code/core/Mage/Eav/Model/Config.php
index 7fa34d1c60a..3ae5711e965 100644
--- a/app/code/core/Mage/Eav/Model/Config.php
+++ b/app/code/core/Mage/Eav/Model/Config.php
@@ -127,6 +127,248 @@ public function setCurrentStoreId($storeId)
$this->_currentStoreId = $storeId;
}
+ /**
+ * Get entity type object by entity type code/identifier
+ *
+ * @param mixed $code
+ * @param string|null $field
+ * @return Mage_Eav_Model_Entity_Type
+ * @throws Mage_Core_Exception
+ * @throws Exception
+ */
+ public function getEntityType($code, $field = null)
+ {
+ if ($code instanceof Mage_Eav_Model_Entity_Type) {
+ return $code;
+ }
+
+ // initialize entity type cache
+ if (!isset($this->_entityTypes)) {
+ $this->_initializeStore();
+ }
+
+ // lookup by id
+ if (empty($field) && is_numeric($code)) {
+ if (isset($this->_entityTypes[$code])) {
+ return $this->_entityTypes[$code];
+ } else {
+ Mage::throwException('Invalid entity type: ' . $code);
+ }
+ }
+
+ // lookup by code
+ if (empty($field) || $field == 'entity_type_code') {
+ if (isset($this->_entityTypeByCode[$code])) {
+ return $this->_entityTypeByCode[$code];
+ } else {
+ Mage::throwException('Invalid entity type: ' . $code);
+ }
+ }
+
+ // lookup by other field
+ foreach ($this->_entityTypes as $entityType) {
+ if ($entityType->getData($field) == $code) {
+ return $entityType;
+ }
+ }
+
+ Mage::throwException('Failed to find entity eav/entity_type for ' . $field . '=' . $code);
+ }
+
+ /**
+ * Get attribute by code for entity type
+ *
+ * @param mixed $entityType
+ * @param mixed $code
+ * @param int|null $storeId
+ * @return Mage_Eav_Model_Entity_Attribute_Abstract|false
+ * @throws Mage_Core_Exception
+ * @throws Exception
+ */
+ public function getAttribute($entityType, $code, $storeId = null)
+ {
+ if ($code instanceof Mage_Eav_Model_Entity_Attribute_Interface) {
+ return $code;
+ }
+
+ $storeId = $storeId !== null ? $storeId : $this->_storeId();
+ $this->_initializeStore($storeId);
+ $entityType = $this->getEntityType($entityType);
+
+ // lookup id by code
+ if (!is_numeric($code) && isset($this->_entityTypeAttributeIdByCode[$storeId][$entityType->getId()][$code])) {
+ $code = $this->_entityTypeAttributeIdByCode[$storeId][$entityType->getId()][$code];
+ }
+
+ // get model
+ $attribute = null;
+ if (isset($this->_entityTypeAttributes[$storeId][$entityType->getId()][$code])) {
+ $attributeData = $this->_entityTypeAttributes[$storeId][$entityType->getId()][$code];
+ if (is_array($attributeData)) {
+ $attribute = $this->_hydrateAttribute($attributeData);
+ $this->_entityTypeAttributes[$storeId][$entityType->getId()][$attribute->getId()] = $attribute;
+ } else {
+ $attribute = $attributeData;
+ }
+ } else {
+ $attribute = $this->_getDefaultAttributeIfExists($entityType, $code, $storeId);
+ }
+
+ // return an empty model to avoid breaking compatibility
+ if (!$attribute) {
+ $attribute = $this->_hydrateAttribute(['entity_type_id' => $entityType->getId()]);
+ }
+
+ return $attribute;
+ }
+
+ /**
+ * @param mixed $entityType
+ * @return Mage_Eav_Model_Entity_Attribute_Abstract[]
+ * @throws Mage_Core_Exception
+ */
+ public function getAttributes($entityType)
+ {
+ Varien_Profiler::start('EAV: ' . __METHOD__);
+
+ $entityType = $this->getEntityType($entityType);
+ $attributes = [];
+ $storeId = $this->_storeId();
+ // need to access attributes to ensure they are hydrated and initialized
+ foreach (array_keys($this->_entityTypeAttributes[$storeId][$entityType->getId()]) as $attributeId) {
+ $attributes[] = $this->getAttribute($entityType, $attributeId, $storeId);
+ }
+
+ Varien_Profiler::stop('EAV: ' . __METHOD__);
+
+ return $attributes;
+ }
+
+ /**
+ * Get codes of all entity type attributes
+ *
+ * @param Mage_Eav_Model_Entity_Type $entityType
+ * @param Varien_Object $object
+ * @return array
+ * @throws Mage_Core_Exception
+ * @throws Exception
+ */
+ public function getEntityAttributeCodes($entityType, $object = null)
+ {
+ $entityType = $this->getEntityType($entityType);
+ $attributeSetId = 0;
+ if (($object instanceof Varien_Object) && $object->getAttributeSetId()) {
+ $attributeSetId = $object->getAttributeSetId();
+ }
+
+ // Technically store id is irrelevant for attribute sets, they are the same in all store scopes.
+ // Use current store id when not specified to avoid loading two store-scope attribute data sets from cache
+ $storeId = $this->_storeId();
+ if (($object instanceof Varien_Object) && $object->getStoreId()) {
+ $storeId = $object->getStoreId();
+ }
+ $this->_initializeStore($storeId);
+
+ if ($attributeSetId) {
+ $attributeIds = $this->getAttributeSetAttributeIds($attributeSetId);
+ $attributeCodes = [];
+ foreach ($attributeIds as $attributeId) {
+ $attribute = $this->getAttribute($entityType, $attributeId, $storeId);
+ // need to verify attribute actually exists to avoid problems
+ // with deleted attributes that left behind some remnants
+ if ($attribute) {
+ $attributeCodes[] = $attribute->getAttributeCode();
+ }
+ }
+ return $attributeCodes;
+ } else {
+ return isset($this->_entityTypeAttributeIdByCode[$storeId][$entityType->getId()])
+ ? array_keys($this->_entityTypeAttributeIdByCode[$storeId][$entityType->getId()])
+ : [];
+ }
+ }
+
+ /**
+ * @param int|int[] $attributeSetId
+ * @return int[]
+ */
+ public function getAttributeSetAttributeIds($attributeSetId)
+ {
+ if (!is_array($attributeSetId)) {
+ $attributeSetId = [$attributeSetId];
+ }
+
+ $attributes = [];
+
+ foreach ($attributeSetId as $setId) {
+ foreach ($this->_attributeSetInfo as $attributeId => $sets) {
+ if (isset($sets[$setId])) {
+ $attributes[$attributeId] = true;
+ }
+ }
+ }
+
+ return array_keys($attributes);
+ }
+
+ /**
+ * Return first attribute sorting information found for a given list of attribute sets
+ * @param int $attributeId
+ * @param int|int[] $attributeSetIds
+ * @return false|array
+ */
+ public function getAttributeSetGroupInfo($attributeId, $attributeSetIds)
+ {
+ if (!is_array($attributeSetIds)) {
+ $attributeSetIds = [$attributeSetIds];
+ }
+
+ foreach ($attributeSetIds as $attributeSetId) {
+ if (isset($this->_attributeSetInfo[$attributeId][$attributeSetId])) {
+ return $this->_attributeSetInfo[$attributeId][$attributeSetId];
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * @param mixed $entityType
+ * @param string $attribute
+ * @return Mage_Eav_Model_Entity_Attribute_Abstract|null
+ * @throws Mage_Core_Exception
+ * @deprecated Equivalent to getAttribute(...), use getAttribute(...) instead
+ * Get attribute object for collection usage
+ *
+ */
+ public function getCollectionAttribute($entityType, $attribute)
+ {
+ return $this->getAttribute($entityType, $attribute);
+ }
+
+ /**
+ * @param mixed $entityType
+ * @param array $attributes
+ * @return Mage_Eav_Model_Config
+ * @deprecated No longer required to preload only collection attributes explicitly
+ * Prepare attributes for usage in EAV collection
+ *
+ */
+ public function loadCollectionAttributes($entityType, $attributes)
+ {
+ return $this;
+ }
+
+ /**
+ * @param string|Mage_Eav_Model_Entity_Type $entityType
+ * @return $this
+ * @deprecated No longer required. All attribute data is cached on-access.
+ */
+ public function importAttributesData($entityType, array $attributes)
+ {
+ return $this;
+ }
+
/**
* @throws Mage_Core_Model_Store_Exception
*/
@@ -384,54 +626,6 @@ protected function _hydrateAttribute($attributeData)
return $attribute;
}
- /**
- * Get entity type object by entity type code/identifier
- *
- * @param mixed $code
- * @param string|null $field
- * @return Mage_Eav_Model_Entity_Type
- * @throws Mage_Core_Exception
- * @throws Exception
- */
- public function getEntityType($code, $field = null)
- {
- if ($code instanceof Mage_Eav_Model_Entity_Type) {
- return $code;
- }
-
- // initialize entity type cache
- if (!isset($this->_entityTypes)) {
- $this->_initializeStore();
- }
-
- // lookup by id
- if (empty($field) && is_numeric($code)) {
- if (isset($this->_entityTypes[$code])) {
- return $this->_entityTypes[$code];
- } else {
- Mage::throwException('Invalid entity type: ' . $code);
- }
- }
-
- // lookup by code
- if (empty($field) || $field == 'entity_type_code') {
- if (isset($this->_entityTypeByCode[$code])) {
- return $this->_entityTypeByCode[$code];
- } else {
- Mage::throwException('Invalid entity type: ' . $code);
- }
- }
-
- // lookup by other field
- foreach ($this->_entityTypes as $entityType) {
- if ($entityType->getData($field) == $code) {
- return $entityType;
- }
- }
-
- Mage::throwException('Failed to find entity eav/entity_type for ' . $field . '=' . $code);
- }
-
/**
* Default attributes are loaded only on getAttribute(...) call to avoid infinite loading loop between
* Entity_Type->getEntity() which itself requires this class and re-triggers loading.
@@ -464,198 +658,4 @@ protected function _getDefaultAttributeIfExists($entityType, $attributeCode, $st
$this->_defaultAttributes[$storeId][$entityType->getId()][$attributeCode] = false;
return false;
}
-
- /**
- * Get attribute by code for entity type
- *
- * @param mixed $entityType
- * @param mixed $code
- * @param int|null $storeId
- * @return Mage_Eav_Model_Entity_Attribute_Abstract|false
- * @throws Mage_Core_Exception
- * @throws Exception
- */
- public function getAttribute($entityType, $code, $storeId = null)
- {
- if ($code instanceof Mage_Eav_Model_Entity_Attribute_Interface) {
- return $code;
- }
-
- $storeId = $storeId !== null ? $storeId : $this->_storeId();
- $this->_initializeStore($storeId);
- $entityType = $this->getEntityType($entityType);
-
- // lookup id by code
- if (!is_numeric($code) && isset($this->_entityTypeAttributeIdByCode[$storeId][$entityType->getId()][$code])) {
- $code = $this->_entityTypeAttributeIdByCode[$storeId][$entityType->getId()][$code];
- }
-
- // get model
- $attribute = null;
- if (isset($this->_entityTypeAttributes[$storeId][$entityType->getId()][$code])) {
- $attributeData = $this->_entityTypeAttributes[$storeId][$entityType->getId()][$code];
- if (is_array($attributeData)) {
- $attribute = $this->_hydrateAttribute($attributeData);
- $this->_entityTypeAttributes[$storeId][$entityType->getId()][$attribute->getId()] = $attribute;
- } else {
- $attribute = $attributeData;
- }
- } else {
- $attribute = $this->_getDefaultAttributeIfExists($entityType, $code, $storeId);
- }
-
- // return an empty model to avoid breaking compatibility
- if (!$attribute) {
- $attribute = $this->_hydrateAttribute(['entity_type_id' => $entityType->getId()]);
- }
-
- return $attribute;
- }
-
- /**
- * @param mixed $entityType
- * @return Mage_Eav_Model_Entity_Attribute_Abstract[]
- * @throws Mage_Core_Exception
- */
- public function getAttributes($entityType)
- {
- Varien_Profiler::start('EAV: ' . __METHOD__);
-
- $entityType = $this->getEntityType($entityType);
- $attributes = [];
- $storeId = $this->_storeId();
- // need to access attributes to ensure they are hydrated and initialized
- foreach (array_keys($this->_entityTypeAttributes[$storeId][$entityType->getId()]) as $attributeId) {
- $attributes[] = $this->getAttribute($entityType, $attributeId, $storeId);
- }
-
- Varien_Profiler::stop('EAV: ' . __METHOD__);
-
- return $attributes;
- }
-
- /**
- * Get codes of all entity type attributes
- *
- * @param Mage_Eav_Model_Entity_Type $entityType
- * @param Varien_Object $object
- * @return array
- * @throws Mage_Core_Exception
- * @throws Exception
- */
- public function getEntityAttributeCodes($entityType, $object = null)
- {
- $entityType = $this->getEntityType($entityType);
- $attributeSetId = 0;
- if (($object instanceof Varien_Object) && $object->getAttributeSetId()) {
- $attributeSetId = $object->getAttributeSetId();
- }
-
- // Technically store id is irrelevant for attribute sets, they are the same in all store scopes.
- // Use current store id when not specified to avoid loading two store-scope attribute data sets from cache
- $storeId = $this->_storeId();
- if (($object instanceof Varien_Object) && $object->getStoreId()) {
- $storeId = $object->getStoreId();
- }
- $this->_initializeStore($storeId);
-
- if ($attributeSetId) {
- $attributeIds = $this->getAttributeSetAttributeIds($attributeSetId);
- $attributeCodes = [];
- foreach ($attributeIds as $attributeId) {
- $attribute = $this->getAttribute($entityType, $attributeId, $storeId);
- // need to verify attribute actually exists to avoid problems
- // with deleted attributes that left behind some remnants
- if ($attribute) {
- $attributeCodes[] = $attribute->getAttributeCode();
- }
- }
- return $attributeCodes;
- } else {
- return isset($this->_entityTypeAttributeIdByCode[$storeId][$entityType->getId()])
- ? array_keys($this->_entityTypeAttributeIdByCode[$storeId][$entityType->getId()])
- : [];
- }
- }
-
- /**
- * @param int|int[] $attributeSetId
- * @return int[]
- */
- public function getAttributeSetAttributeIds($attributeSetId)
- {
- if (!is_array($attributeSetId)) {
- $attributeSetId = [$attributeSetId];
- }
-
- $attributes = [];
-
- foreach ($attributeSetId as $setId) {
- foreach ($this->_attributeSetInfo as $attributeId => $sets) {
- if (isset($sets[$setId])) {
- $attributes[$attributeId] = true;
- }
- }
- }
-
- return array_keys($attributes);
- }
-
- /**
- * Return first attribute sorting information found for a given list of attribute sets
- * @param int $attributeId
- * @param int|int[] $attributeSetIds
- * @return false|array
- */
- public function getAttributeSetGroupInfo($attributeId, $attributeSetIds)
- {
- if (!is_array($attributeSetIds)) {
- $attributeSetIds = [$attributeSetIds];
- }
-
- foreach ($attributeSetIds as $attributeSetId) {
- if (isset($this->_attributeSetInfo[$attributeId][$attributeSetId])) {
- return $this->_attributeSetInfo[$attributeId][$attributeSetId];
- }
- }
-
- return false;
- }
-
- /**
- * @param mixed $entityType
- * @param string $attribute
- * @return Mage_Eav_Model_Entity_Attribute_Abstract|null
- * @throws Mage_Core_Exception
- * @deprecated Equivalent to getAttribute(...), use getAttribute(...) instead
- * Get attribute object for collection usage
- *
- */
- public function getCollectionAttribute($entityType, $attribute)
- {
- return $this->getAttribute($entityType, $attribute);
- }
-
- /**
- * @param mixed $entityType
- * @param array $attributes
- * @return Mage_Eav_Model_Config
- * @deprecated No longer required to preload only collection attributes explicitly
- * Prepare attributes for usage in EAV collection
- *
- */
- public function loadCollectionAttributes($entityType, $attributes)
- {
- return $this;
- }
-
- /**
- * @param string|Mage_Eav_Model_Entity_Type $entityType
- * @return $this
- * @deprecated No longer required. All attribute data is cached on-access.
- */
- public function importAttributesData($entityType, array $attributes)
- {
- return $this;
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Convert/Adapter/Entity.php b/app/code/core/Mage/Eav/Model/Convert/Adapter/Entity.php
index 8a9ba661313..e49591eeb92 100644
--- a/app/code/core/Mage/Eav/Model/Convert/Adapter/Entity.php
+++ b/app/code/core/Mage/Eav/Model/Convert/Adapter/Entity.php
@@ -52,22 +52,6 @@ public function getStoreId()
return $this->_store->getId();
}
- /**
- * @return array
- */
- protected function _parseVars()
- {
- $varFilters = $this->getVars();
- $filters = [];
- foreach ($varFilters as $key => $val) {
- if (substr($key, 0, 6) === 'filter') {
- $keys = explode('/', $key, 2);
- $filters[$keys[1]] = $val;
- }
- }
- return $filters;
- }
-
/**
* @param array $attrFilterArray
* @param array $attrToDb
@@ -185,28 +169,6 @@ public function getFilter()
return $this->_filter;
}
- /**
- * @param array $fields
- * @param string $name
- * @return array|bool
- */
- protected function getFieldValue($fields = [], $name = '')
- {
- $result = [];
- if ($fields && $name) {
- foreach ($fields as $index => $value) {
- $exp = explode('/', $index);
- if (isset($exp[1]) && $exp[0] == $name) {
- $result[$exp[1]] = $value;
- }
- }
- if ($result) {
- return $result;
- }
- }
- return false;
- }
-
/**
* @param array $joinAttr
* @throws Exception
@@ -319,17 +281,6 @@ public function load()
return $this;
}
- /**
- * Retrieve collection for load
- *
- * @param string $entityType
- * @return Mage_Eav_Model_Entity_Collection|false
- */
- protected function _getCollectionForLoad($entityType)
- {
- return Mage::getResourceModel($entityType . '_collection');
- }
-
/**
* @return $this
* @throws Varien_Convert_Exception
@@ -364,4 +315,53 @@ public function save()
}
return $this;
}
+
+ /**
+ * @return array
+ */
+ protected function _parseVars()
+ {
+ $varFilters = $this->getVars();
+ $filters = [];
+ foreach ($varFilters as $key => $val) {
+ if (substr($key, 0, 6) === 'filter') {
+ $keys = explode('/', $key, 2);
+ $filters[$keys[1]] = $val;
+ }
+ }
+ return $filters;
+ }
+
+ /**
+ * @param array $fields
+ * @param string $name
+ * @return array|bool
+ */
+ protected function getFieldValue($fields = [], $name = '')
+ {
+ $result = [];
+ if ($fields && $name) {
+ foreach ($fields as $index => $value) {
+ $exp = explode('/', $index);
+ if (isset($exp[1]) && $exp[0] == $name) {
+ $result[$exp[1]] = $value;
+ }
+ }
+ if ($result) {
+ return $result;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Retrieve collection for load
+ *
+ * @param string $entityType
+ * @return Mage_Eav_Model_Entity_Collection|false
+ */
+ protected function _getCollectionForLoad($entityType)
+ {
+ return Mage::getResourceModel($entityType . '_collection');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Entity/Abstract.php b/app/code/core/Mage/Eav/Model/Entity/Abstract.php
index 2afd0c8245f..d5c55ba7604 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Abstract.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Abstract.php
@@ -177,34 +177,6 @@ public function setConnection($read, $write = null)
return $this;
}
- protected function _construct() {}
-
- /**
- * Retrieve connection for read data
- *
- * @return Varien_Db_Adapter_Interface|false
- */
- protected function _getReadAdapter()
- {
- if (is_string($this->_read)) {
- $this->_read = Mage::getSingleton('core/resource')->getConnection($this->_read);
- }
- return $this->_read;
- }
-
- /**
- * Retrieve connection for write data
- *
- * @return Varien_Db_Adapter_Interface|false
- */
- protected function _getWriteAdapter()
- {
- if (is_string($this->_write)) {
- $this->_write = Mage::getSingleton('core/resource')->getConnection($this->_write);
- }
- return $this->_write;
- }
-
/**
* Retrieve read DB connection
*
@@ -407,28 +379,6 @@ public function getAttribute($attribute)
return $attribute;
}
- /**
- * Return default static virtual attribute that doesn't exists in EAV attributes
- *
- * @param string $attributeCode
- * @return Mage_Eav_Model_Entity_Attribute
- */
- protected function _getDefaultAttribute($attributeCode)
- {
- $entityTypeId = $this->getEntityType()->getId();
- if (!isset(self::$_defaultAttributes[$entityTypeId][$attributeCode])) {
- $attribute = Mage::getModel($this->getEntityType()->getAttributeModel())
- ->setAttributeCode($attributeCode)
- ->setBackendType(Mage_Eav_Model_Entity_Attribute_Abstract::TYPE_STATIC)
- ->setIsGlobal(1)
- ->setEntityType($this->getEntityType())
- ->setEntityTypeId($this->getEntityType()->getId());
- self::$_defaultAttributes[$entityTypeId][$attributeCode] = $attribute;
- }
-
- return self::$_defaultAttributes[$entityTypeId][$attributeCode];
- }
-
/**
* Adding attribute to entity
*
@@ -567,18 +517,6 @@ public function attributesCompare($attribute1, $attribute2)
return 0;
}
- /**
- * Check whether the attribute is Applicable to the object
- *
- * @param Varien_Object $object
- * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute
- * @return bool
- */
- protected function _isApplicableAttribute($object, $attribute)
- {
- return true;
- }
-
/**
* Walk through the attributes and run method with optional arguments
*
@@ -647,23 +585,6 @@ public function walkAttributes($partMethod, array $args = [])
return $results;
}
- /**
- * Check whether attribute instance (attribute, backend, frontend or source) has method and applicable
- *
- * @param Mage_Eav_Model_Entity_Attribute_Abstract|Mage_Eav_Model_Entity_Attribute_Backend_Abstract|Mage_Eav_Model_Entity_Attribute_Frontend_Abstract|Mage_Eav_Model_Entity_Attribute_Source_Abstract $instance
- * @param string $method
- * @param array $args array of arguments
- * @return bool
- */
- protected function _isCallableAttributeInstance($instance, $method, $args)
- {
- if (!is_object($instance) || !method_exists($instance, $method)) {
- return false;
- }
-
- return true;
- }
-
/**
* Get attributes by name array
*
@@ -942,6 +863,218 @@ public function load($object, $entityId, $attributes = [])
return $this;
}
+ /**
+ * Save entity's attributes into the object's resource
+ *
+ * @return $this
+ */
+ public function save(Varien_Object $object)
+ {
+ if ($object->isDeleted()) {
+ return $this->delete($object);
+ }
+
+ if (!$this->isPartialSave()) {
+ $this->loadAllAttributes($object);
+ }
+
+ if (!$object->getEntityTypeId()) {
+ $object->setEntityTypeId($this->getTypeId());
+ }
+
+ $object->setParentId((int) $object->getParentId());
+
+ $this->_beforeSave($object);
+ $this->_processSaveData($this->_collectSaveData($object));
+ $this->_afterSave($object);
+
+ return $this;
+ }
+
+ /**
+ * Save attribute
+ *
+ * @param string $attributeCode
+ * @return $this
+ */
+ public function saveAttribute(Varien_Object $object, $attributeCode)
+ {
+ $this->_attributeValuesToSave = [];
+ $this->_attributeValuesToDelete = [];
+
+ $attribute = $this->getAttribute($attributeCode);
+ $backend = $attribute->getBackend();
+ $table = $backend->getTable();
+ $entity = $attribute->getEntity();
+ $entityIdField = $entity->getEntityIdField();
+ $adapter = $this->_getWriteAdapter();
+
+ $row = [
+ 'entity_type_id' => $entity->getTypeId(),
+ 'attribute_id' => $attribute->getId(),
+ $entityIdField => $object->getData($entityIdField),
+ ];
+
+ $newValue = $object->getData($attributeCode);
+ if ($attribute->isValueEmpty($newValue)) {
+ $newValue = null;
+ }
+
+ $whereArr = [];
+ foreach ($row as $field => $value) {
+ $whereArr[] = $adapter->quoteInto($field . '=?', $value);
+ }
+ $where = implode(' AND ', $whereArr);
+
+ $adapter->beginTransaction();
+
+ try {
+ $select = $adapter->select()
+ ->from($table, 'value_id')
+ ->where($where);
+ $origValueId = $adapter->fetchOne($select);
+
+ if ($origValueId === false && ($newValue !== null)) {
+ $this->_insertAttribute($object, $attribute, $newValue);
+ } elseif ($origValueId !== false && ($newValue !== null)) {
+ $this->_updateAttribute($object, $attribute, $origValueId, $newValue);
+ } elseif ($origValueId !== false && ($newValue === null)) {
+ $adapter->delete($table, $where);
+ }
+ $this->_processAttributeValues();
+ $adapter->commit();
+ } catch (Exception $e) {
+ $adapter->rollBack();
+ throw $e;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Delete entity using current object's data
+ *
+ * @param int|string|Varien_Object $object
+ * @return $this
+ * @throws Exception
+ */
+ public function delete($object)
+ {
+ if (is_numeric($object)) {
+ $id = (int) $object;
+ } elseif ($object instanceof Varien_Object) {
+ $id = (int) $object->getId();
+ }
+
+ $this->_beforeDelete($object);
+
+ try {
+ $where = [
+ $this->getEntityIdField() . '=?' => $id,
+ ];
+ $this->_getWriteAdapter()->delete($this->getEntityTable(), $where);
+ $this->loadAllAttributes($object);
+ foreach (array_keys($this->getAttributesByTable()) as $table) {
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $this->_getWriteAdapter()->delete($table, $where);
+ }
+ } catch (Exception $e) {
+ throw $e;
+ }
+
+ $this->_afterDelete($object);
+ return $this;
+ }
+
+ /**
+ * Retrieve default entity static attributes
+ *
+ * @return array
+ */
+ public function getDefaultAttributes()
+ {
+ return array_unique(array_merge($this->_getDefaultAttributes(), [$this->getEntityIdField()]));
+ }
+
+ protected function _construct() {}
+
+ /**
+ * Retrieve connection for read data
+ *
+ * @return Varien_Db_Adapter_Interface|false
+ */
+ protected function _getReadAdapter()
+ {
+ if (is_string($this->_read)) {
+ $this->_read = Mage::getSingleton('core/resource')->getConnection($this->_read);
+ }
+ return $this->_read;
+ }
+
+ /**
+ * Retrieve connection for write data
+ *
+ * @return Varien_Db_Adapter_Interface|false
+ */
+ protected function _getWriteAdapter()
+ {
+ if (is_string($this->_write)) {
+ $this->_write = Mage::getSingleton('core/resource')->getConnection($this->_write);
+ }
+ return $this->_write;
+ }
+
+ /**
+ * Return default static virtual attribute that doesn't exists in EAV attributes
+ *
+ * @param string $attributeCode
+ * @return Mage_Eav_Model_Entity_Attribute
+ */
+ protected function _getDefaultAttribute($attributeCode)
+ {
+ $entityTypeId = $this->getEntityType()->getId();
+ if (!isset(self::$_defaultAttributes[$entityTypeId][$attributeCode])) {
+ $attribute = Mage::getModel($this->getEntityType()->getAttributeModel())
+ ->setAttributeCode($attributeCode)
+ ->setBackendType(Mage_Eav_Model_Entity_Attribute_Abstract::TYPE_STATIC)
+ ->setIsGlobal(1)
+ ->setEntityType($this->getEntityType())
+ ->setEntityTypeId($this->getEntityType()->getId());
+ self::$_defaultAttributes[$entityTypeId][$attributeCode] = $attribute;
+ }
+
+ return self::$_defaultAttributes[$entityTypeId][$attributeCode];
+ }
+
+ /**
+ * Check whether the attribute is Applicable to the object
+ *
+ * @param Varien_Object $object
+ * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute
+ * @return bool
+ */
+ protected function _isApplicableAttribute($object, $attribute)
+ {
+ return true;
+ }
+
+ /**
+ * Check whether attribute instance (attribute, backend, frontend or source) has method and applicable
+ *
+ * @param Mage_Eav_Model_Entity_Attribute_Abstract|Mage_Eav_Model_Entity_Attribute_Backend_Abstract|Mage_Eav_Model_Entity_Attribute_Frontend_Abstract|Mage_Eav_Model_Entity_Attribute_Source_Abstract $instance
+ * @param string $method
+ * @param array $args array of arguments
+ * @return bool
+ */
+ protected function _isCallableAttributeInstance($instance, $method, $args)
+ {
+ if (!is_object($instance) || !method_exists($instance, $method)) {
+ return false;
+ }
+
+ return true;
+ }
+
/**
* Load model attributes data
*
@@ -1059,34 +1192,6 @@ protected function _setAttributeValue($object, $valueRow)
return $this;
}
- /**
- * Save entity's attributes into the object's resource
- *
- * @return $this
- */
- public function save(Varien_Object $object)
- {
- if ($object->isDeleted()) {
- return $this->delete($object);
- }
-
- if (!$this->isPartialSave()) {
- $this->loadAllAttributes($object);
- }
-
- if (!$object->getEntityTypeId()) {
- $object->setEntityTypeId($this->getTypeId());
- }
-
- $object->setParentId((int) $object->getParentId());
-
- $this->_beforeSave($object);
- $this->_processSaveData($this->_collectSaveData($object));
- $this->_afterSave($object);
-
- return $this;
- }
-
/**
* Retrieve Object instance with original data
*
@@ -1501,101 +1606,6 @@ protected function _deleteAttributes($object, $table, $info)
return $this;
}
- /**
- * Save attribute
- *
- * @param string $attributeCode
- * @return $this
- */
- public function saveAttribute(Varien_Object $object, $attributeCode)
- {
- $this->_attributeValuesToSave = [];
- $this->_attributeValuesToDelete = [];
-
- $attribute = $this->getAttribute($attributeCode);
- $backend = $attribute->getBackend();
- $table = $backend->getTable();
- $entity = $attribute->getEntity();
- $entityIdField = $entity->getEntityIdField();
- $adapter = $this->_getWriteAdapter();
-
- $row = [
- 'entity_type_id' => $entity->getTypeId(),
- 'attribute_id' => $attribute->getId(),
- $entityIdField => $object->getData($entityIdField),
- ];
-
- $newValue = $object->getData($attributeCode);
- if ($attribute->isValueEmpty($newValue)) {
- $newValue = null;
- }
-
- $whereArr = [];
- foreach ($row as $field => $value) {
- $whereArr[] = $adapter->quoteInto($field . '=?', $value);
- }
- $where = implode(' AND ', $whereArr);
-
- $adapter->beginTransaction();
-
- try {
- $select = $adapter->select()
- ->from($table, 'value_id')
- ->where($where);
- $origValueId = $adapter->fetchOne($select);
-
- if ($origValueId === false && ($newValue !== null)) {
- $this->_insertAttribute($object, $attribute, $newValue);
- } elseif ($origValueId !== false && ($newValue !== null)) {
- $this->_updateAttribute($object, $attribute, $origValueId, $newValue);
- } elseif ($origValueId !== false && ($newValue === null)) {
- $adapter->delete($table, $where);
- }
- $this->_processAttributeValues();
- $adapter->commit();
- } catch (Exception $e) {
- $adapter->rollBack();
- throw $e;
- }
-
- return $this;
- }
-
- /**
- * Delete entity using current object's data
- *
- * @param int|string|Varien_Object $object
- * @return $this
- * @throws Exception
- */
- public function delete($object)
- {
- if (is_numeric($object)) {
- $id = (int) $object;
- } elseif ($object instanceof Varien_Object) {
- $id = (int) $object->getId();
- }
-
- $this->_beforeDelete($object);
-
- try {
- $where = [
- $this->getEntityIdField() . '=?' => $id,
- ];
- $this->_getWriteAdapter()->delete($this->getEntityTable(), $where);
- $this->loadAllAttributes($object);
- foreach (array_keys($this->getAttributesByTable()) as $table) {
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $this->_getWriteAdapter()->delete($table, $where);
- }
- } catch (Exception $e) {
- throw $e;
- }
-
- $this->_afterDelete($object);
- return $this;
- }
-
/**
* After Load Entity process
*
@@ -1671,16 +1681,6 @@ protected function _getDefaultAttributes()
return ['entity_type_id', 'attribute_set_id', 'created_at', 'updated_at', 'parent_id', 'increment_id'];
}
- /**
- * Retrieve default entity static attributes
- *
- * @return array
- */
- public function getDefaultAttributes()
- {
- return array_unique(array_merge($this->_getDefaultAttributes(), [$this->getEntityIdField()]));
- }
-
/**
* After set config process
*
diff --git a/app/code/core/Mage/Eav/Model/Entity/Attribute.php b/app/code/core/Mage/Eav/Model/Entity/Attribute.php
index 8e2d97718eb..57410c2338b 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Attribute.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Attribute.php
@@ -36,6 +36,9 @@
*/
class Mage_Eav_Model_Entity_Attribute extends Mage_Eav_Model_Entity_Attribute_Abstract
{
+ public const ATTRIBUTE_CODE_MAX_LENGTH = 30;
+
+ public const CACHE_TAG = 'EAV_ATTRIBUTE';
/**
* Prefix of model events names
*
@@ -43,8 +46,6 @@ class Mage_Eav_Model_Entity_Attribute extends Mage_Eav_Model_Entity_Attribute_Ab
*/
protected $_eventPrefix = 'eav_entity_attribute';
- public const ATTRIBUTE_CODE_MAX_LENGTH = 30;
-
/**
* Parameter name in event
*
@@ -53,57 +54,8 @@ class Mage_Eav_Model_Entity_Attribute extends Mage_Eav_Model_Entity_Attribute_Ab
* @var string
*/
protected $_eventObject = 'attribute';
-
- public const CACHE_TAG = 'EAV_ATTRIBUTE';
protected $_cacheTag = 'EAV_ATTRIBUTE';
- /**
- * Retrieve default attribute backend model by attribute code
- *
- * @return string
- */
- protected function _getDefaultBackendModel()
- {
- switch ($this->getAttributeCode()) {
- case 'created_at':
- return 'eav/entity_attribute_backend_time_created';
-
- case 'updated_at':
- return 'eav/entity_attribute_backend_time_updated';
-
- case 'store_id':
- return 'eav/entity_attribute_backend_store';
-
- case 'increment_id':
- return 'eav/entity_attribute_backend_increment';
- }
-
- return parent::_getDefaultBackendModel();
- }
-
- /**
- * Retrieve default attribute frontend model
- *
- * @return string
- */
- protected function _getDefaultFrontendModel()
- {
- return parent::_getDefaultFrontendModel();
- }
-
- /**
- * Retrieve default attribute source model
- *
- * @return string
- */
- protected function _getDefaultSourceModel()
- {
- if ($this->getAttributeCode() == 'store_id') {
- return 'eav/entity_attribute_source_store';
- }
- return parent::_getDefaultSourceModel();
- }
-
/**
* Delete entity
*
@@ -133,87 +85,6 @@ public function loadEntityAttributeIdBySet()
return $this;
}
- /**
- * Prepare data for save
- *
- * @inheritDoc
- * @throws Mage_Eav_Exception
- */
- protected function _beforeSave()
- {
- /**
- * Check for maximum attribute_code length
- */
- if (isset($this->_data['attribute_code']) &&
- !Zend_Validate::is(
- $this->_data['attribute_code'],
- 'StringLength',
- ['max' => self::ATTRIBUTE_CODE_MAX_LENGTH],
- )
- ) {
- throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Maximum length of attribute code must be less then %s symbols', self::ATTRIBUTE_CODE_MAX_LENGTH));
- }
-
- $defaultValue = $this->getDefaultValue();
- $hasDefaultValue = ((string) $defaultValue != '');
-
- if ($this->getBackendType() == 'decimal' && $hasDefaultValue) {
- $locale = Mage::app()->getLocale()->getLocaleCode();
- if (!Zend_Locale_Format::isNumber($defaultValue, ['locale' => $locale])) {
- throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Invalid default decimal value'));
- }
-
- try {
- $filter = new Zend_Filter_LocalizedToNormalized(
- ['locale' => Mage::app()->getLocale()->getLocaleCode()],
- );
- $this->setDefaultValue($filter->filter($defaultValue));
- } catch (Exception $e) {
- throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Invalid default decimal value'));
- }
- }
-
- if ($this->getBackendType() == 'datetime') {
- if (!$this->getBackendModel()) {
- $this->setBackendModel('eav/entity_attribute_backend_datetime');
- }
-
- if (!$this->getFrontendModel()) {
- $this->setFrontendModel('eav/entity_attribute_frontend_datetime');
- }
-
- // save default date value as timestamp
- if ($hasDefaultValue) {
- $format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
- try {
- $defaultValue = Mage::app()->getLocale()->date($defaultValue, $format, null, false)->toValue();
- $this->setDefaultValue($defaultValue);
- } catch (Exception $e) {
- throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Invalid default date'));
- }
- }
- }
-
- if ($this->getBackendType() == 'gallery') {
- if (!$this->getBackendModel()) {
- $this->setBackendModel('eav/entity_attribute_backend_media');
- }
- }
-
- return parent::_beforeSave();
- }
-
- /**
- * Save additional data
- *
- * @inheritDoc
- */
- protected function _afterSave()
- {
- $this->_getResource()->saveInSetIncluding($this);
- return parent::_afterSave();
- }
-
/**
* Detect backend storage type using frontend input type
*
@@ -341,4 +212,132 @@ public function getStoreLabel($storeId = null)
}
return $this->getFrontendLabel();
}
+
+ /**
+ * Retrieve default attribute backend model by attribute code
+ *
+ * @return string
+ */
+ protected function _getDefaultBackendModel()
+ {
+ switch ($this->getAttributeCode()) {
+ case 'created_at':
+ return 'eav/entity_attribute_backend_time_created';
+
+ case 'updated_at':
+ return 'eav/entity_attribute_backend_time_updated';
+
+ case 'store_id':
+ return 'eav/entity_attribute_backend_store';
+
+ case 'increment_id':
+ return 'eav/entity_attribute_backend_increment';
+ }
+
+ return parent::_getDefaultBackendModel();
+ }
+
+ /**
+ * Retrieve default attribute frontend model
+ *
+ * @return string
+ */
+ protected function _getDefaultFrontendModel()
+ {
+ return parent::_getDefaultFrontendModel();
+ }
+
+ /**
+ * Retrieve default attribute source model
+ *
+ * @return string
+ */
+ protected function _getDefaultSourceModel()
+ {
+ if ($this->getAttributeCode() == 'store_id') {
+ return 'eav/entity_attribute_source_store';
+ }
+ return parent::_getDefaultSourceModel();
+ }
+
+ /**
+ * Prepare data for save
+ *
+ * @inheritDoc
+ * @throws Mage_Eav_Exception
+ */
+ protected function _beforeSave()
+ {
+ /**
+ * Check for maximum attribute_code length
+ */
+ if (isset($this->_data['attribute_code']) &&
+ !Zend_Validate::is(
+ $this->_data['attribute_code'],
+ 'StringLength',
+ ['max' => self::ATTRIBUTE_CODE_MAX_LENGTH],
+ )
+ ) {
+ throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Maximum length of attribute code must be less then %s symbols', self::ATTRIBUTE_CODE_MAX_LENGTH));
+ }
+
+ $defaultValue = $this->getDefaultValue();
+ $hasDefaultValue = ((string) $defaultValue != '');
+
+ if ($this->getBackendType() == 'decimal' && $hasDefaultValue) {
+ $locale = Mage::app()->getLocale()->getLocaleCode();
+ if (!Zend_Locale_Format::isNumber($defaultValue, ['locale' => $locale])) {
+ throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Invalid default decimal value'));
+ }
+
+ try {
+ $filter = new Zend_Filter_LocalizedToNormalized(
+ ['locale' => Mage::app()->getLocale()->getLocaleCode()],
+ );
+ $this->setDefaultValue($filter->filter($defaultValue));
+ } catch (Exception $e) {
+ throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Invalid default decimal value'));
+ }
+ }
+
+ if ($this->getBackendType() == 'datetime') {
+ if (!$this->getBackendModel()) {
+ $this->setBackendModel('eav/entity_attribute_backend_datetime');
+ }
+
+ if (!$this->getFrontendModel()) {
+ $this->setFrontendModel('eav/entity_attribute_frontend_datetime');
+ }
+
+ // save default date value as timestamp
+ if ($hasDefaultValue) {
+ $format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
+ try {
+ $defaultValue = Mage::app()->getLocale()->date($defaultValue, $format, null, false)->toValue();
+ $this->setDefaultValue($defaultValue);
+ } catch (Exception $e) {
+ throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Invalid default date'));
+ }
+ }
+ }
+
+ if ($this->getBackendType() == 'gallery') {
+ if (!$this->getBackendModel()) {
+ $this->setBackendModel('eav/entity_attribute_backend_media');
+ }
+ }
+
+ return parent::_beforeSave();
+ }
+
+ /**
+ * Save additional data
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave()
+ {
+ $this->_getResource()->saveInSetIncluding($this);
+ return parent::_afterSave();
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php b/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php
index 90587c14615..44623d6f98a 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php
@@ -113,11 +113,6 @@ abstract class Mage_Eav_Model_Entity_Attribute_Abstract extends Mage_Core_Model_
*/
protected $_attributeValidationPassed = false;
- protected function _construct()
- {
- $this->_init('eav/entity_attribute');
- }
-
/**
* Load attribute data by code
*
@@ -499,30 +494,6 @@ public function usesSource()
|| $this->getData('source_model') != '';
}
- /**
- * @return string
- */
- protected function _getDefaultBackendModel()
- {
- return Mage_Eav_Model_Entity::DEFAULT_BACKEND_MODEL;
- }
-
- /**
- * @return string
- */
- protected function _getDefaultFrontendModel()
- {
- return Mage_Eav_Model_Entity::DEFAULT_FRONTEND_MODEL;
- }
-
- /**
- * @return string
- */
- protected function _getDefaultSourceModel()
- {
- return $this->getEntity()->getDefaultAttributeSourceModel();
- }
-
/**
* @param mixed $value
* @return bool
@@ -740,85 +711,6 @@ public function _getFlatColumnsDdlDefinition()
return $columns;
}
- /**
- * Retrieve flat columns definition in old format (before MMDB support)
- * Used in database compatible mode
- *
- * @return array
- */
- protected function _getFlatColumnsOldDefinition()
- {
- $columns = [];
- switch ($this->getBackendType()) {
- case 'static':
- $describe = $this->_getResource()->describeTable($this->getBackend()->getTable());
- if (!isset($describe[$this->getAttributeCode()])) {
- break;
- }
- $prop = $describe[$this->getAttributeCode()];
- $type = $prop['DATA_TYPE'];
- if (isset($prop['PRECISION'], $prop['SCALE'])) {
- $type .= "({$prop['PRECISION']},{$prop['SCALE']})";
- } else {
- $type .= (isset($prop['LENGTH']) && $prop['LENGTH']) ? "({$prop['LENGTH']})" : '';
- }
- $columns[$this->getAttributeCode()] = [
- 'type' => $type,
- 'unsigned' => $prop['UNSIGNED'] ? true : false,
- 'is_null' => $prop['NULLABLE'],
- 'default' => $prop['DEFAULT'],
- 'extra' => null,
- ];
- break;
- case 'datetime':
- $columns[$this->getAttributeCode()] = [
- 'type' => 'datetime',
- 'unsigned' => false,
- 'is_null' => true,
- 'default' => null,
- 'extra' => null,
- ];
- break;
- case 'decimal':
- $columns[$this->getAttributeCode()] = [
- 'type' => 'decimal(12,4)',
- 'unsigned' => false,
- 'is_null' => true,
- 'default' => null,
- 'extra' => null,
- ];
- break;
- case 'int':
- $columns[$this->getAttributeCode()] = [
- 'type' => 'int',
- 'unsigned' => false,
- 'is_null' => true,
- 'default' => null,
- 'extra' => null,
- ];
- break;
- case 'text':
- $columns[$this->getAttributeCode()] = [
- 'type' => 'text',
- 'unsigned' => false,
- 'is_null' => true,
- 'default' => null,
- 'extra' => null,
- ];
- break;
- case 'varchar':
- $columns[$this->getAttributeCode()] = [
- 'type' => 'varchar(255)',
- 'unsigned' => false,
- 'is_null' => true,
- 'default' => null,
- 'extra' => null,
- ];
- break;
- }
- return $columns;
- }
-
/**
* Retrieve index data for flat table
*
@@ -930,4 +822,112 @@ public function getApplyTo()
{
return [];
}
+
+ protected function _construct()
+ {
+ $this->_init('eav/entity_attribute');
+ }
+
+ /**
+ * @return string
+ */
+ protected function _getDefaultBackendModel()
+ {
+ return Mage_Eav_Model_Entity::DEFAULT_BACKEND_MODEL;
+ }
+
+ /**
+ * @return string
+ */
+ protected function _getDefaultFrontendModel()
+ {
+ return Mage_Eav_Model_Entity::DEFAULT_FRONTEND_MODEL;
+ }
+
+ /**
+ * @return string
+ */
+ protected function _getDefaultSourceModel()
+ {
+ return $this->getEntity()->getDefaultAttributeSourceModel();
+ }
+
+ /**
+ * Retrieve flat columns definition in old format (before MMDB support)
+ * Used in database compatible mode
+ *
+ * @return array
+ */
+ protected function _getFlatColumnsOldDefinition()
+ {
+ $columns = [];
+ switch ($this->getBackendType()) {
+ case 'static':
+ $describe = $this->_getResource()->describeTable($this->getBackend()->getTable());
+ if (!isset($describe[$this->getAttributeCode()])) {
+ break;
+ }
+ $prop = $describe[$this->getAttributeCode()];
+ $type = $prop['DATA_TYPE'];
+ if (isset($prop['PRECISION'], $prop['SCALE'])) {
+ $type .= "({$prop['PRECISION']},{$prop['SCALE']})";
+ } else {
+ $type .= (isset($prop['LENGTH']) && $prop['LENGTH']) ? "({$prop['LENGTH']})" : '';
+ }
+ $columns[$this->getAttributeCode()] = [
+ 'type' => $type,
+ 'unsigned' => $prop['UNSIGNED'] ? true : false,
+ 'is_null' => $prop['NULLABLE'],
+ 'default' => $prop['DEFAULT'],
+ 'extra' => null,
+ ];
+ break;
+ case 'datetime':
+ $columns[$this->getAttributeCode()] = [
+ 'type' => 'datetime',
+ 'unsigned' => false,
+ 'is_null' => true,
+ 'default' => null,
+ 'extra' => null,
+ ];
+ break;
+ case 'decimal':
+ $columns[$this->getAttributeCode()] = [
+ 'type' => 'decimal(12,4)',
+ 'unsigned' => false,
+ 'is_null' => true,
+ 'default' => null,
+ 'extra' => null,
+ ];
+ break;
+ case 'int':
+ $columns[$this->getAttributeCode()] = [
+ 'type' => 'int',
+ 'unsigned' => false,
+ 'is_null' => true,
+ 'default' => null,
+ 'extra' => null,
+ ];
+ break;
+ case 'text':
+ $columns[$this->getAttributeCode()] = [
+ 'type' => 'text',
+ 'unsigned' => false,
+ 'is_null' => true,
+ 'default' => null,
+ 'extra' => null,
+ ];
+ break;
+ case 'varchar':
+ $columns[$this->getAttributeCode()] = [
+ 'type' => 'varchar(255)',
+ 'unsigned' => false,
+ 'is_null' => true,
+ 'default' => null,
+ 'extra' => null,
+ ];
+ break;
+ }
+ return $columns;
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Entity/Attribute/Backend/Time/Created.php b/app/code/core/Mage/Eav/Model/Entity/Attribute/Backend/Time/Created.php
index def2dac6b72..81fb0330789 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Attribute/Backend/Time/Created.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Attribute/Backend/Time/Created.php
@@ -22,20 +22,6 @@
*/
class Mage_Eav_Model_Entity_Attribute_Backend_Time_Created extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
- /**
- * Returns date format if it matches a certain mask.
- * @param string $date
- * @return null|string
- */
- protected function _getFormat($date)
- {
- if (is_string($date) && (preg_match('#^\d{4,4}-\d{2,2}-\d{2,2}\s\d{2,2}:\d{2,2}:\d{2,2}$#', $date)
- || preg_match('#^\d{4,4}-\d{2,2}-\d{2,2}\w{1,1}\d{2,2}:\d{2,2}:\d{2,2}[+-]\d{2,2}:\d{2,2}$#', $date))
- ) {
- return 'yyyy-MM-dd HH:mm:ss';
- }
- return null;
- }
/**
* Set created date
* Set created date in UTC time zone
@@ -78,4 +64,18 @@ public function afterLoad($object)
return $this;
}
+ /**
+ * Returns date format if it matches a certain mask.
+ * @param string $date
+ * @return null|string
+ */
+ protected function _getFormat($date)
+ {
+ if (is_string($date) && (preg_match('#^\d{4,4}-\d{2,2}-\d{2,2}\s\d{2,2}:\d{2,2}:\d{2,2}$#', $date)
+ || preg_match('#^\d{4,4}-\d{2,2}-\d{2,2}\w{1,1}\d{2,2}:\d{2,2}:\d{2,2}[+-]\d{2,2}:\d{2,2}$#', $date))
+ ) {
+ return 'yyyy-MM-dd HH:mm:ss';
+ }
+ return null;
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php b/app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php
index 3926dd2f27f..e9f2cd48dcb 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php
@@ -149,39 +149,6 @@ public function getClass()
return $out;
}
- /**
- * Return validate class by attribute input validation rule
- *
- * @return string|false
- */
- protected function _getInputValidateClass()
- {
- $class = false;
- $validateRules = $this->getAttribute()->getValidateRules();
- if (!empty($validateRules['input_validation'])) {
- switch ($validateRules['input_validation']) {
- case 'alphanumeric':
- $class = 'validate-alphanum';
- break;
- case 'numeric':
- $class = 'validate-digits';
- break;
- case 'alpha':
- $class = 'validate-alpha';
- break;
- case 'email':
- $class = 'validate-email';
- break;
- case 'url':
- $class = 'validate-url';
- break;
- default:
- break;
- }
- }
- return $class;
- }
-
/**
* Reireive config field
*
@@ -231,4 +198,37 @@ public function getInputRendererClass()
}
return null;
}
+
+ /**
+ * Return validate class by attribute input validation rule
+ *
+ * @return string|false
+ */
+ protected function _getInputValidateClass()
+ {
+ $class = false;
+ $validateRules = $this->getAttribute()->getValidateRules();
+ if (!empty($validateRules['input_validation'])) {
+ switch ($validateRules['input_validation']) {
+ case 'alphanumeric':
+ $class = 'validate-alphanum';
+ break;
+ case 'numeric':
+ $class = 'validate-digits';
+ break;
+ case 'alpha':
+ $class = 'validate-alpha';
+ break;
+ case 'email':
+ $class = 'validate-email';
+ break;
+ case 'url':
+ $class = 'validate-url';
+ break;
+ default:
+ break;
+ }
+ }
+ return $class;
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Entity/Attribute/Group.php b/app/code/core/Mage/Eav/Model/Entity/Attribute/Group.php
index 38ea6fea032..0ea7710dde2 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Attribute/Group.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Attribute/Group.php
@@ -36,11 +36,6 @@
*/
class Mage_Eav_Model_Entity_Attribute_Group extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('eav/entity_attribute_group');
- }
-
/**
* Checks if current attribute group exists
*
@@ -60,4 +55,8 @@ public function deleteGroups()
{
return $this->_getResource()->deleteGroups($this);
}
+ protected function _construct()
+ {
+ $this->_init('eav/entity_attribute_group');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Entity/Attribute/Set.php b/app/code/core/Mage/Eav/Model/Entity/Attribute/Set.php
index d0b6b114669..9faeebd526d 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Attribute/Set.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Attribute/Set.php
@@ -47,11 +47,6 @@ class Mage_Eav_Model_Entity_Attribute_Set extends Mage_Core_Model_Abstract
*/
protected $_eventPrefix = 'eav_entity_attribute_set';
- protected function _construct()
- {
- $this->_init('eav/entity_attribute_set');
- }
-
/**
* Init attribute set from skeleton (another attribute set)
*
@@ -264,4 +259,9 @@ public function getDefaultGroupId($setId = null)
}
return $groupId;
}
+
+ protected function _construct()
+ {
+ $this->_init('eav/entity_attribute_set');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php b/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php
index 5e2b41da7e2..39382861798 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php
@@ -116,11 +116,6 @@ public function __construct($resource = null)
$this->_initSelect();
}
- /**
- * Initialize collection
- */
- protected function _construct() {}
-
/**
* Retrieve table name
*
@@ -132,54 +127,6 @@ public function getTable($table)
return $this->getResource()->getTable($table);
}
- /**
- * Prepare static entity fields
- *
- * @return $this
- */
- protected function _prepareStaticFields()
- {
- foreach ($this->getEntity()->getDefaultAttributes() as $field) {
- $this->_staticFields[$field] = $field;
- }
- return $this;
- }
-
- /**
- * Init select
- *
- * @return $this
- */
- protected function _initSelect()
- {
- $this->getSelect()->from(['e' => $this->getEntity()->getEntityTable()]);
-
- if ($this->getEntity()->getEntityTable() === Mage_Eav_Model_Entity::DEFAULT_ENTITY_TABLE && $this->getEntity()->getTypeId()) {
- $this->addAttributeToFilter('entity_type_id', $this->getEntity()->getTypeId());
- }
-
- return $this;
- }
-
- /**
- * Standard resource collection initialization
- *
- * @param string $model
- * @param null|string $entityModel
- * @return $this
- */
- protected function _init($model, $entityModel = null)
- {
- $this->setItemObjectClass(Mage::getConfig()->getModelClassName($model));
- if ($entityModel === null) {
- $entityModel = $model;
- }
- $entity = Mage::getResourceSingleton($entityModel);
- $this->setEntity($entity);
-
- return $this;
- }
-
/**
* Set entity to use for attributes
*
@@ -378,25 +325,6 @@ public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC)
return $this;
}
- /**
- * Retrieve attribute expression by specified column
- *
- * @param string $field
- * @return string|Zend_Db_Expr
- */
- protected function _prepareOrderExpression($field)
- {
- foreach ($this->getSelect()->getPart(Zend_Db_Select::COLUMNS) as $columnEntry) {
- if ($columnEntry[2] != $field) {
- continue;
- }
- if ($columnEntry[1] instanceof Zend_Db_Expr) {
- return $columnEntry[1];
- }
- }
- return $field;
- }
-
/**
* Add attribute to entities in collection
*
@@ -887,27 +815,6 @@ public function load($printQuery = false, $logQuery = false)
return $this;
}
- /**
- * Clone and reset collection
- *
- * @param int $limit
- * @param int $offset
- * @return Varien_Db_Select
- * @throws Mage_Core_Exception
- */
- protected function _getAllIdsSelect($limit = null, $offset = null)
- {
- $idsSelect = clone $this->getSelect();
- $idsSelect->reset(Zend_Db_Select::ORDER);
- $idsSelect->reset(Zend_Db_Select::LIMIT_COUNT);
- $idsSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
- $idsSelect->reset(Zend_Db_Select::COLUMNS);
- $idsSelect->columns('e.' . $this->getEntity()->getIdFieldName());
- $idsSelect->limit($limit, $offset);
-
- return $idsSelect;
- }
-
/**
* Retrieve all ids for collection
*
@@ -1142,6 +1049,164 @@ public function _loadAttributes($printQuery = false, $logQuery = false)
return $this;
}
+ /**
+ * Set sorting order
+ *
+ * $attribute can also be an array of attributes
+ *
+ * @inheritDoc
+ */
+ public function setOrder($attribute, $dir = self::SORT_ORDER_ASC)
+ {
+ if (is_array($attribute)) {
+ foreach ($attribute as $attr) {
+ parent::setOrder($attr, $dir);
+ }
+ return $this;
+ }
+ return parent::setOrder($attribute, $dir);
+ }
+
+ /**
+ * Retrieve array of attributes
+ *
+ * @param array $arrAttributes
+ * @return array
+ */
+ public function toArray($arrAttributes = [])
+ {
+ $arr = [];
+ foreach ($this->_items as $k => $item) {
+ $arr[$k] = $item->toArray($arrAttributes);
+ }
+ return $arr;
+ }
+
+ /**
+ * Returns already loaded element ids
+ *
+ * return array
+ */
+ public function getLoadedIds()
+ {
+ return array_keys($this->_items);
+ }
+
+ /**
+ * Prepare select for load
+ *
+ * @param Varien_Db_Select $select OPTIONAL
+ * @return string
+ */
+ public function _prepareSelect(Varien_Db_Select $select)
+ {
+ if ($this->_useAnalyticFunction) {
+ /** @var Mage_Core_Model_Resource_Helper_Mysql4 $helper */
+ $helper = Mage::getResourceHelper('core');
+ return $helper->getQueryUsingAnalyticFunction($select);
+ }
+
+ return (string) $select;
+ }
+
+ public function isModuleEnabled(string $moduleName, string $helperAlias = 'core'): bool
+ {
+ return Mage::helper($helperAlias)->isModuleEnabled($moduleName);
+ }
+
+ /**
+ * Initialize collection
+ */
+ protected function _construct() {}
+
+ /**
+ * Prepare static entity fields
+ *
+ * @return $this
+ */
+ protected function _prepareStaticFields()
+ {
+ foreach ($this->getEntity()->getDefaultAttributes() as $field) {
+ $this->_staticFields[$field] = $field;
+ }
+ return $this;
+ }
+
+ /**
+ * Init select
+ *
+ * @return $this
+ */
+ protected function _initSelect()
+ {
+ $this->getSelect()->from(['e' => $this->getEntity()->getEntityTable()]);
+
+ if ($this->getEntity()->getEntityTable() === Mage_Eav_Model_Entity::DEFAULT_ENTITY_TABLE && $this->getEntity()->getTypeId()) {
+ $this->addAttributeToFilter('entity_type_id', $this->getEntity()->getTypeId());
+ }
+
+ return $this;
+ }
+
+ /**
+ * Standard resource collection initialization
+ *
+ * @param string $model
+ * @param null|string $entityModel
+ * @return $this
+ */
+ protected function _init($model, $entityModel = null)
+ {
+ $this->setItemObjectClass(Mage::getConfig()->getModelClassName($model));
+ if ($entityModel === null) {
+ $entityModel = $model;
+ }
+ $entity = Mage::getResourceSingleton($entityModel);
+ $this->setEntity($entity);
+
+ return $this;
+ }
+
+ /**
+ * Retrieve attribute expression by specified column
+ *
+ * @param string $field
+ * @return string|Zend_Db_Expr
+ */
+ protected function _prepareOrderExpression($field)
+ {
+ foreach ($this->getSelect()->getPart(Zend_Db_Select::COLUMNS) as $columnEntry) {
+ if ($columnEntry[2] != $field) {
+ continue;
+ }
+ if ($columnEntry[1] instanceof Zend_Db_Expr) {
+ return $columnEntry[1];
+ }
+ }
+ return $field;
+ }
+
+ /**
+ * Clone and reset collection
+ *
+ * @param int $limit
+ * @param int $offset
+ * @return Varien_Db_Select
+ * @throws Mage_Core_Exception
+ */
+ protected function _getAllIdsSelect($limit = null, $offset = null)
+ {
+ $idsSelect = clone $this->getSelect();
+ $idsSelect->reset(Zend_Db_Select::ORDER);
+ $idsSelect->reset(Zend_Db_Select::LIMIT_COUNT);
+ $idsSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
+ $idsSelect->reset(Zend_Db_Select::COLUMNS);
+ $idsSelect->columns('e.' . $this->getEntity()->getIdFieldName());
+ $idsSelect->limit($limit, $offset);
+
+ return $idsSelect;
+ }
+
/**
* Retrieve attributes load select
*
@@ -1412,39 +1477,6 @@ protected function _getAttributeConditionSql($attribute, $condition, $joinType =
return $conditionSql;
}
- /**
- * Set sorting order
- *
- * $attribute can also be an array of attributes
- *
- * @inheritDoc
- */
- public function setOrder($attribute, $dir = self::SORT_ORDER_ASC)
- {
- if (is_array($attribute)) {
- foreach ($attribute as $attr) {
- parent::setOrder($attr, $dir);
- }
- return $this;
- }
- return parent::setOrder($attribute, $dir);
- }
-
- /**
- * Retrieve array of attributes
- *
- * @param array $arrAttributes
- * @return array
- */
- public function toArray($arrAttributes = [])
- {
- $arr = [];
- foreach ($this->_items as $k => $item) {
- $arr[$k] = $item->toArray($arrAttributes);
- }
- return $arr;
- }
-
/**
* Treat "order by" items as attributes to sort
*
@@ -1489,36 +1521,4 @@ protected function _reset()
return $this;
}
-
- /**
- * Returns already loaded element ids
- *
- * return array
- */
- public function getLoadedIds()
- {
- return array_keys($this->_items);
- }
-
- /**
- * Prepare select for load
- *
- * @param Varien_Db_Select $select OPTIONAL
- * @return string
- */
- public function _prepareSelect(Varien_Db_Select $select)
- {
- if ($this->_useAnalyticFunction) {
- /** @var Mage_Core_Model_Resource_Helper_Mysql4 $helper */
- $helper = Mage::getResourceHelper('core');
- return $helper->getQueryUsingAnalyticFunction($select);
- }
-
- return (string) $select;
- }
-
- public function isModuleEnabled(string $moduleName, string $helperAlias = 'core'): bool
- {
- return Mage::helper($helperAlias)->isModuleEnabled($moduleName);
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Entity/Setup.php b/app/code/core/Mage/Eav/Model/Entity/Setup.php
index 23bc9445ba5..3aecb09b7d4 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Setup.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Setup.php
@@ -24,13 +24,6 @@
*/
class Mage_Eav_Model_Entity_Setup extends Mage_Core_Model_Resource_Setup
{
- /**
- * General Attribute Group Name
- *
- * @var string
- */
- protected $_generalGroupName = 'General';
-
/**
* Default attribute group name to id pairs
*
@@ -39,6 +32,12 @@ class Mage_Eav_Model_Entity_Setup extends Mage_Core_Model_Resource_Setup
public $defaultGroupIdAssociations = [
'General' => 1,
];
+ /**
+ * General Attribute Group Name
+ *
+ * @var string
+ */
+ protected $_generalGroupName = 'General';
/**
* Default attribute group name
@@ -591,73 +590,6 @@ public function getDefaultAttributeGroupId($entityType, $attributeSetId = null)
return $this->getConnection()->fetchOne($select, $bind);
}
- /******************* ATTRIBUTES *****************/
-
- /**
- * Retrieve value from array by key or return default value
- *
- * @param array $array
- * @param string $key
- * @param string $default
- * @return string
- */
- protected function _getValue($array, $key, $default = null)
- {
- if (isset($array[$key]) && is_bool($array[$key])) {
- $array[$key] = (int) $array[$key];
- }
- return $array[$key] ?? $default;
- }
-
- /**
- * Prepare attribute values to save
- *
- * @param array $attr
- * @return array
- */
- protected function _prepareValues($attr)
- {
- return [
- 'backend_model' => $this->_getValue($attr, 'backend'),
- 'backend_type' => $this->_getValue($attr, 'type', 'varchar'),
- 'backend_table' => $this->_getValue($attr, 'table'),
- 'frontend_model' => $this->_getValue($attr, 'frontend'),
- 'frontend_input' => $this->_getValue($attr, 'input', 'text'),
- 'frontend_label' => $this->_getValue($attr, 'label'),
- 'frontend_class' => $this->_getValue($attr, 'frontend_class'),
- 'source_model' => $this->_getValue($attr, 'source'),
- 'is_required' => $this->_getValue($attr, 'required', 1),
- 'is_user_defined' => $this->_getValue($attr, 'user_defined', 0),
- 'default_value' => $this->_getValue($attr, 'default'),
- 'is_unique' => $this->_getValue($attr, 'unique', 0),
- 'note' => $this->_getValue($attr, 'note'),
- 'is_global' => $this->_getValue($attr, 'global', 1),
- ];
- }
-
- /**
- * Validate attribute data before insert into table
- *
- * @param array $data
- * @throws Mage_Eav_Exception
- * @return true
- */
- protected function _validateAttributeData($data)
- {
- $attributeCodeMaxLength = Mage_Eav_Model_Entity_Attribute::ATTRIBUTE_CODE_MAX_LENGTH;
-
- if (isset($data['attribute_code']) &&
- !Zend_Validate::is($data['attribute_code'], 'StringLength', ['max' => $attributeCodeMaxLength])
- ) {
- throw Mage::exception(
- 'Mage_Eav',
- Mage::helper('eav')->__('Maximum length of attribute code must be less then %s symbols', $attributeCodeMaxLength),
- );
- }
-
- return true;
- }
-
/**
* Add attribute to an entity type
*
@@ -815,105 +747,6 @@ public function updateAttribute($entityTypeId, $id, $field, $value = null, $sort
return $this;
}
- /**
- * Update Attribute data
- *
- * @param mixed $entityTypeId
- * @param mixed $id
- * @param string $field
- * @param mixed $value
- * @param int $sortOrder
- * @return $this
- */
- protected function _updateAttribute($entityTypeId, $id, $field, $value = null, $sortOrder = null)
- {
- if ($sortOrder !== null) {
- $this->updateTableRow(
- 'eav/entity_attribute',
- 'attribute_id',
- $this->getAttributeId($entityTypeId, $id),
- 'sort_order',
- $sortOrder,
- );
- }
-
- $attributeFields = $this->_getAttributeTableFields();
- if (is_array($field)) {
- $bind = [];
- foreach ($field as $k => $v) {
- if (isset($attributeFields[$k])) {
- $bind[$k] = $this->getConnection()->prepareColumnValue($attributeFields[$k], $v);
- }
- }
- if (!$bind) {
- return $this;
- }
- $field = $bind;
- } else {
- if (!isset($attributeFields[$field])) {
- return $this;
- }
- }
-
- $this->updateTableRow(
- 'eav/attribute',
- 'attribute_id',
- $this->getAttributeId($entityTypeId, $id),
- $field,
- $value,
- 'entity_type_id',
- $this->getEntityTypeId($entityTypeId),
- );
-
- return $this;
- }
-
- /**
- * Update Attribute Additional data
- *
- * @param mixed $entityTypeId
- * @param mixed $id
- * @param string $field
- * @param mixed $value
- * @return $this
- */
- protected function _updateAttributeAdditionalData($entityTypeId, $id, $field, $value = null)
- {
- $additionalTable = $this->getEntityType($entityTypeId, 'additional_attribute_table');
- if (!$additionalTable) {
- return $this;
- }
- $additionalTableExists = $this->getConnection()->isTableExists($this->getTable($additionalTable));
- if ($additionalTable && $additionalTableExists) {
- $attributeFields = $this->getConnection()->describeTable($this->getTable($additionalTable));
- if (is_array($field)) {
- $bind = [];
- foreach ($field as $k => $v) {
- if (isset($attributeFields[$k])) {
- $bind[$k] = $this->getConnection()->prepareColumnValue($attributeFields[$k], $v);
- }
- }
- if (!$bind) {
- return $this;
- }
- $field = $bind;
- } else {
- if (!isset($attributeFields[$field])) {
- return $this;
- }
- }
- $this->updateTableRow(
- $this->getTable($additionalTable),
- 'attribute_id',
- $this->getAttributeId($entityTypeId, $id),
- $field,
- $value,
- );
- }
-
- return $this;
- }
-
/**
* Retrieve Attribute Data By Id or Code
*
@@ -1457,6 +1290,172 @@ public function createEntityTables($baseTableName, array $options = [])
return $this;
}
+ /******************* ATTRIBUTES *****************/
+
+ /**
+ * Retrieve value from array by key or return default value
+ *
+ * @param array $array
+ * @param string $key
+ * @param string $default
+ * @return string
+ */
+ protected function _getValue($array, $key, $default = null)
+ {
+ if (isset($array[$key]) && is_bool($array[$key])) {
+ $array[$key] = (int) $array[$key];
+ }
+ return $array[$key] ?? $default;
+ }
+
+ /**
+ * Prepare attribute values to save
+ *
+ * @param array $attr
+ * @return array
+ */
+ protected function _prepareValues($attr)
+ {
+ return [
+ 'backend_model' => $this->_getValue($attr, 'backend'),
+ 'backend_type' => $this->_getValue($attr, 'type', 'varchar'),
+ 'backend_table' => $this->_getValue($attr, 'table'),
+ 'frontend_model' => $this->_getValue($attr, 'frontend'),
+ 'frontend_input' => $this->_getValue($attr, 'input', 'text'),
+ 'frontend_label' => $this->_getValue($attr, 'label'),
+ 'frontend_class' => $this->_getValue($attr, 'frontend_class'),
+ 'source_model' => $this->_getValue($attr, 'source'),
+ 'is_required' => $this->_getValue($attr, 'required', 1),
+ 'is_user_defined' => $this->_getValue($attr, 'user_defined', 0),
+ 'default_value' => $this->_getValue($attr, 'default'),
+ 'is_unique' => $this->_getValue($attr, 'unique', 0),
+ 'note' => $this->_getValue($attr, 'note'),
+ 'is_global' => $this->_getValue($attr, 'global', 1),
+ ];
+ }
+
+ /**
+ * Validate attribute data before insert into table
+ *
+ * @param array $data
+ * @throws Mage_Eav_Exception
+ * @return true
+ */
+ protected function _validateAttributeData($data)
+ {
+ $attributeCodeMaxLength = Mage_Eav_Model_Entity_Attribute::ATTRIBUTE_CODE_MAX_LENGTH;
+
+ if (isset($data['attribute_code']) &&
+ !Zend_Validate::is($data['attribute_code'], 'StringLength', ['max' => $attributeCodeMaxLength])
+ ) {
+ throw Mage::exception(
+ 'Mage_Eav',
+ Mage::helper('eav')->__('Maximum length of attribute code must be less then %s symbols', $attributeCodeMaxLength),
+ );
+ }
+
+ return true;
+ }
+
+ /**
+ * Update Attribute data
+ *
+ * @param mixed $entityTypeId
+ * @param mixed $id
+ * @param string $field
+ * @param mixed $value
+ * @param int $sortOrder
+ * @return $this
+ */
+ protected function _updateAttribute($entityTypeId, $id, $field, $value = null, $sortOrder = null)
+ {
+ if ($sortOrder !== null) {
+ $this->updateTableRow(
+ 'eav/entity_attribute',
+ 'attribute_id',
+ $this->getAttributeId($entityTypeId, $id),
+ 'sort_order',
+ $sortOrder,
+ );
+ }
+
+ $attributeFields = $this->_getAttributeTableFields();
+ if (is_array($field)) {
+ $bind = [];
+ foreach ($field as $k => $v) {
+ if (isset($attributeFields[$k])) {
+ $bind[$k] = $this->getConnection()->prepareColumnValue($attributeFields[$k], $v);
+ }
+ }
+ if (!$bind) {
+ return $this;
+ }
+ $field = $bind;
+ } else {
+ if (!isset($attributeFields[$field])) {
+ return $this;
+ }
+ }
+
+ $this->updateTableRow(
+ 'eav/attribute',
+ 'attribute_id',
+ $this->getAttributeId($entityTypeId, $id),
+ $field,
+ $value,
+ 'entity_type_id',
+ $this->getEntityTypeId($entityTypeId),
+ );
+
+ return $this;
+ }
+
+ /**
+ * Update Attribute Additional data
+ *
+ * @param mixed $entityTypeId
+ * @param mixed $id
+ * @param string $field
+ * @param mixed $value
+ * @return $this
+ */
+ protected function _updateAttributeAdditionalData($entityTypeId, $id, $field, $value = null)
+ {
+ $additionalTable = $this->getEntityType($entityTypeId, 'additional_attribute_table');
+ if (!$additionalTable) {
+ return $this;
+ }
+ $additionalTableExists = $this->getConnection()->isTableExists($this->getTable($additionalTable));
+ if ($additionalTable && $additionalTableExists) {
+ $attributeFields = $this->getConnection()->describeTable($this->getTable($additionalTable));
+ if (is_array($field)) {
+ $bind = [];
+ foreach ($field as $k => $v) {
+ if (isset($attributeFields[$k])) {
+ $bind[$k] = $this->getConnection()->prepareColumnValue($attributeFields[$k], $v);
+ }
+ }
+ if (!$bind) {
+ return $this;
+ }
+ $field = $bind;
+ } else {
+ if (!isset($attributeFields[$field])) {
+ return $this;
+ }
+ }
+ $this->updateTableRow(
+ $this->getTable($additionalTable),
+ 'attribute_id',
+ $this->getAttributeId($entityTypeId, $id),
+ $field,
+ $value,
+ );
+ }
+
+ return $this;
+ }
+
/**
* Retrieve attribute table fields
*
diff --git a/app/code/core/Mage/Eav/Model/Entity/Store.php b/app/code/core/Mage/Eav/Model/Entity/Store.php
index 9d1276de5d5..81e117dae34 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Store.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Store.php
@@ -31,11 +31,6 @@
*/
class Mage_Eav_Model_Entity_Store extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('eav/entity_store');
- }
-
/**
* Load entity by store
*
@@ -48,4 +43,8 @@ public function loadByEntityStore($entityTypeId, $storeId)
$this->_getResource()->loadByEntityStore($this, $entityTypeId, $storeId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('eav/entity_store');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Entity/Type.php b/app/code/core/Mage/Eav/Model/Entity/Type.php
index 3d68e09ef07..fb82234dded 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Type.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Type.php
@@ -72,11 +72,6 @@ class Mage_Eav_Model_Entity_Type extends Mage_Core_Model_Abstract
*/
protected $_sets;
- protected function _construct()
- {
- $this->_init('eav/entity_type');
- }
-
/**
* Load type by code
*
@@ -133,22 +128,6 @@ public function newAttributeCollection($setId = null)
return $collection;
}
- /**
- * Init and retrieve attribute collection
- *
- * @return Mage_Core_Model_Resource_Db_Collection_Abstract|object
- */
- protected function _getAttributeCollection()
- {
- $collection = Mage::getModel('eav/entity_attribute')->getCollection();
- $objectsModel = $this->getAttributeModel();
- if ($objectsModel) {
- $collection->setModel($objectsModel);
- }
-
- return $collection;
- }
-
/**
* Retrieve entity tpe sets collection
*
@@ -356,4 +335,25 @@ public function getEntityAttributeCollection()
}
return 'eav/entity_attribute_collection';
}
+
+ protected function _construct()
+ {
+ $this->_init('eav/entity_type');
+ }
+
+ /**
+ * Init and retrieve attribute collection
+ *
+ * @return Mage_Core_Model_Resource_Db_Collection_Abstract|object
+ */
+ protected function _getAttributeCollection()
+ {
+ $collection = Mage::getModel('eav/entity_attribute')->getCollection();
+ $objectsModel = $this->getAttributeModel();
+ if ($objectsModel) {
+ $collection->setModel($objectsModel);
+ }
+
+ return $collection;
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Form.php b/app/code/core/Mage/Eav/Model/Form.php
index 54d5e85ec9f..cf2c319ec06 100644
--- a/app/code/core/Mage/Eav/Model/Form.php
+++ b/app/code/core/Mage/Eav/Model/Form.php
@@ -114,16 +114,6 @@ public function __construct()
}
}
- /**
- * Get EAV Entity Form Attribute Collection
- *
- * @return mixed
- */
- protected function _getFormAttributeCollection()
- {
- return Mage::getResourceModel($this->_moduleName . '/form_attribute_collection');
- }
-
/**
* Set current store
*
@@ -303,19 +293,6 @@ public function getSystemAttributes()
return $this->_systemAttributes;
}
- /**
- * Return attribute data model by attribute
- *
- * @return Mage_Eav_Model_Attribute_Data_Abstract
- */
- protected function _getAttributeDataModel(Mage_Eav_Model_Entity_Attribute $attribute)
- {
- $dataModel = Mage_Eav_Model_Attribute_Data::factory($attribute, $this->getEntity());
- $dataModel->setIsAjaxRequest($this->getIsAjaxRequest());
-
- return $dataModel;
- }
-
/**
* Prepare request with data and returns it
*
@@ -518,6 +495,29 @@ public function ignoreInvisible($setValue = null)
return $this->_ignoreInvisible;
}
+ /**
+ * Get EAV Entity Form Attribute Collection
+ *
+ * @return mixed
+ */
+ protected function _getFormAttributeCollection()
+ {
+ return Mage::getResourceModel($this->_moduleName . '/form_attribute_collection');
+ }
+
+ /**
+ * Return attribute data model by attribute
+ *
+ * @return Mage_Eav_Model_Attribute_Data_Abstract
+ */
+ protected function _getAttributeDataModel(Mage_Eav_Model_Entity_Attribute $attribute)
+ {
+ $dataModel = Mage_Eav_Model_Attribute_Data::factory($attribute, $this->getEntity());
+ $dataModel->setIsAjaxRequest($this->getIsAjaxRequest());
+
+ return $dataModel;
+ }
+
/**
* Whether the specified attribute needs to skip rendering/validation
*
diff --git a/app/code/core/Mage/Eav/Model/Form/Element.php b/app/code/core/Mage/Eav/Model/Form/Element.php
index 9d745fbf8d1..e58a724e1d5 100644
--- a/app/code/core/Mage/Eav/Model/Form/Element.php
+++ b/app/code/core/Mage/Eav/Model/Form/Element.php
@@ -42,6 +42,21 @@ class Mage_Eav_Model_Form_Element extends Mage_Core_Model_Abstract
*/
protected $_eventPrefix = 'eav_form_element';
+ /**
+ * Retrieve EAV Attribute instance
+ *
+ * @return Mage_Eav_Model_Entity_Attribute
+ */
+ public function getAttribute()
+ {
+ if (!$this->hasData('attribute')) {
+ $attribute = Mage::getSingleton('eav/config')
+ ->getAttribute($this->getEntityTypeId(), $this->getAttributeId());
+ $this->setData('attribute', $attribute);
+ }
+ return $this->_getData('attribute');
+ }
+
protected function _construct()
{
$this->_init('eav/form_element');
@@ -64,19 +79,4 @@ protected function _beforeSave()
return parent::_beforeSave();
}
-
- /**
- * Retrieve EAV Attribute instance
- *
- * @return Mage_Eav_Model_Entity_Attribute
- */
- public function getAttribute()
- {
- if (!$this->hasData('attribute')) {
- $attribute = Mage::getSingleton('eav/config')
- ->getAttribute($this->getEntityTypeId(), $this->getAttributeId());
- $this->setData('attribute', $attribute);
- }
- return $this->_getData('attribute');
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Form/Fieldset.php b/app/code/core/Mage/Eav/Model/Form/Fieldset.php
index 79923822ad6..00e5800372d 100644
--- a/app/code/core/Mage/Eav/Model/Form/Fieldset.php
+++ b/app/code/core/Mage/Eav/Model/Form/Fieldset.php
@@ -42,29 +42,6 @@ class Mage_Eav_Model_Form_Fieldset extends Mage_Core_Model_Abstract
*/
protected $_eventPrefix = 'eav_form_fieldset';
- protected function _construct()
- {
- $this->_init('eav/form_fieldset');
- }
-
- /**
- * Validate data before save data
- *
- * @throws Mage_Core_Exception
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- if (!$this->getTypeId()) {
- Mage::throwException(Mage::helper('eav')->__('Invalid form type.'));
- }
- if (!$this->getStoreId() && $this->getLabel()) {
- $this->setStoreLabel($this->getStoreId(), $this->getLabel());
- }
-
- return parent::_beforeSave();
- }
-
/**
* Retrieve fieldset labels for stores
*
@@ -116,4 +93,27 @@ public function getStoreId()
}
return $this->_getData('store_id');
}
+
+ protected function _construct()
+ {
+ $this->_init('eav/form_fieldset');
+ }
+
+ /**
+ * Validate data before save data
+ *
+ * @throws Mage_Core_Exception
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ if (!$this->getTypeId()) {
+ Mage::throwException(Mage::helper('eav')->__('Invalid form type.'));
+ }
+ if (!$this->getStoreId() && $this->getLabel()) {
+ $this->setStoreLabel($this->getStoreId(), $this->getLabel());
+ }
+
+ return parent::_beforeSave();
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Form/Type.php b/app/code/core/Mage/Eav/Model/Form/Type.php
index 9137bca9239..a25faa0d931 100644
--- a/app/code/core/Mage/Eav/Model/Form/Type.php
+++ b/app/code/core/Mage/Eav/Model/Form/Type.php
@@ -43,14 +43,6 @@ class Mage_Eav_Model_Form_Type extends Mage_Core_Model_Abstract
*/
protected $_eventPrefix = 'eav_form_type';
- /**
- * Initialize resource model
- */
- protected function _construct()
- {
- $this->_init('eav/form_type');
- }
-
/**
* Retrieve assigned Eav Entity types
*
@@ -134,4 +126,12 @@ public function createFromSkeleton(Mage_Eav_Model_Form_Type $skeleton)
return $this;
}
+
+ /**
+ * Initialize resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('eav/form_type');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Attribute.php b/app/code/core/Mage/Eav/Model/Resource/Attribute.php
index 776fa39ba21..f1a2a207ea0 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Attribute.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Attribute.php
@@ -22,6 +22,47 @@
*/
abstract class Mage_Eav_Model_Resource_Attribute extends Mage_Eav_Model_Resource_Entity_Attribute
{
+ /**
+ * Return scope values for attribute and website
+ *
+ * @return array
+ */
+ public function getScopeValues(Mage_Eav_Model_Attribute $object)
+ {
+ $adapter = $this->_getReadAdapter();
+ $bind = [
+ 'attribute_id' => (int) $object->getId(),
+ 'website_id' => (int) $object->getWebsite()->getId(),
+ ];
+ $select = $adapter->select()
+ ->from($this->_getEavWebsiteTable())
+ ->where('attribute_id = :attribute_id')
+ ->where('website_id = :website_id')
+ ->limit(1);
+ $result = $adapter->fetchRow($select, $bind);
+
+ if (!$result) {
+ $result = [];
+ }
+
+ return $result;
+ }
+
+ /**
+ * Return forms in which the attribute
+ *
+ * @return array
+ */
+ public function getUsedInForms(Mage_Core_Model_Abstract $object)
+ {
+ $adapter = $this->_getReadAdapter();
+ $bind = ['attribute_id' => (int) $object->getId()];
+ $select = $adapter->select()
+ ->from($this->_getFormAttributeTable(), 'form_code')
+ ->where('attribute_id = :attribute_id');
+
+ return $adapter->fetchCol($select, $bind);
+ }
/**
* Get EAV website table
*
@@ -150,46 +191,4 @@ protected function _afterSave(Mage_Core_Model_Abstract $object)
return parent::_afterSave($object);
}
-
- /**
- * Return scope values for attribute and website
- *
- * @return array
- */
- public function getScopeValues(Mage_Eav_Model_Attribute $object)
- {
- $adapter = $this->_getReadAdapter();
- $bind = [
- 'attribute_id' => (int) $object->getId(),
- 'website_id' => (int) $object->getWebsite()->getId(),
- ];
- $select = $adapter->select()
- ->from($this->_getEavWebsiteTable())
- ->where('attribute_id = :attribute_id')
- ->where('website_id = :website_id')
- ->limit(1);
- $result = $adapter->fetchRow($select, $bind);
-
- if (!$result) {
- $result = [];
- }
-
- return $result;
- }
-
- /**
- * Return forms in which the attribute
- *
- * @return array
- */
- public function getUsedInForms(Mage_Core_Model_Abstract $object)
- {
- $adapter = $this->_getReadAdapter();
- $bind = ['attribute_id' => (int) $object->getId()];
- $select = $adapter->select()
- ->from($this->_getFormAttributeTable(), 'form_code')
- ->where('attribute_id = :attribute_id');
-
- return $adapter->fetchCol($select, $bind);
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Attribute/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Attribute/Collection.php
index 364a07735e8..23d1e14c384 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Attribute/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Attribute/Collection.php
@@ -41,23 +41,6 @@ abstract class Mage_Eav_Model_Resource_Attribute_Collection extends Mage_Eav_Mod
*/
protected $_entityType;
- /**
- * Default attribute entity type code
- *
- * @return string
- */
- abstract protected function _getEntityTypeCode();
-
- /**
- * Get EAV website table
- *
- * Get table, where website-dependent attribute parameters are stored
- * If realization doesn't demand this functionality, let this function just return null
- *
- * @return string|null
- */
- abstract protected function _getEavWebsiteTable();
-
/**
* Return eav entity type instance
*
@@ -97,6 +80,82 @@ public function getWebsite()
return $this->_website;
}
+ /**
+ * Specify attribute entity type filter.
+ * Entity type is defined.
+ *
+ * @param int $type
+ * @return $this
+ */
+ public function setEntityTypeFilter($type)
+ {
+ return $this;
+ }
+
+ /**
+ * Specify filter by "is_visible" field
+ *
+ * @return $this
+ */
+ public function addVisibleFilter()
+ {
+ return $this->addFieldToFilter('is_visible', 1);
+ }
+
+ /**
+ * Exclude system hidden attributes
+ *
+ * @return $this
+ */
+ public function addSystemHiddenFilter()
+ {
+ $field = '(CASE WHEN additional_table.is_system = 1 AND additional_table.is_visible = 0 THEN 1 ELSE 0 END)';
+ $resultCondition = $this->_getConditionSql($field, 0);
+ $this->_select->where($resultCondition);
+ return $this;
+ }
+
+ /**
+ * Exclude system hidden attributes but include password hash
+ *
+ * @return $this
+ */
+ public function addSystemHiddenFilterWithPasswordHash()
+ {
+ $field = '(CASE WHEN additional_table.is_system = 1 AND additional_table.is_visible = 0
+ AND main_table.attribute_code != "' . self::EAV_CODE_PASSWORD_HASH . '" THEN 1 ELSE 0 END)';
+ $resultCondition = $this->_getConditionSql($field, 0);
+ $this->_select->where($resultCondition);
+ return $this;
+ }
+
+ /**
+ * Add exclude hidden frontend input attribute filter to collection
+ *
+ * @return $this
+ */
+ public function addExcludeHiddenFrontendFilter()
+ {
+ return $this->addFieldToFilter('main_table.frontend_input', ['neq' => 'hidden']);
+ }
+
+ /**
+ * Default attribute entity type code
+ *
+ * @return string
+ */
+ abstract protected function _getEntityTypeCode();
+
+ /**
+ * Get EAV website table
+ *
+ * Get table, where website-dependent attribute parameters are stored
+ * If realization doesn't demand this functionality, let this function just return null
+ *
+ * @return string|null
+ */
+ abstract protected function _getEavWebsiteTable();
+
/**
* Initialize collection select
*
@@ -179,63 +238,4 @@ protected function _initSelect()
return $this;
}
-
- /**
- * Specify attribute entity type filter.
- * Entity type is defined.
- *
- * @param int $type
- * @return $this
- */
- public function setEntityTypeFilter($type)
- {
- return $this;
- }
-
- /**
- * Specify filter by "is_visible" field
- *
- * @return $this
- */
- public function addVisibleFilter()
- {
- return $this->addFieldToFilter('is_visible', 1);
- }
-
- /**
- * Exclude system hidden attributes
- *
- * @return $this
- */
- public function addSystemHiddenFilter()
- {
- $field = '(CASE WHEN additional_table.is_system = 1 AND additional_table.is_visible = 0 THEN 1 ELSE 0 END)';
- $resultCondition = $this->_getConditionSql($field, 0);
- $this->_select->where($resultCondition);
- return $this;
- }
-
- /**
- * Exclude system hidden attributes but include password hash
- *
- * @return $this
- */
- public function addSystemHiddenFilterWithPasswordHash()
- {
- $field = '(CASE WHEN additional_table.is_system = 1 AND additional_table.is_visible = 0
- AND main_table.attribute_code != "' . self::EAV_CODE_PASSWORD_HASH . '" THEN 1 ELSE 0 END)';
- $resultCondition = $this->_getConditionSql($field, 0);
- $this->_select->where($resultCondition);
- return $this;
- }
-
- /**
- * Add exclude hidden frontend input attribute filter to collection
- *
- * @return $this
- */
- public function addExcludeHiddenFrontendFilter()
- {
- return $this->addFieldToFilter('main_table.frontend_input', ['neq' => 'hidden']);
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Config.php b/app/code/core/Mage/Eav/Model/Resource/Config.php
index e09b3750f3f..8f75e8a777f 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Config.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Config.php
@@ -36,6 +36,36 @@ class Mage_Eav_Model_Resource_Config extends Mage_Core_Model_Resource_Db_Abstrac
*/
protected static $_attributes = [];
+ /**
+ * Retrieve entity type data
+ *
+ * @param string $entityType
+ * @return array
+ */
+ public function fetchEntityTypeData($entityType)
+ {
+ $this->_loadTypes();
+
+ if (is_numeric($entityType)) {
+ $info = self::$_entityTypes['by_id'][$entityType] ?? null;
+ } else {
+ $info = self::$_entityTypes['by_code'][$entityType] ?? null;
+ }
+
+ $data = [];
+ if ($info) {
+ $data['entity'] = $info;
+ $attributes = $this->_loadTypeAttributes($info['entity_type_id']);
+ $data['attributes'] = [];
+ foreach ($attributes as $attribute) {
+ $data['attributes'][$attribute['attribute_id']] = $attribute;
+ $data['attributes'][$attribute['attribute_code']] = $attribute['attribute_id'];
+ }
+ }
+
+ return $data;
+ }
+
protected function _construct()
{
$this->_init('eav/entity_type', 'entity_type_id');
@@ -84,34 +114,4 @@ protected function _loadTypeAttributes($typeId)
return self::$_attributes[$typeId];
}
-
- /**
- * Retrieve entity type data
- *
- * @param string $entityType
- * @return array
- */
- public function fetchEntityTypeData($entityType)
- {
- $this->_loadTypes();
-
- if (is_numeric($entityType)) {
- $info = self::$_entityTypes['by_id'][$entityType] ?? null;
- } else {
- $info = self::$_entityTypes['by_code'][$entityType] ?? null;
- }
-
- $data = [];
- if ($info) {
- $data['entity'] = $info;
- $attributes = $this->_loadTypeAttributes($info['entity_type_id']);
- $data['attributes'] = [];
- foreach ($attributes as $attribute) {
- $data['attributes'][$attribute['attribute_id']] = $attribute;
- $data['attributes'][$attribute['attribute_code']] = $attribute['attribute_id'];
- }
- }
-
- return $data;
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute.php
index cd1a89b365a..db7924136de 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute.php
@@ -29,107 +29,264 @@ class Mage_Eav_Model_Resource_Entity_Attribute extends Mage_Core_Model_Resource_
*/
protected static $_entityAttributes = [];
- protected function _construct()
+ /**
+ * Load attribute data by attribute code
+ *
+ * @param int $entityTypeId
+ * @param string $code
+ * @return bool
+ */
+ public function loadByCode(Mage_Core_Model_Abstract $object, $entityTypeId, $code)
{
- $this->_init('eav/attribute', 'attribute_id');
+ $bind = [':entity_type_id' => $entityTypeId];
+ $select = $this->_getLoadSelect('attribute_code', $code, $object)
+ ->where('entity_type_id = :entity_type_id');
+ $data = $this->_getReadAdapter()->fetchRow($select, $bind);
+
+ if ($data) {
+ $object->setData($data);
+ $this->_afterLoad($object);
+ return true;
+ }
+ return false;
}
/**
+ * Delete entity
+ *
* @return $this
*/
- protected function _initUniqueFields()
+ public function deleteEntity(Mage_Core_Model_Abstract $object)
{
- $this->_uniqueFields = [[
- 'field' => ['attribute_code', 'entity_type_id'],
- 'title' => Mage::helper('eav')->__('Attribute with the same code'),
- ]];
+ if (!$object->getEntityAttributeId()) {
+ return $this;
+ }
+
+ $this->_getWriteAdapter()->delete($this->getTable('eav/entity_attribute'), [
+ 'entity_attribute_id = ?' => $object->getEntityAttributeId(),
+ ]);
+
return $this;
}
/**
- * Load all entity type attributes
+ * Save in set including
*
- * @param int $entityTypeId
* @return $this
*/
- protected function _loadTypeAttributes($entityTypeId)
+ public function saveInSetIncluding(Mage_Core_Model_Abstract $object)
{
- if (!isset(self::$_entityAttributes[$entityTypeId])) {
- $adapter = $this->_getReadAdapter();
- $bind = [':entity_type_id' => $entityTypeId];
- $select = $adapter->select()
- ->from($this->getMainTable())
- ->where('entity_type_id = :entity_type_id');
+ $attributeId = (int) $object->getId();
+ $setId = (int) $object->getAttributeSetId();
+ $groupId = (int) $object->getAttributeGroupId();
- $data = $adapter->fetchAll($select, $bind);
- foreach ($data as $row) {
- self::$_entityAttributes[$entityTypeId][$row['attribute_code']] = $row;
- }
+ if ($setId && $groupId && $object->getEntityTypeId()) {
+ $adapter = $this->_getWriteAdapter();
+ $table = $this->getTable('eav/entity_attribute');
+
+ $sortOrder = (($object->getSortOrder()) ? $object->getSortOrder() : $this->_getMaxSortOrder($object) + 1);
+ $data = [
+ 'entity_type_id' => $object->getEntityTypeId(),
+ 'attribute_set_id' => $setId,
+ 'attribute_group_id' => $groupId,
+ 'attribute_id' => $attributeId,
+ 'sort_order' => $sortOrder,
+ ];
+
+ $where = [
+ 'attribute_id =?' => $attributeId,
+ 'attribute_set_id =?' => $setId,
+ ];
+
+ $adapter->delete($table, $where);
+ $adapter->insert($table, $data);
}
return $this;
}
/**
- * Load attribute data by attribute code
+ * Retrieve attribute id by entity type code and attribute code
*
- * @param int $entityTypeId
+ * @param string $entityType
* @param string $code
- * @return bool
+ * @return int
*/
- public function loadByCode(Mage_Core_Model_Abstract $object, $entityTypeId, $code)
+ public function getIdByCode($entityType, $code)
{
- $bind = [':entity_type_id' => $entityTypeId];
- $select = $this->_getLoadSelect('attribute_code', $code, $object)
- ->where('entity_type_id = :entity_type_id');
- $data = $this->_getReadAdapter()->fetchRow($select, $bind);
+ $adapter = $this->_getReadAdapter();
+ $bind = [
+ ':entity_type_code' => $entityType,
+ ':attribute_code' => $code,
+ ];
+ $select = $adapter->select()
+ ->from(['a' => $this->getTable('eav/attribute')], ['a.attribute_id'])
+ ->join(
+ ['t' => $this->getTable('eav/entity_type')],
+ 'a.entity_type_id = t.entity_type_id',
+ [],
+ )
+ ->where('t.entity_type_code = :entity_type_code')
+ ->where('a.attribute_code = :attribute_code');
- if ($data) {
- $object->setData($data);
- $this->_afterLoad($object);
- return true;
- }
- return false;
+ return $adapter->fetchOne($select, $bind);
}
/**
- * Retrieve Max Sort order for attribute in group
+ * Retrieve attribute codes by front-end type
*
- * @return int
+ * @param string $frontendType
+ * @return array
*/
- private function _getMaxSortOrder(Mage_Core_Model_Abstract $object)
+ public function getAttributeCodesByFrontendType($frontendType)
{
- if ((int) $object->getAttributeGroupId() > 0) {
- $adapter = $this->_getReadAdapter();
- $bind = [
- ':attribute_set_id' => $object->getAttributeSetId(),
- ':attribute_group_id' => $object->getAttributeGroupId(),
- ];
- $select = $adapter->select()
- ->from($this->getTable('eav/entity_attribute'), new Zend_Db_Expr('MAX(sort_order)'))
- ->where('attribute_set_id = :attribute_set_id')
- ->where('attribute_group_id = :attribute_group_id');
+ $adapter = $this->_getReadAdapter();
+ $bind = [':frontend_input' => $frontendType];
+ $select = $adapter->select()
+ ->from($this->getTable('eav/attribute'), 'attribute_code')
+ ->where('frontend_input = :frontend_input');
- return $adapter->fetchOne($select, $bind);
+ return $adapter->fetchCol($select, $bind);
+ }
+
+ /**
+ * Retrieve Select For Flat Attribute update
+ *
+ * @param int $storeId
+ * @return Varien_Db_Select
+ */
+ public function getFlatUpdateSelect(Mage_Eav_Model_Entity_Attribute_Abstract $attribute, $storeId)
+ {
+ $adapter = $this->_getReadAdapter();
+ $joinConditionTemplate = '%s.entity_id = %s.entity_id'
+ . ' AND %s.entity_type_id = ' . $attribute->getEntityTypeId()
+ . ' AND %s.attribute_id = ' . $attribute->getId()
+ . ' AND %s.store_id = %d';
+ $joinCondition = sprintf(
+ $joinConditionTemplate,
+ 'e',
+ 't1',
+ 't1',
+ 't1',
+ 't1',
+ Mage_Core_Model_App::ADMIN_STORE_ID,
+ );
+ if ($attribute->getFlatAddChildData()) {
+ $joinCondition .= ' AND e.child_id = t1.entity_id';
}
- return 0;
+ $valueExpr = $adapter->getCheckSql('t2.value_id > 0', 't2.value', 't1.value');
+
+ $select = $adapter->select()
+ ->joinLeft(
+ ['t1' => $attribute->getBackend()->getTable()],
+ $joinCondition,
+ [],
+ )
+ ->joinLeft(
+ ['t2' => $attribute->getBackend()->getTable()],
+ sprintf($joinConditionTemplate, 'e', 't2', 't2', 't2', 't2', $storeId),
+ [$attribute->getAttributeCode() => $valueExpr],
+ );
+ if ($attribute->getFlatAddChildData()) {
+ $select->where('e.is_child = ?', 0);
+ }
+
+ return $select;
}
/**
- * Delete entity
+ * Returns the column descriptions for a table
+ *
+ * @param string $table
+ * @return array
+ */
+ public function describeTable($table)
+ {
+ return $this->_getReadAdapter()->describeTable($table);
+ }
+
+ /**
+ * Retrieve additional attribute table name for specified entity type
+ *
+ * @param int $entityTypeId
+ * @return string
+ */
+ public function getAdditionalAttributeTable($entityTypeId)
+ {
+ return Mage::getResourceSingleton('eav/entity_type')->getAdditionalAttributeTable($entityTypeId);
+ }
+
+ /**
+ * Retrieve store labels by given attribute id
+ *
+ * @param int $attributeId
+ * @return array
+ */
+ public function getStoreLabelsByAttributeId($attributeId)
+ {
+ $adapter = $this->_getReadAdapter();
+ $bind = [':attribute_id' => $attributeId];
+ $select = $adapter->select()
+ ->from($this->getTable('eav/attribute_label'), ['store_id', 'value'])
+ ->where('attribute_id = :attribute_id');
+
+ return $adapter->fetchPairs($select, $bind);
+ }
+
+ /**
+ * Load by given attributes ids and return only exist attribute ids
+ *
+ * @param array $attributeIds
+ * @return array
+ */
+ public function getValidAttributeIds($attributeIds)
+ {
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from($this->getMainTable(), ['attribute_id'])
+ ->where('attribute_id IN (?)', $attributeIds);
+
+ return $adapter->fetchCol($select);
+ }
+
+ protected function _construct()
+ {
+ $this->_init('eav/attribute', 'attribute_id');
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _initUniqueFields()
+ {
+ $this->_uniqueFields = [[
+ 'field' => ['attribute_code', 'entity_type_id'],
+ 'title' => Mage::helper('eav')->__('Attribute with the same code'),
+ ]];
+ return $this;
+ }
+
+ /**
+ * Load all entity type attributes
*
+ * @param int $entityTypeId
* @return $this
*/
- public function deleteEntity(Mage_Core_Model_Abstract $object)
+ protected function _loadTypeAttributes($entityTypeId)
{
- if (!$object->getEntityAttributeId()) {
- return $this;
- }
+ if (!isset(self::$_entityAttributes[$entityTypeId])) {
+ $adapter = $this->_getReadAdapter();
+ $bind = [':entity_type_id' => $entityTypeId];
+ $select = $adapter->select()
+ ->from($this->getMainTable())
+ ->where('entity_type_id = :entity_type_id');
- $this->_getWriteAdapter()->delete($this->getTable('eav/entity_attribute'), [
- 'entity_attribute_id = ?' => $object->getEntityAttributeId(),
- ]);
+ $data = $adapter->fetchAll($select, $bind);
+ foreach ($data as $row) {
+ self::$_entityAttributes[$entityTypeId][$row['attribute_code']] = $row;
+ }
+ }
return $this;
}
@@ -234,42 +391,6 @@ protected function _saveAdditionalAttributeData(Mage_Core_Model_Abstract $object
return $this;
}
- /**
- * Save in set including
- *
- * @return $this
- */
- public function saveInSetIncluding(Mage_Core_Model_Abstract $object)
- {
- $attributeId = (int) $object->getId();
- $setId = (int) $object->getAttributeSetId();
- $groupId = (int) $object->getAttributeGroupId();
-
- if ($setId && $groupId && $object->getEntityTypeId()) {
- $adapter = $this->_getWriteAdapter();
- $table = $this->getTable('eav/entity_attribute');
-
- $sortOrder = (($object->getSortOrder()) ? $object->getSortOrder() : $this->_getMaxSortOrder($object) + 1);
- $data = [
- 'entity_type_id' => $object->getEntityTypeId(),
- 'attribute_set_id' => $setId,
- 'attribute_group_id' => $groupId,
- 'attribute_id' => $attributeId,
- 'sort_order' => $sortOrder,
- ];
-
- $where = [
- 'attribute_id =?' => $attributeId,
- 'attribute_set_id =?' => $setId,
- ];
-
- $adapter->delete($table, $where);
- $adapter->insert($table, $data);
- }
-
- return $this;
- }
-
/**
* Save attribute options
*
@@ -369,118 +490,6 @@ protected function _saveOption(Mage_Core_Model_Abstract $object)
return $this;
}
- /**
- * Retrieve attribute id by entity type code and attribute code
- *
- * @param string $entityType
- * @param string $code
- * @return int
- */
- public function getIdByCode($entityType, $code)
- {
- $adapter = $this->_getReadAdapter();
- $bind = [
- ':entity_type_code' => $entityType,
- ':attribute_code' => $code,
- ];
- $select = $adapter->select()
- ->from(['a' => $this->getTable('eav/attribute')], ['a.attribute_id'])
- ->join(
- ['t' => $this->getTable('eav/entity_type')],
- 'a.entity_type_id = t.entity_type_id',
- [],
- )
- ->where('t.entity_type_code = :entity_type_code')
- ->where('a.attribute_code = :attribute_code');
-
- return $adapter->fetchOne($select, $bind);
- }
-
- /**
- * Retrieve attribute codes by front-end type
- *
- * @param string $frontendType
- * @return array
- */
- public function getAttributeCodesByFrontendType($frontendType)
- {
- $adapter = $this->_getReadAdapter();
- $bind = [':frontend_input' => $frontendType];
- $select = $adapter->select()
- ->from($this->getTable('eav/attribute'), 'attribute_code')
- ->where('frontend_input = :frontend_input');
-
- return $adapter->fetchCol($select, $bind);
- }
-
- /**
- * Retrieve Select For Flat Attribute update
- *
- * @param int $storeId
- * @return Varien_Db_Select
- */
- public function getFlatUpdateSelect(Mage_Eav_Model_Entity_Attribute_Abstract $attribute, $storeId)
- {
- $adapter = $this->_getReadAdapter();
- $joinConditionTemplate = '%s.entity_id = %s.entity_id'
- . ' AND %s.entity_type_id = ' . $attribute->getEntityTypeId()
- . ' AND %s.attribute_id = ' . $attribute->getId()
- . ' AND %s.store_id = %d';
- $joinCondition = sprintf(
- $joinConditionTemplate,
- 'e',
- 't1',
- 't1',
- 't1',
- 't1',
- Mage_Core_Model_App::ADMIN_STORE_ID,
- );
- if ($attribute->getFlatAddChildData()) {
- $joinCondition .= ' AND e.child_id = t1.entity_id';
- }
-
- $valueExpr = $adapter->getCheckSql('t2.value_id > 0', 't2.value', 't1.value');
-
- $select = $adapter->select()
- ->joinLeft(
- ['t1' => $attribute->getBackend()->getTable()],
- $joinCondition,
- [],
- )
- ->joinLeft(
- ['t2' => $attribute->getBackend()->getTable()],
- sprintf($joinConditionTemplate, 'e', 't2', 't2', 't2', 't2', $storeId),
- [$attribute->getAttributeCode() => $valueExpr],
- );
- if ($attribute->getFlatAddChildData()) {
- $select->where('e.is_child = ?', 0);
- }
-
- return $select;
- }
-
- /**
- * Returns the column descriptions for a table
- *
- * @param string $table
- * @return array
- */
- public function describeTable($table)
- {
- return $this->_getReadAdapter()->describeTable($table);
- }
-
- /**
- * Retrieve additional attribute table name for specified entity type
- *
- * @param int $entityTypeId
- * @return string
- */
- public function getAdditionalAttributeTable($entityTypeId)
- {
- return Mage::getResourceSingleton('eav/entity_type')->getAdditionalAttributeTable($entityTypeId);
- }
-
/**
* Load additional attribute data.
* Load label of current active store
@@ -514,35 +523,26 @@ protected function _afterLoad(Mage_Core_Model_Abstract $object)
}
/**
- * Retrieve store labels by given attribute id
+ * Retrieve Max Sort order for attribute in group
*
- * @param int $attributeId
- * @return array
+ * @return int
*/
- public function getStoreLabelsByAttributeId($attributeId)
+ private function _getMaxSortOrder(Mage_Core_Model_Abstract $object)
{
- $adapter = $this->_getReadAdapter();
- $bind = [':attribute_id' => $attributeId];
- $select = $adapter->select()
- ->from($this->getTable('eav/attribute_label'), ['store_id', 'value'])
- ->where('attribute_id = :attribute_id');
-
- return $adapter->fetchPairs($select, $bind);
- }
+ if ((int) $object->getAttributeGroupId() > 0) {
+ $adapter = $this->_getReadAdapter();
+ $bind = [
+ ':attribute_set_id' => $object->getAttributeSetId(),
+ ':attribute_group_id' => $object->getAttributeGroupId(),
+ ];
+ $select = $adapter->select()
+ ->from($this->getTable('eav/entity_attribute'), new Zend_Db_Expr('MAX(sort_order)'))
+ ->where('attribute_set_id = :attribute_set_id')
+ ->where('attribute_group_id = :attribute_group_id');
- /**
- * Load by given attributes ids and return only exist attribute ids
- *
- * @param array $attributeIds
- * @return array
- */
- public function getValidAttributeIds($attributeIds)
- {
- $adapter = $this->_getReadAdapter();
- $select = $adapter->select()
- ->from($this->getMainTable(), ['attribute_id'])
- ->where('attribute_id IN (?)', $attributeIds);
+ return $adapter->fetchOne($select, $bind);
+ }
- return $adapter->fetchCol($select);
+ return 0;
}
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Collection.php
index 56db7a6f6da..b353c844e9e 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Collection.php
@@ -42,35 +42,6 @@ class Mage_Eav_Model_Resource_Entity_Attribute_Collection extends Mage_Core_Mode
*/
protected $_addedStoreLabelsFlag = false;
- /**
- * Resource model initialization
- *
- */
- protected function _construct()
- {
- $this->_init('eav/entity_attribute');
- }
-
- /**
- * Return array of fields to load attribute values
- *
- * @return array
- */
- protected function _getLoadDataFields()
- {
- return [
- 'attribute_id',
- 'entity_type_id',
- 'attribute_code',
- 'attribute_model',
- 'backend_model',
- 'backend_type',
- 'backend_table',
- 'frontend_input',
- 'source_model',
- ];
- }
-
/**
* Specify select columns which are used for load attribute values
*
@@ -318,6 +289,91 @@ public function addSetInfo($flag = true)
return $this;
}
+ /**
+ * Load is used in configurable products flag
+ * @deprecated
+ *
+ * @return $this
+ */
+ public function checkConfigurableProducts()
+ {
+ return $this;
+ }
+
+ /**
+ * Specify collection attribute codes filter
+ *
+ * @param string | array $code
+ * @return $this
+ */
+ public function setCodeFilter($code)
+ {
+ if (empty($code)) {
+ return $this;
+ }
+ if (!is_array($code)) {
+ $code = [$code];
+ }
+
+ return $this->addFieldToFilter('attribute_code', ['in' => $code]);
+ }
+
+ /**
+ * Add store label to attribute by specified store id
+ *
+ * @param int $storeId
+ * @return $this
+ */
+ public function addStoreLabel($storeId)
+ {
+ // if not called previously
+ if ($this->_addedStoreLabelsFlag === false) {
+ $adapter = $this->getConnection();
+ $joinExpression = $adapter
+ ->quoteInto('al.attribute_id = main_table.attribute_id AND al.store_id = ?', (int) $storeId);
+ $this->getSelect()->joinLeft(
+ ['al' => $this->getTable('eav/attribute_label')],
+ $joinExpression,
+ ['store_label' => $adapter->getIfNullSql('al.value', 'main_table.frontend_label')],
+ );
+ $this->_addedStoreLabelsFlag = $storeId;
+ } elseif ($this->_addedStoreLabelsFlag !== $storeId) {
+ // check that previous call $storeId matches current call
+ throw new Exception('Cannot call addStoreLabel for different store views on the same collection');
+ }
+
+ return $this;
+ }
+
+ /**
+ * Resource model initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('eav/entity_attribute');
+ }
+
+ /**
+ * Return array of fields to load attribute values
+ *
+ * @return array
+ */
+ protected function _getLoadDataFields()
+ {
+ return [
+ 'attribute_id',
+ 'entity_type_id',
+ 'attribute_code',
+ 'attribute_model',
+ 'backend_model',
+ 'backend_type',
+ 'backend_table',
+ 'frontend_input',
+ 'source_model',
+ ];
+ }
+
/**
* Ad information about attribute sets to collection result data
*
@@ -379,60 +435,4 @@ protected function _afterLoadData()
return parent::_afterLoadData();
}
-
- /**
- * Load is used in configurable products flag
- * @deprecated
- *
- * @return $this
- */
- public function checkConfigurableProducts()
- {
- return $this;
- }
-
- /**
- * Specify collection attribute codes filter
- *
- * @param string | array $code
- * @return $this
- */
- public function setCodeFilter($code)
- {
- if (empty($code)) {
- return $this;
- }
- if (!is_array($code)) {
- $code = [$code];
- }
-
- return $this->addFieldToFilter('attribute_code', ['in' => $code]);
- }
-
- /**
- * Add store label to attribute by specified store id
- *
- * @param int $storeId
- * @return $this
- */
- public function addStoreLabel($storeId)
- {
- // if not called previously
- if ($this->_addedStoreLabelsFlag === false) {
- $adapter = $this->getConnection();
- $joinExpression = $adapter
- ->quoteInto('al.attribute_id = main_table.attribute_id AND al.store_id = ?', (int) $storeId);
- $this->getSelect()->joinLeft(
- ['al' => $this->getTable('eav/attribute_label')],
- $joinExpression,
- ['store_label' => $adapter->getIfNullSql('al.value', 'main_table.frontend_label')],
- );
- $this->_addedStoreLabelsFlag = $storeId;
- } elseif ($this->_addedStoreLabelsFlag !== $storeId) {
- // check that previous call $storeId matches current call
- throw new Exception('Cannot call addStoreLabel for different store views on the same collection');
- }
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Group.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Group.php
index b3450947438..0429a3268c4 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Group.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Group.php
@@ -22,11 +22,6 @@
*/
class Mage_Eav_Model_Resource_Entity_Attribute_Group extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('eav/attribute_group', 'attribute_group_id');
- }
-
/**
* Checks if attribute group exists
*
@@ -48,6 +43,37 @@ public function itemExists($object)
return $adapter->fetchRow($select, $bind) > 0;
}
+ /**
+ * Set any group default if old one was removed
+ *
+ * @param int $attributeSetId
+ * @return $this
+ */
+ public function updateDefaultGroup($attributeSetId)
+ {
+ $adapter = $this->_getWriteAdapter();
+ $bind = [':attribute_set_id' => $attributeSetId];
+ $select = $adapter->select()
+ ->from($this->getMainTable(), $this->getIdFieldName())
+ ->where('attribute_set_id = :attribute_set_id')
+ ->order('default_id ' . Varien_Data_Collection::SORT_ORDER_DESC)
+ ->limit(1);
+
+ $groupId = $adapter->fetchOne($select, $bind);
+
+ if ($groupId) {
+ $data = ['default_id' => 1];
+ $where = ['attribute_group_id =?' => $groupId];
+ $adapter->update($this->getMainTable(), $data, $where);
+ }
+
+ return $this;
+ }
+ protected function _construct()
+ {
+ $this->_init('eav/attribute_group', 'attribute_group_id');
+ }
+
/**
* Perform actions before object save
*
@@ -94,31 +120,4 @@ protected function _getMaxSortOrder($object)
return $adapter->fetchOne($select, $bind);
}
-
- /**
- * Set any group default if old one was removed
- *
- * @param int $attributeSetId
- * @return $this
- */
- public function updateDefaultGroup($attributeSetId)
- {
- $adapter = $this->_getWriteAdapter();
- $bind = [':attribute_set_id' => $attributeSetId];
- $select = $adapter->select()
- ->from($this->getMainTable(), $this->getIdFieldName())
- ->where('attribute_set_id = :attribute_set_id')
- ->order('default_id ' . Varien_Data_Collection::SORT_ORDER_DESC)
- ->limit(1);
-
- $groupId = $adapter->fetchOne($select, $bind);
-
- if ($groupId) {
- $data = ['default_id' => 1];
- $where = ['attribute_group_id =?' => $groupId];
- $adapter->update($this->getMainTable(), $data, $where);
- }
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Group/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Group/Collection.php
index 8969d845300..41b686597ce 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Group/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Group/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Eav_Model_Resource_Entity_Attribute_Group_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Init resource model for collection
- *
- */
- protected function _construct()
- {
- $this->_init('eav/entity_attribute_group');
- }
-
/**
* Set Attribute Set Filter
*
@@ -54,4 +45,12 @@ public function setSortOrder($direction = self::SORT_ORDER_ASC)
{
return $this->addOrder('sort_order', $direction);
}
+ /**
+ * Init resource model for collection
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('eav/entity_attribute_group');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php
index 30ccb293d89..fd7d52ea933 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php
@@ -22,11 +22,6 @@
*/
class Mage_Eav_Model_Resource_Entity_Attribute_Option extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('eav/attribute_option', 'option_id');
- }
-
/**
* Add Join with option value for collection select
*
@@ -131,4 +126,8 @@ public function getFlatUpdateSelect(
return $select;
}
+ protected function _construct()
+ {
+ $this->_init('eav/attribute_option', 'option_id');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option/Collection.php
index e727596e3a6..29cdf5d7e43 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option/Collection.php
@@ -29,12 +29,6 @@ class Mage_Eav_Model_Resource_Entity_Attribute_Option_Collection extends Mage_Co
*/
protected $_optionValueTable;
- protected function _construct()
- {
- $this->_init('eav/entity_attribute_option');
- $this->_optionValueTable = Mage::getSingleton('core/resource')->getTableName('eav/attribute_option_value');
- }
-
/**
* Set attribute filter
*
@@ -139,4 +133,10 @@ public function setPositionOrder($dir = self::SORT_ORDER_ASC, $sortAlpha = false
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('eav/entity_attribute_option');
+ $this->_optionValueTable = Mage::getSingleton('core/resource')->getTableName('eav/attribute_option_value');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set.php
index 82459722715..f2e866cd253 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set.php
@@ -22,42 +22,6 @@
*/
class Mage_Eav_Model_Resource_Entity_Attribute_Set extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('eav/attribute_set', 'attribute_set_id');
- }
-
- /**
- * Perform actions after object save
- *
- * @inheritDoc
- */
- protected function _afterSave(Mage_Core_Model_Abstract $object)
- {
- if ($object->getGroups()) {
- foreach ($object->getGroups() as $group) {
- $group->setAttributeSetId($object->getId());
- if ($group->itemExists() && !$group->getId()) {
- continue;
- }
- $group->save();
- }
- }
- if ($object->getRemoveGroups()) {
- foreach ($object->getRemoveGroups() as $group) {
- $group->delete();
- }
- Mage::getResourceModel('eav/entity_attribute_group')->updateDefaultGroup($object->getId());
- }
- if ($object->getRemoveAttributes()) {
- foreach ($object->getRemoveAttributes() as $attribute) {
- $attribute->deleteEntity();
- }
- }
-
- return parent::_afterSave($object);
- }
-
/**
* Validate attribute set name
*
@@ -156,4 +120,39 @@ public function getDefaultGroupId($setId)
->limit(1);
return $adapter->fetchOne($select, $bind);
}
+ protected function _construct()
+ {
+ $this->_init('eav/attribute_set', 'attribute_set_id');
+ }
+
+ /**
+ * Perform actions after object save
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave(Mage_Core_Model_Abstract $object)
+ {
+ if ($object->getGroups()) {
+ foreach ($object->getGroups() as $group) {
+ $group->setAttributeSetId($object->getId());
+ if ($group->itemExists() && !$group->getId()) {
+ continue;
+ }
+ $group->save();
+ }
+ }
+ if ($object->getRemoveGroups()) {
+ foreach ($object->getRemoveGroups() as $group) {
+ $group->delete();
+ }
+ Mage::getResourceModel('eav/entity_attribute_group')->updateDefaultGroup($object->getId());
+ }
+ if ($object->getRemoveAttributes()) {
+ foreach ($object->getRemoveAttributes() as $attribute) {
+ $attribute->deleteEntity();
+ }
+ }
+
+ return parent::_afterSave($object);
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set/Collection.php
index 87a6966a874..131f1aab81c 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Eav_Model_Resource_Entity_Attribute_Set_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('eav/entity_attribute_set');
- }
-
/**
* Add filter by entity type id to collection
*
@@ -57,4 +52,8 @@ public function toOptionHash()
{
return parent::_toOptionHash('attribute_set_id', 'attribute_set_name');
}
+ protected function _construct()
+ {
+ $this->_init('eav/entity_attribute_set');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Store.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Store.php
index 96aa293fcf8..1e8766e5280 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Store.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Store.php
@@ -22,11 +22,6 @@
*/
class Mage_Eav_Model_Resource_Entity_Store extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('eav/entity_store', 'entity_store_id');
- }
-
/**
* Load an object by entity type and store
*
@@ -58,4 +53,8 @@ public function loadByEntityStore(Mage_Core_Model_Abstract $object, $entityTypeI
return true;
}
+ protected function _construct()
+ {
+ $this->_init('eav/entity_store', 'entity_store_id');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Type.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Type.php
index 2b8a49e3503..171d3ac3c08 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Type.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Type.php
@@ -22,11 +22,6 @@
*/
class Mage_Eav_Model_Resource_Entity_Type extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('eav/entity_type', 'entity_type_id');
- }
-
/**
* Load Entity Type by Code
*
@@ -55,4 +50,8 @@ public function getAdditionalAttributeTable($entityTypeId)
return $adapter->fetchOne($select, $bind);
}
+ protected function _construct()
+ {
+ $this->_init('eav/entity_type', 'entity_type_id');
+ }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Form/Attribute/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Form/Attribute/Collection.php
index ad80d99bcf2..34204b283cc 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Form/Attribute/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Form/Attribute/Collection.php
@@ -50,32 +50,6 @@ class Mage_Eav_Model_Resource_Form_Attribute_Collection extends Mage_Core_Model_
*/
protected $_entityType;
- /**
- * @throws Mage_Core_Exception
- */
- protected function _construct()
- {
- if (empty($this->_moduleName)) {
- Mage::throwException(Mage::helper('eav')->__('Current module pathname is undefined'));
- }
- if (empty($this->_entityTypeCode)) {
- Mage::throwException(Mage::helper('eav')->__('Current module EAV entity is undefined'));
- }
- }
-
- /**
- * Get EAV website table
- *
- * Get table, where website-dependent attribute parameters are stored
- * If realization doesn't demand this functionality, let this function just return null
- *
- * @return string|null
- */
- protected function _getEavWebsiteTable()
- {
- return null;
- }
-
/**
* Set current store to collection
*
@@ -149,6 +123,32 @@ public function setSortOrder($direction = self::SORT_ORDER_ASC)
return $this->setOrder('ca.sort_order', $direction);
}
+ /**
+ * @throws Mage_Core_Exception
+ */
+ protected function _construct()
+ {
+ if (empty($this->_moduleName)) {
+ Mage::throwException(Mage::helper('eav')->__('Current module pathname is undefined'));
+ }
+ if (empty($this->_entityTypeCode)) {
+ Mage::throwException(Mage::helper('eav')->__('Current module EAV entity is undefined'));
+ }
+ }
+
+ /**
+ * Get EAV website table
+ *
+ * Get table, where website-dependent attribute parameters are stored
+ * If realization doesn't demand this functionality, let this function just return null
+ *
+ * @return string|null
+ */
+ protected function _getEavWebsiteTable()
+ {
+ return null;
+ }
+
/**
* Add joins to select
*
diff --git a/app/code/core/Mage/Eav/Model/Resource/Form/Element/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Form/Element/Collection.php
index c2b00e180d5..2d749976940 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Form/Element/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Form/Element/Collection.php
@@ -22,14 +22,6 @@
*/
class Mage_Eav_Model_Resource_Form_Element_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Initialize collection model
- */
- protected function _construct()
- {
- $this->_init('eav/form_element');
- }
-
/**
* Add Form Type filter to collection
*
@@ -88,6 +80,26 @@ public function setSortOrder()
return $this;
}
+ /**
+ * Load data (join attribute data)
+ *
+ * @inheritDoc
+ */
+ public function load($printQuery = false, $logQuery = false)
+ {
+ if (!$this->isLoaded()) {
+ $this->_joinAttributeData();
+ }
+ return parent::load($printQuery, $logQuery);
+ }
+ /**
+ * Initialize collection model
+ */
+ protected function _construct()
+ {
+ $this->_init('eav/form_element');
+ }
+
/**
* Join attribute data
*
@@ -103,17 +115,4 @@ protected function _joinAttributeData()
return $this;
}
-
- /**
- * Load data (join attribute data)
- *
- * @inheritDoc
- */
- public function load($printQuery = false, $logQuery = false)
- {
- if (!$this->isLoaded()) {
- $this->_joinAttributeData();
- }
- return parent::load($printQuery, $logQuery);
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Form/Fieldset.php b/app/code/core/Mage/Eav/Model/Resource/Form/Fieldset.php
index 118dd8f4ac5..7ae3a1657d5 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Form/Fieldset.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Form/Fieldset.php
@@ -22,6 +22,26 @@
*/
class Mage_Eav_Model_Resource_Form_Fieldset extends Mage_Core_Model_Resource_Db_Abstract
{
+ /**
+ * Retrieve fieldset labels for stores
+ *
+ * @param Mage_Eav_Model_Form_Fieldset $object
+ * @return array
+ */
+ public function getLabels($object)
+ {
+ $objectId = $object->getId();
+ if (!$objectId) {
+ return [];
+ }
+ $adapter = $this->_getReadAdapter();
+ $bind = [':fieldset_id' => $objectId];
+ $select = $adapter->select()
+ ->from($this->getTable('eav/form_fieldset_label'), ['store_id', 'label'])
+ ->where('fieldset_id = :fieldset_id');
+
+ return $adapter->fetchPairs($select, $bind);
+ }
protected function _construct()
{
$this->_init('eav/form_fieldset', 'fieldset_id');
@@ -99,27 +119,6 @@ protected function _afterSave(Mage_Core_Model_Abstract $object)
return parent::_afterSave($object);
}
- /**
- * Retrieve fieldset labels for stores
- *
- * @param Mage_Eav_Model_Form_Fieldset $object
- * @return array
- */
- public function getLabels($object)
- {
- $objectId = $object->getId();
- if (!$objectId) {
- return [];
- }
- $adapter = $this->_getReadAdapter();
- $bind = [':fieldset_id' => $objectId];
- $select = $adapter->select()
- ->from($this->getTable('eav/form_fieldset_label'), ['store_id', 'label'])
- ->where('fieldset_id = :fieldset_id');
-
- return $adapter->fetchPairs($select, $bind);
- }
-
/**
* Retrieve select object for load object data
*
diff --git a/app/code/core/Mage/Eav/Model/Resource/Form/Fieldset/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Form/Fieldset/Collection.php
index 31184ce267c..3c38a7031cb 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Form/Fieldset/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Form/Fieldset/Collection.php
@@ -29,15 +29,6 @@ class Mage_Eav_Model_Resource_Form_Fieldset_Collection extends Mage_Core_Model_R
*/
protected $_storeId;
- /**
- * Initialize collection model
- *
- */
- protected function _construct()
- {
- $this->_init('eav/form_fieldset');
- }
-
/**
* Add Form Type filter to collection
*
@@ -89,6 +80,15 @@ public function setStoreId($storeId)
return $this;
}
+ /**
+ * Initialize collection model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('eav/form_fieldset');
+ }
+
/**
* Initialize select object
*
diff --git a/app/code/core/Mage/Eav/Model/Resource/Form/Type.php b/app/code/core/Mage/Eav/Model/Resource/Form/Type.php
index 09b4b64095b..46ef270df84 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Form/Type.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Form/Type.php
@@ -24,15 +24,6 @@
*/
class Mage_Eav_Model_Resource_Form_Type extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('eav/form_type', 'type_id');
- $this->addUniqueField([
- 'field' => ['code', 'theme', 'store_id'],
- 'title' => Mage::helper('eav')->__('Form Type with the same code'),
- ]);
- }
-
/**
* Load an object
*
@@ -68,6 +59,36 @@ public function getEntityTypes($object)
return $adapter->fetchCol($select, $bind);
}
+ /**
+ * Retrieve form type filtered by given attribute
+ *
+ * @param Mage_Eav_Model_Entity_Attribute_Abstract|int $attribute
+ * @return array
+ */
+ public function getFormTypesByAttribute($attribute)
+ {
+ if ($attribute instanceof Mage_Eav_Model_Entity_Attribute_Abstract) {
+ $attribute = $attribute->getId();
+ }
+ if (!$attribute) {
+ return [];
+ }
+ $bind = [':attribute_id' => $attribute];
+ $select = $this->_getReadAdapter()->select()
+ ->from($this->getTable('eav/form_element'))
+ ->where('attribute_id = :attribute_id');
+
+ return $this->_getReadAdapter()->fetchAll($select, $bind);
+ }
+ protected function _construct()
+ {
+ $this->_init('eav/form_type', 'type_id');
+ $this->addUniqueField([
+ 'field' => ['code', 'theme', 'store_id'],
+ 'title' => Mage::helper('eav')->__('Form Type with the same code'),
+ ]);
+ }
+
/**
* Save entity types after save form type
*
@@ -114,26 +135,4 @@ protected function _afterSave(Mage_Core_Model_Abstract $object)
return parent::_afterSave($object);
}
-
- /**
- * Retrieve form type filtered by given attribute
- *
- * @param Mage_Eav_Model_Entity_Attribute_Abstract|int $attribute
- * @return array
- */
- public function getFormTypesByAttribute($attribute)
- {
- if ($attribute instanceof Mage_Eav_Model_Entity_Attribute_Abstract) {
- $attribute = $attribute->getId();
- }
- if (!$attribute) {
- return [];
- }
- $bind = [':attribute_id' => $attribute];
- $select = $this->_getReadAdapter()->select()
- ->from($this->getTable('eav/form_element'))
- ->where('attribute_id = :attribute_id');
-
- return $this->_getReadAdapter()->fetchAll($select, $bind);
- }
}
diff --git a/app/code/core/Mage/Eav/Model/Resource/Form/Type/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Form/Type/Collection.php
index 410ed1a963d..4a9af74967c 100644
--- a/app/code/core/Mage/Eav/Model/Resource/Form/Type/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Form/Type/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Eav_Model_Resource_Form_Type_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Initialize collection model
- *
- */
- protected function _construct()
- {
- $this->_init('eav/form_type');
- }
-
/**
* Convert items array to array for select options
*
@@ -63,4 +54,12 @@ public function addEntityTypeFilter($entity)
return $this;
}
+ /**
+ * Initialize collection model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('eav/form_type');
+ }
}
diff --git a/app/code/core/Mage/GiftMessage/Block/Adminhtml/Sales/Order/View/Items.php b/app/code/core/Mage/GiftMessage/Block/Adminhtml/Sales/Order/View/Items.php
index d6c2bd87485..63d8d6e04cb 100644
--- a/app/code/core/Mage/GiftMessage/Block/Adminhtml/Sales/Order/View/Items.php
+++ b/app/code/core/Mage/GiftMessage/Block/Adminhtml/Sales/Order/View/Items.php
@@ -117,28 +117,6 @@ public function getFieldIdPrefix()
return 'giftmessage_' . $this->getItem()->getId() . '_';
}
- /**
- * Initialize gift message for entity
- *
- * @return Mage_GiftMessage_Block_Adminhtml_Sales_Order_View_Items
- */
- protected function _initMessage()
- {
- /** @var Mage_GiftMessage_Helper_Message $helper */
- $helper = $this->helper('giftmessage/message');
- $this->_giftMessage[$this->getItem()->getGiftMessageId()] = $helper->getGiftMessage($this->getItem()->getGiftMessageId());
-
- // init default values for giftmessage form
- if (!$this->getMessage()->getSender()) {
- $this->getMessage()->setSender($this->getDefaultSender());
- }
- if (!$this->getMessage()->getRecipient()) {
- $this->getMessage()->setRecipient($this->getDefaultRecipient());
- }
-
- return $this;
- }
-
/**
* Retrieve gift message for entity
*
@@ -216,4 +194,26 @@ public function getMessageText()
{
return $this->escapeHtml($this->getMessage()->getMessage());
}
+
+ /**
+ * Initialize gift message for entity
+ *
+ * @return Mage_GiftMessage_Block_Adminhtml_Sales_Order_View_Items
+ */
+ protected function _initMessage()
+ {
+ /** @var Mage_GiftMessage_Helper_Message $helper */
+ $helper = $this->helper('giftmessage/message');
+ $this->_giftMessage[$this->getItem()->getGiftMessageId()] = $helper->getGiftMessage($this->getItem()->getGiftMessageId());
+
+ // init default values for giftmessage form
+ if (!$this->getMessage()->getSender()) {
+ $this->getMessage()->setSender($this->getDefaultSender());
+ }
+ if (!$this->getMessage()->getRecipient()) {
+ $this->getMessage()->setRecipient($this->getDefaultRecipient());
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/GiftMessage/Block/Message/Form.php b/app/code/core/Mage/GiftMessage/Block/Message/Form.php
index e5941ec33f6..dc01afc4e20 100644
--- a/app/code/core/Mage/GiftMessage/Block/Message/Form.php
+++ b/app/code/core/Mage/GiftMessage/Block/Message/Form.php
@@ -91,18 +91,6 @@ public function getRemoveUrl()
);
}
- /**
- * @return $this
- * @throws Exception
- */
- protected function _initMessage()
- {
- /** @var Mage_GiftMessage_Helper_Message $helper */
- $helper = $this->helper('giftmessage/message');
- $this->_giftMessage = $helper->getGiftMessage($this->getRequest()->getParam('message'));
- return $this;
- }
-
/**
* @return Mage_GiftMessage_Model_Message
* @throws Exception
@@ -142,4 +130,16 @@ public function getUniqueId()
{
return $this->getRequest()->getParam('uniqueId');
}
+
+ /**
+ * @return $this
+ * @throws Exception
+ */
+ protected function _initMessage()
+ {
+ /** @var Mage_GiftMessage_Helper_Message $helper */
+ $helper = $this->helper('giftmessage/message');
+ $this->_giftMessage = $helper->getGiftMessage($this->getRequest()->getParam('message'));
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/GiftMessage/Block/Message/Helper.php b/app/code/core/Mage/GiftMessage/Block/Message/Helper.php
index ba8fb9a4a35..b4fba606d3e 100644
--- a/app/code/core/Mage/GiftMessage/Block/Message/Helper.php
+++ b/app/code/core/Mage/GiftMessage/Block/Message/Helper.php
@@ -118,17 +118,6 @@ public function getEditUrl()
return $helper->getEditUrl($this->getEntity(), $this->getType());
}
- /**
- * @return $this
- */
- protected function _initMessage()
- {
- /** @var Mage_GiftMessage_Helper_Message $helper */
- $helper = $this->helper('giftmessage/message');
- $this->_giftMessage = $helper->getGiftMessage($this->getEntity()->getGiftMessageId());
- return $this;
- }
-
/**
* @return Mage_GiftMessage_Model_Message
*/
@@ -140,4 +129,15 @@ public function getMessage()
return $this->_giftMessage;
}
+
+ /**
+ * @return $this
+ */
+ protected function _initMessage()
+ {
+ /** @var Mage_GiftMessage_Helper_Message $helper */
+ $helper = $this->helper('giftmessage/message');
+ $this->_giftMessage = $helper->getGiftMessage($this->getEntity()->getGiftMessageId());
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/GiftMessage/Block/Message/Inline.php b/app/code/core/Mage/GiftMessage/Block/Message/Inline.php
index 57d9bb4e552..46480f47ba3 100644
--- a/app/code/core/Mage/GiftMessage/Block/Message/Inline.php
+++ b/app/code/core/Mage/GiftMessage/Block/Message/Inline.php
@@ -28,12 +28,6 @@ class Mage_GiftMessage_Block_Message_Inline extends Mage_Core_Block_Template
protected $_type = null;
protected $_giftMessage = null;
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('giftmessage/inline.phtml');
- }
-
/**
* Set entity
*
@@ -88,19 +82,6 @@ public function hasGiftMessage()
return $this->getEntity()->getGiftMessageId() > 0;
}
- /**
- * Init message
- *
- * @return $this
- */
- protected function _initMessage()
- {
- /** @var Mage_GiftMessage_Helper_Message $helper */
- $helper = $this->helper('giftmessage/message');
- $this->_giftMessage = $helper->getGiftMessage($this->getEntity()->getGiftMessageId());
- return $this;
- }
-
/**
* Get default value for From field
*
@@ -272,4 +253,23 @@ public function isItemMessagesAvailable($item)
$type = substr($this->getType(), 0, 5) === 'multi' ? 'address_item' : 'item';
return Mage::helper('giftmessage/message')->isMessagesAvailable($type, $item);
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('giftmessage/inline.phtml');
+ }
+
+ /**
+ * Init message
+ *
+ * @return $this
+ */
+ protected function _initMessage()
+ {
+ /** @var Mage_GiftMessage_Helper_Message $helper */
+ $helper = $this->helper('giftmessage/message');
+ $this->_giftMessage = $helper->getGiftMessage($this->getEntity()->getGiftMessageId());
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/GiftMessage/Helper/Message.php b/app/code/core/Mage/GiftMessage/Helper/Message.php
index bf44f876e38..4e6126f9be4 100644
--- a/app/code/core/Mage/GiftMessage/Helper/Message.php
+++ b/app/code/core/Mage/GiftMessage/Helper/Message.php
@@ -153,23 +153,6 @@ public function isMessagesAvailable($type, Varien_Object $entity, $store = null)
}
}
- /**
- * Check availability of gift messages from store config if flag eq 2.
- *
- * @param bool $productGiftMessageAllow
- * @param bool|int|Mage_Core_Model_Store|null|string $store
- * @return bool
- */
- protected function _getDependenceFromStoreConfig($productGiftMessageAllow, $store = null)
- {
- $result = Mage::getStoreConfigFlag(self::XPATH_CONFIG_GIFT_MESSAGE_ALLOW_ITEMS, $store);
- if ($productGiftMessageAllow === '' || is_null($productGiftMessageAllow)) {
- return $result;
- } else {
- return $productGiftMessageAllow;
- }
- }
-
/**
* Alias for isMessagesAvailable(...)
*
@@ -301,4 +284,21 @@ public function getGiftMessage($messageId = null)
return $message;
}
+
+ /**
+ * Check availability of gift messages from store config if flag eq 2.
+ *
+ * @param bool $productGiftMessageAllow
+ * @param bool|int|Mage_Core_Model_Store|null|string $store
+ * @return bool
+ */
+ protected function _getDependenceFromStoreConfig($productGiftMessageAllow, $store = null)
+ {
+ $result = Mage::getStoreConfigFlag(self::XPATH_CONFIG_GIFT_MESSAGE_ALLOW_ITEMS, $store);
+ if ($productGiftMessageAllow === '' || is_null($productGiftMessageAllow)) {
+ return $result;
+ } else {
+ return $productGiftMessageAllow;
+ }
+ }
}
diff --git a/app/code/core/Mage/GiftMessage/Model/Api.php b/app/code/core/Mage/GiftMessage/Model/Api.php
index 231f64dcab8..1bfe404ff73 100644
--- a/app/code/core/Mage/GiftMessage/Model/Api.php
+++ b/app/code/core/Mage/GiftMessage/Model/Api.php
@@ -22,46 +22,6 @@
*/
class Mage_GiftMessage_Model_Api extends Mage_Checkout_Model_Api_Resource_Product
{
- /**
- * Return an Array of attributes.
- *
- * @param array $arr
- * @return array
- */
- protected function _prepareData($arr)
- {
- if (is_array($arr)) {
- return $arr;
- }
- return [];
- }
-
- /**
- * Raise event for setting a giftMessage.
- *
- * @param String $entityId
- * @param Mage_Core_Controller_Request_Http $request
- * @param Mage_Sales_Model_Quote $quote
- * @return array
- */
- protected function _setGiftMessage($entityId, $request, $quote)
- {
- /**
- * Below code will catch exceptions only in DeveloperMode
- * @see Mage_Core_Model_App::_callObserverMethod($object, $method, $observer)
- * And result of Mage::dispatchEvent will always return an Object of Mage_Core_Model_App.
- */
- try {
- Mage::dispatchEvent(
- 'checkout_controller_onepage_save_shipping_method',
- ['request' => $request, 'quote' => $quote],
- );
- return ['entityId' => $entityId, 'result' => true, 'error' => ''];
- } catch (Exception $e) {
- return ['entityId' => $entityId, 'result' => false, 'error' => $e->getMessage()];
- }
- }
-
/**
* Set GiftMessage for a Quote.
*
@@ -168,4 +128,43 @@ public function setForQuoteItem($quoteItemId, $giftMessage, $store = null)
return $this->_setGiftMessage($quoteItemId, $request, $quote);
}
+ /**
+ * Return an Array of attributes.
+ *
+ * @param array $arr
+ * @return array
+ */
+ protected function _prepareData($arr)
+ {
+ if (is_array($arr)) {
+ return $arr;
+ }
+ return [];
+ }
+
+ /**
+ * Raise event for setting a giftMessage.
+ *
+ * @param String $entityId
+ * @param Mage_Core_Controller_Request_Http $request
+ * @param Mage_Sales_Model_Quote $quote
+ * @return array
+ */
+ protected function _setGiftMessage($entityId, $request, $quote)
+ {
+ /**
+ * Below code will catch exceptions only in DeveloperMode
+ * @see Mage_Core_Model_App::_callObserverMethod($object, $method, $observer)
+ * And result of Mage::dispatchEvent will always return an Object of Mage_Core_Model_App.
+ */
+ try {
+ Mage::dispatchEvent(
+ 'checkout_controller_onepage_save_shipping_method',
+ ['request' => $request, 'quote' => $quote],
+ );
+ return ['entityId' => $entityId, 'result' => true, 'error' => ''];
+ } catch (Exception $e) {
+ return ['entityId' => $entityId, 'result' => false, 'error' => $e->getMessage()];
+ }
+ }
}
diff --git a/app/code/core/Mage/GiftMessage/Model/Message.php b/app/code/core/Mage/GiftMessage/Model/Message.php
index 0ba83754eb5..d6037e12df9 100644
--- a/app/code/core/Mage/GiftMessage/Model/Message.php
+++ b/app/code/core/Mage/GiftMessage/Model/Message.php
@@ -50,11 +50,6 @@ class Mage_GiftMessage_Model_Message extends Mage_Core_Model_Abstract
'quote_address_item' => 'sales/quote_address_item',
];
- protected function _construct()
- {
- $this->_init('giftmessage/message');
- }
-
/**
* Return model from entity type
*
@@ -90,4 +85,9 @@ public static function getAllowedEntityTypes()
{
return self::$_allowedEntityTypes;
}
+
+ protected function _construct()
+ {
+ $this->_init('giftmessage/message');
+ }
}
diff --git a/app/code/core/Mage/GiftMessage/Model/Observer.php b/app/code/core/Mage/GiftMessage/Model/Observer.php
index f3abd3bb1a6..3ba62cd9df6 100644
--- a/app/code/core/Mage/GiftMessage/Model/Observer.php
+++ b/app/code/core/Mage/GiftMessage/Model/Observer.php
@@ -71,21 +71,6 @@ public function salesEventConvertQuoteToOrder(Varien_Event_Observer $observer)
return $this;
}
- /**
- * Geter for available gift messages value from product
- *
- * @deprecated after 1.5.0.0
- * @param Mage_Catalog_Model_Product|integer $product
- * @return int|null
- */
- protected function _getAvailable($product)
- {
- if (is_object($product)) {
- return $product->getGiftMessageAvailable();
- }
- return Mage::getModel('catalog/product')->load($product)->getGiftMessageAvailable();
- }
-
/**
* Operate with gift messages on checkout process
*
@@ -223,4 +208,19 @@ public function salesEventOrderItemToQuoteItem(Varien_Event_Observer $observer)
}
return $this;
}
+
+ /**
+ * Geter for available gift messages value from product
+ *
+ * @deprecated after 1.5.0.0
+ * @param Mage_Catalog_Model_Product|integer $product
+ * @return int|null
+ */
+ protected function _getAvailable($product)
+ {
+ if (is_object($product)) {
+ return $product->getGiftMessageAvailable();
+ }
+ return Mage::getModel('catalog/product')->load($product)->getGiftMessageAvailable();
+ }
}
diff --git a/app/code/core/Mage/ImportExport/Block/Adminhtml/Export/Edit.php b/app/code/core/Mage/ImportExport/Block/Adminhtml/Export/Edit.php
index 1062e90e697..bbc8f4046fa 100644
--- a/app/code/core/Mage/ImportExport/Block/Adminhtml/Export/Edit.php
+++ b/app/code/core/Mage/ImportExport/Block/Adminhtml/Export/Edit.php
@@ -31,6 +31,16 @@ public function __construct()
->removeButton('save');
}
+ /**
+ * Get header text
+ *
+ * @return string
+ */
+ public function getHeaderText()
+ {
+ return Mage::helper('importexport')->__('Export');
+ }
+
/**
* Internal constructor
*/
@@ -42,14 +52,4 @@ protected function _construct()
$this->_blockGroup = 'importexport';
$this->_controller = 'adminhtml_export';
}
-
- /**
- * Get header text
- *
- * @return string
- */
- public function getHeaderText()
- {
- return Mage::helper('importexport')->__('Export');
- }
}
diff --git a/app/code/core/Mage/ImportExport/Block/Adminhtml/Export/Filter.php b/app/code/core/Mage/ImportExport/Block/Adminhtml/Export/Filter.php
index 412cc9d7c7b..d46338b7f89 100644
--- a/app/code/core/Mage/ImportExport/Block/Adminhtml/Export/Filter.php
+++ b/app/code/core/Mage/ImportExport/Block/Adminhtml/Export/Filter.php
@@ -54,6 +54,86 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * Create filter fields for 'Filter' column.
+ *
+ * @param mixed $value
+ * @param bool $isExport
+ * @return string
+ */
+ public function decorateFilter($value, Mage_Eav_Model_Entity_Attribute $row, Varien_Object $column, $isExport)
+ {
+ $value = null;
+ $values = $column->getValues();
+ if (is_array($values) && isset($values[$row->getAttributeCode()])) {
+ $value = $values[$row->getAttributeCode()];
+ }
+ switch (Mage_ImportExport_Model_Export::getAttributeFilterType($row)) {
+ case Mage_ImportExport_Model_Export::FILTER_TYPE_SELECT:
+ $cell = $this->_getSelectHtmlWithValue($row, $value);
+ break;
+ case Mage_ImportExport_Model_Export::FILTER_TYPE_INPUT:
+ $cell = $this->_getInputHtmlWithValue($row, $value);
+ break;
+ case Mage_ImportExport_Model_Export::FILTER_TYPE_DATE:
+ $cell = $this->_getDateFromToHtmlWithValue($row, $value);
+ break;
+ case Mage_ImportExport_Model_Export::FILTER_TYPE_NUMBER:
+ $cell = $this->_getNumberFromToHtmlWithValue($row, $value);
+ break;
+ default:
+ $cell = Mage::helper('importexport')->__('Unknown attribute filter type');
+ }
+ return $cell;
+ }
+
+ /**
+ * Element filter ID getter.
+ *
+ * @param string $attributeCode
+ * @return string
+ */
+ public function getFilterElementId($attributeCode)
+ {
+ return Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP . "_{$attributeCode}";
+ }
+
+ /**
+ * Element filter full name getter.
+ *
+ * @param string $attributeCode
+ * @return string
+ */
+ public function getFilterElementName($attributeCode)
+ {
+ return Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP . "[{$attributeCode}]";
+ }
+
+ /**
+ * Get row edit URL.
+ *
+ * @param Mage_Catalog_Model_Resource_Eav_Attribute $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return '';
+ }
+
+ /**
+ * Prepare collection by setting page number, sorting etc..
+ *
+ * @return Mage_Eav_Model_Resource_Entity_Attribute_Collection
+ */
+ public function prepareCollection(Mage_Eav_Model_Resource_Entity_Attribute_Collection $collection)
+ {
+ $this->_collection = $collection;
+
+ $this->_prepareGrid();
+
+ return $this->_collection;
+ }
+
/**
* Date 'from-to' filter HTML.
*
@@ -368,84 +448,4 @@ protected function _prepareColumns()
return $this;
}
-
- /**
- * Create filter fields for 'Filter' column.
- *
- * @param mixed $value
- * @param bool $isExport
- * @return string
- */
- public function decorateFilter($value, Mage_Eav_Model_Entity_Attribute $row, Varien_Object $column, $isExport)
- {
- $value = null;
- $values = $column->getValues();
- if (is_array($values) && isset($values[$row->getAttributeCode()])) {
- $value = $values[$row->getAttributeCode()];
- }
- switch (Mage_ImportExport_Model_Export::getAttributeFilterType($row)) {
- case Mage_ImportExport_Model_Export::FILTER_TYPE_SELECT:
- $cell = $this->_getSelectHtmlWithValue($row, $value);
- break;
- case Mage_ImportExport_Model_Export::FILTER_TYPE_INPUT:
- $cell = $this->_getInputHtmlWithValue($row, $value);
- break;
- case Mage_ImportExport_Model_Export::FILTER_TYPE_DATE:
- $cell = $this->_getDateFromToHtmlWithValue($row, $value);
- break;
- case Mage_ImportExport_Model_Export::FILTER_TYPE_NUMBER:
- $cell = $this->_getNumberFromToHtmlWithValue($row, $value);
- break;
- default:
- $cell = Mage::helper('importexport')->__('Unknown attribute filter type');
- }
- return $cell;
- }
-
- /**
- * Element filter ID getter.
- *
- * @param string $attributeCode
- * @return string
- */
- public function getFilterElementId($attributeCode)
- {
- return Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP . "_{$attributeCode}";
- }
-
- /**
- * Element filter full name getter.
- *
- * @param string $attributeCode
- * @return string
- */
- public function getFilterElementName($attributeCode)
- {
- return Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP . "[{$attributeCode}]";
- }
-
- /**
- * Get row edit URL.
- *
- * @param Mage_Catalog_Model_Resource_Eav_Attribute $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return '';
- }
-
- /**
- * Prepare collection by setting page number, sorting etc..
- *
- * @return Mage_Eav_Model_Resource_Entity_Attribute_Collection
- */
- public function prepareCollection(Mage_Eav_Model_Resource_Entity_Attribute_Collection $collection)
- {
- $this->_collection = $collection;
-
- $this->_prepareGrid();
-
- return $this->_collection;
- }
}
diff --git a/app/code/core/Mage/ImportExport/Block/Adminhtml/Import/Edit.php b/app/code/core/Mage/ImportExport/Block/Adminhtml/Import/Edit.php
index 9b91e04f26f..96a58cf67c6 100644
--- a/app/code/core/Mage/ImportExport/Block/Adminhtml/Import/Edit.php
+++ b/app/code/core/Mage/ImportExport/Block/Adminhtml/Import/Edit.php
@@ -33,6 +33,16 @@ public function __construct()
->_updateButton('save', 'onclick', 'editForm.postToFrame();');
}
+ /**
+ * Get header text
+ *
+ * @return string
+ */
+ public function getHeaderText()
+ {
+ return Mage::helper('importexport')->__('Import');
+ }
+
/**
* Internal constructor
*/
@@ -44,14 +54,4 @@ protected function _construct()
$this->_blockGroup = 'importexport';
$this->_controller = 'adminhtml_import';
}
-
- /**
- * Get header text
- *
- * @return string
- */
- public function getHeaderText()
- {
- return Mage::helper('importexport')->__('Import');
- }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Export.php b/app/code/core/Mage/ImportExport/Model/Export.php
index c361b8312b0..dd8c4fc8eca 100644
--- a/app/code/core/Mage/ImportExport/Model/Export.php
+++ b/app/code/core/Mage/ImportExport/Model/Export.php
@@ -53,81 +53,6 @@ class Mage_ImportExport_Model_Export extends Mage_ImportExport_Model_Abstract
*/
protected $_writer;
- /**
- * Create instance of entity adapter and returns it.
- *
- * @throws Exception
- * @return Mage_ImportExport_Model_Export_Entity_Abstract
- */
- protected function _getEntityAdapter()
- {
- if (!$this->_entityAdapter) {
- $validTypes = Mage_ImportExport_Model_Config::getModels(self::CONFIG_KEY_ENTITIES);
-
- if (isset($validTypes[$this->getEntity()])) {
- try {
- /** @var Mage_ImportExport_Model_Export_Entity_Abstract $_entityAdapter */
- $_entityAdapter = Mage::getModel($validTypes[$this->getEntity()]['model']);
- $this->_entityAdapter = $_entityAdapter;
- } catch (Exception $e) {
- Mage::logException($e);
- Mage::throwException(
- Mage::helper('importexport')->__('Invalid entity model'),
- );
- }
- if (!$this->_entityAdapter instanceof Mage_ImportExport_Model_Export_Entity_Abstract) {
- Mage::throwException(
- Mage::helper('importexport')->__('Entity adapter obejct must be an instance of Mage_ImportExport_Model_Export_Entity_Abstract'),
- );
- }
- } else {
- Mage::throwException(Mage::helper('importexport')->__('Invalid entity'));
- }
- // check for entity codes integrity
- if ($this->getEntity() != $this->_entityAdapter->getEntityTypeCode()) {
- Mage::throwException(
- Mage::helper('importexport')->__('Input entity code is not equal to entity adapter code'),
- );
- }
- $this->_entityAdapter->setParameters($this->getData());
- }
- return $this->_entityAdapter;
- }
-
- /**
- * Get writer object.
- *
- * @throws Mage_Core_Exception
- * @return Mage_ImportExport_Model_Export_Adapter_Abstract
- */
- protected function _getWriter()
- {
- if (!$this->_writer) {
- $validWriters = Mage_ImportExport_Model_Config::getModels(self::CONFIG_KEY_FORMATS);
-
- if (isset($validWriters[$this->getFileFormat()])) {
- try {
- /** @var Mage_ImportExport_Model_Export_Adapter_Abstract $_writer */
- $_writer = Mage::getModel($validWriters[$this->getFileFormat()]['model']);
- $this->_writer = $_writer;
- } catch (Exception $e) {
- Mage::logException($e);
- Mage::throwException(
- Mage::helper('importexport')->__('Invalid entity model'),
- );
- }
- if (!$this->_writer instanceof Mage_ImportExport_Model_Export_Adapter_Abstract) {
- Mage::throwException(
- Mage::helper('importexport')->__('Adapter object must be an instance of %s', 'Mage_ImportExport_Model_Export_Adapter_Abstract'),
- );
- }
- } else {
- Mage::throwException(Mage::helper('importexport')->__('Invalid file format'));
- }
- }
- return $this->_writer;
- }
-
/**
* Export data and return contents of temporary file.
*
@@ -300,4 +225,79 @@ public function getFileName()
{
return $this->getEntity() . '_' . date('Ymd_His') . '.' . $this->_getWriter()->getFileExtension();
}
+
+ /**
+ * Create instance of entity adapter and returns it.
+ *
+ * @throws Exception
+ * @return Mage_ImportExport_Model_Export_Entity_Abstract
+ */
+ protected function _getEntityAdapter()
+ {
+ if (!$this->_entityAdapter) {
+ $validTypes = Mage_ImportExport_Model_Config::getModels(self::CONFIG_KEY_ENTITIES);
+
+ if (isset($validTypes[$this->getEntity()])) {
+ try {
+ /** @var Mage_ImportExport_Model_Export_Entity_Abstract $_entityAdapter */
+ $_entityAdapter = Mage::getModel($validTypes[$this->getEntity()]['model']);
+ $this->_entityAdapter = $_entityAdapter;
+ } catch (Exception $e) {
+ Mage::logException($e);
+ Mage::throwException(
+ Mage::helper('importexport')->__('Invalid entity model'),
+ );
+ }
+ if (!$this->_entityAdapter instanceof Mage_ImportExport_Model_Export_Entity_Abstract) {
+ Mage::throwException(
+ Mage::helper('importexport')->__('Entity adapter obejct must be an instance of Mage_ImportExport_Model_Export_Entity_Abstract'),
+ );
+ }
+ } else {
+ Mage::throwException(Mage::helper('importexport')->__('Invalid entity'));
+ }
+ // check for entity codes integrity
+ if ($this->getEntity() != $this->_entityAdapter->getEntityTypeCode()) {
+ Mage::throwException(
+ Mage::helper('importexport')->__('Input entity code is not equal to entity adapter code'),
+ );
+ }
+ $this->_entityAdapter->setParameters($this->getData());
+ }
+ return $this->_entityAdapter;
+ }
+
+ /**
+ * Get writer object.
+ *
+ * @throws Mage_Core_Exception
+ * @return Mage_ImportExport_Model_Export_Adapter_Abstract
+ */
+ protected function _getWriter()
+ {
+ if (!$this->_writer) {
+ $validWriters = Mage_ImportExport_Model_Config::getModels(self::CONFIG_KEY_FORMATS);
+
+ if (isset($validWriters[$this->getFileFormat()])) {
+ try {
+ /** @var Mage_ImportExport_Model_Export_Adapter_Abstract $_writer */
+ $_writer = Mage::getModel($validWriters[$this->getFileFormat()]['model']);
+ $this->_writer = $_writer;
+ } catch (Exception $e) {
+ Mage::logException($e);
+ Mage::throwException(
+ Mage::helper('importexport')->__('Invalid entity model'),
+ );
+ }
+ if (!$this->_writer instanceof Mage_ImportExport_Model_Export_Adapter_Abstract) {
+ Mage::throwException(
+ Mage::helper('importexport')->__('Adapter object must be an instance of %s', 'Mage_ImportExport_Model_Export_Adapter_Abstract'),
+ );
+ }
+ } else {
+ Mage::throwException(Mage::helper('importexport')->__('Invalid file format'));
+ }
+ }
+ return $this->_writer;
+ }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Export/Adapter/Abstract.php b/app/code/core/Mage/ImportExport/Model/Export/Adapter/Abstract.php
index 117f07183ce..2c52950a276 100644
--- a/app/code/core/Mage/ImportExport/Model/Export/Adapter/Abstract.php
+++ b/app/code/core/Mage/ImportExport/Model/Export/Adapter/Abstract.php
@@ -82,16 +82,6 @@ final public function __construct($destination = null)
*/
public function destruct() {}
- /**
- * Method called as last step of object instance creation. Can be overridden in child classes.
- *
- * @return Mage_ImportExport_Model_Export_Adapter_Abstract
- */
- protected function _init()
- {
- return $this;
- }
-
/**
* Get contents of export file.
*
@@ -167,4 +157,14 @@ public function getDestination()
* @return Mage_ImportExport_Model_Export_Adapter_Abstract
*/
abstract public function writeRow(array $rowData);
+
+ /**
+ * Method called as last step of object instance creation. Can be overridden in child classes.
+ *
+ * @return Mage_ImportExport_Model_Export_Adapter_Abstract
+ */
+ protected function _init()
+ {
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Export/Adapter/Csv.php b/app/code/core/Mage/ImportExport/Model/Export/Adapter/Csv.php
index 709dc9292bb..ee9f8b54b1a 100644
--- a/app/code/core/Mage/ImportExport/Model/Export/Adapter/Csv.php
+++ b/app/code/core/Mage/ImportExport/Model/Export/Adapter/Csv.php
@@ -63,17 +63,6 @@ public function destruct()
}
}
- /**
- * Method called as last step of object instance creation. Can be overridden in child classes.
- *
- * @return Mage_ImportExport_Model_Export_Adapter_Abstract
- */
- protected function _init()
- {
- $this->_fileHandler = fopen($this->_destination, 'w');
- return $this;
- }
-
/**
* MIME-type for 'Content-Type' header.
*
@@ -125,4 +114,15 @@ public function writeRow(array $rowData)
return $this;
}
+
+ /**
+ * Method called as last step of object instance creation. Can be overridden in child classes.
+ *
+ * @return Mage_ImportExport_Model_Export_Adapter_Abstract
+ */
+ protected function _init()
+ {
+ $this->_fileHandler = fopen($this->_destination, 'w');
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Export/Entity/Abstract.php b/app/code/core/Mage/ImportExport/Model/Export/Entity/Abstract.php
index 763e67d6fb2..31013bb442a 100644
--- a/app/code/core/Mage/ImportExport/Model/Export/Entity/Abstract.php
+++ b/app/code/core/Mage/ImportExport/Model/Export/Entity/Abstract.php
@@ -177,144 +177,6 @@ public function __construct()
$this->_connection = $_connection;
}
- /**
- * Initialize website values.
- *
- * @return $this
- */
- protected function _initWebsites()
- {
- foreach (Mage::app()->getWebsites(true) as $website) {
- $this->_websiteIdToCode[$website->getId()] = $website->getCode();
- }
- return $this;
- }
-
- /**
- * Initialize stores hash.
- *
- * @return $this
- */
- protected function _initStores()
- {
- foreach (Mage::app()->getStores(true) as $store) {
- $this->_storeIdToCode[$store->getId()] = $store->getCode();
- $this->_storeIdToWebsiteId[$store->getId()] = $store->getWebsiteId();
- }
- ksort($this->_storeIdToCode); // to ensure that 'admin' store (ID is zero) goes first
- sort($this->_storeIdToWebsiteId);
-
- return $this;
- }
-
- /**
- * Get attributes codes which are appropriate for export.
- *
- * @return array
- */
- protected function _getExportAttrCodes()
- {
- if (self::$attrCodes === null) {
- if (!empty($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_SKIP])
- && is_array($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_SKIP])
- ) {
- $skipAttr = array_flip($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_SKIP]);
- } else {
- $skipAttr = [];
- }
- $attrCodes = [];
-
- foreach ($this->filterAttributeCollection($this->getAttributeCollection()) as $attribute) {
- if (!isset($skipAttr[$attribute->getAttributeId()])
- || in_array($attribute->getAttributeCode(), $this->_permanentAttributes)
- ) {
- $attrCodes[] = $attribute->getAttributeCode();
- }
- }
- self::$attrCodes = $attrCodes;
- }
- return self::$attrCodes;
- }
-
- /**
- * Initialize attribute option values.
- *
- * @return Mage_ImportExport_Model_Export_Entity_Abstract
- */
- protected function _initAttrValues()
- {
- foreach ($this->getAttributeCollection() as $attribute) {
- $this->_attributeValues[$attribute->getAttributeCode()] = $this->getAttributeOptions($attribute);
- }
- return $this;
- }
-
- /**
- * Apply filter to collection and add not skipped attributes to select.
- *
- * @return Mage_Eav_Model_Entity_Collection_Abstract
- */
- protected function _prepareEntityCollection(Mage_Eav_Model_Entity_Collection_Abstract $collection)
- {
- if (!isset($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP])
- || !is_array($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP])
- ) {
- $exportFilter = [];
- } else {
- $exportFilter = $this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP];
- }
- $exportAttrCodes = $this->_getExportAttrCodes();
-
- foreach ($this->filterAttributeCollection($this->getAttributeCollection()) as $attribute) {
- $attrCode = $attribute->getAttributeCode();
-
- // filter applying
- if (isset($exportFilter[$attrCode])) {
- $attrFilterType = Mage_ImportExport_Model_Export::getAttributeFilterType($attribute);
-
- if (Mage_ImportExport_Model_Export::FILTER_TYPE_SELECT == $attrFilterType) {
- if (is_scalar($exportFilter[$attrCode]) && trim($exportFilter[$attrCode])) {
- $collection->addAttributeToFilter($attrCode, ['eq' => $exportFilter[$attrCode]]);
- }
- } elseif (Mage_ImportExport_Model_Export::FILTER_TYPE_INPUT == $attrFilterType) {
- if (is_scalar($exportFilter[$attrCode]) && trim($exportFilter[$attrCode])) {
- $collection->addAttributeToFilter($attrCode, ['like' => "%{$exportFilter[$attrCode]}%"]);
- }
- } elseif (Mage_ImportExport_Model_Export::FILTER_TYPE_DATE == $attrFilterType) {
- if (is_array($exportFilter[$attrCode]) && count($exportFilter[$attrCode]) == 2) {
- $from = array_shift($exportFilter[$attrCode]);
- $to = array_shift($exportFilter[$attrCode]);
-
- if (is_scalar($from) && !empty($from)) {
- $date = Mage::app()->getLocale()->date($from, null, null, false)->toString('MM/dd/YYYY');
- $collection->addAttributeToFilter($attrCode, ['from' => $date, 'date' => true]);
- }
- if (is_scalar($to) && !empty($to)) {
- $date = Mage::app()->getLocale()->date($to, null, null, false)->toString('MM/dd/YYYY');
- $collection->addAttributeToFilter($attrCode, ['to' => $date, 'date' => true]);
- }
- }
- } elseif (Mage_ImportExport_Model_Export::FILTER_TYPE_NUMBER == $attrFilterType) {
- if (is_array($exportFilter[$attrCode]) && count($exportFilter[$attrCode]) == 2) {
- $from = array_shift($exportFilter[$attrCode]);
- $to = array_shift($exportFilter[$attrCode]);
-
- if (is_numeric($from)) {
- $collection->addAttributeToFilter($attrCode, ['from' => $from]);
- }
- if (is_numeric($to)) {
- $collection->addAttributeToFilter($attrCode, ['to' => $to]);
- }
- }
- }
- }
- if (in_array($attrCode, $exportAttrCodes)) {
- $collection->addAttributeToSelect($attrCode);
- }
- }
- return $collection;
- }
-
/**
* Add error with corresponding current data source row number.
*
@@ -538,4 +400,142 @@ public function setWriter(Mage_ImportExport_Model_Export_Adapter_Abstract $write
return $this;
}
+
+ /**
+ * Initialize website values.
+ *
+ * @return $this
+ */
+ protected function _initWebsites()
+ {
+ foreach (Mage::app()->getWebsites(true) as $website) {
+ $this->_websiteIdToCode[$website->getId()] = $website->getCode();
+ }
+ return $this;
+ }
+
+ /**
+ * Initialize stores hash.
+ *
+ * @return $this
+ */
+ protected function _initStores()
+ {
+ foreach (Mage::app()->getStores(true) as $store) {
+ $this->_storeIdToCode[$store->getId()] = $store->getCode();
+ $this->_storeIdToWebsiteId[$store->getId()] = $store->getWebsiteId();
+ }
+ ksort($this->_storeIdToCode); // to ensure that 'admin' store (ID is zero) goes first
+ sort($this->_storeIdToWebsiteId);
+
+ return $this;
+ }
+
+ /**
+ * Get attributes codes which are appropriate for export.
+ *
+ * @return array
+ */
+ protected function _getExportAttrCodes()
+ {
+ if (self::$attrCodes === null) {
+ if (!empty($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_SKIP])
+ && is_array($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_SKIP])
+ ) {
+ $skipAttr = array_flip($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_SKIP]);
+ } else {
+ $skipAttr = [];
+ }
+ $attrCodes = [];
+
+ foreach ($this->filterAttributeCollection($this->getAttributeCollection()) as $attribute) {
+ if (!isset($skipAttr[$attribute->getAttributeId()])
+ || in_array($attribute->getAttributeCode(), $this->_permanentAttributes)
+ ) {
+ $attrCodes[] = $attribute->getAttributeCode();
+ }
+ }
+ self::$attrCodes = $attrCodes;
+ }
+ return self::$attrCodes;
+ }
+
+ /**
+ * Initialize attribute option values.
+ *
+ * @return Mage_ImportExport_Model_Export_Entity_Abstract
+ */
+ protected function _initAttrValues()
+ {
+ foreach ($this->getAttributeCollection() as $attribute) {
+ $this->_attributeValues[$attribute->getAttributeCode()] = $this->getAttributeOptions($attribute);
+ }
+ return $this;
+ }
+
+ /**
+ * Apply filter to collection and add not skipped attributes to select.
+ *
+ * @return Mage_Eav_Model_Entity_Collection_Abstract
+ */
+ protected function _prepareEntityCollection(Mage_Eav_Model_Entity_Collection_Abstract $collection)
+ {
+ if (!isset($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP])
+ || !is_array($this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP])
+ ) {
+ $exportFilter = [];
+ } else {
+ $exportFilter = $this->_parameters[Mage_ImportExport_Model_Export::FILTER_ELEMENT_GROUP];
+ }
+ $exportAttrCodes = $this->_getExportAttrCodes();
+
+ foreach ($this->filterAttributeCollection($this->getAttributeCollection()) as $attribute) {
+ $attrCode = $attribute->getAttributeCode();
+
+ // filter applying
+ if (isset($exportFilter[$attrCode])) {
+ $attrFilterType = Mage_ImportExport_Model_Export::getAttributeFilterType($attribute);
+
+ if (Mage_ImportExport_Model_Export::FILTER_TYPE_SELECT == $attrFilterType) {
+ if (is_scalar($exportFilter[$attrCode]) && trim($exportFilter[$attrCode])) {
+ $collection->addAttributeToFilter($attrCode, ['eq' => $exportFilter[$attrCode]]);
+ }
+ } elseif (Mage_ImportExport_Model_Export::FILTER_TYPE_INPUT == $attrFilterType) {
+ if (is_scalar($exportFilter[$attrCode]) && trim($exportFilter[$attrCode])) {
+ $collection->addAttributeToFilter($attrCode, ['like' => "%{$exportFilter[$attrCode]}%"]);
+ }
+ } elseif (Mage_ImportExport_Model_Export::FILTER_TYPE_DATE == $attrFilterType) {
+ if (is_array($exportFilter[$attrCode]) && count($exportFilter[$attrCode]) == 2) {
+ $from = array_shift($exportFilter[$attrCode]);
+ $to = array_shift($exportFilter[$attrCode]);
+
+ if (is_scalar($from) && !empty($from)) {
+ $date = Mage::app()->getLocale()->date($from, null, null, false)->toString('MM/dd/YYYY');
+ $collection->addAttributeToFilter($attrCode, ['from' => $date, 'date' => true]);
+ }
+ if (is_scalar($to) && !empty($to)) {
+ $date = Mage::app()->getLocale()->date($to, null, null, false)->toString('MM/dd/YYYY');
+ $collection->addAttributeToFilter($attrCode, ['to' => $date, 'date' => true]);
+ }
+ }
+ } elseif (Mage_ImportExport_Model_Export::FILTER_TYPE_NUMBER == $attrFilterType) {
+ if (is_array($exportFilter[$attrCode]) && count($exportFilter[$attrCode]) == 2) {
+ $from = array_shift($exportFilter[$attrCode]);
+ $to = array_shift($exportFilter[$attrCode]);
+
+ if (is_numeric($from)) {
+ $collection->addAttributeToFilter($attrCode, ['from' => $from]);
+ }
+ if (is_numeric($to)) {
+ $collection->addAttributeToFilter($attrCode, ['to' => $to]);
+ }
+ }
+ }
+ }
+ if (in_array($attrCode, $exportAttrCodes)) {
+ $collection->addAttributeToSelect($attrCode);
+ }
+ }
+ return $collection;
+ }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Export/Entity/Customer.php b/app/code/core/Mage/ImportExport/Model/Export/Entity/Customer.php
index 1e646709ede..a6fd7a428f2 100644
--- a/app/code/core/Mage/ImportExport/Model/Export/Entity/Customer.php
+++ b/app/code/core/Mage/ImportExport/Model/Export/Entity/Customer.php
@@ -73,32 +73,6 @@ public function __construct()
->_initWebsites();
}
- /**
- * Initialize website values.
- *
- * @return $this
- */
- protected function _initWebsites()
- {
- foreach (Mage::app()->getWebsites(true) as $website) {
- $this->_websiteIdToCode[$website->getId()] = $website->getCode();
- }
- return $this;
- }
-
- /**
- * Apply filter to collection and add not skipped attributes to select.
- *
- * @return Mage_Eav_Model_Entity_Collection_Abstract
- */
- protected function _prepareEntityCollection(Mage_Eav_Model_Entity_Collection_Abstract $collection)
- {
- // forced addition default billing and shipping addresses attributes
- return parent::_prepareEntityCollection($collection)->addAttributeToSelect(
- Mage_ImportExport_Model_Import_Entity_Customer_Address::getDefaultAddressAttrMapping(),
- );
- }
-
/**
* Export process and return contents of temporary file
*
@@ -137,6 +111,72 @@ public function exportFile()
];
}
+ /**
+ * Clean up already loaded attribute collection.
+ *
+ * @return Mage_Eav_Model_Resource_Entity_Attribute_Collection
+ */
+ public function filterAttributeCollection(Mage_Eav_Model_Resource_Entity_Attribute_Collection $collection)
+ {
+ foreach (parent::filterAttributeCollection($collection) as $attribute) {
+ if (!empty($this->_attributeOverrides[$attribute->getAttributeCode()])) {
+ $data = $this->_attributeOverrides[$attribute->getAttributeCode()];
+
+ if (isset($data['options_method']) && method_exists($this, $data['options_method'])) {
+ $data['filter_options'] = $this->{$data['options_method']}();
+ }
+ $attribute->addData($data);
+ }
+ }
+ return $collection;
+ }
+
+ /**
+ * Entity attributes collection getter.
+ *
+ * @return Mage_Customer_Model_Resource_Attribute_Collection|Object
+ */
+ public function getAttributeCollection()
+ {
+ return Mage::getResourceModel('customer/attribute_collection');
+ }
+
+ /**
+ * EAV entity type code getter.
+ *
+ * @return string
+ */
+ public function getEntityTypeCode()
+ {
+ return 'customer';
+ }
+
+ /**
+ * Initialize website values.
+ *
+ * @return $this
+ */
+ protected function _initWebsites()
+ {
+ foreach (Mage::app()->getWebsites(true) as $website) {
+ $this->_websiteIdToCode[$website->getId()] = $website->getCode();
+ }
+ return $this;
+ }
+
+ /**
+ * Apply filter to collection and add not skipped attributes to select.
+ *
+ * @return Mage_Eav_Model_Entity_Collection_Abstract
+ */
+ protected function _prepareEntityCollection(Mage_Eav_Model_Entity_Collection_Abstract $collection)
+ {
+ // forced addition default billing and shipping addresses attributes
+ return parent::_prepareEntityCollection($collection)->addAttributeToSelect(
+ Mage_ImportExport_Model_Import_Entity_Customer_Address::getDefaultAddressAttrMapping(),
+ );
+ }
+
/**
* Prepare data for export and write its to temporary file through writer.
*/
@@ -304,46 +344,6 @@ protected function _getNextAddressRow(&$customerAddress)
return [null, null];
}
- /**
- * Clean up already loaded attribute collection.
- *
- * @return Mage_Eav_Model_Resource_Entity_Attribute_Collection
- */
- public function filterAttributeCollection(Mage_Eav_Model_Resource_Entity_Attribute_Collection $collection)
- {
- foreach (parent::filterAttributeCollection($collection) as $attribute) {
- if (!empty($this->_attributeOverrides[$attribute->getAttributeCode()])) {
- $data = $this->_attributeOverrides[$attribute->getAttributeCode()];
-
- if (isset($data['options_method']) && method_exists($this, $data['options_method'])) {
- $data['filter_options'] = $this->{$data['options_method']}();
- }
- $attribute->addData($data);
- }
- }
- return $collection;
- }
-
- /**
- * Entity attributes collection getter.
- *
- * @return Mage_Customer_Model_Resource_Attribute_Collection|Object
- */
- public function getAttributeCollection()
- {
- return Mage::getResourceModel('customer/attribute_collection');
- }
-
- /**
- * EAV entity type code getter.
- *
- * @return string
- */
- public function getEntityTypeCode()
- {
- return 'customer';
- }
-
/**
* Get Address Attributes
*
diff --git a/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php b/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php
index 9febe52ec5c..48a0bf6b71d 100644
--- a/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php
+++ b/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php
@@ -116,6 +116,90 @@ public function __construct()
->_initCategories();
}
+ /**
+ * Export process and return contents of temporary file.
+ *
+ * @deprecated after ver 1.9.2.4 use $this->exportFile() instead
+ *
+ * @return string
+ */
+ public function export()
+ {
+ $this->_prepareExport();
+
+ return $this->getWriter()->getContents();
+ }
+
+ /**
+ * Export process and return temporary file through array.
+ *
+ * This method will return following array:
+ *
+ * array(
+ * 'rows' => count of written rows,
+ * 'value' => path to created file
+ * )
+ *
+ * @return array
+ */
+ public function exportFile()
+ {
+ $this->_prepareExport();
+
+ $writer = $this->getWriter();
+
+ return [
+ 'rows' => $writer->getRowsCount(),
+ 'value' => $writer->getDestination(),
+ ];
+ }
+
+ /**
+ * Clean up already loaded attribute collection.
+ *
+ * @return Mage_Eav_Model_Resource_Entity_Attribute_Collection
+ */
+ public function filterAttributeCollection(Mage_Eav_Model_Resource_Entity_Attribute_Collection $collection)
+ {
+ $validTypes = array_keys($this->_productTypeModels);
+
+ foreach (parent::filterAttributeCollection($collection) as $attribute) {
+ $attrApplyTo = $attribute->getApplyTo();
+ $attrApplyTo = $attrApplyTo ? array_intersect($attrApplyTo, $validTypes) : $validTypes;
+
+ if ($attrApplyTo) {
+ foreach ($attrApplyTo as $productType) { // override attributes by its product type model
+ if ($this->_productTypeModels[$productType]->overrideAttribute($attribute)) {
+ break;
+ }
+ }
+ } else { // remove attributes of not-supported product types
+ $collection->removeItemByKey($attribute->getId());
+ }
+ }
+ return $collection;
+ }
+
+ /**
+ * Entity attributes collection getter.
+ *
+ * @return Mage_Catalog_Model_Resource_Product_Attribute_Collection
+ */
+ public function getAttributeCollection()
+ {
+ return Mage::getResourceModel('catalog/product_attribute_collection');
+ }
+
+ /**
+ * EAV entity type code getter.
+ *
+ * @return string
+ */
+ public function getEntityTypeCode()
+ {
+ return 'catalog_product';
+ }
+
/**
* Initialize attribute sets code-to-id pairs.
*
@@ -519,44 +603,6 @@ protected function _updateDataWithCategoryColumns(&$dataRow, &$rowCategories, $p
return true;
}
- /**
- * Export process and return contents of temporary file.
- *
- * @deprecated after ver 1.9.2.4 use $this->exportFile() instead
- *
- * @return string
- */
- public function export()
- {
- $this->_prepareExport();
-
- return $this->getWriter()->getContents();
- }
-
- /**
- * Export process and return temporary file through array.
- *
- * This method will return following array:
- *
- * array(
- * 'rows' => count of written rows,
- * 'value' => path to created file
- * )
- *
- * @return array
- */
- public function exportFile()
- {
- $this->_prepareExport();
-
- $writer = $this->getWriter();
-
- return [
- 'rows' => $writer->getRowsCount(),
- 'value' => $writer->getDestination(),
- ];
- }
-
/**
* Prepare data for export.
*
@@ -1049,52 +1095,6 @@ protected function _prepareExport()
return $writer->getContents();
}
- /**
- * Clean up already loaded attribute collection.
- *
- * @return Mage_Eav_Model_Resource_Entity_Attribute_Collection
- */
- public function filterAttributeCollection(Mage_Eav_Model_Resource_Entity_Attribute_Collection $collection)
- {
- $validTypes = array_keys($this->_productTypeModels);
-
- foreach (parent::filterAttributeCollection($collection) as $attribute) {
- $attrApplyTo = $attribute->getApplyTo();
- $attrApplyTo = $attrApplyTo ? array_intersect($attrApplyTo, $validTypes) : $validTypes;
-
- if ($attrApplyTo) {
- foreach ($attrApplyTo as $productType) { // override attributes by its product type model
- if ($this->_productTypeModels[$productType]->overrideAttribute($attribute)) {
- break;
- }
- }
- } else { // remove attributes of not-supported product types
- $collection->removeItemByKey($attribute->getId());
- }
- }
- return $collection;
- }
-
- /**
- * Entity attributes collection getter.
- *
- * @return Mage_Catalog_Model_Resource_Product_Attribute_Collection
- */
- public function getAttributeCollection()
- {
- return Mage::getResourceModel('catalog/product_attribute_collection');
- }
-
- /**
- * EAV entity type code getter.
- *
- * @return string
- */
- public function getEntityTypeCode()
- {
- return 'catalog_product';
- }
-
/**
* Initialize attribute option values and types.
*
diff --git a/app/code/core/Mage/ImportExport/Model/Import.php b/app/code/core/Mage/ImportExport/Model/Import.php
index 1bcfc28180d..cfbf82145e7 100644
--- a/app/code/core/Mage/ImportExport/Model/Import.php
+++ b/app/code/core/Mage/ImportExport/Model/Import.php
@@ -68,58 +68,6 @@ class Mage_ImportExport_Model_Import extends Mage_ImportExport_Model_Abstract
],
];
- /**
- * Create instance of entity adapter and returns it.
- *
- * @throws Mage_Core_Exception
- * @return Mage_ImportExport_Model_Import_Entity_Abstract
- */
- protected function _getEntityAdapter()
- {
- if (!$this->_entityAdapter) {
- $validTypes = Mage_ImportExport_Model_Config::getModels(self::CONFIG_KEY_ENTITIES);
-
- if (isset($validTypes[$this->getEntity()])) {
- try {
- /** @var Mage_ImportExport_Model_Import_Entity_Abstract $_entityAdapter */
- $_entityAdapter = Mage::getModel($validTypes[$this->getEntity()]['model']);
- $this->_entityAdapter = $_entityAdapter;
- } catch (Exception $e) {
- Mage::logException($e);
- Mage::throwException(
- Mage::helper('importexport')->__('Invalid entity model'),
- );
- }
- if (!($this->_entityAdapter instanceof Mage_ImportExport_Model_Import_Entity_Abstract)) {
- Mage::throwException(
- Mage::helper('importexport')->__('Entity adapter object must be an instance of Mage_ImportExport_Model_Import_Entity_Abstract'),
- );
- }
- } else {
- Mage::throwException(Mage::helper('importexport')->__('Invalid entity'));
- }
- // check for entity codes integrity
- if ($this->getEntity() != $this->_entityAdapter->getEntityTypeCode()) {
- Mage::throwException(
- Mage::helper('importexport')->__('Input entity code is not equal to entity adapter code'),
- );
- }
- $this->_entityAdapter->setParameters($this->getData());
- }
- return $this->_entityAdapter;
- }
-
- /**
- * Returns source adapter object.
- *
- * @param string $sourceFile Full path to source file
- * @return Mage_ImportExport_Model_Import_Adapter_Abstract
- */
- protected function _getSourceAdapter($sourceFile)
- {
- return Mage_ImportExport_Model_Import_Adapter::findAdapterFor($sourceFile);
- }
-
/**
* Return operation result messages
*
@@ -465,4 +413,56 @@ public function invalidateIndex()
return $this;
}
+
+ /**
+ * Create instance of entity adapter and returns it.
+ *
+ * @throws Mage_Core_Exception
+ * @return Mage_ImportExport_Model_Import_Entity_Abstract
+ */
+ protected function _getEntityAdapter()
+ {
+ if (!$this->_entityAdapter) {
+ $validTypes = Mage_ImportExport_Model_Config::getModels(self::CONFIG_KEY_ENTITIES);
+
+ if (isset($validTypes[$this->getEntity()])) {
+ try {
+ /** @var Mage_ImportExport_Model_Import_Entity_Abstract $_entityAdapter */
+ $_entityAdapter = Mage::getModel($validTypes[$this->getEntity()]['model']);
+ $this->_entityAdapter = $_entityAdapter;
+ } catch (Exception $e) {
+ Mage::logException($e);
+ Mage::throwException(
+ Mage::helper('importexport')->__('Invalid entity model'),
+ );
+ }
+ if (!($this->_entityAdapter instanceof Mage_ImportExport_Model_Import_Entity_Abstract)) {
+ Mage::throwException(
+ Mage::helper('importexport')->__('Entity adapter object must be an instance of Mage_ImportExport_Model_Import_Entity_Abstract'),
+ );
+ }
+ } else {
+ Mage::throwException(Mage::helper('importexport')->__('Invalid entity'));
+ }
+ // check for entity codes integrity
+ if ($this->getEntity() != $this->_entityAdapter->getEntityTypeCode()) {
+ Mage::throwException(
+ Mage::helper('importexport')->__('Input entity code is not equal to entity adapter code'),
+ );
+ }
+ $this->_entityAdapter->setParameters($this->getData());
+ }
+ return $this->_entityAdapter;
+ }
+
+ /**
+ * Returns source adapter object.
+ *
+ * @param string $sourceFile Full path to source file
+ * @return Mage_ImportExport_Model_Import_Adapter_Abstract
+ */
+ protected function _getSourceAdapter($sourceFile)
+ {
+ return Mage_ImportExport_Model_Import_Adapter::findAdapterFor($sourceFile);
+ }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Adapter/Abstract.php b/app/code/core/Mage/ImportExport/Model/Import/Adapter/Abstract.php
index c1836f2d07f..03c89b64dfa 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Adapter/Abstract.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Adapter/Abstract.php
@@ -94,16 +94,6 @@ final public function __construct($source)
*/
public function destruct() {}
- /**
- * Method called as last step of object instance creation. Can be overridden in child classes.
- *
- * @return Mage_ImportExport_Model_Import_Adapter_Abstract
- */
- protected function _init()
- {
- return $this;
- }
-
/**
* Return the current element.
*
@@ -182,4 +172,14 @@ public function getSource()
{
return $this->_source;
}
+
+ /**
+ * Method called as last step of object instance creation. Can be overridden in child classes.
+ *
+ * @return Mage_ImportExport_Model_Import_Adapter_Abstract
+ */
+ protected function _init()
+ {
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Adapter/Csv.php b/app/code/core/Mage/ImportExport/Model/Import/Adapter/Csv.php
index 38541cecc5c..2eeafeac0f7 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Adapter/Csv.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Adapter/Csv.php
@@ -60,18 +60,6 @@ public function destruct()
}
}
- /**
- * Method called as last step of object instance creation. Can be overridden in child classes.
- *
- * @return Mage_ImportExport_Model_Import_Adapter_Abstract
- */
- protected function _init()
- {
- $this->_fileHandler = fopen($this->_source, 'r');
- $this->rewind();
- return $this;
- }
-
/**
* Move forward to next element
*
@@ -129,4 +117,16 @@ public function seek($position)
throw new OutOfBoundsException(Mage::helper('importexport')->__('Invalid seek position'));
}
}
+
+ /**
+ * Method called as last step of object instance creation. Can be overridden in child classes.
+ *
+ * @return Mage_ImportExport_Model_Import_Adapter_Abstract
+ */
+ protected function _init()
+ {
+ $this->_fileHandler = fopen($this->_source, 'r');
+ $this->rewind();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Entity/Abstract.php b/app/code/core/Mage/ImportExport/Model/Import/Entity/Abstract.php
index 8098e525a24..cce46c462f1 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Abstract.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Abstract.php
@@ -193,118 +193,6 @@ public function __construct()
$this->_connection = $_connection;
}
- /**
- * Inner source object getter.
- *
- * @return Mage_ImportExport_Model_Import_Adapter_Abstract
- */
- protected function _getSource()
- {
- if (!$this->_source) {
- Mage::throwException(Mage::helper('importexport')->__('No source specified'));
- }
- return $this->_source;
- }
-
- /**
- * Import data rows.
- *
- * @abstract
- * @return bool
- */
- abstract protected function _importData();
-
- /**
- * Returns boolean TRUE if row scope is default (fundamental) scope.
- *
- * @return true
- */
- protected function _isRowScopeDefault(array $rowData)
- {
- return true;
- }
-
- /**
- * Change row data before saving in DB table.
- *
- * @return array
- */
- protected function _prepareRowForDb(array $rowData)
- {
- /**
- * Convert all empty strings to null values, as
- * a) we don't use empty string in DB
- * b) empty strings instead of numeric values will product errors in Sql Server
- */
- foreach ($rowData as $key => $val) {
- if ($val === '') {
- $rowData[$key] = null;
- }
- }
- return $rowData;
- }
-
- /**
- * Validate data rows and save bunches to DB.
- *
- * @return Mage_ImportExport_Model_Import_Entity_Abstract|void
- */
- protected function _saveValidatedBunches()
- {
- $source = $this->_getSource();
- $productDataSize = 0;
- $bunchRows = [];
- $startNewBunch = false;
- $nextRowBackup = [];
- /** @var Mage_ImportExport_Model_Resource_Helper_Mysql4 $helper */
- $helper = Mage::getResourceHelper('importexport');
- $maxDataSize = $helper->getMaxDataSize();
- $bunchSize = Mage::helper('importexport')->getBunchSize();
-
- /** @var Mage_Core_Helper_Data $coreHelper */
- $coreHelper = Mage::helper('core');
-
- $source->rewind();
- $this->_dataSourceModel->cleanBunches();
-
- while ($source->valid() || $bunchRows) {
- if ($startNewBunch || !$source->valid()) {
- $this->_dataSourceModel->saveBunch($this->getEntityTypeCode(), $this->getBehavior(), $bunchRows);
-
- $bunchRows = $nextRowBackup;
- $productDataSize = strlen(serialize($bunchRows));
- $startNewBunch = false;
- $nextRowBackup = [];
- }
- if ($source->valid()) {
- if ($this->_errorsCount >= $this->_errorsLimit) { // errors limit check
- return;
- }
- $rowData = $coreHelper->unEscapeCSVData($source->current());
-
- $this->_processedRowsCount++;
-
- if ($this->validateRow($rowData, $source->key())) { // add row to bunch for save
- $rowData = $this->_prepareRowForDb($rowData);
- $rowSize = strlen(Mage::helper('core')->jsonEncode($rowData));
-
- // phpcs:ignore Ecg.Performance.Loop.ArraySize
- $isBunchSizeExceeded = ($bunchSize > 0 && count($bunchRows) >= $bunchSize);
-
- if (($productDataSize + $rowSize) >= $maxDataSize || $isBunchSizeExceeded) {
- $startNewBunch = true;
- $nextRowBackup = [$source->key() => $rowData];
- } else {
- $bunchRows[$source->key()] = $rowData;
- $productDataSize += $rowSize;
- }
- }
- $source->next();
- }
- }
- return $this;
- }
-
/**
* Add error with corresponding current data source row number.
*
@@ -682,4 +570,116 @@ public function validateData()
}
return $this;
}
+
+ /**
+ * Inner source object getter.
+ *
+ * @return Mage_ImportExport_Model_Import_Adapter_Abstract
+ */
+ protected function _getSource()
+ {
+ if (!$this->_source) {
+ Mage::throwException(Mage::helper('importexport')->__('No source specified'));
+ }
+ return $this->_source;
+ }
+
+ /**
+ * Import data rows.
+ *
+ * @abstract
+ * @return bool
+ */
+ abstract protected function _importData();
+
+ /**
+ * Returns boolean TRUE if row scope is default (fundamental) scope.
+ *
+ * @return true
+ */
+ protected function _isRowScopeDefault(array $rowData)
+ {
+ return true;
+ }
+
+ /**
+ * Change row data before saving in DB table.
+ *
+ * @return array
+ */
+ protected function _prepareRowForDb(array $rowData)
+ {
+ /**
+ * Convert all empty strings to null values, as
+ * a) we don't use empty string in DB
+ * b) empty strings instead of numeric values will product errors in Sql Server
+ */
+ foreach ($rowData as $key => $val) {
+ if ($val === '') {
+ $rowData[$key] = null;
+ }
+ }
+ return $rowData;
+ }
+
+ /**
+ * Validate data rows and save bunches to DB.
+ *
+ * @return Mage_ImportExport_Model_Import_Entity_Abstract|void
+ */
+ protected function _saveValidatedBunches()
+ {
+ $source = $this->_getSource();
+ $productDataSize = 0;
+ $bunchRows = [];
+ $startNewBunch = false;
+ $nextRowBackup = [];
+ /** @var Mage_ImportExport_Model_Resource_Helper_Mysql4 $helper */
+ $helper = Mage::getResourceHelper('importexport');
+ $maxDataSize = $helper->getMaxDataSize();
+ $bunchSize = Mage::helper('importexport')->getBunchSize();
+
+ /** @var Mage_Core_Helper_Data $coreHelper */
+ $coreHelper = Mage::helper('core');
+
+ $source->rewind();
+ $this->_dataSourceModel->cleanBunches();
+
+ while ($source->valid() || $bunchRows) {
+ if ($startNewBunch || !$source->valid()) {
+ $this->_dataSourceModel->saveBunch($this->getEntityTypeCode(), $this->getBehavior(), $bunchRows);
+
+ $bunchRows = $nextRowBackup;
+ $productDataSize = strlen(serialize($bunchRows));
+ $startNewBunch = false;
+ $nextRowBackup = [];
+ }
+ if ($source->valid()) {
+ if ($this->_errorsCount >= $this->_errorsLimit) { // errors limit check
+ return;
+ }
+ $rowData = $coreHelper->unEscapeCSVData($source->current());
+
+ $this->_processedRowsCount++;
+
+ if ($this->validateRow($rowData, $source->key())) { // add row to bunch for save
+ $rowData = $this->_prepareRowForDb($rowData);
+ $rowSize = strlen(Mage::helper('core')->jsonEncode($rowData));
+
+ // phpcs:ignore Ecg.Performance.Loop.ArraySize
+ $isBunchSizeExceeded = ($bunchSize > 0 && count($bunchRows) >= $bunchSize);
+
+ if (($productDataSize + $rowSize) >= $maxDataSize || $isBunchSizeExceeded) {
+ $startNewBunch = true;
+ $nextRowBackup = [$source->key() => $rowData];
+ } else {
+ $bunchRows[$source->key()] = $rowData;
+ $productDataSize += $rowSize;
+ }
+ }
+ $source->next();
+ }
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer.php b/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer.php
index a5c96958c06..d7b0436f8da 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer.php
@@ -217,6 +217,157 @@ public function __construct()
$this->_addressEntity = Mage::getModel('importexport/import_entity_customer_address', $this);
}
+ /**
+ * Get customer ID. Method tries to find ID from old and new customers. If it fails - it returns NULL.
+ *
+ * @param string $email
+ * @param string $websiteCode
+ * @return string|null
+ */
+ public function getCustomerId($email, $websiteCode)
+ {
+ if (isset($this->_oldCustomers[$email][$websiteCode])) {
+ return $this->_oldCustomers[$email][$websiteCode];
+ } elseif (isset($this->_newCustomers[$email][$websiteCode])) {
+ return $this->_newCustomers[$email][$websiteCode];
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * EAV entity type code getter.
+ *
+ * @abstract
+ * @return string
+ */
+ public function getEntityTypeCode()
+ {
+ return 'customer';
+ }
+
+ /**
+ * Obtain scope of the row from row data.
+ *
+ * @return int
+ */
+ public function getRowScope(array $rowData)
+ {
+ $foundOptions = false;
+ foreach (array_keys($this->_multiSelectAttributes) as $attrCode) {
+ if ($rowData[$attrCode]) {
+ $foundOptions = true;
+ }
+ }
+
+ $scope = self::SCOPE_OPTIONS;
+ if (strlen(trim($rowData[self::COL_EMAIL]))) {
+ $scope = self::SCOPE_DEFAULT;
+ } elseif ($foundOptions) {
+ $scope = self::SCOPE_OPTIONS;
+ } elseif (strlen(trim($rowData[self::COL_POSTCODE]))) {
+ $scope = self::SCOPE_ADDRESS;
+ }
+ return $scope;
+ }
+
+ /**
+ * Is attribute contains particular data (not plain entity attribute).
+ *
+ * @param string $attrCode
+ * @return bool
+ */
+ public function isAttributeParticular($attrCode)
+ {
+ return parent::isAttributeParticular($attrCode) || $this->_addressEntity->isAttributeParticular($attrCode);
+ }
+
+ /**
+ * Validate data row.
+ *
+ * @param int $rowNum
+ * @return bool
+ */
+ public function validateRow(array $rowData, $rowNum)
+ {
+ static $email = null; // e-mail is remembered through all customer rows
+ static $website = null; // website is remembered through all customer rows
+
+ if (isset($this->_validatedRows[$rowNum])) { // check that row is already validated
+ return !isset($this->_invalidRows[$rowNum]);
+ }
+ $this->_validatedRows[$rowNum] = true;
+
+ $rowScope = $this->getRowScope($rowData);
+
+ if (self::SCOPE_DEFAULT == $rowScope) {
+ $this->_processedEntitiesCount++;
+ }
+
+ $email = $rowData[self::COL_EMAIL];
+ $emailToLower = strtolower($rowData[self::COL_EMAIL]);
+ $website = $rowData[self::COL_WEBSITE];
+
+ $oldCustomersToLower = array_change_key_case($this->_oldCustomers, CASE_LOWER);
+ $newCustomersToLower = array_change_key_case($this->_newCustomers, CASE_LOWER);
+
+ // BEHAVIOR_DELETE use specific validation logic
+ if (Mage_ImportExport_Model_Import::BEHAVIOR_DELETE == $this->getBehavior()) {
+ if (self::SCOPE_DEFAULT == $rowScope
+ && !isset($oldCustomersToLower[$emailToLower][$website])
+ ) {
+ $this->addRowError(self::ERROR_EMAIL_SITE_NOT_FOUND, $rowNum);
+ }
+ } elseif (self::SCOPE_DEFAULT == $rowScope) { // row is SCOPE_DEFAULT = new customer block begins
+ if (!Zend_Validate::is($email, 'EmailAddress')) {
+ $this->addRowError(self::ERROR_INVALID_EMAIL, $rowNum);
+ } elseif (!isset($this->_websiteCodeToId[$website])) {
+ $this->addRowError(self::ERROR_INVALID_WEBSITE, $rowNum);
+ } else {
+ if (isset($newCustomersToLower[$emailToLower][$website])) {
+ $this->addRowError(self::ERROR_DUPLICATE_EMAIL_SITE, $rowNum);
+ }
+ $this->_newCustomers[$email][$website] = false;
+
+ if (!empty($rowData[self::COL_STORE]) && !isset($this->_storeCodeToId[$rowData[self::COL_STORE]])) {
+ $this->addRowError(self::ERROR_INVALID_STORE, $rowNum);
+ }
+ // check password
+ if (isset($rowData['password']) && strlen($rowData['password'])
+ && Mage::helper('core/string')->strlen($rowData['password']) < self::MAX_PASSWD_LENGTH
+ ) {
+ $this->addRowError(self::ERROR_PASSWORD_LENGTH, $rowNum);
+ }
+ // check simple attributes
+ foreach ($this->_attributes as $attrCode => $attrParams) {
+ if (in_array($attrCode, $this->_ignoredAttributes)) {
+ continue;
+ }
+ if (isset($rowData[$attrCode]) && strlen($rowData[$attrCode])) {
+ $this->isAttributeValid($attrCode, $attrParams, $rowData, $rowNum);
+ } elseif ($attrParams['is_required'] && !isset($oldCustomersToLower[$emailToLower][$website])) {
+ $this->addRowError(self::ERROR_VALUE_IS_REQUIRED, $rowNum, $attrCode);
+ }
+ }
+ }
+ if (isset($this->_invalidRows[$rowNum])) {
+ $email = false; // mark row as invalid for next address rows
+ }
+ } elseif (self::SCOPE_OPTIONS != $rowScope) {
+ if ($email === null) { // first row is not SCOPE_DEFAULT
+ $this->addRowError(self::ERROR_EMAIL_IS_EMPTY, $rowNum);
+ } elseif ($email === false) { // SCOPE_DEFAULT row is invalid
+ $this->addRowError(self::ERROR_ROW_IS_ORPHAN, $rowNum);
+ }
+ }
+
+ if ($rowScope != self::SCOPE_OPTIONS) {
+ $this->_addressEntity->validateRow($rowData, $rowNum);
+ }
+
+ return !isset($this->_invalidRows[$rowNum]);
+ }
+
/**
* Delete customers.
*
@@ -509,155 +660,4 @@ protected function _saveCustomerEntity(array $entityRowsIn, array $entityRowsUp)
}
return $this;
}
-
- /**
- * Get customer ID. Method tries to find ID from old and new customers. If it fails - it returns NULL.
- *
- * @param string $email
- * @param string $websiteCode
- * @return string|null
- */
- public function getCustomerId($email, $websiteCode)
- {
- if (isset($this->_oldCustomers[$email][$websiteCode])) {
- return $this->_oldCustomers[$email][$websiteCode];
- } elseif (isset($this->_newCustomers[$email][$websiteCode])) {
- return $this->_newCustomers[$email][$websiteCode];
- } else {
- return null;
- }
- }
-
- /**
- * EAV entity type code getter.
- *
- * @abstract
- * @return string
- */
- public function getEntityTypeCode()
- {
- return 'customer';
- }
-
- /**
- * Obtain scope of the row from row data.
- *
- * @return int
- */
- public function getRowScope(array $rowData)
- {
- $foundOptions = false;
- foreach (array_keys($this->_multiSelectAttributes) as $attrCode) {
- if ($rowData[$attrCode]) {
- $foundOptions = true;
- }
- }
-
- $scope = self::SCOPE_OPTIONS;
- if (strlen(trim($rowData[self::COL_EMAIL]))) {
- $scope = self::SCOPE_DEFAULT;
- } elseif ($foundOptions) {
- $scope = self::SCOPE_OPTIONS;
- } elseif (strlen(trim($rowData[self::COL_POSTCODE]))) {
- $scope = self::SCOPE_ADDRESS;
- }
- return $scope;
- }
-
- /**
- * Is attribute contains particular data (not plain entity attribute).
- *
- * @param string $attrCode
- * @return bool
- */
- public function isAttributeParticular($attrCode)
- {
- return parent::isAttributeParticular($attrCode) || $this->_addressEntity->isAttributeParticular($attrCode);
- }
-
- /**
- * Validate data row.
- *
- * @param int $rowNum
- * @return bool
- */
- public function validateRow(array $rowData, $rowNum)
- {
- static $email = null; // e-mail is remembered through all customer rows
- static $website = null; // website is remembered through all customer rows
-
- if (isset($this->_validatedRows[$rowNum])) { // check that row is already validated
- return !isset($this->_invalidRows[$rowNum]);
- }
- $this->_validatedRows[$rowNum] = true;
-
- $rowScope = $this->getRowScope($rowData);
-
- if (self::SCOPE_DEFAULT == $rowScope) {
- $this->_processedEntitiesCount++;
- }
-
- $email = $rowData[self::COL_EMAIL];
- $emailToLower = strtolower($rowData[self::COL_EMAIL]);
- $website = $rowData[self::COL_WEBSITE];
-
- $oldCustomersToLower = array_change_key_case($this->_oldCustomers, CASE_LOWER);
- $newCustomersToLower = array_change_key_case($this->_newCustomers, CASE_LOWER);
-
- // BEHAVIOR_DELETE use specific validation logic
- if (Mage_ImportExport_Model_Import::BEHAVIOR_DELETE == $this->getBehavior()) {
- if (self::SCOPE_DEFAULT == $rowScope
- && !isset($oldCustomersToLower[$emailToLower][$website])
- ) {
- $this->addRowError(self::ERROR_EMAIL_SITE_NOT_FOUND, $rowNum);
- }
- } elseif (self::SCOPE_DEFAULT == $rowScope) { // row is SCOPE_DEFAULT = new customer block begins
- if (!Zend_Validate::is($email, 'EmailAddress')) {
- $this->addRowError(self::ERROR_INVALID_EMAIL, $rowNum);
- } elseif (!isset($this->_websiteCodeToId[$website])) {
- $this->addRowError(self::ERROR_INVALID_WEBSITE, $rowNum);
- } else {
- if (isset($newCustomersToLower[$emailToLower][$website])) {
- $this->addRowError(self::ERROR_DUPLICATE_EMAIL_SITE, $rowNum);
- }
- $this->_newCustomers[$email][$website] = false;
-
- if (!empty($rowData[self::COL_STORE]) && !isset($this->_storeCodeToId[$rowData[self::COL_STORE]])) {
- $this->addRowError(self::ERROR_INVALID_STORE, $rowNum);
- }
- // check password
- if (isset($rowData['password']) && strlen($rowData['password'])
- && Mage::helper('core/string')->strlen($rowData['password']) < self::MAX_PASSWD_LENGTH
- ) {
- $this->addRowError(self::ERROR_PASSWORD_LENGTH, $rowNum);
- }
- // check simple attributes
- foreach ($this->_attributes as $attrCode => $attrParams) {
- if (in_array($attrCode, $this->_ignoredAttributes)) {
- continue;
- }
- if (isset($rowData[$attrCode]) && strlen($rowData[$attrCode])) {
- $this->isAttributeValid($attrCode, $attrParams, $rowData, $rowNum);
- } elseif ($attrParams['is_required'] && !isset($oldCustomersToLower[$emailToLower][$website])) {
- $this->addRowError(self::ERROR_VALUE_IS_REQUIRED, $rowNum, $attrCode);
- }
- }
- }
- if (isset($this->_invalidRows[$rowNum])) {
- $email = false; // mark row as invalid for next address rows
- }
- } elseif (self::SCOPE_OPTIONS != $rowScope) {
- if ($email === null) { // first row is not SCOPE_DEFAULT
- $this->addRowError(self::ERROR_EMAIL_IS_EMPTY, $rowNum);
- } elseif ($email === false) { // SCOPE_DEFAULT row is invalid
- $this->addRowError(self::ERROR_ROW_IS_ORPHAN, $rowNum);
- }
- }
-
- if ($rowScope != self::SCOPE_OPTIONS) {
- $this->_addressEntity->validateRow($rowData, $rowNum);
- }
-
- return !isset($this->_invalidRows[$rowNum]);
- }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer/Address.php b/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer/Address.php
index 162583b3a5b..f85d5462d47 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer/Address.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer/Address.php
@@ -136,6 +136,92 @@ public function __construct(Mage_ImportExport_Model_Import_Entity_Customer $cust
}
}
+ /**
+ * Get column name which holds value for attribute with specified code.
+ *
+ * @static
+ * @param string $attrCode
+ * @return string
+ */
+ public static function getColNameForAttrCode($attrCode)
+ {
+ return self::COL_NAME_PREFIX . $attrCode;
+ }
+
+ /**
+ * Customer default addresses column name to customer attribute mapping array.
+ *
+ * @static
+ * @return array
+ */
+ public static function getDefaultAddressAttrMapping()
+ {
+ return self::$_defaultAddressAttrMapping;
+ }
+
+ /**
+ * EAV entity type code getter.
+ *
+ * @return string
+ */
+ public function getEntityTypeCode()
+ {
+ return 'customer_address';
+ }
+
+ /**
+ * Is attribute contains particular data (not plain entity attribute).
+ *
+ * @param string $attrCode
+ * @return bool
+ */
+ public function isAttributeParticular($attrCode)
+ {
+ return isset($this->_attributes[$attrCode]) || in_array($attrCode, $this->_particularAttributes);
+ }
+
+ /**
+ * Validate data row.
+ *
+ * @param int $rowNum
+ * @return bool
+ */
+ public function validateRow(array $rowData, $rowNum)
+ {
+ $rowIsValid = true;
+
+ if ($this->_isRowWithAddress($rowData)) {
+ foreach ($this->_attributes as $colName => $attrParams) {
+ if (isset($rowData[$colName]) && strlen($rowData[$colName])) {
+ $rowIsValid &= $this->_customer->isAttributeValid($colName, $attrParams, $rowData, $rowNum);
+ } elseif ($attrParams['is_required']) {
+ $this->_customer->addRowError(
+ Mage_ImportExport_Model_Import_Entity_Customer::ERROR_VALUE_IS_REQUIRED,
+ $rowNum,
+ $colName,
+ );
+ $rowIsValid = false;
+ }
+ }
+ // validate region for countries with known region list
+ if ($rowIsValid) {
+ $regionColName = self::getColNameForAttrCode('region');
+ $countryColName = self::getColNameForAttrCode('country_id');
+ $countryRegions = $this->_countryRegions[strtolower($rowData[$countryColName])] ?? [];
+
+ if (!empty($rowData[$regionColName])
+ && !empty($countryRegions)
+ && !isset($countryRegions[strtolower($rowData[$regionColName])])
+ ) {
+ $this->_customer->addRowError(self::ERROR_INVALID_REGION, $rowNum);
+
+ $rowIsValid = false;
+ }
+ }
+ }
+ return $rowIsValid;
+ }
+
/**
* Import data rows.
*
@@ -407,92 +493,6 @@ protected function _saveCustomerDefaults(array $defaults)
return $this;
}
- /**
- * Get column name which holds value for attribute with specified code.
- *
- * @static
- * @param string $attrCode
- * @return string
- */
- public static function getColNameForAttrCode($attrCode)
- {
- return self::COL_NAME_PREFIX . $attrCode;
- }
-
- /**
- * Customer default addresses column name to customer attribute mapping array.
- *
- * @static
- * @return array
- */
- public static function getDefaultAddressAttrMapping()
- {
- return self::$_defaultAddressAttrMapping;
- }
-
- /**
- * EAV entity type code getter.
- *
- * @return string
- */
- public function getEntityTypeCode()
- {
- return 'customer_address';
- }
-
- /**
- * Is attribute contains particular data (not plain entity attribute).
- *
- * @param string $attrCode
- * @return bool
- */
- public function isAttributeParticular($attrCode)
- {
- return isset($this->_attributes[$attrCode]) || in_array($attrCode, $this->_particularAttributes);
- }
-
- /**
- * Validate data row.
- *
- * @param int $rowNum
- * @return bool
- */
- public function validateRow(array $rowData, $rowNum)
- {
- $rowIsValid = true;
-
- if ($this->_isRowWithAddress($rowData)) {
- foreach ($this->_attributes as $colName => $attrParams) {
- if (isset($rowData[$colName]) && strlen($rowData[$colName])) {
- $rowIsValid &= $this->_customer->isAttributeValid($colName, $attrParams, $rowData, $rowNum);
- } elseif ($attrParams['is_required']) {
- $this->_customer->addRowError(
- Mage_ImportExport_Model_Import_Entity_Customer::ERROR_VALUE_IS_REQUIRED,
- $rowNum,
- $colName,
- );
- $rowIsValid = false;
- }
- }
- // validate region for countries with known region list
- if ($rowIsValid) {
- $regionColName = self::getColNameForAttrCode('region');
- $countryColName = self::getColNameForAttrCode('country_id');
- $countryRegions = $this->_countryRegions[strtolower($rowData[$countryColName])] ?? [];
-
- if (!empty($rowData[$regionColName])
- && !empty($countryRegions)
- && !isset($countryRegions[strtolower($rowData[$regionColName])])
- ) {
- $this->_customer->addRowError(self::ERROR_INVALID_REGION, $rowNum);
-
- $rowIsValid = false;
- }
- }
- }
- return $rowIsValid;
- }
-
/**
* Get current scope
*
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php
index 302a3a3d961..3d80870c877 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php
@@ -27,11 +27,6 @@ class Mage_ImportExport_Model_Import_Entity_Product extends Mage_ImportExport_Mo
*/
public const CONFIG_KEY_PRODUCT_TYPES = 'global/importexport/import_product_types';
- /**
- * Allowed column name format
- */
- private const COL_NAME_FORMAT = '/[\x00-\x1F\x7F]/';
-
/**
* Size of bunch - part of products to save in one step.
*/
@@ -231,6 +226,11 @@ class Mage_ImportExport_Model_Import_Entity_Product extends Mage_ImportExport_Mo
*/
public const ERROR_INVALID_PRODUCT_SKU = 'invalidSku';
+ /**
+ * Allowed column name format
+ */
+ private const COL_NAME_FORMAT = '/[\x00-\x1F\x7F]/';
+
/**
* Pairs of attribute set ID-to-name.
*
@@ -445,6 +445,212 @@ public function __construct()
->_initCustomerGroups();
}
+ /**
+ * Attribute set ID-to-name pairs getter.
+ *
+ * @return array
+ */
+ public function getAttrSetIdToName()
+ {
+ return $this->_attrSetIdToName;
+ }
+
+ /**
+ * DB connection getter.
+ *
+ * @return Varien_Db_Adapter_Pdo_Mysql
+ */
+ public function getConnection()
+ {
+ return $this->_connection;
+ }
+
+ /**
+ * EAV entity type code getter.
+ *
+ * @abstract
+ * @return string
+ */
+ public function getEntityTypeCode()
+ {
+ return 'catalog_product';
+ }
+
+ /**
+ * New products SKU data.
+ *
+ * @return array
+ */
+ public function getNewSku()
+ {
+ return $this->_newSku;
+ }
+
+ /**
+ * Get next bunch of validatetd rows.
+ *
+ * @return array|null
+ */
+ public function getNextBunch()
+ {
+ return $this->_dataSourceModel->getNextBunch();
+ }
+
+ /**
+ * Existing products SKU getter.
+ *
+ * @return array
+ */
+ public function getOldSku()
+ {
+ return $this->_oldSku;
+ }
+
+ /**
+ * Obtain scope of the row from row data.
+ *
+ * @return int
+ */
+ public function getRowScope(array $rowData)
+ {
+ if (isset($rowData[self::COL_SKU]) && strlen(trim($rowData[self::COL_SKU]))) {
+ return self::SCOPE_DEFAULT;
+ } elseif (empty($rowData[self::COL_STORE])) {
+ return self::SCOPE_NULL;
+ } else {
+ return self::SCOPE_STORE;
+ }
+ }
+
+ /**
+ * All website codes to ID getter.
+ *
+ * @return array
+ */
+ public function getWebsiteCodes()
+ {
+ return $this->_websiteCodeToId;
+ }
+
+ /**
+ * Validate data row.
+ *
+ * @param int $rowNum
+ * @return bool
+ */
+ public function validateRow(array $rowData, $rowNum)
+ {
+ static $sku = null; // SKU is remembered through all product rows
+
+ if (isset($this->_validatedRows[$rowNum])) { // check that row is already validated
+ return !isset($this->_invalidRows[$rowNum]);
+ }
+ $this->_validatedRows[$rowNum] = true;
+
+ if (isset($this->_newSku[$rowData[self::COL_SKU]])) {
+ $this->addRowError(self::ERROR_DUPLICATE_SKU, $rowNum);
+ return false;
+ }
+ $rowScope = $this->getRowScope($rowData);
+
+ // BEHAVIOR_DELETE use specific validation logic
+ if (Mage_ImportExport_Model_Import::BEHAVIOR_DELETE == $this->getBehavior()) {
+ if (self::SCOPE_DEFAULT == $rowScope && !isset($this->_oldSku[$rowData[self::COL_SKU]])) {
+ $this->addRowError(self::ERROR_SKU_NOT_FOUND_FOR_DELETE, $rowNum);
+ return false;
+ }
+ return true;
+ }
+
+ $this->_validate($rowData, $rowNum, $sku);
+
+ if (self::SCOPE_DEFAULT == $rowScope) { // SKU is specified, row is SCOPE_DEFAULT, new product block begins
+ $this->_processedEntitiesCount++;
+
+ $sku = $rowData[self::COL_SKU];
+
+ if (isset($this->_oldSku[$sku])) { // can we get all necessary data from existent DB product?
+ // check for supported type of existing product
+ if (isset($this->_productTypeModels[$this->_oldSku[$sku]['type_id']])) {
+ $this->_newSku[$sku] = [
+ 'entity_id' => $this->_oldSku[$sku]['entity_id'],
+ 'type_id' => $this->_oldSku[$sku]['type_id'],
+ 'attr_set_id' => $this->_oldSku[$sku]['attr_set_id'],
+ 'attr_set_code' => $this->_attrSetIdToName[$this->_oldSku[$sku]['attr_set_id']],
+ ];
+ } else {
+ $this->addRowError(self::ERROR_TYPE_UNSUPPORTED, $rowNum);
+ $sku = false; // child rows of legacy products with unsupported types are orphans
+ }
+ } else { // validate new product type and attribute set
+ if (!isset($rowData[self::COL_TYPE])
+ || !isset($this->_productTypeModels[$rowData[self::COL_TYPE]])
+ ) {
+ $this->addRowError(self::ERROR_INVALID_TYPE, $rowNum);
+ } elseif (!isset($rowData[self::COL_ATTR_SET])
+ || !isset($this->_attrSetNameToId[$rowData[self::COL_ATTR_SET]])
+ ) {
+ $this->addRowError(self::ERROR_INVALID_ATTR_SET, $rowNum);
+ } elseif (!isset($this->_newSku[$sku])) {
+ $this->_newSku[$sku] = [
+ 'entity_id' => null,
+ 'type_id' => $rowData[self::COL_TYPE],
+ 'attr_set_id' => $this->_attrSetNameToId[$rowData[self::COL_ATTR_SET]],
+ 'attr_set_code' => $rowData[self::COL_ATTR_SET],
+ ];
+ }
+ if (isset($this->_invalidRows[$rowNum])) {
+ // mark SCOPE_DEFAULT row as invalid for future child rows if product not in DB already
+ $sku = false;
+ }
+ }
+ } else {
+ if ($sku === null) {
+ $this->addRowError(self::ERROR_SKU_IS_EMPTY, $rowNum);
+ } elseif ($sku === false) {
+ $this->addRowError(self::ERROR_ROW_IS_ORPHAN, $rowNum);
+ } elseif (self::SCOPE_STORE == $rowScope && !isset($this->_storeCodeToId[$rowData[self::COL_STORE]])) {
+ $this->addRowError(self::ERROR_INVALID_STORE, $rowNum);
+ }
+ }
+ if (!isset($this->_invalidRows[$rowNum])) {
+ // set attribute set code into row data for followed attribute validation in type model
+ $rowData[self::COL_ATTR_SET] = $this->_newSku[$sku]['attr_set_code'];
+
+ $rowAttributesValid = $this->_productTypeModels[$this->_newSku[$sku]['type_id']]->isRowValid(
+ $rowData,
+ $rowNum,
+ !isset($this->_oldSku[$sku]),
+ );
+ if (!$rowAttributesValid && self::SCOPE_DEFAULT == $rowScope) {
+ $sku = false; // mark SCOPE_DEFAULT row as invalid for future child rows
+ }
+ }
+ return !isset($this->_invalidRows[$rowNum]);
+ }
+
+ /**
+ * Get array of affected products
+ *
+ * @return array
+ */
+ public function getAffectedEntityIds()
+ {
+ $productIds = [];
+ while ($bunch = $this->_dataSourceModel->getNextBunch()) {
+ foreach ($bunch as $rowNum => $rowData) {
+ if (!$this->isRowAllowedToImport($rowData, $rowNum)) {
+ continue;
+ }
+ if (!isset($this->_newSku[$rowData[self::COL_SKU]]['entity_id'])) {
+ continue;
+ }
+ $productIds[] = $this->_newSku[$rowData[self::COL_SKU]]['entity_id'];
+ }
+ }
+ return $productIds;
+ }
+
/**
* Delete products.
*
@@ -1990,190 +2196,6 @@ protected function _filterRowData(&$rowData)
}
}
- /**
- * Attribute set ID-to-name pairs getter.
- *
- * @return array
- */
- public function getAttrSetIdToName()
- {
- return $this->_attrSetIdToName;
- }
-
- /**
- * DB connection getter.
- *
- * @return Varien_Db_Adapter_Pdo_Mysql
- */
- public function getConnection()
- {
- return $this->_connection;
- }
-
- /**
- * EAV entity type code getter.
- *
- * @abstract
- * @return string
- */
- public function getEntityTypeCode()
- {
- return 'catalog_product';
- }
-
- /**
- * New products SKU data.
- *
- * @return array
- */
- public function getNewSku()
- {
- return $this->_newSku;
- }
-
- /**
- * Get next bunch of validatetd rows.
- *
- * @return array|null
- */
- public function getNextBunch()
- {
- return $this->_dataSourceModel->getNextBunch();
- }
-
- /**
- * Existing products SKU getter.
- *
- * @return array
- */
- public function getOldSku()
- {
- return $this->_oldSku;
- }
-
- /**
- * Obtain scope of the row from row data.
- *
- * @return int
- */
- public function getRowScope(array $rowData)
- {
- if (isset($rowData[self::COL_SKU]) && strlen(trim($rowData[self::COL_SKU]))) {
- return self::SCOPE_DEFAULT;
- } elseif (empty($rowData[self::COL_STORE])) {
- return self::SCOPE_NULL;
- } else {
- return self::SCOPE_STORE;
- }
- }
-
- /**
- * All website codes to ID getter.
- *
- * @return array
- */
- public function getWebsiteCodes()
- {
- return $this->_websiteCodeToId;
- }
-
- /**
- * Validate data row.
- *
- * @param int $rowNum
- * @return bool
- */
- public function validateRow(array $rowData, $rowNum)
- {
- static $sku = null; // SKU is remembered through all product rows
-
- if (isset($this->_validatedRows[$rowNum])) { // check that row is already validated
- return !isset($this->_invalidRows[$rowNum]);
- }
- $this->_validatedRows[$rowNum] = true;
-
- if (isset($this->_newSku[$rowData[self::COL_SKU]])) {
- $this->addRowError(self::ERROR_DUPLICATE_SKU, $rowNum);
- return false;
- }
- $rowScope = $this->getRowScope($rowData);
-
- // BEHAVIOR_DELETE use specific validation logic
- if (Mage_ImportExport_Model_Import::BEHAVIOR_DELETE == $this->getBehavior()) {
- if (self::SCOPE_DEFAULT == $rowScope && !isset($this->_oldSku[$rowData[self::COL_SKU]])) {
- $this->addRowError(self::ERROR_SKU_NOT_FOUND_FOR_DELETE, $rowNum);
- return false;
- }
- return true;
- }
-
- $this->_validate($rowData, $rowNum, $sku);
-
- if (self::SCOPE_DEFAULT == $rowScope) { // SKU is specified, row is SCOPE_DEFAULT, new product block begins
- $this->_processedEntitiesCount++;
-
- $sku = $rowData[self::COL_SKU];
-
- if (isset($this->_oldSku[$sku])) { // can we get all necessary data from existent DB product?
- // check for supported type of existing product
- if (isset($this->_productTypeModels[$this->_oldSku[$sku]['type_id']])) {
- $this->_newSku[$sku] = [
- 'entity_id' => $this->_oldSku[$sku]['entity_id'],
- 'type_id' => $this->_oldSku[$sku]['type_id'],
- 'attr_set_id' => $this->_oldSku[$sku]['attr_set_id'],
- 'attr_set_code' => $this->_attrSetIdToName[$this->_oldSku[$sku]['attr_set_id']],
- ];
- } else {
- $this->addRowError(self::ERROR_TYPE_UNSUPPORTED, $rowNum);
- $sku = false; // child rows of legacy products with unsupported types are orphans
- }
- } else { // validate new product type and attribute set
- if (!isset($rowData[self::COL_TYPE])
- || !isset($this->_productTypeModels[$rowData[self::COL_TYPE]])
- ) {
- $this->addRowError(self::ERROR_INVALID_TYPE, $rowNum);
- } elseif (!isset($rowData[self::COL_ATTR_SET])
- || !isset($this->_attrSetNameToId[$rowData[self::COL_ATTR_SET]])
- ) {
- $this->addRowError(self::ERROR_INVALID_ATTR_SET, $rowNum);
- } elseif (!isset($this->_newSku[$sku])) {
- $this->_newSku[$sku] = [
- 'entity_id' => null,
- 'type_id' => $rowData[self::COL_TYPE],
- 'attr_set_id' => $this->_attrSetNameToId[$rowData[self::COL_ATTR_SET]],
- 'attr_set_code' => $rowData[self::COL_ATTR_SET],
- ];
- }
- if (isset($this->_invalidRows[$rowNum])) {
- // mark SCOPE_DEFAULT row as invalid for future child rows if product not in DB already
- $sku = false;
- }
- }
- } else {
- if ($sku === null) {
- $this->addRowError(self::ERROR_SKU_IS_EMPTY, $rowNum);
- } elseif ($sku === false) {
- $this->addRowError(self::ERROR_ROW_IS_ORPHAN, $rowNum);
- } elseif (self::SCOPE_STORE == $rowScope && !isset($this->_storeCodeToId[$rowData[self::COL_STORE]])) {
- $this->addRowError(self::ERROR_INVALID_STORE, $rowNum);
- }
- }
- if (!isset($this->_invalidRows[$rowNum])) {
- // set attribute set code into row data for followed attribute validation in type model
- $rowData[self::COL_ATTR_SET] = $this->_newSku[$sku]['attr_set_code'];
-
- $rowAttributesValid = $this->_productTypeModels[$this->_newSku[$sku]['type_id']]->isRowValid(
- $rowData,
- $rowNum,
- !isset($this->_oldSku[$sku]),
- );
- if (!$rowAttributesValid && self::SCOPE_DEFAULT == $rowScope) {
- $sku = false; // mark SCOPE_DEFAULT row as invalid for future child rows
- }
- }
- return !isset($this->_invalidRows[$rowNum]);
- }
-
/**
* Common validation
*
@@ -2191,28 +2213,6 @@ protected function _validate($rowData, $rowNum, $sku)
$this->_isProductSkuValid($rowData, $rowNum);
}
- /**
- * Get array of affected products
- *
- * @return array
- */
- public function getAffectedEntityIds()
- {
- $productIds = [];
- while ($bunch = $this->_dataSourceModel->getNextBunch()) {
- foreach ($bunch as $rowNum => $rowData) {
- if (!$this->isRowAllowedToImport($rowData, $rowNum)) {
- continue;
- }
- if (!isset($this->_newSku[$rowData[self::COL_SKU]]['entity_id'])) {
- continue;
- }
- $productIds[] = $this->_newSku[$rowData[self::COL_SKU]]['entity_id'];
- }
- }
- return $productIds;
- }
-
/**
* Get product url_key attribute id
*
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Type/Abstract.php b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Type/Abstract.php
index 7f384c62260..0500cb0f43c 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Type/Abstract.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Type/Abstract.php
@@ -109,6 +109,101 @@ final public function __construct(array $params)
}
}
+ /**
+ * Particular attribute names getter.
+ *
+ * @return array
+ */
+ public function getParticularAttributes()
+ {
+ return $this->_particularAttributes;
+ }
+
+ /**
+ * Validate row attributes. Pass VALID row data ONLY as argument.
+ *
+ * @param int $rowNum
+ * @param bool $isNewProduct OPTIONAL.
+ * @return bool
+ */
+ public function isRowValid(array $rowData, $rowNum, $isNewProduct = true)
+ {
+ $error = false;
+ $rowScope = $this->_entityModel->getRowScope($rowData);
+
+ if (Mage_ImportExport_Model_Import_Entity_Product::SCOPE_NULL != $rowScope) {
+ foreach ($this->_getProductAttributes($rowData) as $attrCode => $attrParams) {
+ // check value for non-empty in the case of required attribute?
+ if (isset($rowData[$attrCode]) && strlen($rowData[$attrCode])) {
+ $error |= !$this->_entityModel->isAttributeValid($attrCode, $attrParams, $rowData, $rowNum);
+ } elseif ($this->_isAttributeRequiredCheckNeeded($attrCode)
+ && $attrParams['is_required']
+ ) {
+ // For the default scope - if this is a new product or
+ // for an old product, if the imported doc has the column present for the attrCode
+ if (Mage_ImportExport_Model_Import_Entity_Product::SCOPE_DEFAULT == $rowScope &&
+ ($isNewProduct || array_key_exists($attrCode, $rowData))
+ ) {
+ $this->_entityModel->addRowError(
+ Mage_ImportExport_Model_Import_Entity_Product::ERROR_VALUE_IS_REQUIRED,
+ $rowNum,
+ $attrCode,
+ );
+ $error = true;
+ }
+ }
+ }
+ }
+ $error |= !$this->_isParticularAttributesValid($rowData, $rowNum);
+
+ return !$error;
+ }
+
+ /**
+ * Additional check for model availability. If method returns FALSE - model is not suitable for data processing.
+ *
+ * @return bool
+ */
+ public function isSuitable()
+ {
+ return true;
+ }
+
+ /**
+ * Prepare attributes values for save: remove non-existent, remove empty values, remove static.
+ *
+ * @param bool $withDefaultValue
+ * @return array
+ */
+ public function prepareAttributesForSave(array $rowData, $withDefaultValue = true)
+ {
+ $resultAttrs = [];
+
+ foreach ($this->_getProductAttributes($rowData) as $attrCode => $attrParams) {
+ if (!$attrParams['is_static']) {
+ if (isset($rowData[$attrCode]) && strlen($rowData[$attrCode])) {
+ $resultAttrs[$attrCode] =
+ ($attrParams['type'] == 'select' || $attrParams['type'] == 'multiselect')
+ ? $attrParams['options'][strtolower($rowData[$attrCode])]
+ : $rowData[$attrCode];
+ } elseif ($withDefaultValue && $attrParams['default_value'] !== null) {
+ $resultAttrs[$attrCode] = $attrParams['default_value'];
+ }
+ }
+ }
+ return $resultAttrs;
+ }
+
+ /**
+ * Save product type specific data.
+ *
+ * @return Mage_ImportExport_Model_Import_Entity_Product_Type_Abstract
+ */
+ public function saveData()
+ {
+ return $this;
+ }
+
/**
* Add attribute parameters to appropriate attribute set.
*
@@ -217,99 +312,4 @@ protected function _isPriceCorr($value)
{
return preg_match('/^-?\d+\.?\d*%?$/', $value);
}
-
- /**
- * Particular attribute names getter.
- *
- * @return array
- */
- public function getParticularAttributes()
- {
- return $this->_particularAttributes;
- }
-
- /**
- * Validate row attributes. Pass VALID row data ONLY as argument.
- *
- * @param int $rowNum
- * @param bool $isNewProduct OPTIONAL.
- * @return bool
- */
- public function isRowValid(array $rowData, $rowNum, $isNewProduct = true)
- {
- $error = false;
- $rowScope = $this->_entityModel->getRowScope($rowData);
-
- if (Mage_ImportExport_Model_Import_Entity_Product::SCOPE_NULL != $rowScope) {
- foreach ($this->_getProductAttributes($rowData) as $attrCode => $attrParams) {
- // check value for non-empty in the case of required attribute?
- if (isset($rowData[$attrCode]) && strlen($rowData[$attrCode])) {
- $error |= !$this->_entityModel->isAttributeValid($attrCode, $attrParams, $rowData, $rowNum);
- } elseif ($this->_isAttributeRequiredCheckNeeded($attrCode)
- && $attrParams['is_required']
- ) {
- // For the default scope - if this is a new product or
- // for an old product, if the imported doc has the column present for the attrCode
- if (Mage_ImportExport_Model_Import_Entity_Product::SCOPE_DEFAULT == $rowScope &&
- ($isNewProduct || array_key_exists($attrCode, $rowData))
- ) {
- $this->_entityModel->addRowError(
- Mage_ImportExport_Model_Import_Entity_Product::ERROR_VALUE_IS_REQUIRED,
- $rowNum,
- $attrCode,
- );
- $error = true;
- }
- }
- }
- }
- $error |= !$this->_isParticularAttributesValid($rowData, $rowNum);
-
- return !$error;
- }
-
- /**
- * Additional check for model availability. If method returns FALSE - model is not suitable for data processing.
- *
- * @return bool
- */
- public function isSuitable()
- {
- return true;
- }
-
- /**
- * Prepare attributes values for save: remove non-existent, remove empty values, remove static.
- *
- * @param bool $withDefaultValue
- * @return array
- */
- public function prepareAttributesForSave(array $rowData, $withDefaultValue = true)
- {
- $resultAttrs = [];
-
- foreach ($this->_getProductAttributes($rowData) as $attrCode => $attrParams) {
- if (!$attrParams['is_static']) {
- if (isset($rowData[$attrCode]) && strlen($rowData[$attrCode])) {
- $resultAttrs[$attrCode] =
- ($attrParams['type'] == 'select' || $attrParams['type'] == 'multiselect')
- ? $attrParams['options'][strtolower($rowData[$attrCode])]
- : $rowData[$attrCode];
- } elseif ($withDefaultValue && $attrParams['default_value'] !== null) {
- $resultAttrs[$attrCode] = $attrParams['default_value'];
- }
- }
- }
- return $resultAttrs;
- }
-
- /**
- * Save product type specific data.
- *
- * @return Mage_ImportExport_Model_Import_Entity_Product_Type_Abstract
- */
- public function saveData()
- {
- return $this;
- }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Type/Configurable.php b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Type/Configurable.php
index 9df3e6f4e95..aa2b661d327 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Type/Configurable.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Type/Configurable.php
@@ -116,6 +116,157 @@ class Mage_ImportExport_Model_Import_Entity_Product_Type_Configurable extends Ma
*/
protected $_superAttrValuesCombs = null;
+ /**
+ * Save product type specific data.
+ *
+ * @throws Exception
+ * @return Mage_ImportExport_Model_Import_Entity_Product_Type_Abstract
+ */
+ public function saveData()
+ {
+ $connection = $this->_entityModel->getConnection();
+ $mainTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute');
+ $labelTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute_label');
+ $priceTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute_pricing');
+ $linkTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link');
+ $relationTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_relation');
+ $newSku = $this->_entityModel->getNewSku();
+ $oldSku = $this->_entityModel->getOldSku();
+ $productSuperData = [];
+ $productSuperAttrId = null;
+ $productId = null;
+ $productData = null;
+ /** @var Mage_ImportExport_Model_Resource_Helper_Mysql4 $helper */
+ $helper = Mage::getResourceHelper('importexport');
+ $nextAttrId = $helper->getNextAutoincrement($mainTable);
+
+ if ($this->_entityModel->getBehavior() == Mage_ImportExport_Model_Import::BEHAVIOR_APPEND) {
+ $this->_loadSkuSuperData();
+ }
+ $this->_loadSkuSuperAttributeValues();
+
+ while ($bunch = $this->_entityModel->getNextBunch()) {
+ $superAttributes = [
+ 'attributes' => [],
+ 'labels' => [],
+ 'pricing' => [],
+ 'super_link' => [],
+ 'relation' => [],
+ ];
+ foreach ($bunch as $rowNum => $rowData) {
+ if (!$this->_entityModel->isRowAllowedToImport($rowData, $rowNum)) {
+ continue;
+ }
+ // remember SCOPE_DEFAULT row data
+ $scope = $this->_entityModel->getRowScope($rowData);
+ if (Mage_ImportExport_Model_Import_Entity_Product::SCOPE_DEFAULT == $scope) {
+ $productData = $newSku[$rowData[Mage_ImportExport_Model_Import_Entity_Product::COL_SKU]];
+
+ if ($this->_type != $productData['type_id']) {
+ $productData = null;
+ continue;
+ }
+ $productId = $productData['entity_id'];
+
+ $this->_processSuperData($productSuperData, $superAttributes);
+
+ $productSuperData = [
+ 'product_id' => $productId,
+ 'attr_set_code' => $productData['attr_set_code'],
+ 'used_attributes' => empty($this->_skuSuperData[$productId])
+ ? [] : $this->_skuSuperData[$productId],
+ 'assoc_ids' => [],
+ ];
+ } elseif ($productData === null) {
+ continue;
+ }
+ if (!empty($rowData['_super_products_sku'])) {
+ if (isset($newSku[$rowData['_super_products_sku']])) {
+ $productSuperData['assoc_ids'][$newSku[$rowData['_super_products_sku']]['entity_id']] = true;
+ } elseif (isset($oldSku[$rowData['_super_products_sku']])) {
+ $productSuperData['assoc_ids'][$oldSku[$rowData['_super_products_sku']]['entity_id']] = true;
+ }
+ }
+ if (empty($rowData['_super_attribute_code'])) {
+ continue;
+ }
+ $attrParams = $this->_superAttributes[$rowData['_super_attribute_code']];
+
+ if ($this->_getSuperAttributeId($productId, $attrParams['id'])) {
+ $productSuperAttrId = $this->_getSuperAttributeId($productId, $attrParams['id']);
+ } elseif (!isset($superAttributes['attributes'][$productId][$attrParams['id']])) {
+ $productSuperAttrId = $nextAttrId++;
+ $superAttributes['attributes'][$productId][$attrParams['id']] = [
+ 'product_super_attribute_id' => $productSuperAttrId, 'position' => 0,
+ ];
+ $superAttributes['labels'][] = [
+ 'product_super_attribute_id' => $productSuperAttrId,
+ 'store_id' => 0,
+ 'use_default' => 1,
+ 'value' => $attrParams['frontend_label'],
+ ];
+ }
+ if (isset($rowData['_super_attribute_option']) && strlen($rowData['_super_attribute_option'])) {
+ $optionId = $attrParams['options'][strtolower($rowData['_super_attribute_option'])];
+
+ if (!isset($productSuperData['used_attributes'][$attrParams['id']][$optionId])) {
+ $productSuperData['used_attributes'][$attrParams['id']][$optionId] = false;
+ }
+ if (!empty($rowData['_super_attribute_price_corr'])) {
+ $superAttributes['pricing'][] = [
+ 'product_super_attribute_id' => $productSuperAttrId,
+ 'value_index' => $optionId,
+ 'is_percent' => substr($rowData['_super_attribute_price_corr'], -1) === '%',
+ 'pricing_value' => (float) rtrim($rowData['_super_attribute_price_corr'], '%'),
+ 'website_id' => 0,
+ ];
+ }
+ }
+ }
+ // save last product super data
+ $this->_processSuperData($productSuperData, $superAttributes);
+
+ // remove old data if needed
+ if ($this->_entityModel->getBehavior() != Mage_ImportExport_Model_Import::BEHAVIOR_APPEND
+ && $superAttributes['attributes']
+ ) {
+ $quoted = $connection->quoteInto('IN (?)', array_keys($superAttributes['attributes']));
+ $connection->delete($mainTable, "product_id {$quoted}");
+ $connection->delete($linkTable, "parent_id {$quoted}");
+ $connection->delete($relationTable, "parent_id {$quoted}");
+ }
+ $mainData = [];
+
+ foreach ($superAttributes['attributes'] as $productId => $attributesData) {
+ foreach ($attributesData as $attrId => $row) {
+ $row['product_id'] = $productId;
+ $row['attribute_id'] = $attrId;
+ $mainData[] = $row;
+ }
+ }
+ if ($mainData) {
+ $connection->insertOnDuplicate($mainTable, $mainData);
+ }
+ if ($superAttributes['labels']) {
+ $connection->insertOnDuplicate($labelTable, $superAttributes['labels']);
+ }
+ if ($superAttributes['pricing']) {
+ $connection->insertOnDuplicate(
+ $priceTable,
+ $superAttributes['pricing'],
+ ['is_percent', 'pricing_value'],
+ );
+ }
+ if ($superAttributes['super_link']) {
+ $connection->insertOnDuplicate($linkTable, $superAttributes['super_link']);
+ }
+ if ($superAttributes['relation']) {
+ $connection->insertOnDuplicate($relationTable, $superAttributes['relation']);
+ }
+ }
+ return $this;
+ }
+
/**
* Add attribute parameters to appropriate attribute set.
*
@@ -336,155 +487,4 @@ protected function _processSuperData(array $superData, array &$superAttributes)
}
return $this;
}
-
- /**
- * Save product type specific data.
- *
- * @throws Exception
- * @return Mage_ImportExport_Model_Import_Entity_Product_Type_Abstract
- */
- public function saveData()
- {
- $connection = $this->_entityModel->getConnection();
- $mainTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute');
- $labelTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute_label');
- $priceTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute_pricing');
- $linkTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link');
- $relationTable = Mage::getSingleton('core/resource')->getTableName('catalog/product_relation');
- $newSku = $this->_entityModel->getNewSku();
- $oldSku = $this->_entityModel->getOldSku();
- $productSuperData = [];
- $productSuperAttrId = null;
- $productId = null;
- $productData = null;
- /** @var Mage_ImportExport_Model_Resource_Helper_Mysql4 $helper */
- $helper = Mage::getResourceHelper('importexport');
- $nextAttrId = $helper->getNextAutoincrement($mainTable);
-
- if ($this->_entityModel->getBehavior() == Mage_ImportExport_Model_Import::BEHAVIOR_APPEND) {
- $this->_loadSkuSuperData();
- }
- $this->_loadSkuSuperAttributeValues();
-
- while ($bunch = $this->_entityModel->getNextBunch()) {
- $superAttributes = [
- 'attributes' => [],
- 'labels' => [],
- 'pricing' => [],
- 'super_link' => [],
- 'relation' => [],
- ];
- foreach ($bunch as $rowNum => $rowData) {
- if (!$this->_entityModel->isRowAllowedToImport($rowData, $rowNum)) {
- continue;
- }
- // remember SCOPE_DEFAULT row data
- $scope = $this->_entityModel->getRowScope($rowData);
- if (Mage_ImportExport_Model_Import_Entity_Product::SCOPE_DEFAULT == $scope) {
- $productData = $newSku[$rowData[Mage_ImportExport_Model_Import_Entity_Product::COL_SKU]];
-
- if ($this->_type != $productData['type_id']) {
- $productData = null;
- continue;
- }
- $productId = $productData['entity_id'];
-
- $this->_processSuperData($productSuperData, $superAttributes);
-
- $productSuperData = [
- 'product_id' => $productId,
- 'attr_set_code' => $productData['attr_set_code'],
- 'used_attributes' => empty($this->_skuSuperData[$productId])
- ? [] : $this->_skuSuperData[$productId],
- 'assoc_ids' => [],
- ];
- } elseif ($productData === null) {
- continue;
- }
- if (!empty($rowData['_super_products_sku'])) {
- if (isset($newSku[$rowData['_super_products_sku']])) {
- $productSuperData['assoc_ids'][$newSku[$rowData['_super_products_sku']]['entity_id']] = true;
- } elseif (isset($oldSku[$rowData['_super_products_sku']])) {
- $productSuperData['assoc_ids'][$oldSku[$rowData['_super_products_sku']]['entity_id']] = true;
- }
- }
- if (empty($rowData['_super_attribute_code'])) {
- continue;
- }
- $attrParams = $this->_superAttributes[$rowData['_super_attribute_code']];
-
- if ($this->_getSuperAttributeId($productId, $attrParams['id'])) {
- $productSuperAttrId = $this->_getSuperAttributeId($productId, $attrParams['id']);
- } elseif (!isset($superAttributes['attributes'][$productId][$attrParams['id']])) {
- $productSuperAttrId = $nextAttrId++;
- $superAttributes['attributes'][$productId][$attrParams['id']] = [
- 'product_super_attribute_id' => $productSuperAttrId, 'position' => 0,
- ];
- $superAttributes['labels'][] = [
- 'product_super_attribute_id' => $productSuperAttrId,
- 'store_id' => 0,
- 'use_default' => 1,
- 'value' => $attrParams['frontend_label'],
- ];
- }
- if (isset($rowData['_super_attribute_option']) && strlen($rowData['_super_attribute_option'])) {
- $optionId = $attrParams['options'][strtolower($rowData['_super_attribute_option'])];
-
- if (!isset($productSuperData['used_attributes'][$attrParams['id']][$optionId])) {
- $productSuperData['used_attributes'][$attrParams['id']][$optionId] = false;
- }
- if (!empty($rowData['_super_attribute_price_corr'])) {
- $superAttributes['pricing'][] = [
- 'product_super_attribute_id' => $productSuperAttrId,
- 'value_index' => $optionId,
- 'is_percent' => substr($rowData['_super_attribute_price_corr'], -1) === '%',
- 'pricing_value' => (float) rtrim($rowData['_super_attribute_price_corr'], '%'),
- 'website_id' => 0,
- ];
- }
- }
- }
- // save last product super data
- $this->_processSuperData($productSuperData, $superAttributes);
-
- // remove old data if needed
- if ($this->_entityModel->getBehavior() != Mage_ImportExport_Model_Import::BEHAVIOR_APPEND
- && $superAttributes['attributes']
- ) {
- $quoted = $connection->quoteInto('IN (?)', array_keys($superAttributes['attributes']));
- $connection->delete($mainTable, "product_id {$quoted}");
- $connection->delete($linkTable, "parent_id {$quoted}");
- $connection->delete($relationTable, "parent_id {$quoted}");
- }
- $mainData = [];
-
- foreach ($superAttributes['attributes'] as $productId => $attributesData) {
- foreach ($attributesData as $attrId => $row) {
- $row['product_id'] = $productId;
- $row['attribute_id'] = $attrId;
- $mainData[] = $row;
- }
- }
- if ($mainData) {
- $connection->insertOnDuplicate($mainTable, $mainData);
- }
- if ($superAttributes['labels']) {
- $connection->insertOnDuplicate($labelTable, $superAttributes['labels']);
- }
- if ($superAttributes['pricing']) {
- $connection->insertOnDuplicate(
- $priceTable,
- $superAttributes['pricing'],
- ['is_percent', 'pricing_value'],
- );
- }
- if ($superAttributes['super_link']) {
- $connection->insertOnDuplicate($linkTable, $superAttributes['super_link']);
- }
- if ($superAttributes['relation']) {
- $connection->insertOnDuplicate($relationTable, $superAttributes['relation']);
- }
- }
- return $this;
- }
}
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Proxy/Product.php b/app/code/core/Mage/ImportExport/Model/Import/Proxy/Product.php
index ec95df36908..b6f3632a9bb 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Proxy/Product.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Proxy/Product.php
@@ -22,11 +22,6 @@
*/
class Mage_ImportExport_Model_Import_Proxy_Product extends Mage_Catalog_Model_Product
{
- /**
- * DO NOT Initialize resources.
- */
- protected function _construct() {}
-
/**
* Retrieve object id
*
@@ -36,4 +31,8 @@ public function getId()
{
return $this->_getData('id');
}
+ /**
+ * DO NOT Initialize resources.
+ */
+ protected function _construct() {}
}
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Uploader.php b/app/code/core/Mage/ImportExport/Model/Import/Uploader.php
index ee2825f3727..4ef99673951 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Uploader.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Uploader.php
@@ -22,6 +22,7 @@
*/
class Mage_ImportExport_Model_Import_Uploader extends Mage_Core_Model_File_Uploader
{
+ public const DEFAULT_FILE_TYPE = 'application/octet-stream';
protected $_tmpDir = '';
protected $_destDir = '';
protected $_allowedMimeTypes = [
@@ -31,7 +32,6 @@ class Mage_ImportExport_Model_Import_Uploader extends Mage_Core_Model_File_Uploa
'gif' => 'image/gif',
'png' => 'image/png',
];
- public const DEFAULT_FILE_TYPE = 'application/octet-stream';
/**
* Mage_ImportExport_Model_Import_Uploader constructor.
@@ -82,6 +82,56 @@ public function move($fileName)
return $result;
}
+ /**
+ * Obtain TMP file path prefix
+ *
+ * @return string
+ */
+ public function getTmpDir()
+ {
+ return $this->_tmpDir;
+ }
+
+ /**
+ * Set TMP file path prefix
+ *
+ * @param string $path
+ * @return bool
+ */
+ public function setTmpDir($path)
+ {
+ if (is_string($path) && is_readable($path)) {
+ $this->_tmpDir = $path;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Obtain destination file path prefix
+ *
+ * @return string
+ */
+ public function getDestDir()
+ {
+ return $this->_destDir;
+ }
+
+ /**
+ * Set destination file path prefix
+ *
+ * @param string $path
+ * @return bool
+ */
+ public function setDestDir($path)
+ {
+ if (is_string($path) && is_writable($path)) {
+ $this->_destDir = $path;
+ return true;
+ }
+ return false;
+ }
+
/**
* Prepare information about the file for moving
*
@@ -154,56 +204,6 @@ protected function _getMimeTypeByExt($ext)
return '';
}
- /**
- * Obtain TMP file path prefix
- *
- * @return string
- */
- public function getTmpDir()
- {
- return $this->_tmpDir;
- }
-
- /**
- * Set TMP file path prefix
- *
- * @param string $path
- * @return bool
- */
- public function setTmpDir($path)
- {
- if (is_string($path) && is_readable($path)) {
- $this->_tmpDir = $path;
- return true;
- }
- return false;
- }
-
- /**
- * Obtain destination file path prefix
- *
- * @return string
- */
- public function getDestDir()
- {
- return $this->_destDir;
- }
-
- /**
- * Set destination file path prefix
- *
- * @param string $path
- * @return bool
- */
- public function setDestDir($path)
- {
- if (is_string($path) && is_writable($path)) {
- $this->_destDir = $path;
- return true;
- }
- return false;
- }
-
/**
* Move files from TMP folder into destination folder
*
diff --git a/app/code/core/Mage/ImportExport/Model/Resource/Import/Data.php b/app/code/core/Mage/ImportExport/Model/Resource/Import/Data.php
index 720a56d7f07..817bf9da08e 100644
--- a/app/code/core/Mage/ImportExport/Model/Resource/Import/Data.php
+++ b/app/code/core/Mage/ImportExport/Model/Resource/Import/Data.php
@@ -27,11 +27,6 @@ class Mage_ImportExport_Model_Resource_Import_Data extends Mage_Core_Model_Resou
*/
protected $_iterator = null;
- protected function _construct()
- {
- $this->_init('importexport/importdata', 'id');
- }
-
/**
* Retrieve an external iterator
*
@@ -142,4 +137,9 @@ public function saveBunch($entity, $behavior, array $data)
['behavior' => $behavior, 'entity' => $entity, 'data' => Mage::helper('core')->jsonEncode($data)],
);
}
+
+ protected function _construct()
+ {
+ $this->_init('importexport/importdata', 'id');
+ }
}
diff --git a/app/code/core/Mage/ImportExport/controllers/Adminhtml/ExportController.php b/app/code/core/Mage/ImportExport/controllers/Adminhtml/ExportController.php
index 40120153aef..096a955e524 100644
--- a/app/code/core/Mage/ImportExport/controllers/Adminhtml/ExportController.php
+++ b/app/code/core/Mage/ImportExport/controllers/Adminhtml/ExportController.php
@@ -28,29 +28,6 @@ class Mage_ImportExport_Adminhtml_ExportController extends Mage_Adminhtml_Contro
*/
public const ADMIN_RESOURCE = 'system/convert/export';
- /**
- * Custom constructor.
- */
- protected function _construct()
- {
- // Define module dependent translate
- $this->setUsedModuleName('Mage_ImportExport');
- }
-
- /**
- * Initialize layout.
- *
- * @return $this
- */
- protected function _initAction()
- {
- $this->_title($this->__('Import/Export'))
- ->loadLayout()
- ->_setActiveMenu('system/convert/export');
-
- return $this;
- }
-
/**
* Load data with filter applying and create file for download.
*
@@ -125,4 +102,27 @@ public function getFilterAction()
}
$this->_redirect('*/*/index');
}
+
+ /**
+ * Custom constructor.
+ */
+ protected function _construct()
+ {
+ // Define module dependent translate
+ $this->setUsedModuleName('Mage_ImportExport');
+ }
+
+ /**
+ * Initialize layout.
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->_title($this->__('Import/Export'))
+ ->loadLayout()
+ ->_setActiveMenu('system/convert/export');
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/ImportExport/controllers/Adminhtml/ImportController.php b/app/code/core/Mage/ImportExport/controllers/Adminhtml/ImportController.php
index 6562a0410bd..8f09a164695 100644
--- a/app/code/core/Mage/ImportExport/controllers/Adminhtml/ImportController.php
+++ b/app/code/core/Mage/ImportExport/controllers/Adminhtml/ImportController.php
@@ -28,29 +28,6 @@ class Mage_ImportExport_Adminhtml_ImportController extends Mage_Adminhtml_Contro
*/
public const ADMIN_RESOURCE = 'system/convert/import';
- /**
- * Custom constructor.
- */
- protected function _construct()
- {
- // Define module dependent translate
- $this->setUsedModuleName('Mage_ImportExport');
- }
-
- /**
- * Initialize layout.
- *
- * @return $this
- */
- protected function _initAction()
- {
- $this->_title($this->__('Import/Export'))
- ->loadLayout()
- ->_setActiveMenu('system/convert/import');
-
- return $this;
- }
-
/**
* Index action.
*/
@@ -183,4 +160,27 @@ public function validateAction()
$this->_redirect('*/*/index');
}
}
+
+ /**
+ * Custom constructor.
+ */
+ protected function _construct()
+ {
+ // Define module dependent translate
+ $this->setUsedModuleName('Mage_ImportExport');
+ }
+
+ /**
+ * Initialize layout.
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->_title($this->__('Import/Export'))
+ ->loadLayout()
+ ->_setActiveMenu('system/convert/import');
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Index/Block/Adminhtml/Process/Edit/Form.php b/app/code/core/Mage/Index/Block/Adminhtml/Process/Edit/Form.php
index fe6850a0a59..8cb2ae7aa6b 100644
--- a/app/code/core/Mage/Index/Block/Adminhtml/Process/Edit/Form.php
+++ b/app/code/core/Mage/Index/Block/Adminhtml/Process/Edit/Form.php
@@ -20,6 +20,13 @@
*/
class Mage_Index_Block_Adminhtml_Process_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
+ /**
+ * @return string
+ */
+ public function getActionUrl()
+ {
+ return $this->getUrl('adminhtml/process/save');
+ }
/**
* @return Mage_Adminhtml_Block_Widget_Form
*/
@@ -30,12 +37,4 @@ protected function _prepareForm()
$this->setForm($form);
return parent::_prepareForm();
}
-
- /**
- * @return string
- */
- public function getActionUrl()
- {
- return $this->getUrl('adminhtml/process/save');
- }
}
diff --git a/app/code/core/Mage/Index/Block/Adminhtml/Process/Edit/Tab/Main.php b/app/code/core/Mage/Index/Block/Adminhtml/Process/Edit/Tab/Main.php
index a1f16303c33..8fdb0fc74e5 100644
--- a/app/code/core/Mage/Index/Block/Adminhtml/Process/Edit/Tab/Main.php
+++ b/app/code/core/Mage/Index/Block/Adminhtml/Process/Edit/Tab/Main.php
@@ -20,46 +20,6 @@
*/
class Mage_Index_Block_Adminhtml_Process_Edit_Tab_Main extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
- /**
- * @inheritDoc
- */
- protected function _prepareForm()
- {
- $model = Mage::registry('current_index_process');
- $form = new Varien_Data_Form();
- $form->setHtmlIdPrefix('index_process_');
- $fieldset = $form->addFieldset(
- 'base_fieldset',
- ['legend' => Mage::helper('index')->__('General'), 'class' => 'fieldset-wide'],
- );
-
- $fieldset->addField('process_id', 'hidden', ['name' => 'process', 'value' => $model->getId()]);
-
- $fieldset->addField('name', 'note', [
- 'label' => Mage::helper('index')->__('Index Name'),
- 'title' => Mage::helper('index')->__('Index Name'),
- 'text' => '' . $model->getIndexer()->getName() . '',
- ]);
-
- $fieldset->addField('description', 'note', [
- 'label' => Mage::helper('index')->__('Index Description'),
- 'title' => Mage::helper('index')->__('Index Description'),
- 'text' => $model->getIndexer()->getDescription(),
- ]);
-
- $fieldset->addField('mode', 'select', [
- 'label' => Mage::helper('index')->__('Index Mode'),
- 'title' => Mage::helper('index')->__('Index Mode'),
- 'name' => 'mode',
- 'value' => $model->getMode(),
- 'values' => $model->getModesOptions(),
- ]);
-
- //$form->setValues($model->getData());
- $this->setForm($form);
- return parent::_prepareForm();
- }
-
/**
* Prepare label for tab
*
@@ -99,6 +59,45 @@ public function isHidden()
{
return false;
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareForm()
+ {
+ $model = Mage::registry('current_index_process');
+ $form = new Varien_Data_Form();
+ $form->setHtmlIdPrefix('index_process_');
+ $fieldset = $form->addFieldset(
+ 'base_fieldset',
+ ['legend' => Mage::helper('index')->__('General'), 'class' => 'fieldset-wide'],
+ );
+
+ $fieldset->addField('process_id', 'hidden', ['name' => 'process', 'value' => $model->getId()]);
+
+ $fieldset->addField('name', 'note', [
+ 'label' => Mage::helper('index')->__('Index Name'),
+ 'title' => Mage::helper('index')->__('Index Name'),
+ 'text' => '' . $model->getIndexer()->getName() . '',
+ ]);
+
+ $fieldset->addField('description', 'note', [
+ 'label' => Mage::helper('index')->__('Index Description'),
+ 'title' => Mage::helper('index')->__('Index Description'),
+ 'text' => $model->getIndexer()->getDescription(),
+ ]);
+
+ $fieldset->addField('mode', 'select', [
+ 'label' => Mage::helper('index')->__('Index Mode'),
+ 'title' => Mage::helper('index')->__('Index Mode'),
+ 'name' => 'mode',
+ 'value' => $model->getMode(),
+ 'values' => $model->getModesOptions(),
+ ]);
+
+ //$form->setValues($model->getData());
+ $this->setForm($form);
+ return parent::_prepareForm();
+ }
/**
* Check permission for passed action
diff --git a/app/code/core/Mage/Index/Block/Adminhtml/Process/Grid.php b/app/code/core/Mage/Index/Block/Adminhtml/Process/Grid.php
index 9daee9c0fbd..77079e5a796 100644
--- a/app/code/core/Mage/Index/Block/Adminhtml/Process/Grid.php
+++ b/app/code/core/Mage/Index/Block/Adminhtml/Process/Grid.php
@@ -48,6 +48,87 @@ public function __construct()
$this->_pagerVisibility = false;
}
+ /**
+ * Decorate status column values
+ *
+ * @param string $value
+ * @param Mage_Index_Model_Process $row
+ * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
+ * @param bool $isExport
+ *
+ * @return string
+ */
+ public function decorateStatus($value, $row, $column, $isExport)
+ {
+ $class = '';
+ switch ($row->getStatus()) {
+ case Mage_Index_Model_Process::STATUS_PENDING:
+ $class = 'grid-severity-notice';
+ break;
+ case Mage_Index_Model_Process::STATUS_RUNNING:
+ $class = 'grid-severity-major';
+ break;
+ case Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX:
+ $class = 'grid-severity-critical';
+ break;
+ }
+ return '' . $value . '';
+ }
+
+ /**
+ * Decorate "Update Required" column values
+ *
+ * @param string $value
+ * @param Mage_Index_Model_Process $row
+ * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
+ * @param bool $isExport
+ *
+ * @return string
+ */
+ public function decorateUpdateRequired($value, $row, $column, $isExport)
+ {
+ $class = '';
+ switch ($row->getUpdateRequired()) {
+ case 0:
+ $class = 'grid-severity-notice';
+ break;
+ case 1:
+ $class = 'grid-severity-critical';
+ break;
+ }
+ return '' . $value . '';
+ }
+
+ /**
+ * Decorate last run date coumn
+ *
+ * @param string $value
+ * @param Mage_Index_Model_Process $row
+ * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
+ * @param bool $isExport
+ *
+ * @return string
+ */
+ public function decorateDate($value, $row, $column, $isExport)
+ {
+ if (!$value) {
+ return $this->__('Never');
+ }
+ return $value;
+ }
+
+ /**
+ * Get row edit url
+ *
+ * @param Mage_Index_Model_Process $row
+ *
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['process' => $row->getId()]);
+ }
+
/**
* Prepare grid collection
*
@@ -168,87 +249,6 @@ protected function _prepareColumns()
return $this;
}
- /**
- * Decorate status column values
- *
- * @param string $value
- * @param Mage_Index_Model_Process $row
- * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
- * @param bool $isExport
- *
- * @return string
- */
- public function decorateStatus($value, $row, $column, $isExport)
- {
- $class = '';
- switch ($row->getStatus()) {
- case Mage_Index_Model_Process::STATUS_PENDING:
- $class = 'grid-severity-notice';
- break;
- case Mage_Index_Model_Process::STATUS_RUNNING:
- $class = 'grid-severity-major';
- break;
- case Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX:
- $class = 'grid-severity-critical';
- break;
- }
- return '' . $value . '';
- }
-
- /**
- * Decorate "Update Required" column values
- *
- * @param string $value
- * @param Mage_Index_Model_Process $row
- * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
- * @param bool $isExport
- *
- * @return string
- */
- public function decorateUpdateRequired($value, $row, $column, $isExport)
- {
- $class = '';
- switch ($row->getUpdateRequired()) {
- case 0:
- $class = 'grid-severity-notice';
- break;
- case 1:
- $class = 'grid-severity-critical';
- break;
- }
- return '' . $value . '';
- }
-
- /**
- * Decorate last run date coumn
- *
- * @param string $value
- * @param Mage_Index_Model_Process $row
- * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
- * @param bool $isExport
- *
- * @return string
- */
- public function decorateDate($value, $row, $column, $isExport)
- {
- if (!$value) {
- return $this->__('Never');
- }
- return $value;
- }
-
- /**
- * Get row edit url
- *
- * @param Mage_Index_Model_Process $row
- *
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['process' => $row->getId()]);
- }
-
/**
* Add mass-actions to grid
*
diff --git a/app/code/core/Mage/Index/Model/Event.php b/app/code/core/Mage/Index/Model/Event.php
index 7e6c3a597ee..d966650d6f1 100644
--- a/app/code/core/Mage/Index/Model/Event.php
+++ b/app/code/core/Mage/Index/Model/Event.php
@@ -61,14 +61,6 @@ class Mage_Index_Model_Event extends Mage_Core_Model_Abstract
*/
protected $_process = null;
- /**
- * Initialize resource
- */
- protected function _construct()
- {
- $this->_init('index/event');
- }
-
/**
* Specify process object
*
@@ -142,37 +134,6 @@ public function getProcessIds()
return $this->_processIds;
}
- /**
- * Merge new data
- *
- * @param array $previous
- * @param mixed $current
- * @return array
- */
- protected function _mergeNewDataRecursive($previous, $current)
- {
- if (!is_array($current)) {
- if (!is_null($current)) {
- $previous[] = $current;
- }
- return $previous;
- }
-
- foreach (array_keys($previous) as $key) {
- if (array_key_exists($key, $current) && !is_null($current[$key]) && is_array($previous[$key])) {
- if (!is_string($key) || is_array($current[$key])) {
- $current[$key] = $this->_mergeNewDataRecursive($previous[$key], $current[$key]);
- }
- } elseif (!array_key_exists($key, $current) || is_null($current[$key])) {
- $current[$key] = $previous[$key];
- } elseif (!is_array($previous[$key]) && !is_string($key)) {
- $current[] = $previous[$key];
- }
- }
-
- return $current;
- }
-
/**
* Merge previous event data to object.
* Used for events duplicated protection
@@ -317,6 +278,45 @@ public function getType()
return $this->_getData('type');
}
+ /**
+ * Initialize resource
+ */
+ protected function _construct()
+ {
+ $this->_init('index/event');
+ }
+
+ /**
+ * Merge new data
+ *
+ * @param array $previous
+ * @param mixed $current
+ * @return array
+ */
+ protected function _mergeNewDataRecursive($previous, $current)
+ {
+ if (!is_array($current)) {
+ if (!is_null($current)) {
+ $previous[] = $current;
+ }
+ return $previous;
+ }
+
+ foreach (array_keys($previous) as $key) {
+ if (array_key_exists($key, $current) && !is_null($current[$key]) && is_array($previous[$key])) {
+ if (!is_string($key) || is_array($current[$key])) {
+ $current[$key] = $this->_mergeNewDataRecursive($previous[$key], $current[$key]);
+ }
+ } elseif (!array_key_exists($key, $current) || is_null($current[$key])) {
+ $current[$key] = $previous[$key];
+ } elseif (!is_array($previous[$key]) && !is_string($key)) {
+ $current[] = $previous[$key];
+ }
+ }
+
+ return $current;
+ }
+
/**
* Serelaize old and new data arrays before saving
*
diff --git a/app/code/core/Mage/Index/Model/Indexer.php b/app/code/core/Mage/Index/Model/Indexer.php
index d2aec7c6948..58f6fab2cd6 100644
--- a/app/code/core/Mage/Index/Model/Indexer.php
+++ b/app/code/core/Mage/Index/Model/Indexer.php
@@ -323,6 +323,28 @@ public function processEntityAction(Varien_Object $entity, $entityType, $eventTy
return $this;
}
+ /**
+ * Allow DDL operations while indexing
+ *
+ * @return $this
+ */
+ public function allowTableChanges()
+ {
+ $this->_allowTableChanges = true;
+ return $this;
+ }
+
+ /**
+ * Disallow DDL operations while indexing
+ *
+ * @return $this
+ */
+ public function disallowTableChanges()
+ {
+ $this->_allowTableChanges = false;
+ return $this;
+ }
+
/**
* Run all processes method with parameters
* Run by depends priority
@@ -430,28 +452,6 @@ protected function _changeProcessKeyStatus($process, $enable = true)
return false;
}
- /**
- * Allow DDL operations while indexing
- *
- * @return $this
- */
- public function allowTableChanges()
- {
- $this->_allowTableChanges = true;
- return $this;
- }
-
- /**
- * Disallow DDL operations while indexing
- *
- * @return $this
- */
- public function disallowTableChanges()
- {
- $this->_allowTableChanges = false;
- return $this;
- }
-
/**
* Get event type name
*
diff --git a/app/code/core/Mage/Index/Model/Indexer/Abstract.php b/app/code/core/Mage/Index/Model/Indexer/Abstract.php
index 1824c840cf2..f7cdec59419 100644
--- a/app/code/core/Mage/Index/Model/Indexer/Abstract.php
+++ b/app/code/core/Mage/Index/Model/Indexer/Abstract.php
@@ -59,16 +59,6 @@ public function getDescription()
return '';
}
- /**
- * Register indexer required data inside event object
- */
- abstract protected function _registerEvent(Mage_Index_Model_Event $event);
-
- /**
- * Process event based on event state data
- */
- abstract protected function _processEvent(Mage_Index_Model_Event $event);
-
/**
* Register data required by process in event object
*
@@ -213,4 +203,14 @@ public function isVisible()
{
return $this->_isVisible;
}
+
+ /**
+ * Register indexer required data inside event object
+ */
+ abstract protected function _registerEvent(Mage_Index_Model_Event $event);
+
+ /**
+ * Process event based on event state data
+ */
+ abstract protected function _processEvent(Mage_Index_Model_Event $event);
}
diff --git a/app/code/core/Mage/Index/Model/Lock.php b/app/code/core/Mage/Index/Model/Lock.php
index 64b00178600..7b9aba87574 100644
--- a/app/code/core/Mage/Index/Model/Lock.php
+++ b/app/code/core/Mage/Index/Model/Lock.php
@@ -115,6 +115,38 @@ public function setLock($lockName, $file = false, $block = false)
}
}
+ /**
+ * Release named lock by name
+ *
+ * @param string $lockName
+ * @param bool $file
+ * @return bool
+ */
+ public function releaseLock($lockName, $file = false)
+ {
+ if ($file) {
+ return $this->_releaseLockFile($lockName);
+ } else {
+ return $this->_releaseLockDb($lockName);
+ }
+ }
+
+ /**
+ * Check whether the named lock exists
+ *
+ * @param string $lockName
+ * @param bool $file
+ * @return bool
+ */
+ public function isLockExists($lockName, $file = false)
+ {
+ if ($file) {
+ return $this->_isLockExistsFile($lockName);
+ } else {
+ return $this->_isLockExistsDb($lockName);
+ }
+ }
+
/**
* Set named file lock
*
@@ -162,22 +194,6 @@ protected function _setLockDb($lockName, $block = false)
return false;
}
- /**
- * Release named lock by name
- *
- * @param string $lockName
- * @param bool $file
- * @return bool
- */
- public function releaseLock($lockName, $file = false)
- {
- if ($file) {
- return $this->_releaseLockFile($lockName);
- } else {
- return $this->_releaseLockDb($lockName);
- }
- }
-
/**
* Release named file lock by name
*
@@ -208,22 +224,6 @@ protected function _releaseLockDb($lockName)
return false;
}
- /**
- * Check whether the named lock exists
- *
- * @param string $lockName
- * @param bool $file
- * @return bool
- */
- public function isLockExists($lockName, $file = false)
- {
- if ($file) {
- return $this->_isLockExistsFile($lockName);
- } else {
- return $this->_isLockExistsDb($lockName);
- }
- }
-
/**
* Check whether the named file lock exists
*
diff --git a/app/code/core/Mage/Index/Model/Lock/Storage/Db.php b/app/code/core/Mage/Index/Model/Lock/Storage/Db.php
index 493d184b8cd..f4e67a2a1e9 100644
--- a/app/code/core/Mage/Index/Model/Lock/Storage/Db.php
+++ b/app/code/core/Mage/Index/Model/Lock/Storage/Db.php
@@ -40,16 +40,6 @@ public function __construct()
$this->_helper = Mage::getResourceHelper('index');
}
- /**
- * @param string $name
- * @return string
- */
- protected function _prepareLockName($name)
- {
- $config = $this->_connection->getConfig();
- return $config['dbname'] . '.' . $name;
- }
-
/**
* Set named lock
*
@@ -85,4 +75,14 @@ public function isLockExists($lockName)
$lockName = $this->_prepareLockName($lockName);
return $this->_helper->isLocked($lockName);
}
+
+ /**
+ * @param string $name
+ * @return string
+ */
+ protected function _prepareLockName($name)
+ {
+ $config = $this->_connection->getConfig();
+ return $config['dbname'] . '.' . $name;
+ }
}
diff --git a/app/code/core/Mage/Index/Model/Process.php b/app/code/core/Mage/Index/Model/Process.php
index 0021f06b82e..a1d8b3487d0 100644
--- a/app/code/core/Mage/Index/Model/Process.php
+++ b/app/code/core/Mage/Index/Model/Process.php
@@ -83,40 +83,6 @@ class Mage_Index_Model_Process extends Mage_Core_Model_Abstract
*/
protected $_allowTableChanges = true;
- /**
- * Initialize resource
- */
- protected function _construct()
- {
- $this->_init('index/process');
- }
-
- /**
- * Set indexer class name as data namespace for event object
- *
- * @return $this
- */
- protected function _setEventNamespace(Mage_Index_Model_Event $event)
- {
- $namespace = get_class($this->getIndexer());
- $event->setDataNamespace($namespace);
- $event->setProcess($this);
- return $this;
- }
-
- /**
- * Remove indexer namespace from event
- *
- * @param Mage_Index_Model_Event $event
- * @return $this
- */
- protected function _resetEventNamespace($event)
- {
- $event->setDataNamespace(null);
- $event->setProcess(null);
- return $this;
- }
-
/**
* Register data required by process in event object
*
@@ -353,35 +319,6 @@ public function indexEvents($entity = null, $type = null)
return $this;
}
- /**
- * Process all events of the collection
- *
- * @param bool $skipUnmatched
- * @return $this
- */
- protected function _processEventsCollection(
- Mage_Index_Model_Resource_Event_Collection $eventsCollection,
- $skipUnmatched = true
- ) {
- // We can't reload the collection because of transaction
- while ($event = $eventsCollection->fetchItem()) {
- /** @var Mage_Index_Model_Event $event */
- try {
- $this->processEvent($event);
- if (!$skipUnmatched) {
- $eventProcessIds = $event->getProcessIds();
- if (!isset($eventProcessIds[$this->getId()])) {
- $event->addProcessId($this->getId());
- }
- }
- } catch (Exception $e) {
- $event->addProcessId($this->getId(), self::EVENT_STATUS_ERROR);
- }
- $event->save();
- }
- return $this;
- }
-
/**
* Update status process/event association
*
@@ -404,19 +341,6 @@ public function getProcessLockName()
return 'index_process_' . $this->getId();
}
- /**
- * Returns Lock object.
- *
- * @return Mage_Index_Model_Lock|null
- */
- protected function _getLockInstance()
- {
- if (is_null($this->_lockInstance)) {
- $this->_lockInstance = Mage_Index_Model_Lock::getInstance();
- }
- return $this->_lockInstance;
- }
-
/**
* Lock process without blocking.
* This method allow to protect multiple process running and fast lock validation.
@@ -621,4 +545,80 @@ public function getUnprocessedEventsCollection()
$eventsCollection->addProcessFilter($this, self::EVENT_STATUS_NEW);
return $eventsCollection;
}
+
+ /**
+ * Initialize resource
+ */
+ protected function _construct()
+ {
+ $this->_init('index/process');
+ }
+
+ /**
+ * Set indexer class name as data namespace for event object
+ *
+ * @return $this
+ */
+ protected function _setEventNamespace(Mage_Index_Model_Event $event)
+ {
+ $namespace = get_class($this->getIndexer());
+ $event->setDataNamespace($namespace);
+ $event->setProcess($this);
+ return $this;
+ }
+
+ /**
+ * Remove indexer namespace from event
+ *
+ * @param Mage_Index_Model_Event $event
+ * @return $this
+ */
+ protected function _resetEventNamespace($event)
+ {
+ $event->setDataNamespace(null);
+ $event->setProcess(null);
+ return $this;
+ }
+
+ /**
+ * Process all events of the collection
+ *
+ * @param bool $skipUnmatched
+ * @return $this
+ */
+ protected function _processEventsCollection(
+ Mage_Index_Model_Resource_Event_Collection $eventsCollection,
+ $skipUnmatched = true
+ ) {
+ // We can't reload the collection because of transaction
+ while ($event = $eventsCollection->fetchItem()) {
+ /** @var Mage_Index_Model_Event $event */
+ try {
+ $this->processEvent($event);
+ if (!$skipUnmatched) {
+ $eventProcessIds = $event->getProcessIds();
+ if (!isset($eventProcessIds[$this->getId()])) {
+ $event->addProcessId($this->getId());
+ }
+ }
+ } catch (Exception $e) {
+ $event->addProcessId($this->getId(), self::EVENT_STATUS_ERROR);
+ }
+ $event->save();
+ }
+ return $this;
+ }
+
+ /**
+ * Returns Lock object.
+ *
+ * @return Mage_Index_Model_Lock|null
+ */
+ protected function _getLockInstance()
+ {
+ if (is_null($this->_lockInstance)) {
+ $this->_lockInstance = Mage_Index_Model_Lock::getInstance();
+ }
+ return $this->_lockInstance;
+ }
}
diff --git a/app/code/core/Mage/Index/Model/Resource/Abstract.php b/app/code/core/Mage/Index/Model/Resource/Abstract.php
index b9a9cdfc762..8fd46d06cbf 100644
--- a/app/code/core/Mage/Index/Model/Resource/Abstract.php
+++ b/app/code/core/Mage/Index/Model/Resource/Abstract.php
@@ -58,16 +58,6 @@ public function reindexAll()
return $this;
}
- /**
- * Get DB adapter for index data processing
- *
- * @return Varien_Db_Adapter_Interface
- */
- protected function _getIndexAdapter()
- {
- return $this->_getWriteAdapter();
- }
-
/**
* Get index table name with additional suffix
*
@@ -263,4 +253,14 @@ public function enableTableKeys()
}
return $this;
}
+
+ /**
+ * Get DB adapter for index data processing
+ *
+ * @return Varien_Db_Adapter_Interface
+ */
+ protected function _getIndexAdapter()
+ {
+ return $this->_getWriteAdapter();
+ }
}
diff --git a/app/code/core/Mage/Index/Model/Resource/Event.php b/app/code/core/Mage/Index/Model/Resource/Event.php
index 25e3e846540..e79dfff25b1 100644
--- a/app/code/core/Mage/Index/Model/Resource/Event.php
+++ b/app/code/core/Mage/Index/Model/Resource/Event.php
@@ -22,6 +22,46 @@
*/
class Mage_Index_Model_Resource_Event extends Mage_Core_Model_Resource_Db_Abstract
{
+ /**
+ * Update status for events of process
+ *
+ * @param int|array|Mage_Index_Model_Process $process
+ * @param string $status
+ * @return $this
+ */
+ public function updateProcessEvents($process, $status = Mage_Index_Model_Process::EVENT_STATUS_DONE)
+ {
+ $whereCondition = '';
+ if ($process instanceof Mage_Index_Model_Process) {
+ $whereCondition = ['process_id = ?' => $process->getId()];
+ } elseif (is_array($process) && !empty($process)) {
+ $whereCondition = ['process_id IN (?)' => $process];
+ } elseif (!is_array($whereCondition)) {
+ $whereCondition = ['process_id = ?' => $process];
+ }
+ $this->_getWriteAdapter()->update(
+ $this->getTable('index/process_event'),
+ ['status' => $status],
+ $whereCondition,
+ );
+ return $this;
+ }
+
+ /**
+ * Retrieve unprocessed events list by specified process
+ *
+ * @param Mage_Index_Model_Process $process
+ * @return array
+ */
+ public function getUnprocessedEvents($process)
+ {
+ $select = $this->_getReadAdapter()->select()
+ ->from($this->getTable('index/process_event'))
+ ->where('process_id = ?', $process->getId())
+ ->where('status = ?', Mage_Index_Model_Process::EVENT_STATUS_NEW);
+
+ return $this->_getReadAdapter()->fetchAll($select);
+ }
protected function _construct()
{
$this->_init('index/event', 'event_id');
@@ -88,45 +128,4 @@ protected function _afterSave(Mage_Core_Model_Abstract $object)
}
return parent::_afterSave($object);
}
-
- /**
- * Update status for events of process
- *
- * @param int|array|Mage_Index_Model_Process $process
- * @param string $status
- * @return $this
- */
- public function updateProcessEvents($process, $status = Mage_Index_Model_Process::EVENT_STATUS_DONE)
- {
- $whereCondition = '';
- if ($process instanceof Mage_Index_Model_Process) {
- $whereCondition = ['process_id = ?' => $process->getId()];
- } elseif (is_array($process) && !empty($process)) {
- $whereCondition = ['process_id IN (?)' => $process];
- } elseif (!is_array($whereCondition)) {
- $whereCondition = ['process_id = ?' => $process];
- }
- $this->_getWriteAdapter()->update(
- $this->getTable('index/process_event'),
- ['status' => $status],
- $whereCondition,
- );
- return $this;
- }
-
- /**
- * Retrieve unprocessed events list by specified process
- *
- * @param Mage_Index_Model_Process $process
- * @return array
- */
- public function getUnprocessedEvents($process)
- {
- $select = $this->_getReadAdapter()->select()
- ->from($this->getTable('index/process_event'))
- ->where('process_id = ?', $process->getId())
- ->where('status = ?', Mage_Index_Model_Process::EVENT_STATUS_NEW);
-
- return $this->_getReadAdapter()->fetchAll($select);
- }
}
diff --git a/app/code/core/Mage/Index/Model/Resource/Event/Collection.php b/app/code/core/Mage/Index/Model/Resource/Event/Collection.php
index 4de7290bc44..618c5e63e96 100644
--- a/app/code/core/Mage/Index/Model/Resource/Event/Collection.php
+++ b/app/code/core/Mage/Index/Model/Resource/Event/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Index_Model_Resource_Event_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Initialize resource
- *
- */
- protected function _construct()
- {
- $this->_init('index/event');
- }
-
/**
* Add filter by entity
*
@@ -91,6 +82,28 @@ public function addProcessFilter($process, $status = null)
return $this;
}
+ /**
+ * Reset collection state
+ *
+ * @return $this
+ */
+ public function reset()
+ {
+ $this->_totalRecords = null;
+ $this->_data = null;
+ $this->_isCollectionLoaded = false;
+ $this->_items = [];
+ return $this;
+ }
+ /**
+ * Initialize resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('index/event');
+ }
+
/**
* Join index_process_event table to event table
*
@@ -108,18 +121,4 @@ protected function _joinProcessEventTable()
}
return $this;
}
-
- /**
- * Reset collection state
- *
- * @return $this
- */
- public function reset()
- {
- $this->_totalRecords = null;
- $this->_data = null;
- $this->_isCollectionLoaded = false;
- $this->_items = [];
- return $this;
- }
}
diff --git a/app/code/core/Mage/Index/Model/Resource/Process.php b/app/code/core/Mage/Index/Model/Resource/Process.php
index a58c96f4295..86590f37746 100644
--- a/app/code/core/Mage/Index/Model/Resource/Process.php
+++ b/app/code/core/Mage/Index/Model/Resource/Process.php
@@ -22,11 +22,6 @@
*/
class Mage_Index_Model_Resource_Process extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('index/process', 'process_id');
- }
-
/**
* Update process/event association row status
*
@@ -106,20 +101,6 @@ public function updateStatus($process, $status)
return $this;
}
- /**
- * Updates process data
- * @param int $processId
- * @param array $data
- * @return $this
- */
- protected function _updateProcessData($processId, $data)
- {
- $bind = ['process_id=?' => $processId];
- $this->_getWriteAdapter()->update($this->getMainTable(), $data, $bind);
-
- return $this;
- }
-
/**
* Update process start date
*
@@ -151,4 +132,22 @@ public function isInTransaction()
{
return $this->_getWriteAdapter()->getTransactionLevel() > 0;
}
+ protected function _construct()
+ {
+ $this->_init('index/process', 'process_id');
+ }
+
+ /**
+ * Updates process data
+ * @param int $processId
+ * @param array $data
+ * @return $this
+ */
+ protected function _updateProcessData($processId, $data)
+ {
+ $bind = ['process_id=?' => $processId];
+ $this->_getWriteAdapter()->update($this->getMainTable(), $data, $bind);
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Index/Model/Resource/Process/Collection.php b/app/code/core/Mage/Index/Model/Resource/Process/Collection.php
index 11440829fe6..a7c33f34b1c 100644
--- a/app/code/core/Mage/Index/Model/Resource/Process/Collection.php
+++ b/app/code/core/Mage/Index/Model/Resource/Process/Collection.php
@@ -32,15 +32,6 @@ class Mage_Index_Model_Resource_Process_Collection extends Mage_Core_Model_Resou
*/
protected $_eventPrefix = 'process_collection';
- /**
- * Initialize resource
- *
- */
- protected function _construct()
- {
- $this->_init('index/process');
- }
-
/**
* Add count of unprocessed events to process collection
*
@@ -65,4 +56,13 @@ public function addEventsStats()
);
return $this;
}
+
+ /**
+ * Initialize resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('index/process');
+ }
}
diff --git a/app/code/core/Mage/Index/controllers/Adminhtml/ProcessController.php b/app/code/core/Mage/Index/controllers/Adminhtml/ProcessController.php
index 9b0c439485b..b5829e9e06d 100644
--- a/app/code/core/Mage/Index/controllers/Adminhtml/ProcessController.php
+++ b/app/code/core/Mage/Index/controllers/Adminhtml/ProcessController.php
@@ -26,24 +26,6 @@ class Mage_Index_Adminhtml_ProcessController extends Mage_Adminhtml_Controller_A
*/
public const ADMIN_RESOURCE = 'system/index';
- /**
- * Initialize process object by request
- *
- * @return Mage_Index_Model_Process|false
- */
- protected function _initProcess()
- {
- $processId = $this->getRequest()->getParam('process');
- if ($processId) {
- /** @var Mage_Index_Model_Process $process */
- $process = Mage::getModel('index/process')->load($processId);
- if ($process->getId() && $process->getIndexer()->isVisible()) {
- return $process;
- }
- }
- return false;
- }
-
/**
* Display processes grid action
*/
@@ -227,4 +209,22 @@ public function massChangeModeAction()
$this->_redirect('*/*/list');
}
+
+ /**
+ * Initialize process object by request
+ *
+ * @return Mage_Index_Model_Process|false
+ */
+ protected function _initProcess()
+ {
+ $processId = $this->getRequest()->getParam('process');
+ if ($processId) {
+ /** @var Mage_Index_Model_Process $process */
+ $process = Mage::getModel('index/process')->load($processId);
+ if ($process->getId() && $process->getIndexer()->isVisible()) {
+ return $process;
+ }
+ }
+ return false;
+ }
}
diff --git a/app/code/core/Mage/Install/Model/Installer/Config.php b/app/code/core/Mage/Install/Model/Installer/Config.php
index 1a3a5bb9dcc..a0b35daee54 100644
--- a/app/code/core/Mage/Install/Model/Installer/Config.php
+++ b/app/code/core/Mage/Install/Model/Installer/Config.php
@@ -121,6 +121,32 @@ public function getFormData()
->setEnableCharts('1');
}
+ public function replaceTmpInstallDate($date = null)
+ {
+ $stamp = strtotime((string) $date);
+ $localXml = file_get_contents($this->_localConfigFile);
+ $localXml = str_replace(self::TMP_INSTALL_DATE_VALUE, date('r', $stamp ? $stamp : time()), $localXml);
+ file_put_contents($this->_localConfigFile, $localXml);
+
+ return $this;
+ }
+
+ /**
+ * @param string|null $key
+ * @return $this
+ */
+ public function replaceTmpEncryptKey($key = null)
+ {
+ if (!$key) {
+ $key = md5(Mage::helper('core')->getRandomString(10));
+ }
+ $localXml = file_get_contents($this->_localConfigFile);
+ $localXml = str_replace(self::TMP_ENCRYPT_KEY_VALUE, $key, $localXml);
+ file_put_contents($this->_localConfigFile, $localXml);
+
+ return $this;
+ }
+
/**
* @param array $data
* @return $this
@@ -166,30 +192,4 @@ protected function _checkUrl($url, $secure = false)
}
return $this;
}
-
- public function replaceTmpInstallDate($date = null)
- {
- $stamp = strtotime((string) $date);
- $localXml = file_get_contents($this->_localConfigFile);
- $localXml = str_replace(self::TMP_INSTALL_DATE_VALUE, date('r', $stamp ? $stamp : time()), $localXml);
- file_put_contents($this->_localConfigFile, $localXml);
-
- return $this;
- }
-
- /**
- * @param string|null $key
- * @return $this
- */
- public function replaceTmpEncryptKey($key = null)
- {
- if (!$key) {
- $key = md5(Mage::helper('core')->getRandomString(10));
- }
- $localXml = file_get_contents($this->_localConfigFile);
- $localXml = str_replace(self::TMP_ENCRYPT_KEY_VALUE, $key, $localXml);
- file_put_contents($this->_localConfigFile, $localXml);
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Install/Model/Installer/Console.php b/app/code/core/Mage/Install/Model/Installer/Console.php
index 8d8fa109907..8e4c84d74e7 100644
--- a/app/code/core/Mage/Install/Model/Installer/Console.php
+++ b/app/code/core/Mage/Install/Model/Installer/Console.php
@@ -49,45 +49,6 @@ class Mage_Install_Model_Installer_Console extends Mage_Install_Model_Installer_
*/
protected $_app;
- /**
- * Get available options list
- *
- * @return array
- */
- protected function _getOptions()
- {
- if (is_null($this->_options)) {
- $this->_options = [
- 'license_agreement_accepted' => ['required' => true, 'comment' => ''],
- 'locale' => ['required' => true, 'comment' => ''],
- 'timezone' => ['required' => true, 'comment' => ''],
- 'default_currency' => ['required' => true, 'comment' => ''],
- 'db_model' => ['comment' => ''],
- 'db_host' => ['required' => true, 'comment' => ''],
- 'db_name' => ['required' => true, 'comment' => ''],
- 'db_user' => ['required' => true, 'comment' => ''],
- 'db_pass' => ['comment' => ''],
- 'db_prefix' => ['comment' => ''],
- 'url' => ['required' => true, 'comment' => ''],
- 'skip_url_validation' => ['comment' => ''],
- 'use_rewrites' => ['required' => true, 'comment' => ''],
- 'use_secure' => ['required' => true, 'comment' => ''],
- 'secure_base_url' => ['required' => true, 'comment' => ''],
- 'use_secure_admin' => ['required' => true, 'comment' => ''],
- 'admin_lastname' => ['required' => true, 'comment' => ''],
- 'admin_firstname' => ['required' => true, 'comment' => ''],
- 'admin_email' => ['required' => true, 'comment' => ''],
- 'admin_username' => ['required' => true, 'comment' => ''],
- 'admin_password' => ['required' => true, 'comment' => ''],
- 'encryption_key' => ['comment' => ''],
- 'session_save' => ['comment' => ''],
- 'admin_frontname' => ['comment' => ''],
- 'enable_charts' => ['comment' => ''],
- ];
- }
- return $this->_options;
- }
-
/**
* Set and validate arguments
*
@@ -196,34 +157,6 @@ public function getErrors()
return $this->_getDataModel()->getErrors();
}
- /**
- * Check flag value
- *
- * Returns true for 'yes', 1, 'true'
- * Case insensitive
- *
- * @param string $value
- * @return bool
- */
- protected function _checkFlag($value)
- {
- return ($value == 1)
- || preg_match('/^(yes|y|true)$/i', $value);
- }
-
- /**
- * Get data model (used to store data between installation steps
- *
- * @return Mage_Install_Model_Installer_Data
- */
- protected function _getDataModel()
- {
- if (is_null($this->_dataModel)) {
- $this->_dataModel = Mage::getModel('install/installer_data');
- }
- return $this->_dataModel;
- }
-
/**
* Get encryption key from data model
*
@@ -255,57 +188,6 @@ public function init(Mage_Core_Model_App $app)
return true;
}
- /**
- * Prepare data and save it in data model
- *
- * @return $this
- */
- protected function _prepareData()
- {
- /**
- * Locale settings
- */
- $this->_getDataModel()->setLocaleData([
- 'locale' => $this->_args['locale'],
- 'timezone' => $this->_args['timezone'],
- 'currency' => $this->_args['default_currency'],
- ]);
-
- /**
- * Database and web config
- */
- $this->_getDataModel()->setConfigData([
- 'db_model' => $this->_args['db_model'],
- 'db_host' => $this->_args['db_host'],
- 'db_name' => $this->_args['db_name'],
- 'db_user' => $this->_args['db_user'],
- 'db_pass' => $this->_args['db_pass'],
- 'db_prefix' => $this->_args['db_prefix'],
- 'use_rewrites' => $this->_checkFlag($this->_args['use_rewrites']),
- 'use_secure' => $this->_checkFlag($this->_args['use_secure']),
- 'unsecure_base_url' => $this->_args['url'],
- 'secure_base_url' => $this->_args['secure_base_url'],
- 'use_secure_admin' => $this->_checkFlag($this->_args['use_secure_admin']),
- 'session_save' => $this->_checkSessionSave($this->_args['session_save']),
- 'admin_frontname' => $this->_checkAdminFrontname($this->_args['admin_frontname']),
- 'skip_url_validation' => $this->_checkFlag($this->_args['skip_url_validation']),
- 'enable_charts' => $this->_checkFlag($this->_args['enable_charts']),
- ]);
-
- /**
- * Primary admin user
- */
- $this->_getDataModel()->setAdminData([
- 'firstname' => $this->_args['admin_firstname'],
- 'lastname' => $this->_args['admin_lastname'],
- 'email' => $this->_args['admin_email'],
- 'username' => $this->_args['admin_username'],
- 'new_password' => $this->_args['admin_password'],
- ]);
-
- return $this;
- }
-
/**
* Install Magento
*
@@ -465,4 +347,122 @@ public function checkConsole($url = null)
header('Location: ' . $url);
return false;
}
+
+ /**
+ * Get available options list
+ *
+ * @return array
+ */
+ protected function _getOptions()
+ {
+ if (is_null($this->_options)) {
+ $this->_options = [
+ 'license_agreement_accepted' => ['required' => true, 'comment' => ''],
+ 'locale' => ['required' => true, 'comment' => ''],
+ 'timezone' => ['required' => true, 'comment' => ''],
+ 'default_currency' => ['required' => true, 'comment' => ''],
+ 'db_model' => ['comment' => ''],
+ 'db_host' => ['required' => true, 'comment' => ''],
+ 'db_name' => ['required' => true, 'comment' => ''],
+ 'db_user' => ['required' => true, 'comment' => ''],
+ 'db_pass' => ['comment' => ''],
+ 'db_prefix' => ['comment' => ''],
+ 'url' => ['required' => true, 'comment' => ''],
+ 'skip_url_validation' => ['comment' => ''],
+ 'use_rewrites' => ['required' => true, 'comment' => ''],
+ 'use_secure' => ['required' => true, 'comment' => ''],
+ 'secure_base_url' => ['required' => true, 'comment' => ''],
+ 'use_secure_admin' => ['required' => true, 'comment' => ''],
+ 'admin_lastname' => ['required' => true, 'comment' => ''],
+ 'admin_firstname' => ['required' => true, 'comment' => ''],
+ 'admin_email' => ['required' => true, 'comment' => ''],
+ 'admin_username' => ['required' => true, 'comment' => ''],
+ 'admin_password' => ['required' => true, 'comment' => ''],
+ 'encryption_key' => ['comment' => ''],
+ 'session_save' => ['comment' => ''],
+ 'admin_frontname' => ['comment' => ''],
+ 'enable_charts' => ['comment' => ''],
+ ];
+ }
+ return $this->_options;
+ }
+
+ /**
+ * Check flag value
+ *
+ * Returns true for 'yes', 1, 'true'
+ * Case insensitive
+ *
+ * @param string $value
+ * @return bool
+ */
+ protected function _checkFlag($value)
+ {
+ return ($value == 1)
+ || preg_match('/^(yes|y|true)$/i', $value);
+ }
+
+ /**
+ * Get data model (used to store data between installation steps
+ *
+ * @return Mage_Install_Model_Installer_Data
+ */
+ protected function _getDataModel()
+ {
+ if (is_null($this->_dataModel)) {
+ $this->_dataModel = Mage::getModel('install/installer_data');
+ }
+ return $this->_dataModel;
+ }
+
+ /**
+ * Prepare data and save it in data model
+ *
+ * @return $this
+ */
+ protected function _prepareData()
+ {
+ /**
+ * Locale settings
+ */
+ $this->_getDataModel()->setLocaleData([
+ 'locale' => $this->_args['locale'],
+ 'timezone' => $this->_args['timezone'],
+ 'currency' => $this->_args['default_currency'],
+ ]);
+
+ /**
+ * Database and web config
+ */
+ $this->_getDataModel()->setConfigData([
+ 'db_model' => $this->_args['db_model'],
+ 'db_host' => $this->_args['db_host'],
+ 'db_name' => $this->_args['db_name'],
+ 'db_user' => $this->_args['db_user'],
+ 'db_pass' => $this->_args['db_pass'],
+ 'db_prefix' => $this->_args['db_prefix'],
+ 'use_rewrites' => $this->_checkFlag($this->_args['use_rewrites']),
+ 'use_secure' => $this->_checkFlag($this->_args['use_secure']),
+ 'unsecure_base_url' => $this->_args['url'],
+ 'secure_base_url' => $this->_args['secure_base_url'],
+ 'use_secure_admin' => $this->_checkFlag($this->_args['use_secure_admin']),
+ 'session_save' => $this->_checkSessionSave($this->_args['session_save']),
+ 'admin_frontname' => $this->_checkAdminFrontname($this->_args['admin_frontname']),
+ 'skip_url_validation' => $this->_checkFlag($this->_args['skip_url_validation']),
+ 'enable_charts' => $this->_checkFlag($this->_args['enable_charts']),
+ ]);
+
+ /**
+ * Primary admin user
+ */
+ $this->_getDataModel()->setAdminData([
+ 'firstname' => $this->_args['admin_firstname'],
+ 'lastname' => $this->_args['admin_lastname'],
+ 'email' => $this->_args['admin_email'],
+ 'username' => $this->_args['admin_username'],
+ 'new_password' => $this->_args['admin_password'],
+ ]);
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Install/Model/Installer/Db.php b/app/code/core/Mage/Install/Model/Installer/Db.php
index 5fedd095eb0..11990c5b707 100644
--- a/app/code/core/Mage/Install/Model/Installer/Db.php
+++ b/app/code/core/Mage/Install/Model/Installer/Db.php
@@ -91,6 +91,18 @@ public function checkDbConnectionData($data)
return $data;
}
+ /**
+ * Check database connection
+ *
+ * @param array $data
+ *
+ * @deprecated since 1.5.0.0
+ */
+ public function checkDatabase($data)
+ {
+ $this->checkDbConnectionData($data);
+ }
+
/**
* Check database connection data
*
@@ -167,16 +179,4 @@ protected function _getConnenctionType()
{
return (string) Mage::getConfig()->getNode('global/resources/default_setup/connection/type');
}
-
- /**
- * Check database connection
- *
- * @param array $data
- *
- * @deprecated since 1.5.0.0
- */
- public function checkDatabase($data)
- {
- $this->checkDbConnectionData($data);
- }
}
diff --git a/app/code/core/Mage/Install/Model/Installer/Db/Abstract.php b/app/code/core/Mage/Install/Model/Installer/Db/Abstract.php
index 0a4e2fe0160..808478f3c63 100644
--- a/app/code/core/Mage/Install/Model/Installer/Db/Abstract.php
+++ b/app/code/core/Mage/Install/Model/Installer/Db/Abstract.php
@@ -103,21 +103,6 @@ public function supportEngine()
return true;
}
- /**
- * Create new connection with custom config
- *
- * @return Varien_Db_Adapter_Interface
- */
- protected function _getConnection()
- {
- if (!isset($this->_connection)) {
- $resource = Mage::getSingleton('core/resource');
- $connection = $resource->createConnection('install', $this->getType(), $this->getConnectionData());
- $this->_connection = $connection;
- }
- return $this->_connection;
- }
-
/**
* Return pdo type
*
@@ -142,4 +127,19 @@ public function getRequiredExtensions()
}
return $extensions;
}
+
+ /**
+ * Create new connection with custom config
+ *
+ * @return Varien_Db_Adapter_Interface
+ */
+ protected function _getConnection()
+ {
+ if (!isset($this->_connection)) {
+ $resource = Mage::getSingleton('core/resource');
+ $connection = $resource->createConnection('install', $this->getType(), $this->getConnectionData());
+ $this->_connection = $connection;
+ }
+ return $this->_connection;
+ }
}
diff --git a/app/code/core/Mage/Install/controllers/WizardController.php b/app/code/core/Mage/Install/controllers/WizardController.php
index b80edff6327..045dafbbd5c 100644
--- a/app/code/core/Mage/Install/controllers/WizardController.php
+++ b/app/code/core/Mage/Install/controllers/WizardController.php
@@ -33,59 +33,6 @@ public function preDispatch()
parent::preDispatch();
}
- /**
- * Retrieve installer object
- *
- * @return Mage_Install_Model_Installer
- */
- protected function _getInstaller()
- {
- return Mage::getSingleton('install/installer');
- }
-
- /**
- * Retrieve wizard
- *
- * @return Mage_Install_Model_Wizard
- */
- protected function _getWizard()
- {
- return Mage::getSingleton('install/wizard');
- }
-
- /**
- * Prepare layout
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- $this->loadLayout('install_wizard');
- $step = $this->_getWizard()->getStepByRequest($this->getRequest());
- if ($step) {
- $step->setActive(true);
- }
-
- $leftBlock = $this->getLayout()->createBlock('install/state', 'install.state');
- $this->getLayout()->getBlock('left')->append($leftBlock);
- return $this;
- }
-
- /**
- * Checking installation status
- *
- * @return bool
- * @SuppressWarnings("PHPMD.ExitExpression")
- */
- protected function _checkIfInstalled()
- {
- if ($this->_getInstaller()->isApplicationInstalled()) {
- $this->getResponse()->setRedirect(Mage::getBaseUrl())->sendResponse();
- exit;
- }
- return true;
- }
-
/**
* Index action
*/
@@ -366,4 +313,57 @@ public function checkSecureHostAction()
$this->getResponse()->setHeader('Transfer-encoding', '', true);
$this->getResponse()->setBody(Mage_Install_Model_Installer::INSTALLER_HOST_RESPONSE);
}
+
+ /**
+ * Retrieve installer object
+ *
+ * @return Mage_Install_Model_Installer
+ */
+ protected function _getInstaller()
+ {
+ return Mage::getSingleton('install/installer');
+ }
+
+ /**
+ * Retrieve wizard
+ *
+ * @return Mage_Install_Model_Wizard
+ */
+ protected function _getWizard()
+ {
+ return Mage::getSingleton('install/wizard');
+ }
+
+ /**
+ * Prepare layout
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $this->loadLayout('install_wizard');
+ $step = $this->_getWizard()->getStepByRequest($this->getRequest());
+ if ($step) {
+ $step->setActive(true);
+ }
+
+ $leftBlock = $this->getLayout()->createBlock('install/state', 'install.state');
+ $this->getLayout()->getBlock('left')->append($leftBlock);
+ return $this;
+ }
+
+ /**
+ * Checking installation status
+ *
+ * @return bool
+ * @SuppressWarnings("PHPMD.ExitExpression")
+ */
+ protected function _checkIfInstalled()
+ {
+ if ($this->_getInstaller()->isApplicationInstalled()) {
+ $this->getResponse()->setRedirect(Mage::getBaseUrl())->sendResponse();
+ exit;
+ }
+ return true;
+ }
}
diff --git a/app/code/core/Mage/Log/Model/Aggregation.php b/app/code/core/Mage/Log/Model/Aggregation.php
index 5a70b23d44c..dab0a7b1949 100644
--- a/app/code/core/Mage/Log/Model/Aggregation.php
+++ b/app/code/core/Mage/Log/Model/Aggregation.php
@@ -32,14 +32,6 @@ class Mage_Log_Model_Aggregation extends Mage_Core_Model_Abstract
*/
protected $_lastRecord;
- /**
- * Init model
- */
- protected function _construct()
- {
- $this->_init('log/aggregation');
- }
-
/**
* Run action
*/
@@ -51,6 +43,27 @@ public function run()
}
}
+ /**
+ * @return false|string
+ */
+ public function getLastRecordDate()
+ {
+ $result = $this->_getResource()->getLastRecordDate();
+ if (!$result) {
+ $result = $this->_date(strtotime('now - 2 months'));
+ }
+
+ return $result;
+ }
+
+ /**
+ * Init model
+ */
+ protected function _construct()
+ {
+ $this->_init('log/aggregation');
+ }
+
/**
* Process
*
@@ -128,19 +141,6 @@ private function _getCounts($from, $to, $store)
return $this->_getResource()->getCounts($from, $to, $store);
}
- /**
- * @return false|string
- */
- public function getLastRecordDate()
- {
- $result = $this->_getResource()->getLastRecordDate();
- if (!$result) {
- $result = $this->_date(strtotime('now - 2 months'));
- }
-
- return $result;
- }
-
/**
* @param string|int $in
* @param null $offset deprecated
diff --git a/app/code/core/Mage/Log/Model/Cron.php b/app/code/core/Mage/Log/Model/Cron.php
index d6af064f543..83c382a2fd2 100644
--- a/app/code/core/Mage/Log/Model/Cron.php
+++ b/app/code/core/Mage/Log/Model/Cron.php
@@ -34,6 +34,31 @@ class Mage_Log_Model_Cron extends Mage_Core_Model_Abstract
*/
protected $_errors = [];
+ /**
+ * Clean logs
+ *
+ * @return $this
+ */
+ public function logClean()
+ {
+ if (!Mage::getStoreConfigFlag(self::XML_PATH_LOG_CLEAN_ENABLED)) {
+ return $this;
+ }
+
+ $this->_errors = [];
+
+ try {
+ Mage::getModel('log/log')->clean();
+ } catch (Exception $e) {
+ $this->_errors[] = $e->getMessage();
+ $this->_errors[] = $e->getTrace();
+ }
+
+ $this->_sendLogCleanEmail();
+
+ return $this;
+ }
+
/**
* Send Log Clean Warnings
*
@@ -67,29 +92,4 @@ protected function _sendLogCleanEmail()
return $this;
}
-
- /**
- * Clean logs
- *
- * @return $this
- */
- public function logClean()
- {
- if (!Mage::getStoreConfigFlag(self::XML_PATH_LOG_CLEAN_ENABLED)) {
- return $this;
- }
-
- $this->_errors = [];
-
- try {
- Mage::getModel('log/log')->clean();
- } catch (Exception $e) {
- $this->_errors[] = $e->getMessage();
- $this->_errors[] = $e->getTrace();
- }
-
- $this->_sendLogCleanEmail();
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Log/Model/Customer.php b/app/code/core/Mage/Log/Model/Customer.php
index 7597c58da3d..12aeb56e58e 100644
--- a/app/code/core/Mage/Log/Model/Customer.php
+++ b/app/code/core/Mage/Log/Model/Customer.php
@@ -35,16 +35,6 @@
*/
class Mage_Log_Model_Customer extends Mage_Core_Model_Abstract
{
- /**
- * Define resource model
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_init('log/customer');
- }
-
/**
* Load last log by customer id
*
@@ -74,4 +64,13 @@ public function getLoginAtTimestamp()
return null;
}
+ /**
+ * Define resource model
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('log/customer');
+ }
}
diff --git a/app/code/core/Mage/Log/Model/Log.php b/app/code/core/Mage/Log/Model/Log.php
index 3df0d637dd3..d6be5db852c 100644
--- a/app/code/core/Mage/Log/Model/Log.php
+++ b/app/code/core/Mage/Log/Model/Log.php
@@ -37,15 +37,6 @@ class Mage_Log_Model_Log extends Mage_Core_Model_Abstract
{
public const XML_LOG_CLEAN_DAYS = 'system/log/clean_after_day';
- /**
- * Init Resource Model
- *
- */
- protected function _construct()
- {
- $this->_init('log/log');
- }
-
/**
* @return int
*/
@@ -64,4 +55,13 @@ public function clean()
$this->getResource()->clean($this);
return $this;
}
+
+ /**
+ * Init Resource Model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('log/log');
+ }
}
diff --git a/app/code/core/Mage/Log/Model/Resource/Aggregation.php b/app/code/core/Mage/Log/Model/Resource/Aggregation.php
index 2d48b970d43..a367bb96a54 100644
--- a/app/code/core/Mage/Log/Model/Resource/Aggregation.php
+++ b/app/code/core/Mage/Log/Model/Resource/Aggregation.php
@@ -22,11 +22,6 @@
*/
class Mage_Log_Model_Resource_Aggregation extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('log/summary_table', 'log_summary_id');
- }
-
/**
* Retrieve last added record
*
@@ -134,4 +129,8 @@ public function getLogId($from, $to)
return $adapter->fetchOne($select);
}
+ protected function _construct()
+ {
+ $this->_init('log/summary_table', 'log_summary_id');
+ }
}
diff --git a/app/code/core/Mage/Log/Model/Resource/Log.php b/app/code/core/Mage/Log/Model/Resource/Log.php
index ee1141a10df..522f076faf6 100644
--- a/app/code/core/Mage/Log/Model/Resource/Log.php
+++ b/app/code/core/Mage/Log/Model/Resource/Log.php
@@ -22,11 +22,6 @@
*/
class Mage_Log_Model_Resource_Log extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('log/visitor', 'visitor_id');
- }
-
/**
* Clean logs
*
@@ -50,6 +45,10 @@ public function clean(Mage_Log_Model_Log $object)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('log/visitor', 'visitor_id');
+ }
/**
* Clean visitors table
diff --git a/app/code/core/Mage/Log/Model/Resource/Visitor/Collection.php b/app/code/core/Mage/Log/Model/Resource/Visitor/Collection.php
index c7de8d90396..d4689985ea2 100644
--- a/app/code/core/Mage/Log/Model/Resource/Visitor/Collection.php
+++ b/app/code/core/Mage/Log/Model/Resource/Visitor/Collection.php
@@ -99,6 +99,74 @@ class Mage_Log_Model_Resource_Visitor_Collection extends Mage_Core_Model_Resourc
'url' => 'url_info_table.url',
];
+ /**
+ * Filter for customers only
+ *
+ * @return $this
+ */
+ public function showCustomersOnly()
+ {
+ $this->getSelect()
+ ->where('customer_table.customer_id > 0')
+ ->group('customer_table.customer_id');
+
+ return $this;
+ }
+
+ /**
+ * Filter by customer ID, as 'type' field does not exist
+ *
+ * @inheritDoc
+ */
+ public function addFieldToFilter($fieldName, $condition = null)
+ {
+ if ($fieldName == 'type' && is_array($condition) && isset($condition['eq'])) {
+ $fieldName = 'customer_id';
+ if ($condition['eq'] === Mage_Log_Model_Visitor::VISITOR_TYPE_VISITOR) {
+ $condition = ['null' => 1];
+ } else {
+ $condition = ['moreq' => 1];
+ }
+ }
+ return parent::addFieldToFilter($this->_getFieldMap($fieldName), $condition);
+ }
+
+ /**
+ * Load data
+ *
+ * @param bool $printQuery
+ * @param bool $logQuery
+ * @return Mage_Core_Model_Resource_Db_Collection_Abstract
+ */
+ public function load($printQuery = false, $logQuery = false)
+ {
+ if ($this->isLoaded()) {
+ return $this;
+ }
+ Mage::dispatchEvent('log_visitor_collection_load_before', ['collection' => $this]);
+ return parent::load($printQuery, $logQuery);
+ }
+
+ /**
+ * Return true if online filter used
+ *
+ * @return bool
+ */
+ public function getIsOnlineFilterUsed()
+ {
+ return $this->_isOnlineFilterUsed;
+ }
+
+ /**
+ * Filter visitors by specified store ids
+ *
+ * @param array|int $storeIds
+ */
+ public function addVisitorStoreFilter($storeIds)
+ {
+ $this->getSelect()->where('visitor_table.store_id IN (?)', $storeIds);
+ }
+
/**
* Collection resource initialization
*/
@@ -116,20 +184,6 @@ protected function _construct()
$this->_quoteTable = $this->getTable('log/quote_table');
}
- /**
- * Filter for customers only
- *
- * @return $this
- */
- public function showCustomersOnly()
- {
- $this->getSelect()
- ->where('customer_table.customer_id > 0')
- ->group('customer_table.customer_id');
-
- return $this;
- }
-
/**
* Get GROUP BY date format
*
@@ -176,24 +230,6 @@ protected function _getRangeByType($typeCode)
return $range;
}
- /**
- * Filter by customer ID, as 'type' field does not exist
- *
- * @inheritDoc
- */
- public function addFieldToFilter($fieldName, $condition = null)
- {
- if ($fieldName == 'type' && is_array($condition) && isset($condition['eq'])) {
- $fieldName = 'customer_id';
- if ($condition['eq'] === Mage_Log_Model_Visitor::VISITOR_TYPE_VISITOR) {
- $condition = ['null' => 1];
- } else {
- $condition = ['moreq' => 1];
- }
- }
- return parent::addFieldToFilter($this->_getFieldMap($fieldName), $condition);
- }
-
/**
* Return field with table prefix
*
@@ -204,40 +240,4 @@ protected function _getFieldMap($fieldName)
{
return $this->_fieldMap[$fieldName] ?? ('main_table.' . $fieldName);
}
-
- /**
- * Load data
- *
- * @param bool $printQuery
- * @param bool $logQuery
- * @return Mage_Core_Model_Resource_Db_Collection_Abstract
- */
- public function load($printQuery = false, $logQuery = false)
- {
- if ($this->isLoaded()) {
- return $this;
- }
- Mage::dispatchEvent('log_visitor_collection_load_before', ['collection' => $this]);
- return parent::load($printQuery, $logQuery);
- }
-
- /**
- * Return true if online filter used
- *
- * @return bool
- */
- public function getIsOnlineFilterUsed()
- {
- return $this->_isOnlineFilterUsed;
- }
-
- /**
- * Filter visitors by specified store ids
- *
- * @param array|int $storeIds
- */
- public function addVisitorStoreFilter($storeIds)
- {
- $this->getSelect()->where('visitor_table.store_id IN (?)', $storeIds);
- }
}
diff --git a/app/code/core/Mage/Log/Model/Resource/Visitor/Online.php b/app/code/core/Mage/Log/Model/Resource/Visitor/Online.php
index 1b3bb9e345b..bd3406d6b77 100644
--- a/app/code/core/Mage/Log/Model/Resource/Visitor/Online.php
+++ b/app/code/core/Mage/Log/Model/Resource/Visitor/Online.php
@@ -22,11 +22,6 @@
*/
class Mage_Log_Model_Resource_Visitor_Online extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('log/visitor_online', 'visitor_id');
- }
-
/**
* Prepare online visitors for collection
*
@@ -130,4 +125,8 @@ public function prepare(Mage_Log_Model_Visitor_Online $object)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('log/visitor_online', 'visitor_id');
+ }
}
diff --git a/app/code/core/Mage/Log/Model/Resource/Visitor/Online/Collection.php b/app/code/core/Mage/Log/Model/Resource/Visitor/Online/Collection.php
index 5c6c6b6372f..1497c372316 100644
--- a/app/code/core/Mage/Log/Model/Resource/Visitor/Online/Collection.php
+++ b/app/code/core/Mage/Log/Model/Resource/Visitor/Online/Collection.php
@@ -29,15 +29,6 @@ class Mage_Log_Model_Resource_Visitor_Online_Collection extends Mage_Core_Model_
*/
protected $_fields = [];
- /**
- * Initialize collection model
- *
- */
- protected function _construct()
- {
- $this->_init('log/visitor_online');
- }
-
/**
* Add Customer data to collection
*
@@ -127,4 +118,13 @@ public function addFieldToFilter($field, $condition = null)
return parent::addFieldToFilter($field, $condition);
}
+
+ /**
+ * Initialize collection model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('log/visitor_online');
+ }
}
diff --git a/app/code/core/Mage/Log/Model/Visitor.php b/app/code/core/Mage/Log/Model/Visitor.php
index 016bbacb99b..f7f09e7755b 100644
--- a/app/code/core/Mage/Log/Model/Visitor.php
+++ b/app/code/core/Mage/Log/Model/Visitor.php
@@ -95,40 +95,6 @@ public function __construct(array $data = [])
parent::__construct($data);
}
- /**
- * Object initialization
- */
- protected function _construct()
- {
- $this->_init('log/visitor');
- if ($this->_logCondition->isLogDisabled()) {
- $this->_skipRequestLogging = true;
- return;
- }
-
- $ignoreAgents = $this->_config->getNode('global/ignore_user_agents');
- if ($ignoreAgents) {
- $ignoreAgents = $ignoreAgents->asArray();
- $userAgent = $this->_httpHelper->getHttpUserAgent();
- foreach ($ignoreAgents as $ignoreAgent) {
- if (stripos($userAgent, $ignoreAgent) !== false) {
- $this->_skipRequestLogging = true;
- break;
- }
- }
- }
- }
-
- /**
- * Retrieve session object
- *
- * @return Mage_Core_Model_Session_Abstract
- */
- protected function _getSession()
- {
- return $this->_session;
- }
-
/**
* Initialize visitor information from server data
*
@@ -227,21 +193,6 @@ public function initByRequest($observer)
return $this;
}
- /**
- * Check is session new
- *
- * @return bool
- */
- protected function _isVisitorSessionNew()
- {
- $visitorData = $this->_session->getVisitorData();
- $visitorSessionId = null;
- if (is_array($visitorData) && isset($visitorData['session_id'])) {
- $visitorSessionId = $visitorData['session_id'];
- }
- return $this->_session->getSessionId() != $visitorSessionId;
- }
-
/**
* Saving visitor information by request
*
@@ -395,4 +346,53 @@ public function isModuleIgnored($observer)
}
return false;
}
+
+ /**
+ * Object initialization
+ */
+ protected function _construct()
+ {
+ $this->_init('log/visitor');
+ if ($this->_logCondition->isLogDisabled()) {
+ $this->_skipRequestLogging = true;
+ return;
+ }
+
+ $ignoreAgents = $this->_config->getNode('global/ignore_user_agents');
+ if ($ignoreAgents) {
+ $ignoreAgents = $ignoreAgents->asArray();
+ $userAgent = $this->_httpHelper->getHttpUserAgent();
+ foreach ($ignoreAgents as $ignoreAgent) {
+ if (stripos($userAgent, $ignoreAgent) !== false) {
+ $this->_skipRequestLogging = true;
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Retrieve session object
+ *
+ * @return Mage_Core_Model_Session_Abstract
+ */
+ protected function _getSession()
+ {
+ return $this->_session;
+ }
+
+ /**
+ * Check is session new
+ *
+ * @return bool
+ */
+ protected function _isVisitorSessionNew()
+ {
+ $visitorData = $this->_session->getVisitorData();
+ $visitorSessionId = null;
+ if (is_array($visitorData) && isset($visitorData['session_id'])) {
+ $visitorSessionId = $visitorData['session_id'];
+ }
+ return $this->_session->getSessionId() != $visitorSessionId;
+ }
}
diff --git a/app/code/core/Mage/Log/Model/Visitor/Online.php b/app/code/core/Mage/Log/Model/Visitor/Online.php
index 187fbe43129..0402ee50969 100644
--- a/app/code/core/Mage/Log/Model/Visitor/Online.php
+++ b/app/code/core/Mage/Log/Model/Visitor/Online.php
@@ -41,11 +41,6 @@ class Mage_Log_Model_Visitor_Online extends Mage_Core_Model_Abstract
public const XML_PATH_ONLINE_INTERVAL = 'customer/online_customers/online_minutes_interval';
public const XML_PATH_UPDATE_FREQUENCY = 'log/visitor/online_update_frequency';
- protected function _construct()
- {
- $this->_init('log/visitor_online');
- }
-
/**
* Prepare Online visitors collection
*
@@ -105,4 +100,9 @@ public function getOnlineInterval()
}
return $value;
}
+
+ protected function _construct()
+ {
+ $this->_init('log/visitor_online');
+ }
}
diff --git a/app/code/core/Mage/Media/Model/File/Image.php b/app/code/core/Mage/Media/Model/File/Image.php
index 1f685188738..83a21f85eb0 100644
--- a/app/code/core/Mage/Media/Model/File/Image.php
+++ b/app/code/core/Mage/Media/Model/File/Image.php
@@ -22,30 +22,6 @@
*/
class Mage_Media_Model_File_Image extends Mage_Core_Model_Resource_Abstract
{
- /**
- * @return $this
- */
- protected function _construct()
- {
- return $this;
- }
-
- /**
- * @return Varien_Db_Adapter_Interface|false
- */
- protected function _getReadAdapter()
- {
- return false;
- }
-
- /**
- * @return Varien_Db_Adapter_Interface|false
- */
- protected function _getWriteAdapter()
- {
- return false;
- }
-
/**
* @param mixed $file
* @param mixed|null $field
@@ -233,4 +209,27 @@ public function hasSpecialImage(Mage_Media_Model_Image $object)
return false;
}
+ /**
+ * @return $this
+ */
+ protected function _construct()
+ {
+ return $this;
+ }
+
+ /**
+ * @return Varien_Db_Adapter_Interface|false
+ */
+ protected function _getReadAdapter()
+ {
+ return false;
+ }
+
+ /**
+ * @return Varien_Db_Adapter_Interface|false
+ */
+ protected function _getWriteAdapter()
+ {
+ return false;
+ }
}
diff --git a/app/code/core/Mage/Media/Model/Image.php b/app/code/core/Mage/Media/Model/Image.php
index 68840191639..07d4edbfd44 100644
--- a/app/code/core/Mage/Media/Model/Image.php
+++ b/app/code/core/Mage/Media/Model/Image.php
@@ -49,11 +49,6 @@ class Mage_Media_Model_Image extends Mage_Core_Model_Abstract
*/
protected $_params = [];
- protected function _construct()
- {
- $this->_init('media/image');
- }
-
/**
* Set media image config instance
* @return Mage_Media_Model_Image
@@ -287,6 +282,11 @@ public function hasSpecialImage()
return $this->_getResource()->hasSpecialImage($this);
}
+ protected function _construct()
+ {
+ $this->_init('media/image');
+ }
+
protected function _removeResources()
{
if ($this->_image) {
diff --git a/app/code/core/Mage/Newsletter/Model/Problem.php b/app/code/core/Mage/Newsletter/Model/Problem.php
index dfc01c78d55..eeb9201ac13 100644
--- a/app/code/core/Mage/Newsletter/Model/Problem.php
+++ b/app/code/core/Mage/Newsletter/Model/Problem.php
@@ -44,14 +44,6 @@ class Mage_Newsletter_Model_Problem extends Mage_Core_Model_Abstract
*/
protected $_subscriber = null;
- /**
- * Initialize Newsletter Problem Model
- */
- protected function _construct()
- {
- $this->_init('newsletter/problem');
- }
-
/**
* Add Subscriber Data
*
@@ -119,4 +111,12 @@ public function unsubscribe()
}
return $this;
}
+
+ /**
+ * Initialize Newsletter Problem Model
+ */
+ protected function _construct()
+ {
+ $this->_init('newsletter/problem');
+ }
}
diff --git a/app/code/core/Mage/Newsletter/Model/Queue.php b/app/code/core/Mage/Newsletter/Model/Queue.php
index b6ec07909d6..f03d5b5cd0f 100644
--- a/app/code/core/Mage/Newsletter/Model/Queue.php
+++ b/app/code/core/Mage/Newsletter/Model/Queue.php
@@ -47,6 +47,11 @@
*/
class Mage_Newsletter_Model_Queue extends Mage_Core_Model_Template
{
+ public const STATUS_NEVER = 0;
+ public const STATUS_SENDING = 1;
+ public const STATUS_CANCEL = 2;
+ public const STATUS_SENT = 3;
+ public const STATUS_PAUSE = 4;
/**
* Newsletter Template object
*
@@ -82,17 +87,6 @@ class Mage_Newsletter_Model_Queue extends Mage_Core_Model_Template
*/
protected $_stores = [];
- public const STATUS_NEVER = 0;
- public const STATUS_SENDING = 1;
- public const STATUS_CANCEL = 2;
- public const STATUS_SENT = 3;
- public const STATUS_PAUSE = 4;
-
- protected function _construct()
- {
- $this->_init('newsletter/queue');
- }
-
/**
* Return: is this queue newly created or not.
*
@@ -217,20 +211,6 @@ public function sendPerSubscriber($count = 20, array $additionalVariables = [])
return $this;
}
- /**
- * Finish queue: set status SENT and update finish date
- *
- * @return $this
- */
- protected function _finishQueue()
- {
- $this->setQueueFinishAt(Mage::getSingleton('core/date')->gmtDate());
- $this->setQueueStatus(self::STATUS_SENT);
- $this->save();
-
- return $this;
- }
-
/**
* Getter data for saving
*
@@ -352,4 +332,23 @@ public function getType()
{
return $this->getNewsletterType();
}
+
+ protected function _construct()
+ {
+ $this->_init('newsletter/queue');
+ }
+
+ /**
+ * Finish queue: set status SENT and update finish date
+ *
+ * @return $this
+ */
+ protected function _finishQueue()
+ {
+ $this->setQueueFinishAt(Mage::getSingleton('core/date')->gmtDate());
+ $this->setQueueStatus(self::STATUS_SENT);
+ $this->save();
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Newsletter/Model/Resource/Problem/Collection.php b/app/code/core/Mage/Newsletter/Model/Resource/Problem/Collection.php
index 5b577636346..18aadbc7b9b 100644
--- a/app/code/core/Mage/Newsletter/Model/Resource/Problem/Collection.php
+++ b/app/code/core/Mage/Newsletter/Model/Resource/Problem/Collection.php
@@ -41,15 +41,6 @@ class Mage_Newsletter_Model_Resource_Problem_Collection extends Mage_Core_Model_
*/
protected $_problemGrouped = false;
- /**
- * Define resource model and model
- *
- */
- protected function _construct()
- {
- $this->_init('newsletter/problem');
- }
-
/**
* Adds subscribers info
*
@@ -88,6 +79,31 @@ public function addQueueInfo()
return $this;
}
+ /**
+ * Loads collection and adds customers info
+ *
+ * @param bool $printQuery
+ * @param bool $logQuery
+ * @return $this
+ */
+ public function load($printQuery = false, $logQuery = false)
+ {
+ parent::load($printQuery, $logQuery);
+ if ($this->_subscribersInfoJoinedFlag && !$this->isLoaded()) {
+ $this->_addCustomersData();
+ }
+ return $this;
+ }
+
+ /**
+ * Define resource model and model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('newsletter/problem');
+ }
+
/**
* Loads customers info to collection
*
@@ -121,20 +137,4 @@ protected function _addCustomersData()
}
}
}
-
- /**
- * Loads collection and adds customers info
- *
- * @param bool $printQuery
- * @param bool $logQuery
- * @return $this
- */
- public function load($printQuery = false, $logQuery = false)
- {
- parent::load($printQuery, $logQuery);
- if ($this->_subscribersInfoJoinedFlag && !$this->isLoaded()) {
- $this->_addCustomersData();
- }
- return $this;
- }
}
diff --git a/app/code/core/Mage/Newsletter/Model/Resource/Queue.php b/app/code/core/Mage/Newsletter/Model/Resource/Queue.php
index dea8b919748..0eba3d72cb7 100644
--- a/app/code/core/Mage/Newsletter/Model/Resource/Queue.php
+++ b/app/code/core/Mage/Newsletter/Model/Resource/Queue.php
@@ -22,11 +22,6 @@
*/
class Mage_Newsletter_Model_Resource_Queue extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('newsletter/queue', 'queue_id');
- }
-
/**
* Add subscribers to queue
*/
@@ -152,6 +147,10 @@ public function getStores(Mage_Newsletter_Model_Queue $queue)
return $result;
}
+ protected function _construct()
+ {
+ $this->_init('newsletter/queue', 'queue_id');
+ }
/**
* Saving template after saving queue action
diff --git a/app/code/core/Mage/Newsletter/Model/Resource/Queue/Collection.php b/app/code/core/Mage/Newsletter/Model/Resource/Queue/Collection.php
index fc3ca3387ea..fe221ec8052 100644
--- a/app/code/core/Mage/Newsletter/Model/Resource/Queue/Collection.php
+++ b/app/code/core/Mage/Newsletter/Model/Resource/Queue/Collection.php
@@ -36,16 +36,6 @@ class Mage_Newsletter_Model_Resource_Queue_Collection extends Mage_Core_Model_Re
*/
protected $_isStoreFilter = false;
- /**
- * Initializes collection
- *
- */
- protected function _construct()
- {
- $this->_map['fields']['queue_id'] = 'main_table.queue_id';
- $this->_init('newsletter/queue');
- }
-
/**
* Joines templates information
*
@@ -64,31 +54,6 @@ public function addTemplateInfo()
return $this;
}
- /**
- * Adds subscribers info to selelect
- *
- * @return $this
- */
- protected function _addSubscriberInfoToSelect()
- {
- /** @var Varien_Db_Select $select */
- $select = $this->getConnection()->select()
- ->from(['qlt' => $this->getTable('newsletter/queue_link')], 'COUNT(qlt.queue_link_id)')
- ->where('qlt.queue_id = main_table.queue_id');
- $totalExpr = new Zend_Db_Expr(sprintf('(%s)', $select->assemble()));
- $select = $this->getConnection()->select()
- ->from(['qls' => $this->getTable('newsletter/queue_link')], 'COUNT(qls.queue_link_id)')
- ->where('qls.queue_id = main_table.queue_id')
- ->where('qls.letter_sent_at IS NOT NULL');
- $sentExpr = new Zend_Db_Expr(sprintf('(%s)', $select->assemble()));
-
- $this->getSelect()->columns([
- 'subscribers_sent' => $sentExpr,
- 'subscribers_total' => $totalExpr,
- ]);
- return $this;
- }
-
/**
* Adds subscribers info to select and loads collection
*
@@ -129,36 +94,6 @@ public function addFieldToFilter($field, $condition = null)
}
}
- /**
- * Returns ids from queue_link table
- *
- * @param string $field
- * @param mixed $condition
- * @return array
- */
- protected function _getIdsFromLink($field, $condition)
- {
- $select = $this->getConnection()->select()
- ->from(
- $this->getTable('newsletter/queue_link'),
- ['queue_id', 'total' => new Zend_Db_Expr('COUNT(queue_link_id)')],
- )
- ->group('queue_id')
- ->having($this->_getConditionSql('total', $condition));
-
- if ($field == 'subscribers_sent') {
- $select->where('letter_sent_at IS NOT NULL');
- }
-
- $idList = $this->getConnection()->fetchCol($select);
-
- if (count($idList)) {
- return $idList;
- }
-
- return [0];
- }
-
/**
* Set filter for queue by subscriber.
*
@@ -235,4 +170,69 @@ public function addStoreFilter($storeIds)
}
return $this;
}
+
+ /**
+ * Initializes collection
+ *
+ */
+ protected function _construct()
+ {
+ $this->_map['fields']['queue_id'] = 'main_table.queue_id';
+ $this->_init('newsletter/queue');
+ }
+
+ /**
+ * Adds subscribers info to selelect
+ *
+ * @return $this
+ */
+ protected function _addSubscriberInfoToSelect()
+ {
+ /** @var Varien_Db_Select $select */
+ $select = $this->getConnection()->select()
+ ->from(['qlt' => $this->getTable('newsletter/queue_link')], 'COUNT(qlt.queue_link_id)')
+ ->where('qlt.queue_id = main_table.queue_id');
+ $totalExpr = new Zend_Db_Expr(sprintf('(%s)', $select->assemble()));
+ $select = $this->getConnection()->select()
+ ->from(['qls' => $this->getTable('newsletter/queue_link')], 'COUNT(qls.queue_link_id)')
+ ->where('qls.queue_id = main_table.queue_id')
+ ->where('qls.letter_sent_at IS NOT NULL');
+ $sentExpr = new Zend_Db_Expr(sprintf('(%s)', $select->assemble()));
+
+ $this->getSelect()->columns([
+ 'subscribers_sent' => $sentExpr,
+ 'subscribers_total' => $totalExpr,
+ ]);
+ return $this;
+ }
+
+ /**
+ * Returns ids from queue_link table
+ *
+ * @param string $field
+ * @param mixed $condition
+ * @return array
+ */
+ protected function _getIdsFromLink($field, $condition)
+ {
+ $select = $this->getConnection()->select()
+ ->from(
+ $this->getTable('newsletter/queue_link'),
+ ['queue_id', 'total' => new Zend_Db_Expr('COUNT(queue_link_id)')],
+ )
+ ->group('queue_id')
+ ->having($this->_getConditionSql('total', $condition));
+
+ if ($field == 'subscribers_sent') {
+ $select->where('letter_sent_at IS NOT NULL');
+ }
+
+ $idList = $this->getConnection()->fetchCol($select);
+
+ if (count($idList)) {
+ return $idList;
+ }
+
+ return [0];
+ }
}
diff --git a/app/code/core/Mage/Newsletter/Model/Resource/Subscriber.php b/app/code/core/Mage/Newsletter/Model/Resource/Subscriber.php
index e38a87b5352..b057e821b30 100644
--- a/app/code/core/Mage/Newsletter/Model/Resource/Subscriber.php
+++ b/app/code/core/Mage/Newsletter/Model/Resource/Subscriber.php
@@ -50,18 +50,6 @@ class Mage_Newsletter_Model_Resource_Subscriber extends Mage_Core_Model_Resource
*/
protected $_messagesScope = 'newsletter/session';
- /**
- * Get tablename from config
- *
- */
- protected function _construct()
- {
- $this->_init('newsletter/subscriber', 'subscriber_id');
- $this->_subscriberLinkTable = $this->getTable('newsletter/queue_link');
- $this->_read = $this->_getReadAdapter();
- $this->_write = $this->_getWriteAdapter();
- }
-
/**
* Set error messages scope
*
@@ -127,16 +115,6 @@ public function loadByCustomer(Mage_Customer_Model_Customer $customer)
return [];
}
- /**
- * Generates random code for subscription confirmation
- *
- * @return string
- */
- protected function _generateRandomCode()
- {
- return Mage::helper('core')->uniqHash();
- }
-
/**
* Updates data when subscriber received
*
@@ -158,4 +136,26 @@ public function received(Mage_Newsletter_Model_Subscriber $subscriber, Mage_News
}
return $this;
}
+
+ /**
+ * Get tablename from config
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('newsletter/subscriber', 'subscriber_id');
+ $this->_subscriberLinkTable = $this->getTable('newsletter/queue_link');
+ $this->_read = $this->_getReadAdapter();
+ $this->_write = $this->_getWriteAdapter();
+ }
+
+ /**
+ * Generates random code for subscription confirmation
+ *
+ * @return string
+ */
+ protected function _generateRandomCode()
+ {
+ return Mage::helper('core')->uniqHash();
+ }
}
diff --git a/app/code/core/Mage/Newsletter/Model/Resource/Subscriber/Collection.php b/app/code/core/Mage/Newsletter/Model/Resource/Subscriber/Collection.php
index 826101b07ec..a55a871dbeb 100644
--- a/app/code/core/Mage/Newsletter/Model/Resource/Subscriber/Collection.php
+++ b/app/code/core/Mage/Newsletter/Model/Resource/Subscriber/Collection.php
@@ -57,24 +57,6 @@ class Mage_Newsletter_Model_Resource_Subscriber_Collection extends Mage_Core_Mod
*/
protected $_countFilterPart = [];
- protected function _construct()
- {
- parent::_construct();
- $this->_init('newsletter/subscriber');
- $this->_queueLinkTable = $this->getTable('newsletter/queue_link');
- $this->_storeTable = $this->getTable('core/store');
-
- // defining mapping for fields represented in several tables
- $this->_map['fields']['customer_lastname'] = 'customer_lastname_table.value';
- $this->_map['fields']['customer_middlename'] = 'customer_middlename_table.value';
- $this->_map['fields']['customer_firstname'] = 'customer_firstname_table.value';
- $this->_map['fields']['type'] = $this->getResource()->getReadConnection()
- ->getCheckSql('main_table.customer_id = 0', '1', '2');
- $this->_map['fields']['website_id'] = 'store.website_id';
- $this->_map['fields']['group_id'] = 'store.group_id';
- $this->_map['fields']['store_id'] = 'main_table.store_id';
- }
-
/**
* Set loading mode subscribers by queue
*
@@ -240,4 +222,22 @@ public function addStoreFilter($storeIds)
$this->addFieldToFilter('main_table.store_id', ['in' => $storeIds]);
return $this;
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('newsletter/subscriber');
+ $this->_queueLinkTable = $this->getTable('newsletter/queue_link');
+ $this->_storeTable = $this->getTable('core/store');
+
+ // defining mapping for fields represented in several tables
+ $this->_map['fields']['customer_lastname'] = 'customer_lastname_table.value';
+ $this->_map['fields']['customer_middlename'] = 'customer_middlename_table.value';
+ $this->_map['fields']['customer_firstname'] = 'customer_firstname_table.value';
+ $this->_map['fields']['type'] = $this->getResource()->getReadConnection()
+ ->getCheckSql('main_table.customer_id = 0', '1', '2');
+ $this->_map['fields']['website_id'] = 'store.website_id';
+ $this->_map['fields']['group_id'] = 'store.group_id';
+ $this->_map['fields']['store_id'] = 'main_table.store_id';
+ }
}
diff --git a/app/code/core/Mage/Newsletter/Model/Resource/Template.php b/app/code/core/Mage/Newsletter/Model/Resource/Template.php
index fc95214dd7f..2336733c5c2 100644
--- a/app/code/core/Mage/Newsletter/Model/Resource/Template.php
+++ b/app/code/core/Mage/Newsletter/Model/Resource/Template.php
@@ -22,11 +22,6 @@
*/
class Mage_Newsletter_Model_Resource_Template extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('newsletter/template', 'template_id');
- }
-
/**
* Load an object by template code
*
@@ -99,6 +94,10 @@ public function checkCodeUsage(Mage_Newsletter_Model_Template $template)
return false;
}
}
+ protected function _construct()
+ {
+ $this->_init('newsletter/template', 'template_id');
+ }
/**
* Perform actions before object save
diff --git a/app/code/core/Mage/Newsletter/Model/Resource/Template/Collection.php b/app/code/core/Mage/Newsletter/Model/Resource/Template/Collection.php
index 28ce312a912..95ac008dc2e 100644
--- a/app/code/core/Mage/Newsletter/Model/Resource/Template/Collection.php
+++ b/app/code/core/Mage/Newsletter/Model/Resource/Template/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Newsletter_Model_Resource_Template_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define resource model and model
- *
- */
- protected function _construct()
- {
- $this->_init('newsletter/template');
- }
-
/**
* Load only actual template
*
@@ -52,4 +43,12 @@ public function toOptionArray()
{
return $this->_toOptionArray('template_id', 'template_code');
}
+ /**
+ * Define resource model and model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('newsletter/template');
+ }
}
diff --git a/app/code/core/Mage/Newsletter/Model/Subscriber.php b/app/code/core/Mage/Newsletter/Model/Subscriber.php
index 91547ae500d..8c63d71d02c 100644
--- a/app/code/core/Mage/Newsletter/Model/Subscriber.php
+++ b/app/code/core/Mage/Newsletter/Model/Subscriber.php
@@ -89,11 +89,6 @@ class Mage_Newsletter_Model_Subscriber extends Mage_Core_Model_Abstract
*/
protected $_isStatusChanged = false;
- protected function _construct()
- {
- $this->_init('newsletter/subscriber');
- }
-
/**
* Alias for getSubscriberId()
*
@@ -613,4 +608,9 @@ public function getSubscriberFullName()
}
return $name;
}
+
+ protected function _construct()
+ {
+ $this->_init('newsletter/subscriber');
+ }
}
diff --git a/app/code/core/Mage/Newsletter/Model/Template.php b/app/code/core/Mage/Newsletter/Model/Template.php
index e9b5688648a..2cd1766d931 100644
--- a/app/code/core/Mage/Newsletter/Model/Template.php
+++ b/app/code/core/Mage/Newsletter/Model/Template.php
@@ -63,15 +63,6 @@ class Mage_Newsletter_Model_Template extends Mage_Core_Model_Email_Template_Abst
*/
protected $_mail;
- /**
- * Initialize resource model
- *
- */
- protected function _construct()
- {
- $this->_init('newsletter/template');
- }
-
/**
* Validate Newsletter template
*
@@ -107,17 +98,6 @@ public function validate()
}
}
- /**
- * Processing object before save data
- *
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- $this->validate();
- return parent::_beforeSave();
- }
-
/**
* Load template by code
*
@@ -417,4 +397,24 @@ public function getTemplateText()
return $this->getData('template_text');
}
+
+ /**
+ * Initialize resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('newsletter/template');
+ }
+
+ /**
+ * Processing object before save data
+ *
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ $this->validate();
+ return parent::_beforeSave();
+ }
}
diff --git a/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Admin/Token/Grid.php b/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Admin/Token/Grid.php
index 5284b239eaf..41092768013 100644
--- a/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Admin/Token/Grid.php
+++ b/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Admin/Token/Grid.php
@@ -35,6 +35,16 @@ public function __construct()
->setDefaultDir(Varien_Db_Select::SQL_DESC);
}
+ /**
+ * Get grid URL
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
/**
* Prepare collection
*
@@ -114,14 +124,4 @@ protected function _prepareMassaction()
return $this;
}
-
- /**
- * Get grid URL
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/AuthorizedTokens/Grid.php b/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/AuthorizedTokens/Grid.php
index 20531051527..5a8c7a27a84 100644
--- a/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/AuthorizedTokens/Grid.php
+++ b/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/AuthorizedTokens/Grid.php
@@ -35,6 +35,67 @@ public function __construct()
->setDefaultDir(Varien_Db_Select::SQL_DESC);
}
+ /**
+ * Get grid URL
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
+ /**
+ * Get revoke URL
+ *
+ * @param Mage_Oauth_Model_Token $row
+ * @return string|null
+ */
+ public function getRevokeUrl($row)
+ {
+ return $this->getUrl('*/*/revoke', ['id' => $row->getId()]);
+ }
+
+ /**
+ * Get delete URL
+ *
+ * @param Mage_Oauth_Model_Token $row
+ * @return string|null
+ */
+ public function getDeleteUrl($row)
+ {
+ return $this->getUrl('*/*/delete', ['id' => $row->getId()]);
+ }
+
+ /**
+ * Decorate user type column
+ *
+ * @param string $value
+ * @param Mage_Oauth_Model_Token $row
+ * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
+ * @param bool $isExport
+ * @return mixed
+ */
+ public function decorateUserType($value, $row, $column, $isExport)
+ {
+ $options = $column->getOptions();
+ return ($row->getCustomerId()) ? $options[1] : $options[0];
+ }
+
+ /**
+ * Decorate user type column
+ *
+ * @param string $value
+ * @param Mage_Oauth_Model_Token $row
+ * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
+ * @param bool $isExport
+ * @return mixed
+ */
+ public function decorateUserId($value, $row, $column, $isExport)
+ {
+ return $row->getCustomerId() ? $row->getCustomerId() : $row->getAdminId();
+ }
+
/**
* Prepare collection
*
@@ -97,38 +158,6 @@ protected function _prepareColumns()
return $this;
}
- /**
- * Get grid URL
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
-
- /**
- * Get revoke URL
- *
- * @param Mage_Oauth_Model_Token $row
- * @return string|null
- */
- public function getRevokeUrl($row)
- {
- return $this->getUrl('*/*/revoke', ['id' => $row->getId()]);
- }
-
- /**
- * Get delete URL
- *
- * @param Mage_Oauth_Model_Token $row
- * @return string|null
- */
- public function getDeleteUrl($row)
- {
- return $this->getUrl('*/*/delete', ['id' => $row->getId()]);
- }
-
/**
* Add mass-actions to grid
*
@@ -160,35 +189,6 @@ protected function _prepareMassaction()
return $this;
}
- /**
- * Decorate user type column
- *
- * @param string $value
- * @param Mage_Oauth_Model_Token $row
- * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
- * @param bool $isExport
- * @return mixed
- */
- public function decorateUserType($value, $row, $column, $isExport)
- {
- $options = $column->getOptions();
- return ($row->getCustomerId()) ? $options[1] : $options[0];
- }
-
- /**
- * Decorate user type column
- *
- * @param string $value
- * @param Mage_Oauth_Model_Token $row
- * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
- * @param bool $isExport
- * @return mixed
- */
- public function decorateUserId($value, $row, $column, $isExport)
- {
- return $row->getCustomerId() ? $row->getCustomerId() : $row->getAdminId();
- }
-
/**
* Check admin permissions
*
diff --git a/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Consumer/Edit.php b/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Consumer/Edit.php
index 436908c11d8..14ff61643ed 100644
--- a/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Consumer/Edit.php
+++ b/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Consumer/Edit.php
@@ -29,19 +29,6 @@ class Mage_Oauth_Block_Adminhtml_Oauth_Consumer_Edit extends Mage_Adminhtml_Bloc
*/
protected $_model;
- /**
- * Get consumer model
- *
- * @return Mage_Oauth_Model_Consumer
- */
- public function getModel()
- {
- if ($this->_model === null) {
- $this->_model = Mage::registry('current_consumer');
- }
- return $this->_model;
- }
-
/**
* Construct edit page
*/
@@ -75,6 +62,19 @@ public function __construct()
}
}
+ /**
+ * Get consumer model
+ *
+ * @return Mage_Oauth_Model_Consumer
+ */
+ public function getModel()
+ {
+ if ($this->_model === null) {
+ $this->_model = Mage::registry('current_consumer');
+ }
+ return $this->_model;
+ }
+
/**
* Get header text
*
diff --git a/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Consumer/Grid.php b/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Consumer/Grid.php
index a6e61c2d56b..ed47cf50910 100644
--- a/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Consumer/Grid.php
+++ b/app/code/core/Mage/Oauth/Block/Adminhtml/Oauth/Consumer/Grid.php
@@ -46,6 +46,30 @@ public function __construct()
$this->_editAllow = $session->isAllowed('system/oauth/consumer/edit');
}
+ /**
+ * Get grid URL
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
+ /**
+ * Get row URL
+ *
+ * @param Mage_Oauth_Model_Consumer $row
+ * @return string|null
+ */
+ public function getRowUrl($row)
+ {
+ if ($this->_editAllow) {
+ return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
+ }
+ return null;
+ }
+
/**
* Prepare collection
*
@@ -81,28 +105,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Get grid URL
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
-
- /**
- * Get row URL
- *
- * @param Mage_Oauth_Model_Consumer $row
- * @return string|null
- */
- public function getRowUrl($row)
- {
- if ($this->_editAllow) {
- return $this->getUrl('*/*/edit', ['id' => $row->getId()]);
- }
- return null;
- }
}
diff --git a/app/code/core/Mage/Oauth/Block/Customer/Token/List.php b/app/code/core/Mage/Oauth/Block/Customer/Token/List.php
index 11f84689282..72c169cc10f 100644
--- a/app/code/core/Mage/Oauth/Block/Customer/Token/List.php
+++ b/app/code/core/Mage/Oauth/Block/Customer/Token/List.php
@@ -29,22 +29,6 @@ class Mage_Oauth_Block_Customer_Token_List extends Mage_Customer_Block_Account_D
*/
protected $_collection;
- /**
- * Prepare collection
- */
- protected function _construct()
- {
- /** @var Mage_Customer_Model_Session $session */
- $session = Mage::getSingleton('customer/session');
-
- /** @var Mage_Oauth_Model_Resource_Token_Collection $collection */
- $collection = Mage::getModel('oauth/token')->getCollection();
- $collection->joinConsumerAsApplication()
- ->addFilterByType(Mage_Oauth_Model_Token::TYPE_ACCESS)
- ->addFilterByCustomerId($session->getCustomerId());
- $this->_collection = $collection;
- }
-
/**
* Get count of total records
*
@@ -65,21 +49,6 @@ public function getToolbarHtml()
return $this->getChildHtml('toolbar');
}
- /**
- * Prepare layout
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Pager $toolbar */
- $toolbar = $this->getLayout()->createBlock('page/html_pager', 'customer_token.toolbar');
- $toolbar->setCollection($this->_collection);
- $this->setChild('toolbar', $toolbar);
- parent::_prepareLayout();
- return $this;
- }
-
/**
* Get collection
*
@@ -157,4 +126,35 @@ public function getChangeStatusConfirmMessage($revokedStatus)
];
return $messages[$revokedStatus];
}
+
+ /**
+ * Prepare collection
+ */
+ protected function _construct()
+ {
+ /** @var Mage_Customer_Model_Session $session */
+ $session = Mage::getSingleton('customer/session');
+
+ /** @var Mage_Oauth_Model_Resource_Token_Collection $collection */
+ $collection = Mage::getModel('oauth/token')->getCollection();
+ $collection->joinConsumerAsApplication()
+ ->addFilterByType(Mage_Oauth_Model_Token::TYPE_ACCESS)
+ ->addFilterByCustomerId($session->getCustomerId());
+ $this->_collection = $collection;
+ }
+
+ /**
+ * Prepare layout
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Pager $toolbar */
+ $toolbar = $this->getLayout()->createBlock('page/html_pager', 'customer_token.toolbar');
+ $toolbar->setCollection($this->_collection);
+ $this->setChild('toolbar', $toolbar);
+ parent::_prepareLayout();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Oauth/Helper/Data.php b/app/code/core/Mage/Oauth/Helper/Data.php
index e5fdffc262b..52ac7cc461f 100644
--- a/app/code/core/Mage/Oauth/Helper/Data.php
+++ b/app/code/core/Mage/Oauth/Helper/Data.php
@@ -68,32 +68,6 @@ class Mage_Oauth_Helper_Data extends Mage_Core_Helper_Abstract
self::ENDPOINT_TOKEN,
];
- /**
- * Generate random string for token or secret or verifier
- *
- * @param int $length String length
- * @return string
- */
- protected function _generateRandomString($length)
- {
- if (function_exists('openssl_random_pseudo_bytes')) {
- // use openssl lib if it is install. It provides a better randomness
- $bytes = openssl_random_pseudo_bytes((int) ceil($length / 2), $strong);
- $hex = bin2hex($bytes); // hex() doubles the length of the string
- $randomString = substr($hex, 0, $length); // we truncate at most 1 char if length parameter is an odd number
- } else {
- // fallback to mt_rand() if openssl is not installed
- /** @var Mage_Core_Helper_Data $helper */
- $helper = Mage::helper('core');
- $randomString = $helper->getRandomString(
- $length,
- Mage_Core_Helper_Data::CHARS_DIGITS . Mage_Core_Helper_Data::CHARS_LOWERS,
- );
- }
-
- return $randomString;
- }
-
/**
* Generate random string for token
*
@@ -240,23 +214,6 @@ public function sendNotificationOnTokenStatusChange($userEmail, $userName, $appl
);
}
- /**
- * Is current authorize page is simple
- *
- * @return bool
- */
- protected function _getIsSimple()
- {
- $simple = false;
- if (stristr($this->_getRequest()->getActionName(), 'simple')
- || !is_null($this->_getRequest()->getParam('simple', null))
- ) {
- $simple = true;
- }
-
- return $simple;
- }
-
/**
* Get authorize endpoint url
*
@@ -295,4 +252,47 @@ public function getOauthToken()
{
return $this->_getRequest()->getParam('oauth_token', null);
}
+
+ /**
+ * Generate random string for token or secret or verifier
+ *
+ * @param int $length String length
+ * @return string
+ */
+ protected function _generateRandomString($length)
+ {
+ if (function_exists('openssl_random_pseudo_bytes')) {
+ // use openssl lib if it is install. It provides a better randomness
+ $bytes = openssl_random_pseudo_bytes((int) ceil($length / 2), $strong);
+ $hex = bin2hex($bytes); // hex() doubles the length of the string
+ $randomString = substr($hex, 0, $length); // we truncate at most 1 char if length parameter is an odd number
+ } else {
+ // fallback to mt_rand() if openssl is not installed
+ /** @var Mage_Core_Helper_Data $helper */
+ $helper = Mage::helper('core');
+ $randomString = $helper->getRandomString(
+ $length,
+ Mage_Core_Helper_Data::CHARS_DIGITS . Mage_Core_Helper_Data::CHARS_LOWERS,
+ );
+ }
+
+ return $randomString;
+ }
+
+ /**
+ * Is current authorize page is simple
+ *
+ * @return bool
+ */
+ protected function _getIsSimple()
+ {
+ $simple = false;
+ if (stristr($this->_getRequest()->getActionName(), 'simple')
+ || !is_null($this->_getRequest()->getParam('simple', null))
+ ) {
+ $simple = true;
+ }
+
+ return $simple;
+ }
}
diff --git a/app/code/core/Mage/Oauth/Model/Consumer.php b/app/code/core/Mage/Oauth/Model/Consumer.php
index e85db94bb2f..488fd980583 100644
--- a/app/code/core/Mage/Oauth/Model/Consumer.php
+++ b/app/code/core/Mage/Oauth/Model/Consumer.php
@@ -51,28 +51,6 @@ class Mage_Oauth_Model_Consumer extends Mage_Core_Model_Abstract
*/
public const SECRET_LENGTH = 32;
- protected function _construct()
- {
- $this->_init('oauth/consumer');
- }
-
- /**
- * BeforeSave actions
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- if (!$this->getId()) {
- $this->setUpdatedAt(time());
- }
- $this->setCallbackUrl(trim($this->getCallbackUrl()));
- $this->setRejectedCallbackUrl(trim($this->getRejectedCallbackUrl()));
- $this->validate();
- parent::_beforeSave();
- return $this;
- }
-
/**
* Validate data
*
@@ -98,4 +76,26 @@ public function validate()
}
return true;
}
+
+ protected function _construct()
+ {
+ $this->_init('oauth/consumer');
+ }
+
+ /**
+ * BeforeSave actions
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ if (!$this->getId()) {
+ $this->setUpdatedAt(time());
+ }
+ $this->setCallbackUrl(trim($this->getCallbackUrl()));
+ $this->setRejectedCallbackUrl(trim($this->getRejectedCallbackUrl()));
+ $this->validate();
+ parent::_beforeSave();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Oauth/Model/Consumer/Validator/KeyLength.php b/app/code/core/Mage/Oauth/Model/Consumer/Validator/KeyLength.php
index 6eac35bccaf..0e211419ca6 100644
--- a/app/code/core/Mage/Oauth/Model/Consumer/Validator/KeyLength.php
+++ b/app/code/core/Mage/Oauth/Model/Consumer/Validator/KeyLength.php
@@ -29,6 +29,17 @@ class Mage_Oauth_Model_Consumer_Validator_KeyLength extends Zend_Validate_String
*/
protected $_name = 'Key';
+ /**
+ * Additional variables available for validation failure messages
+ *
+ * @var array
+ */
+ protected $_messageVariables = [
+ 'min' => '_min',
+ 'max' => '_max',
+ 'name' => '_name',
+ ];
+
/**
* Sets validator options
*
@@ -56,32 +67,6 @@ public function __construct($options = [])
parent::__construct($options);
}
- /**
- * Init validation failure message template definitions
- *
- * @return $this
- */
- protected function _initMessageTemplates()
- {
- $_messageTemplates[self::TOO_LONG] =
- Mage::helper('oauth')->__("%name% '%value%' is too long. It must has length %min% symbols.");
- $_messageTemplates[self::TOO_SHORT] =
- Mage::helper('oauth')->__("%name% '%value%' is too short. It must has length %min% symbols.");
-
- return $this;
- }
-
- /**
- * Additional variables available for validation failure messages
- *
- * @var array
- */
- protected $_messageVariables = [
- 'min' => '_min',
- 'max' => '_max',
- 'name' => '_name',
- ];
-
/**
* Set length
*
@@ -144,4 +129,19 @@ public function getName()
{
return $this->_name;
}
+
+ /**
+ * Init validation failure message template definitions
+ *
+ * @return $this
+ */
+ protected function _initMessageTemplates()
+ {
+ $_messageTemplates[self::TOO_LONG] =
+ Mage::helper('oauth')->__("%name% '%value%' is too long. It must has length %min% symbols.");
+ $_messageTemplates[self::TOO_SHORT] =
+ Mage::helper('oauth')->__("%name% '%value%' is too short. It must has length %min% symbols.");
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Oauth/Model/Observer.php b/app/code/core/Mage/Oauth/Model/Observer.php
index 802c7576e14..957d21ec3fb 100644
--- a/app/code/core/Mage/Oauth/Model/Observer.php
+++ b/app/code/core/Mage/Oauth/Model/Observer.php
@@ -22,16 +22,6 @@
*/
class Mage_Oauth_Model_Observer
{
- /**
- * Retrieve oauth_token param from request
- *
- * @return string|null
- */
- protected function _getOauthToken()
- {
- return Mage::helper('oauth')->getOauthToken();
- }
-
/**
* Redirect customer to callback page after login
*
@@ -89,4 +79,13 @@ public function afterAdminLoginFailed(Varien_Event_Observer $observer)
exit();
}
}
+ /**
+ * Retrieve oauth_token param from request
+ *
+ * @return string|null
+ */
+ protected function _getOauthToken()
+ {
+ return Mage::helper('oauth')->getOauthToken();
+ }
}
diff --git a/app/code/core/Mage/Oauth/Model/Resource/Nonce.php b/app/code/core/Mage/Oauth/Model/Resource/Nonce.php
index 2972d45cfc9..4618a204ab8 100644
--- a/app/code/core/Mage/Oauth/Model/Resource/Nonce.php
+++ b/app/code/core/Mage/Oauth/Model/Resource/Nonce.php
@@ -22,11 +22,6 @@
*/
class Mage_Oauth_Model_Resource_Nonce extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('oauth/nonce', null);
- }
-
/**
* Delete old entries
*
@@ -46,4 +41,8 @@ public function deleteOldEntries($minutes)
return 0;
}
}
+ protected function _construct()
+ {
+ $this->_init('oauth/nonce', null);
+ }
}
diff --git a/app/code/core/Mage/Oauth/Model/Resource/Token.php b/app/code/core/Mage/Oauth/Model/Resource/Token.php
index 9ae8e421fd0..8dc8b632a16 100644
--- a/app/code/core/Mage/Oauth/Model/Resource/Token.php
+++ b/app/code/core/Mage/Oauth/Model/Resource/Token.php
@@ -22,14 +22,6 @@
*/
class Mage_Oauth_Model_Resource_Token extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Initialize resource model
- */
- protected function _construct()
- {
- $this->_init('oauth/token', 'entity_id');
- }
-
/**
* Clean up old authorized tokens for specified consumer-user pairs
*
@@ -81,4 +73,11 @@ public function deleteOldEntries($minutes)
return 0;
}
}
+ /**
+ * Initialize resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('oauth/token', 'entity_id');
+ }
}
diff --git a/app/code/core/Mage/Oauth/Model/Resource/Token/Collection.php b/app/code/core/Mage/Oauth/Model/Resource/Token/Collection.php
index 1b018ade2fc..efa82f46272 100644
--- a/app/code/core/Mage/Oauth/Model/Resource/Token/Collection.php
+++ b/app/code/core/Mage/Oauth/Model/Resource/Token/Collection.php
@@ -22,14 +22,6 @@
*/
class Mage_Oauth_Model_Resource_Token_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Initialize collection model
- */
- protected function _construct()
- {
- $this->_init('oauth/token');
- }
-
/**
* Load collection with consumer data
*
@@ -120,4 +112,11 @@ public function addFilterByRevoked($flag)
$this->addFilter('main_table.revoked', (int) $flag, 'public');
return $this;
}
+ /**
+ * Initialize collection model
+ */
+ protected function _construct()
+ {
+ $this->_init('oauth/token');
+ }
}
diff --git a/app/code/core/Mage/Oauth/Model/Server.php b/app/code/core/Mage/Oauth/Model/Server.php
index 5f5c907f597..d47cb82d04f 100644
--- a/app/code/core/Mage/Oauth/Model/Server.php
+++ b/app/code/core/Mage/Oauth/Model/Server.php
@@ -190,6 +190,145 @@ public function __construct($request = null)
}
}
+ /**
+ * Process request for permanent access token
+ */
+ public function accessToken()
+ {
+ try {
+ $this->_processRequest(self::REQUEST_TOKEN);
+
+ $response = $this->_token->toString();
+ } catch (Exception $e) {
+ $response = $this->reportProblem($e);
+ }
+ $this->_getResponse()->setBody($response);
+ }
+
+ /**
+ * Validate request, authorize token and return it
+ *
+ * @param int $userId Authorization user identifier
+ * @param string $userType Authorization user type
+ * @return Mage_Oauth_Model_Token
+ */
+ public function authorizeToken($userId, $userType)
+ {
+ $token = $this->checkAuthorizeRequest();
+
+ $token->authorize($userId, $userType);
+
+ return $token;
+ }
+
+ /**
+ * Validate request with access token for specified URL
+ *
+ * @return Mage_Oauth_Model_Token
+ */
+ public function checkAccessRequest()
+ {
+ $this->_processRequest(self::REQUEST_RESOURCE);
+
+ return $this->_token;
+ }
+
+ /**
+ * Check authorize request for validity and return token
+ *
+ * @return Mage_Oauth_Model_Token
+ */
+ public function checkAuthorizeRequest()
+ {
+ if (!$this->_request->isGet()) {
+ Mage::throwException('Request is not GET');
+ }
+ $this->_requestType = self::REQUEST_AUTHORIZE;
+
+ $this->_fetchProtocolParamsFromQuery();
+ $this->_initToken();
+
+ return $this->_token;
+ }
+
+ /**
+ * Retrieve array of supported signature methods
+ *
+ * @return array
+ */
+ public static function getSupportedSignatureMethods()
+ {
+ return [self::SIGNATURE_RSA, self::SIGNATURE_HMAC, self::SIGNATURE_PLAIN];
+ }
+
+ /**
+ * Process request for temporary (initiative) token
+ */
+ public function initiateToken()
+ {
+ try {
+ $this->_processRequest(self::REQUEST_INITIATE);
+
+ $response = $this->_token->toString() . '&oauth_callback_confirmed=true';
+ } catch (Exception $e) {
+ $response = $this->reportProblem($e);
+ }
+ $this->_getResponse()->setBody($response);
+ }
+
+ /**
+ * Create response string for problem during request and set HTTP error code
+ *
+ * @param Zend_Controller_Response_Http|null $response OPTIONAL If NULL - will use internal getter
+ * @return string
+ * @throws Zend_Controller_Response_Exception
+ */
+ public function reportProblem(Exception $e, ?Zend_Controller_Response_Http $response = null)
+ {
+ $eMsg = $e->getMessage();
+
+ if ($e instanceof Mage_Oauth_Exception) {
+ $eCode = $e->getCode();
+
+ if (isset($this->_errors[$eCode])) {
+ $errorMsg = $this->_errors[$eCode];
+ $responseCode = $this->_errorsToHttpCode[$eCode];
+ } else {
+ $errorMsg = 'unknown_problem&code=' . $eCode;
+ $responseCode = self::HTTP_INTERNAL_ERROR;
+ }
+ if (self::ERR_PARAMETER_ABSENT == $eCode) {
+ $errorMsg .= '&oauth_parameters_absent=' . $eMsg;
+ } elseif ($eMsg) {
+ $errorMsg .= '&message=' . $eMsg;
+ }
+ } else {
+ $errorMsg = 'internal_error&message=' . ($eMsg ? $eMsg : 'empty_message');
+ $responseCode = self::HTTP_INTERNAL_ERROR;
+ }
+ if (!$response) {
+ $response = $this->_getResponse();
+ }
+ $response->setHttpResponseCode($responseCode);
+
+ return 'oauth_problem=' . $errorMsg;
+ }
+
+ /**
+ * Set response object
+ *
+ * @return $this
+ */
+ public function setResponse(Zend_Controller_Response_Http $response)
+ {
+ $this->_response = $response;
+
+ $this->_response->setHeader(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED, true);
+ $this->_response->setHttpResponseCode(self::HTTP_OK);
+
+ return $this;
+ }
+
/**
* Retrieve protocol and request parameters from request object
*
@@ -564,143 +703,4 @@ protected function _validateVerifierParam()
$this->_throwException('', self::ERR_VERIFIER_INVALID);
}
}
-
- /**
- * Process request for permanent access token
- */
- public function accessToken()
- {
- try {
- $this->_processRequest(self::REQUEST_TOKEN);
-
- $response = $this->_token->toString();
- } catch (Exception $e) {
- $response = $this->reportProblem($e);
- }
- $this->_getResponse()->setBody($response);
- }
-
- /**
- * Validate request, authorize token and return it
- *
- * @param int $userId Authorization user identifier
- * @param string $userType Authorization user type
- * @return Mage_Oauth_Model_Token
- */
- public function authorizeToken($userId, $userType)
- {
- $token = $this->checkAuthorizeRequest();
-
- $token->authorize($userId, $userType);
-
- return $token;
- }
-
- /**
- * Validate request with access token for specified URL
- *
- * @return Mage_Oauth_Model_Token
- */
- public function checkAccessRequest()
- {
- $this->_processRequest(self::REQUEST_RESOURCE);
-
- return $this->_token;
- }
-
- /**
- * Check authorize request for validity and return token
- *
- * @return Mage_Oauth_Model_Token
- */
- public function checkAuthorizeRequest()
- {
- if (!$this->_request->isGet()) {
- Mage::throwException('Request is not GET');
- }
- $this->_requestType = self::REQUEST_AUTHORIZE;
-
- $this->_fetchProtocolParamsFromQuery();
- $this->_initToken();
-
- return $this->_token;
- }
-
- /**
- * Retrieve array of supported signature methods
- *
- * @return array
- */
- public static function getSupportedSignatureMethods()
- {
- return [self::SIGNATURE_RSA, self::SIGNATURE_HMAC, self::SIGNATURE_PLAIN];
- }
-
- /**
- * Process request for temporary (initiative) token
- */
- public function initiateToken()
- {
- try {
- $this->_processRequest(self::REQUEST_INITIATE);
-
- $response = $this->_token->toString() . '&oauth_callback_confirmed=true';
- } catch (Exception $e) {
- $response = $this->reportProblem($e);
- }
- $this->_getResponse()->setBody($response);
- }
-
- /**
- * Create response string for problem during request and set HTTP error code
- *
- * @param Zend_Controller_Response_Http|null $response OPTIONAL If NULL - will use internal getter
- * @return string
- * @throws Zend_Controller_Response_Exception
- */
- public function reportProblem(Exception $e, ?Zend_Controller_Response_Http $response = null)
- {
- $eMsg = $e->getMessage();
-
- if ($e instanceof Mage_Oauth_Exception) {
- $eCode = $e->getCode();
-
- if (isset($this->_errors[$eCode])) {
- $errorMsg = $this->_errors[$eCode];
- $responseCode = $this->_errorsToHttpCode[$eCode];
- } else {
- $errorMsg = 'unknown_problem&code=' . $eCode;
- $responseCode = self::HTTP_INTERNAL_ERROR;
- }
- if (self::ERR_PARAMETER_ABSENT == $eCode) {
- $errorMsg .= '&oauth_parameters_absent=' . $eMsg;
- } elseif ($eMsg) {
- $errorMsg .= '&message=' . $eMsg;
- }
- } else {
- $errorMsg = 'internal_error&message=' . ($eMsg ? $eMsg : 'empty_message');
- $responseCode = self::HTTP_INTERNAL_ERROR;
- }
- if (!$response) {
- $response = $this->_getResponse();
- }
- $response->setHttpResponseCode($responseCode);
-
- return 'oauth_problem=' . $errorMsg;
- }
-
- /**
- * Set response object
- *
- * @return $this
- */
- public function setResponse(Zend_Controller_Response_Http $response)
- {
- $this->_response = $response;
-
- $this->_response->setHeader(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED, true);
- $this->_response->setHttpResponseCode(self::HTTP_OK);
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Oauth/Model/Token.php b/app/code/core/Mage/Oauth/Model/Token.php
index 129c4c67e4c..7c1ab3c85ed 100644
--- a/app/code/core/Mage/Oauth/Model/Token.php
+++ b/app/code/core/Mage/Oauth/Model/Token.php
@@ -69,32 +69,6 @@ class Mage_Oauth_Model_Token extends Mage_Core_Model_Abstract
public const USER_TYPE_ADMIN = 'admin';
public const USER_TYPE_CUSTOMER = 'customer';
- /**
- * Initialize resource model
- */
- protected function _construct()
- {
- $this->_init('oauth/token');
- }
-
- /**
- * "After save" actions
- *
- * @return $this
- */
- protected function _afterSave()
- {
- parent::_afterSave();
-
- //Cleanup old entries
- /** @var Mage_Oauth_Helper_Data $helper */
- $helper = Mage::helper('oauth');
- if ($helper->isCleanupProbability()) {
- $this->_getResource()->deleteOldEntries($helper->getCleanupExpirationPeriod());
- }
- return $this;
- }
-
/**
* Authorize token
*
@@ -202,22 +176,6 @@ public function toString($format = '')
return http_build_query(['oauth_token' => $this->getToken(), 'oauth_token_secret' => $this->getSecret()]);
}
- /**
- * Before save actions
- *
- * @return Mage_Oauth_Model_Token
- */
- protected function _beforeSave()
- {
- $this->validate();
-
- if ($this->isObjectNew() && $this->getCreatedAt() === null) {
- $this->setCreatedAt(Varien_Date::now());
- }
- parent::_beforeSave();
- return $this;
- }
-
/**
* Validate data
*
@@ -281,4 +239,46 @@ public function getConsumer()
return $this->getData('consumer');
}
+
+ /**
+ * Initialize resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('oauth/token');
+ }
+
+ /**
+ * "After save" actions
+ *
+ * @return $this
+ */
+ protected function _afterSave()
+ {
+ parent::_afterSave();
+
+ //Cleanup old entries
+ /** @var Mage_Oauth_Helper_Data $helper */
+ $helper = Mage::helper('oauth');
+ if ($helper->isCleanupProbability()) {
+ $this->_getResource()->deleteOldEntries($helper->getCleanupExpirationPeriod());
+ }
+ return $this;
+ }
+
+ /**
+ * Before save actions
+ *
+ * @return Mage_Oauth_Model_Token
+ */
+ protected function _beforeSave()
+ {
+ $this->validate();
+
+ if ($this->isObjectNew() && $this->getCreatedAt() === null) {
+ $this->setCreatedAt(Varien_Date::now());
+ }
+ parent::_beforeSave();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Oauth/controllers/Adminhtml/Oauth/AuthorizeController.php b/app/code/core/Mage/Oauth/controllers/Adminhtml/Oauth/AuthorizeController.php
index 2f3f5765696..dd40601974a 100644
--- a/app/code/core/Mage/Oauth/controllers/Adminhtml/Oauth/AuthorizeController.php
+++ b/app/code/core/Mage/Oauth/controllers/Adminhtml/Oauth/AuthorizeController.php
@@ -22,19 +22,18 @@
*/
class Mage_Oauth_Adminhtml_Oauth_AuthorizeController extends Mage_Adminhtml_Controller_Action
{
- /**
- * Session name
- *
- * @var string
- */
- protected $_sessionName = 'admin/session';
-
/**
* Array of actions which can be processed without secret key validation
*
* @var array
*/
public $_publicActions = ['index', 'simple', 'confirm', 'confirmSimple','reject', 'rejectSimple'];
+ /**
+ * Session name
+ *
+ * @var string
+ */
+ protected $_sessionName = 'admin/session';
/**
* Disable showing of login form
@@ -90,6 +89,38 @@ public function simpleAction()
$this->renderLayout();
}
+ /**
+ * Confirm token authorization action
+ */
+ public function confirmAction()
+ {
+ $this->_initConfirmPage();
+ }
+
+ /**
+ * Confirm token authorization simple page
+ */
+ public function confirmSimpleAction()
+ {
+ $this->_initConfirmPage();
+ }
+
+ /**
+ * Reject token authorization action
+ */
+ public function rejectAction()
+ {
+ $this->_initRejectPage();
+ }
+
+ /**
+ * Reject token authorization simple page
+ */
+ public function rejectSimpleAction()
+ {
+ $this->_initRejectPage();
+ }
+
/**
* Init authorize page
*
@@ -258,38 +289,6 @@ protected function _checkLoginIsEmpty()
return $error;
}
- /**
- * Confirm token authorization action
- */
- public function confirmAction()
- {
- $this->_initConfirmPage();
- }
-
- /**
- * Confirm token authorization simple page
- */
- public function confirmSimpleAction()
- {
- $this->_initConfirmPage();
- }
-
- /**
- * Reject token authorization action
- */
- public function rejectAction()
- {
- $this->_initRejectPage();
- }
-
- /**
- * Reject token authorization simple page
- */
- public function rejectSimpleAction()
- {
- $this->_initRejectPage();
- }
-
/**
* Check admin permissions for this controller
*
diff --git a/app/code/core/Mage/Oauth/controllers/Adminhtml/Oauth/ConsumerController.php b/app/code/core/Mage/Oauth/controllers/Adminhtml/Oauth/ConsumerController.php
index 2f3cdcc3035..f5d8a0ef990 100644
--- a/app/code/core/Mage/Oauth/controllers/Adminhtml/Oauth/ConsumerController.php
+++ b/app/code/core/Mage/Oauth/controllers/Adminhtml/Oauth/ConsumerController.php
@@ -22,22 +22,6 @@
*/
class Mage_Oauth_Adminhtml_Oauth_ConsumerController extends Mage_Adminhtml_Controller_Action
{
- /**
- * Unset unused data from request
- * Skip getting "key" and "secret" because its generated from server side only
- *
- * @return array
- */
- protected function _filter(array $data)
- {
- foreach (['id', 'back', 'form_key', 'key', 'secret'] as $field) {
- if (isset($data[$field])) {
- unset($data[$field]);
- }
- }
- return $data;
- }
-
/**
* Init titles
*
@@ -227,47 +211,6 @@ public function saveAction()
}
}
- /**
- * @inheritDoc
- */
- protected function _isAllowed()
- {
- $action = $this->getRequest()->getActionName();
- if ($action == 'index') {
- $action = null;
- } else {
- if ($action == 'new' || $action == 'save') {
- $action = 'edit';
- }
- $action = '/' . $action;
- }
- /** @var Mage_Admin_Model_Session $session */
- $session = Mage::getSingleton('admin/session');
- return $session->isAllowed('system/api/oauth_consumer' . $action);
- }
-
- /**
- * Get form data
- *
- * @return array
- */
- protected function _getFormData()
- {
- return $this->_getSession()->getData('consumer_data', true);
- }
-
- /**
- * Set form data
- *
- * @param array $data
- * @return $this
- */
- protected function _setFormData($data)
- {
- $this->_getSession()->setData('consumer_data', $data);
- return $this;
- }
-
/**
* Delete consumer action
*/
@@ -310,4 +253,60 @@ public function deleteAction()
}
$this->_redirect('*/*/index');
}
+ /**
+ * Unset unused data from request
+ * Skip getting "key" and "secret" because its generated from server side only
+ *
+ * @return array
+ */
+ protected function _filter(array $data)
+ {
+ foreach (['id', 'back', 'form_key', 'key', 'secret'] as $field) {
+ if (isset($data[$field])) {
+ unset($data[$field]);
+ }
+ }
+ return $data;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _isAllowed()
+ {
+ $action = $this->getRequest()->getActionName();
+ if ($action == 'index') {
+ $action = null;
+ } else {
+ if ($action == 'new' || $action == 'save') {
+ $action = 'edit';
+ }
+ $action = '/' . $action;
+ }
+ /** @var Mage_Admin_Model_Session $session */
+ $session = Mage::getSingleton('admin/session');
+ return $session->isAllowed('system/api/oauth_consumer' . $action);
+ }
+
+ /**
+ * Get form data
+ *
+ * @return array
+ */
+ protected function _getFormData()
+ {
+ return $this->_getSession()->getData('consumer_data', true);
+ }
+
+ /**
+ * Set form data
+ *
+ * @param array $data
+ * @return $this
+ */
+ protected function _setFormData($data)
+ {
+ $this->_getSession()->setData('consumer_data', $data);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Oauth/controllers/AuthorizeController.php b/app/code/core/Mage/Oauth/controllers/AuthorizeController.php
index 9932e788814..0f9f14875c8 100644
--- a/app/code/core/Mage/Oauth/controllers/AuthorizeController.php
+++ b/app/code/core/Mage/Oauth/controllers/AuthorizeController.php
@@ -29,6 +29,58 @@ class Mage_Oauth_AuthorizeController extends Mage_Core_Controller_Front_Action
*/
protected $_sessionName = 'customer/session';
+ /**
+ * Index action.
+ */
+ public function indexAction()
+ {
+ $this->_initForm();
+ $this->_initLayoutMessages($this->_sessionName);
+ $this->renderLayout();
+ }
+
+ /**
+ * OAuth authorize or allow decline access simple page
+ */
+ public function simpleAction()
+ {
+ $this->_initForm(true);
+ $this->_initLayoutMessages($this->_sessionName);
+ $this->renderLayout();
+ }
+
+ /**
+ * Confirm token authorization action
+ */
+ public function confirmAction()
+ {
+ $this->_initConfirmPage();
+ }
+
+ /**
+ * Confirm token authorization simple page
+ */
+ public function confirmSimpleAction()
+ {
+ $this->_initConfirmPage(true);
+ }
+
+ /**
+ * Reject token authorization action
+ */
+ public function rejectAction()
+ {
+ $this->_initRejectPage();
+ }
+
+ /**
+ * Reject token authorization simple page
+ */
+ public function rejectSimpleAction()
+ {
+ $this->_initRejectPage(true);
+ }
+
/**
* Init authorize page
*
@@ -175,56 +227,4 @@ protected function _initRejectPage($simple = false)
return $this;
}
-
- /**
- * Index action.
- */
- public function indexAction()
- {
- $this->_initForm();
- $this->_initLayoutMessages($this->_sessionName);
- $this->renderLayout();
- }
-
- /**
- * OAuth authorize or allow decline access simple page
- */
- public function simpleAction()
- {
- $this->_initForm(true);
- $this->_initLayoutMessages($this->_sessionName);
- $this->renderLayout();
- }
-
- /**
- * Confirm token authorization action
- */
- public function confirmAction()
- {
- $this->_initConfirmPage();
- }
-
- /**
- * Confirm token authorization simple page
- */
- public function confirmSimpleAction()
- {
- $this->_initConfirmPage(true);
- }
-
- /**
- * Reject token authorization action
- */
- public function rejectAction()
- {
- $this->_initRejectPage();
- }
-
- /**
- * Reject token authorization simple page
- */
- public function rejectSimpleAction()
- {
- $this->_initRejectPage(true);
- }
}
diff --git a/app/code/core/Mage/Oauth/controllers/Customer/TokenController.php b/app/code/core/Mage/Oauth/controllers/Customer/TokenController.php
index c4a6915966d..7317563a38f 100644
--- a/app/code/core/Mage/Oauth/controllers/Customer/TokenController.php
+++ b/app/code/core/Mage/Oauth/controllers/Customer/TokenController.php
@@ -65,21 +65,6 @@ public function indexAction()
$this->renderLayout();
}
- /**
- * Redirect to referrer URL or otherwise to index page without params
- *
- * @return $this
- */
- protected function _redirectBack()
- {
- $url = $this->_getRefererUrl();
- if (Mage::app()->getStore()->getBaseUrl() == $url) {
- $url = Mage::getUrl('*/*/index');
- }
- $this->_redirectUrl($url);
- return $this;
- }
-
/**
* Update revoke status action
*/
@@ -177,4 +162,19 @@ public function deleteAction()
}
$this->_redirectBack();
}
+
+ /**
+ * Redirect to referrer URL or otherwise to index page without params
+ *
+ * @return $this
+ */
+ protected function _redirectBack()
+ {
+ $url = $this->_getRefererUrl();
+ if (Mage::app()->getStore()->getBaseUrl() == $url) {
+ $url = Mage::getUrl('*/*/index');
+ }
+ $this->_redirectUrl($url);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Page/Block/Html/Footer.php b/app/code/core/Mage/Page/Block/Html/Footer.php
index 56f50d9df3e..77a9bb17824 100644
--- a/app/code/core/Mage/Page/Block/Html/Footer.php
+++ b/app/code/core/Mage/Page/Block/Html/Footer.php
@@ -27,15 +27,6 @@ class Mage_Page_Block_Html_Footer extends Mage_Core_Block_Template
*/
protected $_copyright;
- protected function _construct()
- {
- $this->addData(['cache_lifetime' => false]);
- $this->addCacheTag([
- Mage_Core_Model_Store::CACHE_TAG,
- Mage_Cms_Model_Block::CACHE_TAG,
- ]);
- }
-
/**
* Get cache key informative items
*
@@ -87,4 +78,13 @@ public function getChildHtml($name = '', $useCache = true, $sorted = true)
{
return parent::getChildHtml($name, $useCache, $sorted);
}
+
+ protected function _construct()
+ {
+ $this->addData(['cache_lifetime' => false]);
+ $this->addCacheTag([
+ Mage_Core_Model_Store::CACHE_TAG,
+ Mage_Cms_Model_Block::CACHE_TAG,
+ ]);
+ }
}
diff --git a/app/code/core/Mage/Page/Block/Html/Head.php b/app/code/core/Mage/Page/Block/Html/Head.php
index 79e4b285865..45e163e5360 100644
--- a/app/code/core/Mage/Page/Block/Html/Head.php
+++ b/app/code/core/Mage/Page/Block/Html/Head.php
@@ -27,15 +27,6 @@
*/
class Mage_Page_Block_Html_Head extends Mage_Core_Block_Template
{
- /**
- * Initialize template
- *
- */
- protected function _construct()
- {
- $this->setTemplate('page/html/head.phtml');
- }
-
/**
* Add CSS file to HEAD entity
*
@@ -241,105 +232,6 @@ public function getCssJsHtml()
return $html;
}
- /**
- * Merge static and skin files of the same format into 1 set of HEAD directives or even into 1 directive
- *
- * Will attempt to merge into 1 directive, if merging callback is provided. In this case it will generate
- * filenames, rather than render urls.
- * The merger callback is responsible for checking whether files exist, merging them and giving result URL
- *
- * @param string $format - HTML element format for sprintf('', $src, $params)
- * @param array $staticItems - array of relative names of static items to be grabbed from js/ folder
- * @param array $skinItems - array of relative names of skin items to be found in skins according to design config
- * @param callable $mergeCallback
- * @return string
- */
- protected function &_prepareStaticAndSkinElements($format, array $staticItems, array $skinItems, $mergeCallback = null)
- {
- $designPackage = Mage::getDesign();
- $baseJsUrl = Mage::getBaseUrl('js');
- $items = [];
- if ($mergeCallback && !is_callable($mergeCallback)) {
- $mergeCallback = null;
- }
-
- // get static files from the js folder, no need in lookups
- foreach ($staticItems as $params => $rows) {
- foreach ($rows as $name) {
- $items[$params][] = $mergeCallback ? Mage::getBaseDir() . DS . 'js' . DS . $name : $baseJsUrl . $name;
- }
- }
-
- // lookup each file basing on current theme configuration
- foreach ($skinItems as $params => $rows) {
- foreach ($rows as $name) {
- $items[$params][] = $mergeCallback ? $designPackage->getFilename($name, ['_type' => 'skin'])
- : $designPackage->getSkinUrl($name, []);
- }
- }
-
- $html = '';
- foreach ($items as $params => $rows) {
- // attempt to merge
- $mergedUrl = false;
- if ($mergeCallback) {
- $mergedUrl = call_user_func($mergeCallback, $rows);
- }
- // render elements
- $params = trim($params);
- $params = $params ? ' ' . $params : '';
- if ($mergedUrl) {
- $html .= sprintf($format, $mergedUrl, $params);
- } else {
- foreach ($rows as $src) {
- $html .= sprintf($format, $src, $params);
- }
- }
- }
- return $html;
- }
-
- /**
- * Classify HTML head item and queue it into "lines" array
- *
- * @see self::getCssJsHtml()
- * @param array $lines
- * @param string $itemIf
- * @param string $itemType
- * @param string $itemParams
- * @param string $itemName
- * @param array $itemThe
- */
- protected function _separateOtherHtmlHeadElements(&$lines, $itemIf, $itemType, $itemParams, $itemName, $itemThe)
- {
- $params = $itemParams ? ' ' . $itemParams : '';
- $href = $itemName;
- switch ($itemType) {
- case 'rss':
- $lines[$itemIf]['other'][] = sprintf(
- '',
- $href,
- $params,
- );
- break;
- case 'link_rel':
- $lines[$itemIf]['other'][] = sprintf('', $params, $href);
- break;
- }
- }
-
- /**
- * Render arbitrary HTML head items
- *
- * @see self::getCssJsHtml()
- * @param array $items
- * @return string
- */
- protected function _prepareOtherHtmlHeadElements($items)
- {
- return implode(PHP_EOL, $items);
- }
-
/**
* Retrieve Chunked Items
*
@@ -502,6 +394,113 @@ public function getFaviconFile()
}
return $this->_data['favicon_file'];
}
+ /**
+ * Initialize template
+ *
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('page/html/head.phtml');
+ }
+
+ /**
+ * Merge static and skin files of the same format into 1 set of HEAD directives or even into 1 directive
+ *
+ * Will attempt to merge into 1 directive, if merging callback is provided. In this case it will generate
+ * filenames, rather than render urls.
+ * The merger callback is responsible for checking whether files exist, merging them and giving result URL
+ *
+ * @param string $format - HTML element format for sprintf('', $src, $params)
+ * @param array $staticItems - array of relative names of static items to be grabbed from js/ folder
+ * @param array $skinItems - array of relative names of skin items to be found in skins according to design config
+ * @param callable $mergeCallback
+ * @return string
+ */
+ protected function &_prepareStaticAndSkinElements($format, array $staticItems, array $skinItems, $mergeCallback = null)
+ {
+ $designPackage = Mage::getDesign();
+ $baseJsUrl = Mage::getBaseUrl('js');
+ $items = [];
+ if ($mergeCallback && !is_callable($mergeCallback)) {
+ $mergeCallback = null;
+ }
+
+ // get static files from the js folder, no need in lookups
+ foreach ($staticItems as $params => $rows) {
+ foreach ($rows as $name) {
+ $items[$params][] = $mergeCallback ? Mage::getBaseDir() . DS . 'js' . DS . $name : $baseJsUrl . $name;
+ }
+ }
+
+ // lookup each file basing on current theme configuration
+ foreach ($skinItems as $params => $rows) {
+ foreach ($rows as $name) {
+ $items[$params][] = $mergeCallback ? $designPackage->getFilename($name, ['_type' => 'skin'])
+ : $designPackage->getSkinUrl($name, []);
+ }
+ }
+
+ $html = '';
+ foreach ($items as $params => $rows) {
+ // attempt to merge
+ $mergedUrl = false;
+ if ($mergeCallback) {
+ $mergedUrl = call_user_func($mergeCallback, $rows);
+ }
+ // render elements
+ $params = trim($params);
+ $params = $params ? ' ' . $params : '';
+ if ($mergedUrl) {
+ $html .= sprintf($format, $mergedUrl, $params);
+ } else {
+ foreach ($rows as $src) {
+ $html .= sprintf($format, $src, $params);
+ }
+ }
+ }
+ return $html;
+ }
+
+ /**
+ * Classify HTML head item and queue it into "lines" array
+ *
+ * @see self::getCssJsHtml()
+ * @param array $lines
+ * @param string $itemIf
+ * @param string $itemType
+ * @param string $itemParams
+ * @param string $itemName
+ * @param array $itemThe
+ */
+ protected function _separateOtherHtmlHeadElements(&$lines, $itemIf, $itemType, $itemParams, $itemName, $itemThe)
+ {
+ $params = $itemParams ? ' ' . $itemParams : '';
+ $href = $itemName;
+ switch ($itemType) {
+ case 'rss':
+ $lines[$itemIf]['other'][] = sprintf(
+ '',
+ $href,
+ $params,
+ );
+ break;
+ case 'link_rel':
+ $lines[$itemIf]['other'][] = sprintf('', $params, $href);
+ break;
+ }
+ }
+
+ /**
+ * Render arbitrary HTML head items
+ *
+ * @see self::getCssJsHtml()
+ * @param array $items
+ * @return string
+ */
+ protected function _prepareOtherHtmlHeadElements($items)
+ {
+ return implode(PHP_EOL, $items);
+ }
/**
* Retrieve path to Favicon
diff --git a/app/code/core/Mage/Page/Block/Html/Pager.php b/app/code/core/Mage/Page/Block/Html/Pager.php
index 43054d081e6..88ce5f5eae4 100644
--- a/app/code/core/Mage/Page/Block/Html/Pager.php
+++ b/app/code/core/Mage/Page/Block/Html/Pager.php
@@ -63,14 +63,6 @@ class Mage_Page_Block_Html_Pager extends Mage_Core_Block_Template
*/
protected $_frameEnd;
- protected function _construct()
- {
- parent::_construct();
- $this->setData('show_amounts', true);
- $this->setData('use_container', true);
- $this->setTemplate('page/html/pager.phtml');
- }
-
/**
* Return current page
*
@@ -565,6 +557,56 @@ public function canShowNextJump()
return $this->getNextJumpPage() !== null;
}
+ /**
+ * Check if frame data was initialized
+ *
+ * @return bool
+ */
+ public function isFrameInitialized()
+ {
+ return $this->_frameInitialized;
+ }
+
+ /**
+ * Getter for alternative text for Previous link in pagination frame
+ *
+ * @return string
+ */
+ public function getAnchorTextForPrevious()
+ {
+ return Mage::getStoreConfig('design/pagination/anchor_text_for_previous');
+ }
+
+ /**
+ * Getter for alternative text for Next link in pagination frame
+ *
+ * @return string
+ */
+ public function getAnchorTextForNext()
+ {
+ return Mage::getStoreConfig('design/pagination/anchor_text_for_next');
+ }
+
+ /**
+ * Set whether output of the pager is mandatory
+ *
+ * @param bool $isRequired
+ * @return $this
+ */
+ public function setIsOutputRequired($isRequired)
+ {
+ $this->_outputRequired = (bool) $isRequired;
+ return $this;
+ }
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setData('show_amounts', true);
+ $this->setData('use_container', true);
+ $this->setTemplate('page/html/pager.phtml');
+ }
+
/**
* Initialize frame data, such as frame start, frame start etc.
*
@@ -616,48 +658,6 @@ protected function _setFrameInitialized($flag)
return $this;
}
- /**
- * Check if frame data was initialized
- *
- * @return bool
- */
- public function isFrameInitialized()
- {
- return $this->_frameInitialized;
- }
-
- /**
- * Getter for alternative text for Previous link in pagination frame
- *
- * @return string
- */
- public function getAnchorTextForPrevious()
- {
- return Mage::getStoreConfig('design/pagination/anchor_text_for_previous');
- }
-
- /**
- * Getter for alternative text for Next link in pagination frame
- *
- * @return string
- */
- public function getAnchorTextForNext()
- {
- return Mage::getStoreConfig('design/pagination/anchor_text_for_next');
- }
-
- /**
- * Set whether output of the pager is mandatory
- *
- * @param bool $isRequired
- * @return $this
- */
- public function setIsOutputRequired($isRequired)
- {
- $this->_outputRequired = (bool) $isRequired;
- return $this;
- }
-
/**
* Determine whether the pagination should be eventually rendered
*
diff --git a/app/code/core/Mage/Page/Block/Html/Topmenu.php b/app/code/core/Mage/Page/Block/Html/Topmenu.php
index 0ab1ddd6716..e542138b33c 100644
--- a/app/code/core/Mage/Page/Block/Html/Topmenu.php
+++ b/app/code/core/Mage/Page/Block/Html/Topmenu.php
@@ -81,6 +81,49 @@ public function getHtml($outermostClass = '', $childrenWrapClass = '')
return $html;
}
+ /**
+ * Retrieve cache key data
+ *
+ * @return array
+ */
+ public function getCacheKeyInfo()
+ {
+ $shortCacheId = [
+ 'TOPMENU',
+ Mage::app()->getStore()->getId(),
+ Mage::getDesign()->getPackageName(),
+ Mage::getDesign()->getTheme('template'),
+ Mage::getSingleton('customer/session')->getCustomerGroupId(),
+ 'template' => $this->getTemplate(),
+ 'name' => $this->getNameInLayout(),
+ $this->getCurrentEntityKey(),
+ ];
+ $cacheId = $shortCacheId;
+
+ $shortCacheId = array_values($shortCacheId);
+ $shortCacheId = implode('|', $shortCacheId);
+ $shortCacheId = md5($shortCacheId);
+
+ $cacheId['entity_key'] = $this->getCurrentEntityKey();
+ $cacheId['short_cache_id'] = $shortCacheId;
+
+ return $cacheId;
+ }
+
+ /**
+ * Retrieve current entity key
+ *
+ * @return int|string
+ */
+ public function getCurrentEntityKey()
+ {
+ if ($this->_currentEntityKey === null) {
+ $this->_currentEntityKey = Mage::registry('current_entity_key')
+ ? Mage::registry('current_entity_key') : Mage::app()->getStore()->getRootCategoryId();
+ }
+ return $this->_currentEntityKey;
+ }
+
/**
* Recursively generates top menu html from data that is specified in $menuTree
*
@@ -204,47 +247,4 @@ protected function _getMenuItemClasses(Varien_Data_Tree_Node $item)
return $classes;
}
-
- /**
- * Retrieve cache key data
- *
- * @return array
- */
- public function getCacheKeyInfo()
- {
- $shortCacheId = [
- 'TOPMENU',
- Mage::app()->getStore()->getId(),
- Mage::getDesign()->getPackageName(),
- Mage::getDesign()->getTheme('template'),
- Mage::getSingleton('customer/session')->getCustomerGroupId(),
- 'template' => $this->getTemplate(),
- 'name' => $this->getNameInLayout(),
- $this->getCurrentEntityKey(),
- ];
- $cacheId = $shortCacheId;
-
- $shortCacheId = array_values($shortCacheId);
- $shortCacheId = implode('|', $shortCacheId);
- $shortCacheId = md5($shortCacheId);
-
- $cacheId['entity_key'] = $this->getCurrentEntityKey();
- $cacheId['short_cache_id'] = $shortCacheId;
-
- return $cacheId;
- }
-
- /**
- * Retrieve current entity key
- *
- * @return int|string
- */
- public function getCurrentEntityKey()
- {
- if ($this->_currentEntityKey === null) {
- $this->_currentEntityKey = Mage::registry('current_entity_key')
- ? Mage::registry('current_entity_key') : Mage::app()->getStore()->getRootCategoryId();
- }
- return $this->_currentEntityKey;
- }
}
diff --git a/app/code/core/Mage/Page/Block/Html/Topmenu/Renderer.php b/app/code/core/Mage/Page/Block/Html/Topmenu/Renderer.php
index 3f930560b86..733841c6931 100644
--- a/app/code/core/Mage/Page/Block/Html/Topmenu/Renderer.php
+++ b/app/code/core/Mage/Page/Block/Html/Topmenu/Renderer.php
@@ -27,6 +27,24 @@ class Mage_Page_Block_Html_Topmenu_Renderer extends Mage_Page_Block_Html_Topmenu
{
protected $_templateFile;
+ /**
+ * Fetches template. If template has return statement, than its value is used and direct output otherwise.
+ * @param string $childrenWrapClass
+ * @return string
+ */
+ public function render(Varien_Data_Tree_Node $menuTree, $childrenWrapClass)
+ {
+ ob_start();
+ $html = include $this->_templateFile;
+ $directOutput = ob_get_clean();
+
+ if (is_string($html)) {
+ return $html;
+ } else {
+ return $directOutput;
+ }
+ }
+
/**
* Renders block html
* @return string
@@ -60,22 +78,4 @@ protected function _addCacheTags()
$this->addCacheTag($parentBlock->getCacheTags());
}
}
-
- /**
- * Fetches template. If template has return statement, than its value is used and direct output otherwise.
- * @param string $childrenWrapClass
- * @return string
- */
- public function render(Varien_Data_Tree_Node $menuTree, $childrenWrapClass)
- {
- ob_start();
- $html = include $this->_templateFile;
- $directOutput = ob_get_clean();
-
- if (is_string($html)) {
- return $html;
- } else {
- return $directOutput;
- }
- }
}
diff --git a/app/code/core/Mage/Page/Block/Html/Welcome.php b/app/code/core/Mage/Page/Block/Html/Welcome.php
index 43e644a22fe..b2cd9a4087c 100644
--- a/app/code/core/Mage/Page/Block/Html/Welcome.php
+++ b/app/code/core/Mage/Page/Block/Html/Welcome.php
@@ -24,6 +24,19 @@
*/
class Mage_Page_Block_Html_Welcome extends Mage_Core_Block_Template
{
+ /**
+ * Get tags array for saving cache
+ *
+ * @return array
+ */
+ public function getCacheTags()
+ {
+ if ($this->_getSession()->isLoggedIn()) {
+ $this->addModelTags($this->_getSession()->getCustomer());
+ }
+
+ return parent::getCacheTags();
+ }
/**
* Get customer session
*
@@ -51,18 +64,4 @@ protected function _toHtml()
return $this->_data['welcome'];
}
-
- /**
- * Get tags array for saving cache
- *
- * @return array
- */
- public function getCacheTags()
- {
- if ($this->_getSession()->isLoggedIn()) {
- $this->addModelTags($this->_getSession()->getCustomer());
- }
-
- return parent::getCacheTags();
- }
}
diff --git a/app/code/core/Mage/Page/Block/Html/Wrapper.php b/app/code/core/Mage/Page/Block/Html/Wrapper.php
index e6b37dd27dc..a8e1e49d806 100644
--- a/app/code/core/Mage/Page/Block/Html/Wrapper.php
+++ b/app/code/core/Mage/Page/Block/Html/Wrapper.php
@@ -36,6 +36,27 @@ class Mage_Page_Block_Html_Wrapper extends Mage_Core_Block_Abstract
*/
protected $_dependsOnChildren = true;
+ /**
+ * Wrapper element tag name getter
+ * @return string
+ */
+ public function getElementTagName()
+ {
+ $tagName = $this->_getData('html_tag_name');
+ return $tagName ? $tagName : 'div';
+ }
+
+ /**
+ * Setter whether this block depends on children
+ * @param string $depends
+ * @return $this
+ */
+ public function dependsOnChildren($depends = '0')
+ {
+ $this->_dependsOnChildren = (bool) (int) $depends;
+ return $this;
+ }
+
/**
* Render the wrapper element html
* Supports different optional parameters, set in data by keys:
@@ -63,27 +84,6 @@ protected function _toHtml()
return sprintf('<%1$s%2$s%3$s%4$s>%5$s%1$s>', $this->getElementTagName(), $id, $class, $otherParams, $html);
}
- /**
- * Wrapper element tag name getter
- * @return string
- */
- public function getElementTagName()
- {
- $tagName = $this->_getData('html_tag_name');
- return $tagName ? $tagName : 'div';
- }
-
- /**
- * Setter whether this block depends on children
- * @param string $depends
- * @return $this
- */
- public function dependsOnChildren($depends = '0')
- {
- $this->_dependsOnChildren = (bool) (int) $depends;
- return $this;
- }
-
/**
* Whether the wrapper element should be eventually rendered
* If it becomes "invisible", the behaviour will be somewhat similar to core/text_list
diff --git a/app/code/core/Mage/Page/Block/Template/Links.php b/app/code/core/Mage/Page/Block/Template/Links.php
index 01b4cc5ee51..9859c20a205 100644
--- a/app/code/core/Mage/Page/Block/Template/Links.php
+++ b/app/code/core/Mage/Page/Block/Template/Links.php
@@ -36,15 +36,6 @@ class Mage_Page_Block_Template_Links extends Mage_Core_Block_Template
*/
protected $_cacheKeyInfo = null;
- /**
- * Set default template
- *
- */
- protected function _construct()
- {
- $this->setTemplate('page/template/links.phtml');
- }
-
/**
* Get all links
*
@@ -101,24 +92,6 @@ public function addLink(
return $this;
}
- /**
- * Add link into collection
- *
- * @param Varien_Object $link
- * @param int $position
- * @return $this
- */
- protected function _addIntoPosition($link, $position)
- {
- $this->_links[$this->_getNewPosition($position)] = $link;
-
- if ((int) $position > 0) {
- ksort($this->_links);
- }
-
- return $this;
- }
-
/**
* Add block to link list
*
@@ -194,6 +167,47 @@ public function getCacheKeyInfo()
return $this->_cacheKeyInfo;
}
+ /**
+ * Get tags array for saving cache
+ *
+ * @return array
+ */
+ public function getCacheTags()
+ {
+ if (Mage::getSingleton('customer/session')->isLoggedIn()) {
+ $this->addModelTags(Mage::getSingleton('customer/session')->getCustomer());
+ }
+
+ return parent::getCacheTags();
+ }
+
+ /**
+ * Set default template
+ *
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('page/template/links.phtml');
+ }
+
+ /**
+ * Add link into collection
+ *
+ * @param Varien_Object $link
+ * @param int $position
+ * @return $this
+ */
+ protected function _addIntoPosition($link, $position)
+ {
+ $this->_links[$this->_getNewPosition($position)] = $link;
+
+ if ((int) $position > 0) {
+ ksort($this->_links);
+ }
+
+ return $this;
+ }
+
/**
* Prepare tag attributes
*
@@ -251,18 +265,4 @@ protected function _getNewPosition($position = 0)
}
return $position;
}
-
- /**
- * Get tags array for saving cache
- *
- * @return array
- */
- public function getCacheTags()
- {
- if (Mage::getSingleton('customer/session')->isLoggedIn()) {
- $this->addModelTags(Mage::getSingleton('customer/session')->getCustomer());
- }
-
- return parent::getCacheTags();
- }
}
diff --git a/app/code/core/Mage/Page/Block/Template/Links/Block.php b/app/code/core/Mage/Page/Block/Template/Links/Block.php
index 3fe5c720caa..248128cf081 100644
--- a/app/code/core/Mage/Page/Block/Template/Links/Block.php
+++ b/app/code/core/Mage/Page/Block/Template/Links/Block.php
@@ -91,15 +91,6 @@ class Mage_Page_Block_Template_Links_Block extends Mage_Core_Block_Template
*/
protected $_position = 0;
- /**
- * Set default template
- *
- */
- protected function _construct()
- {
- $this->setTemplate('page/template/linksblock.phtml');
- }
-
/**
* Return link position in link list
*
@@ -186,26 +177,6 @@ public function getLinkUrl()
return $this->_url;
}
- /**
- * Prepare tag attributes
- *
- * @param string|array $params
- * @return string
- */
- protected function _prepareParams($params)
- {
- if (is_string($params)) {
- return $params;
- } elseif (is_array($params)) {
- $result = '';
- foreach ($params as $key => $value) {
- $result .= ' ' . $key . '="' . addslashes($value) . '"';
- }
- return $result;
- }
- return '';
- }
-
/**
* Return Li Params
*
@@ -225,4 +196,33 @@ public function getAParams()
{
return $this->_prepareParams($this->_aParams);
}
+
+ /**
+ * Set default template
+ *
+ */
+ protected function _construct()
+ {
+ $this->setTemplate('page/template/linksblock.phtml');
+ }
+
+ /**
+ * Prepare tag attributes
+ *
+ * @param string|array $params
+ * @return string
+ */
+ protected function _prepareParams($params)
+ {
+ if (is_string($params)) {
+ return $params;
+ } elseif (is_array($params)) {
+ $result = '';
+ foreach ($params as $key => $value) {
+ $result .= ' ' . $key . '="' . addslashes($value) . '"';
+ }
+ return $result;
+ }
+ return '';
+ }
}
diff --git a/app/code/core/Mage/Page/Model/Config.php b/app/code/core/Mage/Page/Model/Config.php
index 70095187c24..a485dd952bc 100644
--- a/app/code/core/Mage/Page/Model/Config.php
+++ b/app/code/core/Mage/Page/Model/Config.php
@@ -32,6 +32,46 @@ class Mage_Page_Model_Config
*/
protected $_pageLayouts = null;
+ /**
+ * Retrieve available page layouts
+ *
+ * @return array
+ */
+ public function getPageLayouts()
+ {
+ $this->_initPageLayouts();
+ return $this->_pageLayouts;
+ }
+
+ /**
+ * Retrieve page layout by code
+ *
+ * @param string $layoutCode
+ * @return Varien_Object|false
+ */
+ public function getPageLayout($layoutCode)
+ {
+ $this->_initPageLayouts();
+
+ return $this->_pageLayouts[$layoutCode] ?? false;
+ }
+
+ /**
+ * Retrieve page layout handles
+ *
+ * @return array
+ */
+ public function getPageLayoutHandles()
+ {
+ $handles = [];
+
+ foreach ($this->getPageLayouts() as $layout) {
+ $handles[$layout->getCode()] = $layout->getLayoutHandle();
+ }
+
+ return $handles;
+ }
+
/**
* Initialize page layouts list
*
@@ -72,44 +112,4 @@ protected function _appendPageLayouts($xmlPath)
}
return $this;
}
-
- /**
- * Retrieve available page layouts
- *
- * @return array
- */
- public function getPageLayouts()
- {
- $this->_initPageLayouts();
- return $this->_pageLayouts;
- }
-
- /**
- * Retrieve page layout by code
- *
- * @param string $layoutCode
- * @return Varien_Object|false
- */
- public function getPageLayout($layoutCode)
- {
- $this->_initPageLayouts();
-
- return $this->_pageLayouts[$layoutCode] ?? false;
- }
-
- /**
- * Retrieve page layout handles
- *
- * @return array
- */
- public function getPageLayoutHandles()
- {
- $handles = [];
-
- foreach ($this->getPageLayouts() as $layout) {
- $handles[$layout->getCode()] = $layout->getLayoutHandle();
- }
-
- return $handles;
- }
}
diff --git a/app/code/core/Mage/Paygate/Block/Authorizenet/Form/Cc.php b/app/code/core/Mage/Paygate/Block/Authorizenet/Form/Cc.php
index 002b79726cc..7b743085c31 100644
--- a/app/code/core/Mage/Paygate/Block/Authorizenet/Form/Cc.php
+++ b/app/code/core/Mage/Paygate/Block/Authorizenet/Form/Cc.php
@@ -20,15 +20,6 @@
*/
class Mage_Paygate_Block_Authorizenet_Form_Cc extends Mage_Payment_Block_Form
{
- /**
- * Set block template
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('paygate/form/cc.phtml');
- }
-
/**
* Retrieve payment method form html
*
@@ -74,18 +65,6 @@ public function getAdminCancelUrl()
return Mage::getModel('adminhtml/url')->getUrl('adminhtml/paygate_authorizenet_payment/cancel');
}
- /**
- * Render block HTML
- *
- * @return string
- */
- protected function _toHtml()
- {
- $this->setChild('cards', $this->getCardsBlock());
- $this->setChild('method_form_block', $this->getMethodFormBlock());
- return parent::_toHtml();
- }
-
/**
* Get notice message
*
@@ -177,4 +156,24 @@ public function getCancelButtonHtml()
]);
return $cancelButton->toHtml();
}
+ /**
+ * Set block template
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('paygate/form/cc.phtml');
+ }
+
+ /**
+ * Render block HTML
+ *
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ $this->setChild('cards', $this->getCardsBlock());
+ $this->setChild('method_form_block', $this->getMethodFormBlock());
+ return parent::_toHtml();
+ }
}
diff --git a/app/code/core/Mage/Paygate/Block/Authorizenet/Info/Cc.php b/app/code/core/Mage/Paygate/Block/Authorizenet/Info/Cc.php
index 6f210445dbf..510fffdef24 100644
--- a/app/code/core/Mage/Paygate/Block/Authorizenet/Info/Cc.php
+++ b/app/code/core/Mage/Paygate/Block/Authorizenet/Info/Cc.php
@@ -26,14 +26,6 @@ class Mage_Paygate_Block_Authorizenet_Info_Cc extends Mage_Payment_Block_Info_Cc
* @var bool
*/
protected $_isCheckoutProgressBlockFlag = true;
- /**
- * Set block template
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('paygate/info/cc.phtml');
- }
/**
* Render as PDF
@@ -105,4 +97,12 @@ public function getCards()
}
return $cards;
}
+ /**
+ * Set block template
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('paygate/info/cc.phtml');
+ }
}
diff --git a/app/code/core/Mage/Paygate/Model/Authorizenet.php b/app/code/core/Mage/Paygate/Model/Authorizenet.php
index 59459bd07c1..d8e315993a4 100644
--- a/app/code/core/Mage/Paygate/Model/Authorizenet.php
+++ b/app/code/core/Mage/Paygate/Model/Authorizenet.php
@@ -487,6 +487,110 @@ public function cancelPartialAuthorization(Mage_Payment_Model_Info $payment)
}
}
+ /**
+ * Return cards storage model
+ *
+ * @param Mage_Payment_Model_Info $payment
+ * @return Mage_Paygate_Model_Authorizenet_Cards
+ */
+ public function getCardsStorage($payment = null)
+ {
+ if (is_null($payment)) {
+ $payment = $this->getInfoInstance();
+ }
+ if (is_null($this->_cardsStorage)) {
+ $this->_initCardsStorage($payment);
+ }
+ return $this->_cardsStorage;
+ }
+
+ /**
+ * If partial authorization is started method will return true
+ *
+ * @param Mage_Payment_Model_Info $payment
+ * @return bool
+ */
+ public function isPartialAuthorization($payment = null)
+ {
+ if (is_null($payment)) {
+ $payment = $this->getInfoInstance();
+ }
+ return $payment->getAdditionalInformation($this->_splitTenderIdKey);
+ }
+
+ /**
+ * Mock capture transaction id in invoice
+ *
+ * @param Mage_Sales_Model_Order_Invoice $invoice
+ * @param Mage_Sales_Model_Order_Payment $payment
+ * @return Mage_Payment_Model_Method_Abstract
+ */
+ public function processInvoice($invoice, $payment)
+ {
+ $invoice->setTransactionId(1);
+ return $this;
+ }
+
+ /**
+ * Set transaction ID into creditmemo for informational purposes
+ * @param Mage_Sales_Model_Order_Creditmemo $creditmemo
+ * @param Mage_Sales_Model_Order_Payment $payment
+ * @return Mage_Payment_Model_Method_Abstract
+ */
+ public function processCreditmemo($creditmemo, $payment)
+ {
+ $creditmemo->setTransactionId(1);
+ return $this;
+ }
+
+ /**
+ * Fetch transaction details info
+ *
+ * Update transaction info if there is one placing transaction only
+ *
+ * @param string $transactionId
+ * @return array
+ */
+ public function fetchTransactionInfo(Mage_Payment_Model_Info $payment, $transactionId)
+ {
+ $data = parent::fetchTransactionInfo($payment, $transactionId);
+ $cardsStorage = $this->getCardsStorage($payment);
+
+ if ($cardsStorage->getCardsCount() != 1) {
+ return $data;
+ }
+ $cards = $cardsStorage->getCards();
+ $card = array_shift($cards);
+
+ /*
+ * We need try to get transaction from Mage::registry,
+ * because in cases when fetch calling from Mage_Adminhtml_Sales_TransactionsController::fetchAction()
+ * this line "$transaction = $payment->getTransaction($transactionId)" loads a fetching transaction into a new object,
+ * so some changes (for ex. $transaction->setAdditionalInformation($this->_isTransactionFraud, false) ) will not saved,
+ * because controller have another object for this transaction and Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS isn't includes _isTransactionFraud flag.
+ */
+ $transaction = Mage::registry('current_transaction');
+ if (is_null($transaction)) {
+ //this is for payment info update:
+ $transactionId = $card->getLastTransId();
+ $transaction = $payment->getTransaction($transactionId);
+ }
+ //because in child transaction, the txn_id spoils by added additional word (@see $this->_preauthorizeCaptureCardTransaction()):
+ if (empty($transactionId) || $transaction->getParentId()) {
+ $transactionId = $transaction->getAdditionalInformation($this->_realTransactionIdKey);
+ }
+ $response = $this->_getTransactionDetails($transactionId);
+ $data = array_merge($data, $response->getData());
+
+ if ($response->getResponseCode() == self::RESPONSE_CODE_APPROVED) {
+ $transaction->setAdditionalInformation($this->_isTransactionFraud, false);
+ $payment->setIsTransactionApproved(true);
+ } elseif ($response->getResponseReasonCode() == self::RESPONSE_REASON_CODE_PENDING_REVIEW_DECLINED) {
+ $payment->setIsTransactionDenied(true);
+ }
+ return $data;
+ }
+
/**
* Send request with new payment to gateway
*
@@ -993,110 +1097,6 @@ protected function _initCardsStorage($payment)
$this->_cardsStorage = Mage::getModel('paygate/authorizenet_cards')->setPayment($payment);
}
- /**
- * Return cards storage model
- *
- * @param Mage_Payment_Model_Info $payment
- * @return Mage_Paygate_Model_Authorizenet_Cards
- */
- public function getCardsStorage($payment = null)
- {
- if (is_null($payment)) {
- $payment = $this->getInfoInstance();
- }
- if (is_null($this->_cardsStorage)) {
- $this->_initCardsStorage($payment);
- }
- return $this->_cardsStorage;
- }
-
- /**
- * If partial authorization is started method will return true
- *
- * @param Mage_Payment_Model_Info $payment
- * @return bool
- */
- public function isPartialAuthorization($payment = null)
- {
- if (is_null($payment)) {
- $payment = $this->getInfoInstance();
- }
- return $payment->getAdditionalInformation($this->_splitTenderIdKey);
- }
-
- /**
- * Mock capture transaction id in invoice
- *
- * @param Mage_Sales_Model_Order_Invoice $invoice
- * @param Mage_Sales_Model_Order_Payment $payment
- * @return Mage_Payment_Model_Method_Abstract
- */
- public function processInvoice($invoice, $payment)
- {
- $invoice->setTransactionId(1);
- return $this;
- }
-
- /**
- * Set transaction ID into creditmemo for informational purposes
- * @param Mage_Sales_Model_Order_Creditmemo $creditmemo
- * @param Mage_Sales_Model_Order_Payment $payment
- * @return Mage_Payment_Model_Method_Abstract
- */
- public function processCreditmemo($creditmemo, $payment)
- {
- $creditmemo->setTransactionId(1);
- return $this;
- }
-
- /**
- * Fetch transaction details info
- *
- * Update transaction info if there is one placing transaction only
- *
- * @param string $transactionId
- * @return array
- */
- public function fetchTransactionInfo(Mage_Payment_Model_Info $payment, $transactionId)
- {
- $data = parent::fetchTransactionInfo($payment, $transactionId);
- $cardsStorage = $this->getCardsStorage($payment);
-
- if ($cardsStorage->getCardsCount() != 1) {
- return $data;
- }
- $cards = $cardsStorage->getCards();
- $card = array_shift($cards);
-
- /*
- * We need try to get transaction from Mage::registry,
- * because in cases when fetch calling from Mage_Adminhtml_Sales_TransactionsController::fetchAction()
- * this line "$transaction = $payment->getTransaction($transactionId)" loads a fetching transaction into a new object,
- * so some changes (for ex. $transaction->setAdditionalInformation($this->_isTransactionFraud, false) ) will not saved,
- * because controller have another object for this transaction and Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS isn't includes _isTransactionFraud flag.
- */
- $transaction = Mage::registry('current_transaction');
- if (is_null($transaction)) {
- //this is for payment info update:
- $transactionId = $card->getLastTransId();
- $transaction = $payment->getTransaction($transactionId);
- }
- //because in child transaction, the txn_id spoils by added additional word (@see $this->_preauthorizeCaptureCardTransaction()):
- if (empty($transactionId) || $transaction->getParentId()) {
- $transactionId = $transaction->getAdditionalInformation($this->_realTransactionIdKey);
- }
- $response = $this->_getTransactionDetails($transactionId);
- $data = array_merge($data, $response->getData());
-
- if ($response->getResponseCode() == self::RESPONSE_CODE_APPROVED) {
- $transaction->setAdditionalInformation($this->_isTransactionFraud, false);
- $payment->setIsTransactionApproved(true);
- } elseif ($response->getResponseReasonCode() == self::RESPONSE_REASON_CODE_PENDING_REVIEW_DECLINED) {
- $payment->setIsTransactionDenied(true);
- }
- return $data;
- }
-
/**
* Set split_tender_id to quote payment if needed
*
@@ -1422,28 +1422,6 @@ protected function _registerCard(Varien_Object $response, Mage_Sales_Model_Order
return $card;
}
- /**
- * Reset assigned data in payment info model
- *
- * @param Mage_Payment_Model_Info $payment
- * @return $this
- */
- private function _clearAssignedData($payment)
- {
- $payment->setCcType(null)
- ->setCcOwner(null)
- ->setCcLast4(null)
- ->setCcNumber(null)
- ->setCcCid(null)
- ->setCcExpMonth(null)
- ->setCcExpYear(null)
- ->setCcSsIssue(null)
- ->setCcSsStartMonth(null)
- ->setCcSsStartYear(null)
- ;
- return $this;
- }
-
/**
* Add payment transaction
*
@@ -1631,4 +1609,26 @@ protected function _parseTransactionDetailsXmlResponseToVarienObject(Varien_Simp
return $response;
}
+
+ /**
+ * Reset assigned data in payment info model
+ *
+ * @param Mage_Payment_Model_Info $payment
+ * @return $this
+ */
+ private function _clearAssignedData($payment)
+ {
+ $payment->setCcType(null)
+ ->setCcOwner(null)
+ ->setCcLast4(null)
+ ->setCcNumber(null)
+ ->setCcCid(null)
+ ->setCcExpMonth(null)
+ ->setCcExpYear(null)
+ ->setCcSsIssue(null)
+ ->setCcSsStartMonth(null)
+ ->setCcSsStartYear(null)
+ ;
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Paygate/Model/Authorizenet/Cards.php b/app/code/core/Mage/Paygate/Model/Authorizenet/Cards.php
index e4b78908be9..d5c8d90cf84 100644
--- a/app/code/core/Mage/Paygate/Model/Authorizenet/Cards.php
+++ b/app/code/core/Mage/Paygate/Model/Authorizenet/Cards.php
@@ -169,18 +169,6 @@ public function flushCards()
$this->_payment->setAdditionalInformation(self::CARDS_NAMESPACE, null);
return $this;
}
-
- /**
- * Check for payment instance present
- *
- * @throws Exception
- */
- protected function _isPaymentValid()
- {
- if (!$this->_payment) {
- throw new Exception('Payment instance is not set');
- }
- }
/**
* Return total for cards data fields
*
@@ -197,4 +185,16 @@ public function _getAmount($key)
}
return $amount;
}
+
+ /**
+ * Check for payment instance present
+ *
+ * @throws Exception
+ */
+ protected function _isPaymentValid()
+ {
+ if (!$this->_payment) {
+ throw new Exception('Payment instance is not set');
+ }
+ }
}
diff --git a/app/code/core/Mage/Payment/Block/Form/Banktransfer.php b/app/code/core/Mage/Payment/Block/Form/Banktransfer.php
index 815b01213bd..a60b4d1abb0 100644
--- a/app/code/core/Mage/Payment/Block/Form/Banktransfer.php
+++ b/app/code/core/Mage/Payment/Block/Form/Banktransfer.php
@@ -29,15 +29,6 @@ class Mage_Payment_Block_Form_Banktransfer extends Mage_Payment_Block_Form
*/
protected $_instructions;
- /**
- * Block construction. Set block template.
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('payment/form/banktransfer.phtml');
- }
-
/**
* Get instructions text from config
*
@@ -50,4 +41,13 @@ public function getInstructions()
}
return $this->_instructions;
}
+
+ /**
+ * Block construction. Set block template.
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('payment/form/banktransfer.phtml');
+ }
}
diff --git a/app/code/core/Mage/Payment/Block/Form/Cashondelivery.php b/app/code/core/Mage/Payment/Block/Form/Cashondelivery.php
index 333c7f09924..6938d20d1f5 100644
--- a/app/code/core/Mage/Payment/Block/Form/Cashondelivery.php
+++ b/app/code/core/Mage/Payment/Block/Form/Cashondelivery.php
@@ -29,15 +29,6 @@ class Mage_Payment_Block_Form_Cashondelivery extends Mage_Payment_Block_Form
*/
protected $_instructions;
- /**
- * Block construction. Set block template.
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('payment/form/cashondelivery.phtml');
- }
-
/**
* Get instructions text from config
*
@@ -50,4 +41,13 @@ public function getInstructions()
}
return $this->_instructions;
}
+
+ /**
+ * Block construction. Set block template.
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('payment/form/cashondelivery.phtml');
+ }
}
diff --git a/app/code/core/Mage/Payment/Block/Form/Cc.php b/app/code/core/Mage/Payment/Block/Form/Cc.php
index c7cddd4cb98..7b6a0e9b3f9 100644
--- a/app/code/core/Mage/Payment/Block/Form/Cc.php
+++ b/app/code/core/Mage/Payment/Block/Form/Cc.php
@@ -20,22 +20,6 @@
*/
class Mage_Payment_Block_Form_Cc extends Mage_Payment_Block_Form
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('payment/form/cc.phtml');
- }
-
- /**
- * Retrieve payment configuration object
- *
- * @return Mage_Payment_Model_Config
- */
- protected function _getConfig()
- {
- return Mage::getSingleton('payment/config');
- }
-
/**
* Retrieve availables credit card types
*
@@ -141,6 +125,21 @@ public function getSsStartYears()
}
return [0 => $this->__('Year')] + $years;
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('payment/form/cc.phtml');
+ }
+
+ /**
+ * Retrieve payment configuration object
+ *
+ * @return Mage_Payment_Model_Config
+ */
+ protected function _getConfig()
+ {
+ return Mage::getSingleton('payment/config');
+ }
/**
* Render block HTML
diff --git a/app/code/core/Mage/Payment/Block/Form/Container.php b/app/code/core/Mage/Payment/Block/Form/Container.php
index 75f8641b486..ac0399ef543 100644
--- a/app/code/core/Mage/Payment/Block/Form/Container.php
+++ b/app/code/core/Mage/Payment/Block/Form/Container.php
@@ -24,54 +24,6 @@
*/
class Mage_Payment_Block_Form_Container extends Mage_Core_Block_Template
{
- /**
- * Prepare children blocks
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
-
- /**
- * Create child blocks for payment methods forms
- */
- foreach ($this->getMethods() as $method) {
- $this->setChild(
- 'payment.method.' . $method->getCode(),
- $helper->getMethodFormBlock($method),
- );
- }
-
- return parent::_prepareLayout();
- }
-
- /**
- * Check payment method model
- *
- * @param Mage_Payment_Model_Method_Abstract $method
- * @return bool
- */
- protected function _canUseMethod($method)
- {
- return $method->isApplicableToQuote($this->getQuote(), Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_COUNTRY
- | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_CURRENCY
- | Mage_Payment_Model_Method_Abstract::CHECK_ORDER_TOTAL_MIN_MAX);
- }
-
- /**
- * Check and prepare payment method model
- *
- * Redeclare this method in child classes for declaring method info instance
- *
- * @param Mage_Payment_Model_Method_Abstract $method
- * @return $this
- */
- protected function _assignMethod($method)
- {
- $method->setInfoInstance($this->getQuote()->getPayment());
- return $this;
- }
-
/**
* Declare template for payment method form block
*
@@ -131,4 +83,51 @@ public function getSelectedMethodCode()
}
return false;
}
+ /**
+ * Prepare children blocks
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+
+ /**
+ * Create child blocks for payment methods forms
+ */
+ foreach ($this->getMethods() as $method) {
+ $this->setChild(
+ 'payment.method.' . $method->getCode(),
+ $helper->getMethodFormBlock($method),
+ );
+ }
+
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Check payment method model
+ *
+ * @param Mage_Payment_Model_Method_Abstract $method
+ * @return bool
+ */
+ protected function _canUseMethod($method)
+ {
+ return $method->isApplicableToQuote($this->getQuote(), Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_COUNTRY
+ | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_CURRENCY
+ | Mage_Payment_Model_Method_Abstract::CHECK_ORDER_TOTAL_MIN_MAX);
+ }
+
+ /**
+ * Check and prepare payment method model
+ *
+ * Redeclare this method in child classes for declaring method info instance
+ *
+ * @param Mage_Payment_Model_Method_Abstract $method
+ * @return $this
+ */
+ protected function _assignMethod($method)
+ {
+ $method->setInfoInstance($this->getQuote()->getPayment());
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Payment/Block/Info.php b/app/code/core/Mage/Payment/Block/Info.php
index 7564e47fd73..565e10696d0 100644
--- a/app/code/core/Mage/Payment/Block/Info.php
+++ b/app/code/core/Mage/Payment/Block/Info.php
@@ -31,12 +31,6 @@ class Mage_Payment_Block_Info extends Mage_Core_Block_Template
*/
protected $_paymentSpecificInformation = null;
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('payment/info/default.phtml');
- }
-
/**
* Retrieve info model
*
@@ -143,6 +137,12 @@ public function getIsSecureMode()
return !Mage::app()->getStore($method->getStore())->isAdmin();
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('payment/info/default.phtml');
+ }
+
/**
* Prepare information specific to current payment method
*
diff --git a/app/code/core/Mage/Payment/Block/Info/Banktransfer.php b/app/code/core/Mage/Payment/Block/Info/Banktransfer.php
index 432a4fecb05..45d55f170ab 100644
--- a/app/code/core/Mage/Payment/Block/Info/Banktransfer.php
+++ b/app/code/core/Mage/Payment/Block/Info/Banktransfer.php
@@ -29,12 +29,6 @@ class Mage_Payment_Block_Info_Banktransfer extends Mage_Payment_Block_Info
*/
protected $_instructions;
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('payment/info/banktransfer.phtml');
- }
-
/**
* Get instructions text from order payment
* (or from config, if instructions are missed in payment)
@@ -51,4 +45,10 @@ public function getInstructions()
}
return $this->_instructions;
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('payment/info/banktransfer.phtml');
+ }
}
diff --git a/app/code/core/Mage/Payment/Block/Info/Checkmo.php b/app/code/core/Mage/Payment/Block/Info/Checkmo.php
index fbb231d359d..51b66f53ef4 100644
--- a/app/code/core/Mage/Payment/Block/Info/Checkmo.php
+++ b/app/code/core/Mage/Payment/Block/Info/Checkmo.php
@@ -23,12 +23,6 @@ class Mage_Payment_Block_Info_Checkmo extends Mage_Payment_Block_Info
protected $_payableTo;
protected $_mailingAddress;
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('payment/info/checkmo.phtml');
- }
-
/**
* @return string
*/
@@ -51,6 +45,21 @@ public function getMailingAddress()
return $this->_mailingAddress;
}
+ /**
+ * @return string
+ */
+ public function toPdf()
+ {
+ $this->setTemplate('payment/info/pdf/checkmo.phtml');
+ return $this->toHtml();
+ }
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('payment/info/checkmo.phtml');
+ }
+
/**
* @return $this
*/
@@ -72,13 +81,4 @@ protected function _convertAdditionalData()
}
return $this;
}
-
- /**
- * @return string
- */
- public function toPdf()
- {
- $this->setTemplate('payment/info/pdf/checkmo.phtml');
- return $this->toHtml();
- }
}
diff --git a/app/code/core/Mage/Payment/Block/Info/Container.php b/app/code/core/Mage/Payment/Block/Info/Container.php
index c6e81669a09..590c102ce3e 100644
--- a/app/code/core/Mage/Payment/Block/Info/Container.php
+++ b/app/code/core/Mage/Payment/Block/Info/Container.php
@@ -22,6 +22,32 @@
*/
class Mage_Payment_Block_Info_Container extends Mage_Core_Block_Template
{
+ /**
+ * Retrieve payment info model
+ *
+ * @return Mage_Payment_Model_Info|false
+ */
+ public function getPaymentInfo()
+ {
+ return false;
+ }
+
+ /**
+ * Declare info block template
+ *
+ * @param string $method
+ * @param string $template
+ * @return Mage_Payment_Block_Info_Container
+ */
+ public function setInfoTemplate($method = '', $template = '')
+ {
+ if ($info = $this->getPaymentInfo()) {
+ if ($info->getMethodInstance()->getCode() == $method) {
+ $this->getChild($this->_getInfoBlockName())->setTemplate($template);
+ }
+ }
+ return $this;
+ }
/**
* Add payment info block to layout
*
@@ -50,31 +76,4 @@ protected function _getInfoBlockName()
}
return false;
}
-
- /**
- * Retrieve payment info model
- *
- * @return Mage_Payment_Model_Info|false
- */
- public function getPaymentInfo()
- {
- return false;
- }
-
- /**
- * Declare info block template
- *
- * @param string $method
- * @param string $template
- * @return Mage_Payment_Block_Info_Container
- */
- public function setInfoTemplate($method = '', $template = '')
- {
- if ($info = $this->getPaymentInfo()) {
- if ($info->getMethodInstance()->getCode() == $method) {
- $this->getChild($this->_getInfoBlockName())->setTemplate($template);
- }
- }
- return $this;
- }
}
diff --git a/app/code/core/Mage/Payment/Block/Info/Purchaseorder.php b/app/code/core/Mage/Payment/Block/Info/Purchaseorder.php
index f99eca3b056..43cd34664be 100644
--- a/app/code/core/Mage/Payment/Block/Info/Purchaseorder.php
+++ b/app/code/core/Mage/Payment/Block/Info/Purchaseorder.php
@@ -20,12 +20,6 @@
*/
class Mage_Payment_Block_Info_Purchaseorder extends Mage_Payment_Block_Info
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('payment/info/purchaseorder.phtml');
- }
-
/**
* @return string
*/
@@ -34,4 +28,9 @@ public function toPdf()
$this->setTemplate('payment/info/pdf/purchaseorder.phtml');
return $this->toHtml();
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('payment/info/purchaseorder.phtml');
+ }
}
diff --git a/app/code/core/Mage/Payment/Helper/Data.php b/app/code/core/Mage/Payment/Helper/Data.php
index 3a64034c869..544881d2e42 100644
--- a/app/code/core/Mage/Payment/Helper/Data.php
+++ b/app/code/core/Mage/Payment/Helper/Data.php
@@ -92,19 +92,6 @@ public function getStoreMethods($store = null, $quote = null)
return $res;
}
- /**
- * @param object $a
- * @param object $b
- * @return int
- */
- protected function _sortMethods($a, $b)
- {
- if (is_object($a)) {
- return (int) $a->sort_order < (int) $b->sort_order ? -1 : ((int) $a->sort_order > (int) $b->sort_order ? 1 : 0);
- }
- return 0;
- }
-
/**
* Retrieve payment method form html
*
@@ -316,4 +303,17 @@ public function getZeroSubTotalPaymentAutomaticInvoice($store = null)
{
return Mage::getStoreConfig(Mage_Payment_Model_Method_Free::XML_PATH_PAYMENT_FREE_PAYMENT_ACTION, $store);
}
+
+ /**
+ * @param object $a
+ * @param object $b
+ * @return int
+ */
+ protected function _sortMethods($a, $b)
+ {
+ if (is_object($a)) {
+ return (int) $a->sort_order < (int) $b->sort_order ? -1 : ((int) $a->sort_order > (int) $b->sort_order ? 1 : 0);
+ }
+ return 0;
+ }
}
diff --git a/app/code/core/Mage/Payment/Model/Config.php b/app/code/core/Mage/Payment/Model/Config.php
index 779f81c2553..9c62bc969cb 100644
--- a/app/code/core/Mage/Payment/Model/Config.php
+++ b/app/code/core/Mage/Payment/Model/Config.php
@@ -68,30 +68,6 @@ public function getAllMethods($store = null)
return $methods;
}
- /**
- * @param string $code
- * @param array $config
- * @param null|string|bool|int|Mage_Core_Model_Store $store $store
- * @return false|Mage_Payment_Model_Method_Abstract
- */
- protected function _getMethod($code, $config, $store = null)
- {
- if (isset(self::$_methods[$code])) {
- return self::$_methods[$code];
- }
- if (empty($config['model'])) {
- return false;
- }
- $modelName = $config['model'];
- $method = Mage::getModel($modelName);
- if (!$method) {
- return false;
- }
- $method->setId($code)->setStore($store);
- self::$_methods[$code] = $method;
- return self::$_methods[$code];
- }
-
/**
* Retrieve array of credit card types
*
@@ -169,4 +145,28 @@ public static function compareCcTypes($a, $b)
return -1;
}
}
+
+ /**
+ * @param string $code
+ * @param array $config
+ * @param null|string|bool|int|Mage_Core_Model_Store $store $store
+ * @return false|Mage_Payment_Model_Method_Abstract
+ */
+ protected function _getMethod($code, $config, $store = null)
+ {
+ if (isset(self::$_methods[$code])) {
+ return self::$_methods[$code];
+ }
+ if (empty($config['model'])) {
+ return false;
+ }
+ $modelName = $config['model'];
+ $method = Mage::getModel($modelName);
+ if (!$method) {
+ return false;
+ }
+ $method->setId($code)->setStore($store);
+ self::$_methods[$code] = $method;
+ return self::$_methods[$code];
+ }
}
diff --git a/app/code/core/Mage/Payment/Model/Method/Abstract.php b/app/code/core/Mage/Payment/Model/Method/Abstract.php
index 8fecb02d2c3..327bfca7a9e 100644
--- a/app/code/core/Mage/Payment/Model/Method/Abstract.php
+++ b/app/code/core/Mage/Payment/Model/Method/Abstract.php
@@ -323,16 +323,6 @@ public function canManageRecurringProfiles()
&& ($this instanceof Mage_Payment_Model_Recurring_Profile_MethodInterface);
}
- /**
- * Retrieve model helper
- *
- * @return Mage_Payment_Helper_Data
- */
- protected function _getHelper()
- {
- return Mage::helper('payment');
- }
-
/**
* Retrieve payment method code
*
@@ -740,20 +730,6 @@ public function getConfigPaymentAction()
return $this->getConfigData('payment_action');
}
- /**
- * Log debug data to file
- *
- * @param mixed $debugData
- */
- protected function _debug($debugData)
- {
- if ($this->getDebugFlag()) {
- Mage::getModel('core/log_adapter', 'payment_' . $this->getCode() . '.log')
- ->setFilterDataKeys($this->_debugReplacePrivateDataKeys)
- ->log($debugData);
- }
- }
-
/**
* Define if debugging is enabled
*
@@ -773,4 +749,28 @@ public function debugData($debugData)
{
$this->_debug($debugData);
}
+
+ /**
+ * Retrieve model helper
+ *
+ * @return Mage_Payment_Helper_Data
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('payment');
+ }
+
+ /**
+ * Log debug data to file
+ *
+ * @param mixed $debugData
+ */
+ protected function _debug($debugData)
+ {
+ if ($this->getDebugFlag()) {
+ Mage::getModel('core/log_adapter', 'payment_' . $this->getCode() . '.log')
+ ->setFilterDataKeys($this->_debugReplacePrivateDataKeys)
+ ->log($debugData);
+ }
+ }
}
diff --git a/app/code/core/Mage/Payment/Model/Method/Cc.php b/app/code/core/Mage/Payment/Model/Method/Cc.php
index 80ab880e3bd..846034a539b 100644
--- a/app/code/core/Mage/Payment/Model/Method/Cc.php
+++ b/app/code/core/Mage/Payment/Model/Method/Cc.php
@@ -197,23 +197,6 @@ public function getVerificationRegEx()
];
}
- /**
- * @param string $expYear
- * @param string $expMonth
- * @return bool
- * @throws Zend_Date_Exception
- */
- protected function _validateExpDate($expYear, $expMonth)
- {
- $date = Mage::app()->getLocale()->date();
- if (!$expYear || !$expMonth || ($date->compareYear($expYear) == 1)
- || ($date->compareYear($expYear) == 0 && ($date->compareMonth($expMonth) == 1))
- ) {
- return false;
- }
- return true;
- }
-
/**
* @param string $type
* @return bool
@@ -332,6 +315,23 @@ public function getCentinelValidationData()
return $params;
}
+ /**
+ * @param string $expYear
+ * @param string $expMonth
+ * @return bool
+ * @throws Zend_Date_Exception
+ */
+ protected function _validateExpDate($expYear, $expMonth)
+ {
+ $date = Mage::app()->getLocale()->date();
+ if (!$expYear || !$expMonth || ($date->compareYear($expYear) == 1)
+ || ($date->compareYear($expYear) == 0 && ($date->compareMonth($expMonth) == 1))
+ ) {
+ return false;
+ }
+ return true;
+ }
+
/**
* Order increment ID getter (either real from order or a reserved from quote)
*
diff --git a/app/code/core/Mage/Paypal/Block/Adminhtml/Settlement/Report/Grid.php b/app/code/core/Mage/Paypal/Block/Adminhtml/Settlement/Report/Grid.php
index abb4481d46f..efddc22aa40 100644
--- a/app/code/core/Mage/Paypal/Block/Adminhtml/Settlement/Report/Grid.php
+++ b/app/code/core/Mage/Paypal/Block/Adminhtml/Settlement/Report/Grid.php
@@ -40,6 +40,24 @@ public function __construct()
$this->setUseAjax(true);
}
+ /**
+ * Return grid URL
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid');
+ }
+
+ /**
+ * Return item view URL
+ * @return string
+ */
+ public function getRowUrl($item)
+ {
+ return $this->getUrl('*/*/details', ['id' => $item->getId()]);
+ }
+
/**
* @inheritDoc
*/
@@ -110,22 +128,4 @@ protected function _prepareColumns()
]);
return parent::_prepareColumns();
}
-
- /**
- * Return grid URL
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid');
- }
-
- /**
- * Return item view URL
- * @return string
- */
- public function getRowUrl($item)
- {
- return $this->getUrl('*/*/details', ['id' => $item->getId()]);
- }
}
diff --git a/app/code/core/Mage/Paypal/Block/Adminhtml/System/Config/ApiWizard.php b/app/code/core/Mage/Paypal/Block/Adminhtml/System/Config/ApiWizard.php
index f465de95bb9..f04a401b561 100644
--- a/app/code/core/Mage/Paypal/Block/Adminhtml/System/Config/ApiWizard.php
+++ b/app/code/core/Mage/Paypal/Block/Adminhtml/System/Config/ApiWizard.php
@@ -27,6 +27,17 @@ class Mage_Paypal_Block_Adminhtml_System_Config_ApiWizard extends Mage_Adminhtml
*/
protected $_wizardTemplate = 'paypal/system/config/api_wizard.phtml';
+ /**
+ * Unset some non-related element parameters
+ *
+ * @return string
+ */
+ public function render(Varien_Data_Form_Element_Abstract $element)
+ {
+ $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
+ return parent::render($element);
+ }
+
/**
* Set template to itself
*/
@@ -39,17 +50,6 @@ protected function _prepareLayout()
return $this;
}
- /**
- * Unset some non-related element parameters
- *
- * @return string
- */
- public function render(Varien_Data_Form_Element_Abstract $element)
- {
- $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
- return parent::render($element);
- }
-
/**
* Get the button and scripts contents
*
diff --git a/app/code/core/Mage/Paypal/Block/Adminhtml/System/Config/Fieldset/Deprecated.php b/app/code/core/Mage/Paypal/Block/Adminhtml/System/Config/Fieldset/Deprecated.php
index 76ff1f6ee36..bdb6b18bb1d 100644
--- a/app/code/core/Mage/Paypal/Block/Adminhtml/System/Config/Fieldset/Deprecated.php
+++ b/app/code/core/Mage/Paypal/Block/Adminhtml/System/Config/Fieldset/Deprecated.php
@@ -22,6 +22,45 @@
*/
class Mage_Paypal_Block_Adminhtml_System_Config_Fieldset_Deprecated extends Mage_Paypal_Block_Adminhtml_System_Config_Fieldset_Payment
{
+ /**
+ * Check whether current payment method is enabled on any scope
+ *
+ * @param string $activityPath
+ * @return bool
+ */
+ public function isPaymentEnabledAnyScope($activityPath)
+ {
+ if ((bool) (string) $this->_getConfigModel()->getNode($activityPath, 'default')) {
+ return true;
+ }
+ foreach ($this->_getWebsites() as $website) {
+ if ((bool) (string) $this->_getConfigModel()->getNode($activityPath, 'website', (int) $website->getId())) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Do not render solution if disabled
+ *
+ * @return string
+ */
+ public function render(Varien_Data_Form_Element_Abstract $element)
+ {
+ $isPaymentEnabled = $this->_isPaymentEnabled($element, [$this, 'isPaymentEnabledAnyScope']);
+ if ($this->_wasActive($element) && $isPaymentEnabled) {
+ return parent::render($element);
+ }
+
+ if ($isPaymentEnabled) {
+ $this->_setWasActive($element);
+ return parent::render($element);
+ }
+
+ return '';
+ }
/**
* Get was enabled config path
*
@@ -85,44 +124,4 @@ protected function _getWebsites()
return $this->getWebsites();
}
-
- /**
- * Check whether current payment method is enabled on any scope
- *
- * @param string $activityPath
- * @return bool
- */
- public function isPaymentEnabledAnyScope($activityPath)
- {
- if ((bool) (string) $this->_getConfigModel()->getNode($activityPath, 'default')) {
- return true;
- }
- foreach ($this->_getWebsites() as $website) {
- if ((bool) (string) $this->_getConfigModel()->getNode($activityPath, 'website', (int) $website->getId())) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Do not render solution if disabled
- *
- * @return string
- */
- public function render(Varien_Data_Form_Element_Abstract $element)
- {
- $isPaymentEnabled = $this->_isPaymentEnabled($element, [$this, 'isPaymentEnabledAnyScope']);
- if ($this->_wasActive($element) && $isPaymentEnabled) {
- return parent::render($element);
- }
-
- if ($isPaymentEnabled) {
- $this->_setWasActive($element);
- return parent::render($element);
- }
-
- return '';
- }
}
diff --git a/app/code/core/Mage/Paypal/Block/Express/Shortcut.php b/app/code/core/Mage/Paypal/Block/Express/Shortcut.php
index ac6d827afd3..a79ee1da708 100644
--- a/app/code/core/Mage/Paypal/Block/Express/Shortcut.php
+++ b/app/code/core/Mage/Paypal/Block/Express/Shortcut.php
@@ -67,6 +67,28 @@ class Mage_Paypal_Block_Express_Shortcut extends Mage_Core_Block_Template
*/
protected $_checkoutType = 'paypal/express_checkout';
+ /**
+ * Check is "OR" label position before shortcut
+ *
+ * @return bool
+ */
+ public function isOrPositionBefore()
+ {
+ return ($this->getIsInCatalogProduct() && !$this->getShowOrPosition())
+ || ($this->getShowOrPosition() && $this->getShowOrPosition() === self::POSITION_BEFORE);
+ }
+
+ /**
+ * Check is "OR" label position after shortcut
+ *
+ * @return bool
+ */
+ public function isOrPositionAfter()
+ {
+ return (!$this->getIsInCatalogProduct() && !$this->getShowOrPosition())
+ || ($this->getShowOrPosition() && $this->getShowOrPosition() === self::POSITION_AFTER);
+ }
+
/**
* @return Mage_Core_Block_Abstract
*/
@@ -179,26 +201,4 @@ protected function _toHtml()
}
return parent::_toHtml();
}
-
- /**
- * Check is "OR" label position before shortcut
- *
- * @return bool
- */
- public function isOrPositionBefore()
- {
- return ($this->getIsInCatalogProduct() && !$this->getShowOrPosition())
- || ($this->getShowOrPosition() && $this->getShowOrPosition() === self::POSITION_BEFORE);
- }
-
- /**
- * Check is "OR" label position after shortcut
- *
- * @return bool
- */
- public function isOrPositionAfter()
- {
- return (!$this->getIsInCatalogProduct() && !$this->getShowOrPosition())
- || ($this->getShowOrPosition() && $this->getShowOrPosition() === self::POSITION_AFTER);
- }
}
diff --git a/app/code/core/Mage/Paypal/Block/Hosted/Pro/Iframe.php b/app/code/core/Mage/Paypal/Block/Hosted/Pro/Iframe.php
index 8031ab59784..d02d434ec71 100644
--- a/app/code/core/Mage/Paypal/Block/Hosted/Pro/Iframe.php
+++ b/app/code/core/Mage/Paypal/Block/Hosted/Pro/Iframe.php
@@ -22,15 +22,6 @@
*/
class Mage_Paypal_Block_Hosted_Pro_Iframe extends Mage_Paypal_Block_Iframe
{
- /**
- * Set payment method code
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_paymentMethodCode = Mage_Paypal_Model_Config::METHOD_HOSTEDPRO;
- }
-
/**
* Get iframe action URL
* @return string
@@ -41,4 +32,12 @@ public function getFrameActionUrl()
->getPayment()
->getAdditionalInformation('secure_form_url');
}
+ /**
+ * Set payment method code
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_paymentMethodCode = Mage_Paypal_Model_Config::METHOD_HOSTEDPRO;
+ }
}
diff --git a/app/code/core/Mage/Paypal/Block/Iframe.php b/app/code/core/Mage/Paypal/Block/Iframe.php
index d7637aaf333..64693077964 100644
--- a/app/code/core/Mage/Paypal/Block/Iframe.php
+++ b/app/code/core/Mage/Paypal/Block/Iframe.php
@@ -48,6 +48,61 @@ class Mage_Paypal_Block_Iframe extends Mage_Payment_Block_Form
*/
protected $_block;
+ /**
+ * Get iframe action URL
+ *
+ * @return string
+ * @throws Mage_Core_Exception
+ */
+ public function getFrameActionUrl()
+ {
+ return $this->_getBlock()->getFrameActionUrl();
+ }
+
+ /**
+ * Get secure token
+ *
+ * @return string
+ * @throws Mage_Core_Exception
+ */
+ public function getSecureToken()
+ {
+ return $this->_getBlock()->getSecureToken();
+ }
+
+ /**
+ * Get secure token ID
+ *
+ * @return string
+ * @throws Mage_Core_Exception
+ */
+ public function getSecureTokenId()
+ {
+ return $this->_getBlock()->getSecureTokenId();
+ }
+
+ /**
+ * Get payflow transaction URL
+ *
+ * @return string
+ * @throws Mage_Core_Exception
+ */
+ public function getTransactionUrl()
+ {
+ return $this->_getBlock()->getTransactionUrl();
+ }
+
+ /**
+ * Check sandbox mode
+ *
+ * @return bool
+ * @throws Mage_Core_Exception
+ */
+ public function isTestMode()
+ {
+ return $this->_getBlock()->isTestMode();
+ }
+
/**
* Internal constructor
* Set info template for payment step
@@ -178,59 +233,4 @@ protected function _isAfterPaymentSave()
return false;
}
-
- /**
- * Get iframe action URL
- *
- * @return string
- * @throws Mage_Core_Exception
- */
- public function getFrameActionUrl()
- {
- return $this->_getBlock()->getFrameActionUrl();
- }
-
- /**
- * Get secure token
- *
- * @return string
- * @throws Mage_Core_Exception
- */
- public function getSecureToken()
- {
- return $this->_getBlock()->getSecureToken();
- }
-
- /**
- * Get secure token ID
- *
- * @return string
- * @throws Mage_Core_Exception
- */
- public function getSecureTokenId()
- {
- return $this->_getBlock()->getSecureTokenId();
- }
-
- /**
- * Get payflow transaction URL
- *
- * @return string
- * @throws Mage_Core_Exception
- */
- public function getTransactionUrl()
- {
- return $this->_getBlock()->getTransactionUrl();
- }
-
- /**
- * Check sandbox mode
- *
- * @return bool
- * @throws Mage_Core_Exception
- */
- public function isTestMode()
- {
- return $this->_getBlock()->isTestMode();
- }
}
diff --git a/app/code/core/Mage/Paypal/Block/Payflow/Advanced/Form.php b/app/code/core/Mage/Paypal/Block/Payflow/Advanced/Form.php
index b05a13bb3cb..3bf56cbc4e6 100644
--- a/app/code/core/Mage/Paypal/Block/Payflow/Advanced/Form.php
+++ b/app/code/core/Mage/Paypal/Block/Payflow/Advanced/Form.php
@@ -23,22 +23,21 @@
class Mage_Paypal_Block_Payflow_Advanced_Form extends Mage_Paypal_Block_Payflow_Link_Form
{
/**
- * Set payment method code
+ * Get frame action URL
*
+ * @return string
*/
- protected function _construct()
+ public function getFrameActionUrl()
{
- parent::_construct();
- $this->setTemplate('paypal/payflowadvanced/info.phtml');
+ return $this->getUrl('paypal/payflowadvanced/form', ['_secure' => true]);
}
-
/**
- * Get frame action URL
+ * Set payment method code
*
- * @return string
*/
- public function getFrameActionUrl()
+ protected function _construct()
{
- return $this->getUrl('paypal/payflowadvanced/form', ['_secure' => true]);
+ parent::_construct();
+ $this->setTemplate('paypal/payflowadvanced/info.phtml');
}
}
diff --git a/app/code/core/Mage/Paypal/Block/Payflow/Advanced/Iframe.php b/app/code/core/Mage/Paypal/Block/Payflow/Advanced/Iframe.php
index f7511847903..b6ba1794d17 100644
--- a/app/code/core/Mage/Paypal/Block/Payflow/Advanced/Iframe.php
+++ b/app/code/core/Mage/Paypal/Block/Payflow/Advanced/Iframe.php
@@ -22,15 +22,6 @@
*/
class Mage_Paypal_Block_Payflow_Advanced_Iframe extends Mage_Paypal_Block_Payflow_Link_Iframe
{
- /**
- * Set payment method code
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_paymentMethodCode = Mage_Paypal_Model_Config::METHOD_PAYFLOWADVANCED;
- }
-
/**
* Get frame action URL
* @return string
@@ -53,4 +44,12 @@ public function isTestMode()
->getConfigData('sandbox_flag');
return (bool) $mode;
}
+ /**
+ * Set payment method code
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_paymentMethodCode = Mage_Paypal_Model_Config::METHOD_PAYFLOWADVANCED;
+ }
}
diff --git a/app/code/core/Mage/Paypal/Block/Payflow/Link/Form.php b/app/code/core/Mage/Paypal/Block/Payflow/Link/Form.php
index e5eb68239e9..c1c6b7b4140 100644
--- a/app/code/core/Mage/Paypal/Block/Payflow/Link/Form.php
+++ b/app/code/core/Mage/Paypal/Block/Payflow/Link/Form.php
@@ -23,22 +23,21 @@
class Mage_Paypal_Block_Payflow_Link_Form extends Mage_Payment_Block_Form
{
/**
- * Set payment method code
+ * Get frame action URL
*
+ * @return string
*/
- protected function _construct()
+ public function getFrameActionUrl()
{
- parent::_construct();
- $this->setTemplate('paypal/payflowlink/info.phtml');
+ return $this->getUrl('paypal/payflow/form', ['_secure' => true]);
}
-
/**
- * Get frame action URL
+ * Set payment method code
*
- * @return string
*/
- public function getFrameActionUrl()
+ protected function _construct()
{
- return $this->getUrl('paypal/payflow/form', ['_secure' => true]);
+ parent::_construct();
+ $this->setTemplate('paypal/payflowlink/info.phtml');
}
}
diff --git a/app/code/core/Mage/Paypal/Block/Payflow/Link/Iframe.php b/app/code/core/Mage/Paypal/Block/Payflow/Link/Iframe.php
index 70001bd00f6..477b0e1a102 100644
--- a/app/code/core/Mage/Paypal/Block/Payflow/Link/Iframe.php
+++ b/app/code/core/Mage/Paypal/Block/Payflow/Link/Iframe.php
@@ -22,15 +22,6 @@
*/
class Mage_Paypal_Block_Payflow_Link_Iframe extends Mage_Paypal_Block_Iframe
{
- /**
- * Set payment method code
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_paymentMethodCode = Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK;
- }
-
/**
* Get frame action URL
*
@@ -88,4 +79,12 @@ public function isTestMode()
->getConfigData('sandbox_flag');
return (bool) $mode;
}
+ /**
+ * Set payment method code
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_paymentMethodCode = Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK;
+ }
}
diff --git a/app/code/core/Mage/Paypal/Block/Standard/Form.php b/app/code/core/Mage/Paypal/Block/Standard/Form.php
index 7ec17ec204a..45028abc593 100644
--- a/app/code/core/Mage/Paypal/Block/Standard/Form.php
+++ b/app/code/core/Mage/Paypal/Block/Standard/Form.php
@@ -35,6 +35,15 @@ class Mage_Paypal_Block_Standard_Form extends Mage_Payment_Block_Form
*/
protected $_config;
+ /**
+ * Payment method code getter
+ * @return string
+ */
+ public function getMethodCode()
+ {
+ return $this->_methodCode;
+ }
+
/**
* Set template and redirect message
*
@@ -59,13 +68,4 @@ protected function _construct()
;
parent::_construct();
}
-
- /**
- * Payment method code getter
- * @return string
- */
- public function getMethodCode()
- {
- return $this->_methodCode;
- }
}
diff --git a/app/code/core/Mage/Paypal/Controller/Express/Abstract.php b/app/code/core/Mage/Paypal/Controller/Express/Abstract.php
index a04dbfff98c..f87ba3d0a24 100644
--- a/app/code/core/Mage/Paypal/Controller/Express/Abstract.php
+++ b/app/code/core/Mage/Paypal/Controller/Express/Abstract.php
@@ -52,17 +52,6 @@ abstract class Mage_Paypal_Controller_Express_Abstract extends Mage_Core_Control
*/
protected $_configType;
- /**
- * Instantiate config
- */
- protected function _construct()
- {
- parent::_construct();
- /** @var Mage_Paypal_Model_Config $classInstance */
- $classInstance = Mage::getModel($this->_configType, [$this->_configMethod]);
- $this->_config = $classInstance;
- }
-
/**
* Start Express Checkout by requesting initial token and dispatching customer to PayPal
*/
@@ -384,6 +373,32 @@ public function placeOrderAction()
}
}
+ /**
+ * Redirect to login page
+ *
+ */
+ public function redirectLogin()
+ {
+ $this->setFlag('', 'no-dispatch', true);
+ $this->getResponse()->setRedirect(
+ Mage::helper('core/url')->addRequestParam(
+ Mage::helper('customer')->getLoginUrl(),
+ ['context' => 'checkout'],
+ ),
+ );
+ }
+
+ /**
+ * Instantiate config
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ /** @var Mage_Paypal_Model_Config $classInstance */
+ $classInstance = Mage::getModel($this->_configType, [$this->_configMethod]);
+ $this->_config = $classInstance;
+ }
+
/**
* Process PayPal API's processable errors
*
@@ -495,23 +510,23 @@ protected function _initToken($setToken = null)
}
/**
- * PayPal session instance getter
+ * Return checkout session object
*
- * @return Mage_Paypal_Model_Session
+ * @return Mage_Checkout_Model_Session
*/
- private function _getSession()
+ protected function _getCheckoutSession()
{
- return Mage::getSingleton('paypal/session');
+ return Mage::getSingleton('checkout/session');
}
/**
- * Return checkout session object
+ * PayPal session instance getter
*
- * @return Mage_Checkout_Model_Session
+ * @return Mage_Paypal_Model_Session
*/
- protected function _getCheckoutSession()
+ private function _getSession()
{
- return Mage::getSingleton('checkout/session');
+ return Mage::getSingleton('paypal/session');
}
/**
@@ -526,19 +541,4 @@ private function _getQuote()
}
return $this->_quote;
}
-
- /**
- * Redirect to login page
- *
- */
- public function redirectLogin()
- {
- $this->setFlag('', 'no-dispatch', true);
- $this->getResponse()->setRedirect(
- Mage::helper('core/url')->addRequestParam(
- Mage::helper('customer')->getLoginUrl(),
- ['context' => 'checkout'],
- ),
- );
- }
}
diff --git a/app/code/core/Mage/Paypal/Helper/Data.php b/app/code/core/Mage/Paypal/Helper/Data.php
index 5222803b75b..ff3b5127eca 100644
--- a/app/code/core/Mage/Paypal/Helper/Data.php
+++ b/app/code/core/Mage/Paypal/Helper/Data.php
@@ -22,8 +22,6 @@
*/
class Mage_Paypal_Helper_Data extends Mage_Core_Helper_Abstract
{
- protected $_moduleName = 'Mage_Paypal';
-
/**
* US country code
*/
@@ -33,6 +31,7 @@ class Mage_Paypal_Helper_Data extends Mage_Core_Helper_Abstract
* Config path for merchant country
*/
public const MERCHANT_COUNTRY_CONFIG_PATH = 'paypal/general/merchant_country';
+ protected $_moduleName = 'Mage_Paypal';
/**
* Cache for shouldAskToCreateBillingAgreement()
diff --git a/app/code/core/Mage/Paypal/Model/Api/Abstract.php b/app/code/core/Mage/Paypal/Model/Api/Abstract.php
index ba66a505243..a5f5bf709fe 100644
--- a/app/code/core/Mage/Paypal/Model/Api/Abstract.php
+++ b/app/code/core/Mage/Paypal/Model/Api/Abstract.php
@@ -316,6 +316,26 @@ public function addRecurringPaymentProfiles(array $items)
return $this;
}
+ /**
+ * Define if debugging is enabled
+ *
+ * @return bool
+ */
+ public function getDebugFlag()
+ {
+ return $this->_config->debug;
+ }
+
+ /**
+ * Check whether API certificate authentication should be used
+ *
+ * @return bool
+ */
+ public function getUseCertAuthentication()
+ {
+ return (bool) $this->_config->apiAuthentication;
+ }
+
/**
* Export $this public data to private request array
*
@@ -559,24 +579,4 @@ protected function _debug($debugData)
->log($debugData);
}
}
-
- /**
- * Define if debugging is enabled
- *
- * @return bool
- */
- public function getDebugFlag()
- {
- return $this->_config->debug;
- }
-
- /**
- * Check whether API certificate authentication should be used
- *
- * @return bool
- */
- public function getUseCertAuthentication()
- {
- return (bool) $this->_config->apiAuthentication;
- }
}
diff --git a/app/code/core/Mage/Paypal/Model/Api/Nvp.php b/app/code/core/Mage/Paypal/Model/Api/Nvp.php
index 07ca5731558..c1aeaf41a5e 100644
--- a/app/code/core/Mage/Paypal/Model/Api/Nvp.php
+++ b/app/code/core/Mage/Paypal/Model/Api/Nvp.php
@@ -900,19 +900,6 @@ public function formatShippingOptionsCallback()
return $this->_buildQuery($response);
}
- /**
- * Add method to request array
- *
- * @param string $methodName
- * @param array $request
- * @return array
- */
- protected function _addMethodToRequest($methodName, $request)
- {
- $request['METHOD'] = $methodName;
- return $request;
- }
-
/**
* Do the API call
*
@@ -1011,6 +998,19 @@ public function setRawResponseNeeded($flag)
return $this;
}
+ /**
+ * Add method to request array
+ *
+ * @param string $methodName
+ * @param array $request
+ * @return array
+ */
+ protected function _addMethodToRequest($methodName, $request)
+ {
+ $request['METHOD'] = $methodName;
+ return $request;
+ }
+
/**
* Handle logical errors
*
diff --git a/app/code/core/Mage/Paypal/Model/Cart.php b/app/code/core/Mage/Paypal/Model/Cart.php
index a57a6d71583..1aecea1dbe2 100644
--- a/app/code/core/Mage/Paypal/Model/Cart.php
+++ b/app/code/core/Mage/Paypal/Model/Cart.php
@@ -263,6 +263,31 @@ public function isShippingAsItem($setValue = null)
return $this->_totalAsItem('_isShippingAsItem', $setValue);
}
+ /**
+ * Check whether items are valid
+ *
+ * @return bool
+ */
+ public function areItemsValid()
+ {
+ return $this->_areItemsValid;
+ }
+
+ /**
+ * Check whether any item has negative amount
+ *
+ * @return bool
+ */
+ public function hasNegativeItemAmount()
+ {
+ foreach ($this->_items as $item) {
+ if ($item->getAmount() < 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
/**
* (re)Render all items and totals
*/
@@ -415,16 +440,6 @@ protected function _validate()
$this->_areItemsValid = $this->_areItemsValid && $this->_areTotalsValid;
}
- /**
- * Check whether items are valid
- *
- * @return bool
- */
- public function areItemsValid()
- {
- return $this->_areItemsValid;
- }
-
/**
* Add a usual line item with amount and qty
*
@@ -504,19 +519,4 @@ private function _applyHiddenTaxWorkaround($salesEntity)
$this->_totals[self::TOTAL_TAX] += (float) $salesEntity->getBaseHiddenTaxAmount();
$this->_totals[self::TOTAL_TAX] += (float) $salesEntity->getBaseShippingHiddenTaxAmount();
}
-
- /**
- * Check whether any item has negative amount
- *
- * @return bool
- */
- public function hasNegativeItemAmount()
- {
- foreach ($this->_items as $item) {
- if ($item->getAmount() < 0) {
- return true;
- }
- }
- return false;
- }
}
diff --git a/app/code/core/Mage/Paypal/Model/Cert.php b/app/code/core/Mage/Paypal/Model/Cert.php
index fb3fd4fd878..ac81201ebde 100644
--- a/app/code/core/Mage/Paypal/Model/Cert.php
+++ b/app/code/core/Mage/Paypal/Model/Cert.php
@@ -27,11 +27,6 @@ class Mage_Paypal_Model_Cert extends Mage_Core_Model_Abstract
*/
public const BASEPATH_PAYPAL_CERT = 'cert/paypal';
- protected function _construct()
- {
- $this->_init('paypal/cert');
- }
-
/**
* Load model by website id
*
@@ -66,6 +61,11 @@ public function getCertPath()
return $certFile;
}
+ protected function _construct()
+ {
+ $this->_init('paypal/cert');
+ }
+
/**
* Create physical certificate file based on DB data
*
diff --git a/app/code/core/Mage/Paypal/Model/Config.php b/app/code/core/Mage/Paypal/Model/Config.php
index 6415dbc27d7..59fa8d5a990 100644
--- a/app/code/core/Mage/Paypal/Model/Config.php
+++ b/app/code/core/Mage/Paypal/Model/Config.php
@@ -644,6 +644,33 @@ public function __construct($params = [])
}
}
+ /**
+ * Config field magic getter
+ * The specified key can be either in camelCase or under_score format
+ * Tries to map specified value according to set payment method code, into the configuration value
+ * Sets the values into public class parameters, to avoid redundant calls of this method
+ *
+ * @param string $key
+ * @return string|null
+ */
+ public function __get($key)
+ {
+ if (array_key_exists($key, $this->_config)) {
+ return $this->_config[$key];
+ }
+
+ $underscored = strtolower(preg_replace('/(.)([A-Z])/', '$1_$2', $key));
+ if (array_key_exists($underscored, $this->_config)) {
+ return $this->_config[$underscored];
+ }
+
+ $value = Mage::getStoreConfig($this->_getSpecificConfigPath($underscored), $this->_storeId);
+ $value = $this->_prepareValue($underscored, $value);
+ $this->_config[$key] = $value;
+ $this->_config[$underscored] = $value;
+ return $value;
+ }
+
/**
* Method code setter
*
@@ -770,53 +797,6 @@ public function isMethodAvailable($methodCode = null)
return $result;
}
- /**
- * Config field magic getter
- * The specified key can be either in camelCase or under_score format
- * Tries to map specified value according to set payment method code, into the configuration value
- * Sets the values into public class parameters, to avoid redundant calls of this method
- *
- * @param string $key
- * @return string|null
- */
- public function __get($key)
- {
- if (array_key_exists($key, $this->_config)) {
- return $this->_config[$key];
- }
-
- $underscored = strtolower(preg_replace('/(.)([A-Z])/', '$1_$2', $key));
- if (array_key_exists($underscored, $this->_config)) {
- return $this->_config[$underscored];
- }
-
- $value = Mage::getStoreConfig($this->_getSpecificConfigPath($underscored), $this->_storeId);
- $value = $this->_prepareValue($underscored, $value);
- $this->_config[$key] = $value;
- $this->_config[$underscored] = $value;
- return $value;
- }
-
- /**
- * Perform additional config value preparation and return new value if needed
- *
- * @param string $key Underscored key
- * @param string $value Old value
- * @return string Modified value or old value
- */
- protected function _prepareValue($key, $value)
- {
- // Always set payment action as "Sale" for Unilateral payments in EC
- if ($key == 'payment_action'
- && $value != self::PAYMENT_ACTION_SALE
- && $this->_methodCode == self::METHOD_WPP_EXPRESS
- && $this->shouldUseUnilateralPayments()
- ) {
- return self::PAYMENT_ACTION_SALE;
- }
- return $value;
- }
-
/**
* Return merchant country codes supported by PayPal
*
@@ -1550,6 +1530,98 @@ public function exportExpressCheckoutStyleSettings(Varien_Object $to)
}
}
+ /**
+ * Payment API authentication methods source getter
+ *
+ * @return array
+ */
+ public function getApiAuthenticationMethods()
+ {
+ return [
+ '0' => Mage::helper('paypal')->__('API Signature'),
+ '1' => Mage::helper('paypal')->__('API Certificate'),
+ ];
+ }
+
+ /**
+ * Api certificate getter
+ *
+ * @return string
+ */
+ public function getApiCertificate()
+ {
+ $websiteId = Mage::app()->getStore($this->_storeId)->getWebsiteId();
+ return Mage::getModel('paypal/cert')->loadByWebsite($websiteId, false)->getCertPath();
+ }
+
+ /**
+ * Get PublisherId from stored config
+ *
+ * @return mixed
+ */
+ public function getBmlPublisherId()
+ {
+ return Mage::getStoreConfig('payment/paypal_express_bml/publisher_id', $this->_storeId);
+ }
+
+ /**
+ * Get Display option from stored config
+ * @param string $section
+ *
+ * @return mixed
+ */
+ public function getBmlDisplay($section)
+ {
+ $display = Mage::getStoreConfig('payment/paypal_express_bml/' . $section . '_display', $this->_storeId);
+ $ecActive = Mage::getStoreConfig('payment/paypal_express/active', $this->_storeId);
+ $ecUkActive = Mage::getStoreConfig('payment/paypaluk_express/active', $this->_storeId);
+ $bmlActive = Mage::getStoreConfig('payment/paypal_express_bml/active', $this->_storeId);
+ $bmlUkActive = Mage::getStoreConfig('payment/paypaluk_express_bml/active', $this->_storeId);
+ return (($bmlActive && $ecActive) || ($bmlUkActive && $ecUkActive)) ? $display : 0;
+ }
+
+ /**
+ * Get Position option from stored config
+ * @param string $section
+ *
+ * @return mixed
+ */
+ public function getBmlPosition($section)
+ {
+ return Mage::getStoreConfig('payment/paypal_express_bml/' . $section . '_position', $this->_storeId);
+ }
+
+ /**
+ * Get Size option from stored config
+ * @param string $section
+ *
+ * @return mixed
+ */
+ public function getBmlSize($section)
+ {
+ return Mage::getStoreConfig('payment/paypal_express_bml/' . $section . '_size', $this->_storeId);
+ }
+
+ /**
+ * Perform additional config value preparation and return new value if needed
+ *
+ * @param string $key Underscored key
+ * @param string $value Old value
+ * @return string Modified value or old value
+ */
+ protected function _prepareValue($key, $value)
+ {
+ // Always set payment action as "Sale" for Unilateral payments in EC
+ if ($key == 'payment_action'
+ && $value != self::PAYMENT_ACTION_SALE
+ && $this->_methodCode == self::METHOD_WPP_EXPRESS
+ && $this->shouldUseUnilateralPayments()
+ ) {
+ return self::PAYMENT_ACTION_SALE;
+ }
+ return $value;
+ }
+
/**
* Dynamic PayPal image URL getter
* Also can render dynamic Acceptance Mark
@@ -1871,76 +1943,4 @@ protected function _mapMethodFieldset($fieldName)
return null;
}
}
-
- /**
- * Payment API authentication methods source getter
- *
- * @return array
- */
- public function getApiAuthenticationMethods()
- {
- return [
- '0' => Mage::helper('paypal')->__('API Signature'),
- '1' => Mage::helper('paypal')->__('API Certificate'),
- ];
- }
-
- /**
- * Api certificate getter
- *
- * @return string
- */
- public function getApiCertificate()
- {
- $websiteId = Mage::app()->getStore($this->_storeId)->getWebsiteId();
- return Mage::getModel('paypal/cert')->loadByWebsite($websiteId, false)->getCertPath();
- }
-
- /**
- * Get PublisherId from stored config
- *
- * @return mixed
- */
- public function getBmlPublisherId()
- {
- return Mage::getStoreConfig('payment/paypal_express_bml/publisher_id', $this->_storeId);
- }
-
- /**
- * Get Display option from stored config
- * @param string $section
- *
- * @return mixed
- */
- public function getBmlDisplay($section)
- {
- $display = Mage::getStoreConfig('payment/paypal_express_bml/' . $section . '_display', $this->_storeId);
- $ecActive = Mage::getStoreConfig('payment/paypal_express/active', $this->_storeId);
- $ecUkActive = Mage::getStoreConfig('payment/paypaluk_express/active', $this->_storeId);
- $bmlActive = Mage::getStoreConfig('payment/paypal_express_bml/active', $this->_storeId);
- $bmlUkActive = Mage::getStoreConfig('payment/paypaluk_express_bml/active', $this->_storeId);
- return (($bmlActive && $ecActive) || ($bmlUkActive && $ecUkActive)) ? $display : 0;
- }
-
- /**
- * Get Position option from stored config
- * @param string $section
- *
- * @return mixed
- */
- public function getBmlPosition($section)
- {
- return Mage::getStoreConfig('payment/paypal_express_bml/' . $section . '_position', $this->_storeId);
- }
-
- /**
- * Get Size option from stored config
- * @param string $section
- *
- * @return mixed
- */
- public function getBmlSize($section)
- {
- return Mage::getStoreConfig('payment/paypal_express_bml/' . $section . '_size', $this->_storeId);
- }
}
diff --git a/app/code/core/Mage/Paypal/Model/Direct.php b/app/code/core/Mage/Paypal/Model/Direct.php
index aca456621b3..bb01fb1af84 100644
--- a/app/code/core/Mage/Paypal/Model/Direct.php
+++ b/app/code/core/Mage/Paypal/Model/Direct.php
@@ -280,6 +280,22 @@ public function fetchTransactionInfo(Mage_Payment_Model_Info $payment, $transact
return $this->_pro->fetchTransactionInfo($payment, $transactionId);
}
+ /**
+ * Check void availability
+ *
+ * @return bool
+ */
+ public function canVoid(Varien_Object $payment)
+ {
+ if ($payment instanceof Mage_Sales_Model_Order_Invoice
+ || $payment instanceof Mage_Sales_Model_Order_Creditmemo
+ ) {
+ return false;
+ }
+
+ return $this->_canVoid;
+ }
+
/**
* Place an order with authorization or capture action
*
@@ -366,20 +382,4 @@ protected function _importResultToPayment($api, $payment)
$payment->setTransactionId($api->getTransactionId())->setIsTransactionClosed(0);
$this->_pro->importPaymentInfo($api, $payment);
}
-
- /**
- * Check void availability
- *
- * @return bool
- */
- public function canVoid(Varien_Object $payment)
- {
- if ($payment instanceof Mage_Sales_Model_Order_Invoice
- || $payment instanceof Mage_Sales_Model_Order_Creditmemo
- ) {
- return false;
- }
-
- return $this->_canVoid;
- }
}
diff --git a/app/code/core/Mage/Paypal/Model/Express.php b/app/code/core/Mage/Paypal/Model/Express.php
index d2e27b1a905..9b8aa9cadfd 100644
--- a/app/code/core/Mage/Paypal/Model/Express.php
+++ b/app/code/core/Mage/Paypal/Model/Express.php
@@ -80,28 +80,6 @@ public function __construct($params = [])
$this->_setApiProcessableErrors();
}
- /**
- * Set processable error codes to API model
- *
- * @return Mage_Paypal_Model_Api_Nvp
- */
- protected function _setApiProcessableErrors()
- {
- return $this->_pro->getApi()->setProcessableErrors(
- [
- Mage_Paypal_Model_Api_ProcessableException::API_INTERNAL_ERROR,
- Mage_Paypal_Model_Api_ProcessableException::API_UNABLE_PROCESS_PAYMENT_ERROR_CODE,
- Mage_Paypal_Model_Api_ProcessableException::API_DO_EXPRESS_CHECKOUT_FAIL,
- Mage_Paypal_Model_Api_ProcessableException::API_UNABLE_TRANSACTION_COMPLETE,
- Mage_Paypal_Model_Api_ProcessableException::API_TRANSACTION_EXPIRED,
- Mage_Paypal_Model_Api_ProcessableException::API_MAX_PAYMENT_ATTEMPTS_EXCEEDED,
- Mage_Paypal_Model_Api_ProcessableException::API_COUNTRY_FILTER_DECLINE,
- Mage_Paypal_Model_Api_ProcessableException::API_MAXIMUM_AMOUNT_FILTER_DECLINE,
- Mage_Paypal_Model_Api_ProcessableException::API_OTHER_FILTER_DECLINE,
- ],
- );
- }
-
/**
* Store setter
* Also updates store ID in config object
@@ -537,61 +515,6 @@ public function assignData($data)
return $result;
}
- /**
- * Place an order with authorization or capture action
- *
- * @param float $amount
- * @return $this
- */
- protected function _placeOrder(Mage_Sales_Model_Order_Payment $payment, $amount)
- {
- $order = $payment->getOrder();
-
- // prepare api call
- $token = $payment->getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_TOKEN);
- $api = $this->_pro->getApi()
- ->setToken($token)
- ->setPayerId($payment->
- getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID))
- ->setAmount($amount)
- ->setPaymentAction($this->_pro->getConfig()->paymentAction)
- ->setNotifyUrl(Mage::getUrl('paypal/ipn/'))
- ->setInvNum($order->getIncrementId())
- ->setCurrencyCode($order->getBaseCurrencyCode())
- ->setPaypalCart(Mage::getModel('paypal/cart', [$order]))
- ->setIsLineItemsEnabled($this->_pro->getConfig()->lineItemsEnabled);
-
- // call api and get details from it
- $api->callDoExpressCheckoutPayment();
-
- $this->_importToPayment($api, $payment);
- return $this;
- }
-
- /**
- * Import payment info to payment
- *
- * @param Mage_Paypal_Model_Api_Nvp $api
- * @param Mage_Sales_Model_Order_Payment $payment
- */
- protected function _importToPayment($api, $payment)
- {
- $payment->setTransactionId($api->getTransactionId())->setIsTransactionClosed(0)
- ->setAdditionalInformation(
- Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_REDIRECT,
- $api->getRedirectRequired(),
- );
-
- if ($api->getBillingAgreementId()) {
- $payment->setBillingAgreementData([
- 'billing_agreement_id' => $api->getBillingAgreementId(),
- 'method_code' => Mage_Paypal_Model_Config::METHOD_BILLING_AGREEMENT,
- ]);
- }
-
- $this->_pro->importPaymentInfo($api, $payment);
- }
-
/**
* Check void availability
*
@@ -650,6 +573,83 @@ public function canCapture()
return $this->_canCapture;
}
+ /**
+ * Set processable error codes to API model
+ *
+ * @return Mage_Paypal_Model_Api_Nvp
+ */
+ protected function _setApiProcessableErrors()
+ {
+ return $this->_pro->getApi()->setProcessableErrors(
+ [
+ Mage_Paypal_Model_Api_ProcessableException::API_INTERNAL_ERROR,
+ Mage_Paypal_Model_Api_ProcessableException::API_UNABLE_PROCESS_PAYMENT_ERROR_CODE,
+ Mage_Paypal_Model_Api_ProcessableException::API_DO_EXPRESS_CHECKOUT_FAIL,
+ Mage_Paypal_Model_Api_ProcessableException::API_UNABLE_TRANSACTION_COMPLETE,
+ Mage_Paypal_Model_Api_ProcessableException::API_TRANSACTION_EXPIRED,
+ Mage_Paypal_Model_Api_ProcessableException::API_MAX_PAYMENT_ATTEMPTS_EXCEEDED,
+ Mage_Paypal_Model_Api_ProcessableException::API_COUNTRY_FILTER_DECLINE,
+ Mage_Paypal_Model_Api_ProcessableException::API_MAXIMUM_AMOUNT_FILTER_DECLINE,
+ Mage_Paypal_Model_Api_ProcessableException::API_OTHER_FILTER_DECLINE,
+ ],
+ );
+ }
+
+ /**
+ * Place an order with authorization or capture action
+ *
+ * @param float $amount
+ * @return $this
+ */
+ protected function _placeOrder(Mage_Sales_Model_Order_Payment $payment, $amount)
+ {
+ $order = $payment->getOrder();
+
+ // prepare api call
+ $token = $payment->getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_TOKEN);
+ $api = $this->_pro->getApi()
+ ->setToken($token)
+ ->setPayerId($payment->
+ getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID))
+ ->setAmount($amount)
+ ->setPaymentAction($this->_pro->getConfig()->paymentAction)
+ ->setNotifyUrl(Mage::getUrl('paypal/ipn/'))
+ ->setInvNum($order->getIncrementId())
+ ->setCurrencyCode($order->getBaseCurrencyCode())
+ ->setPaypalCart(Mage::getModel('paypal/cart', [$order]))
+ ->setIsLineItemsEnabled($this->_pro->getConfig()->lineItemsEnabled);
+
+ // call api and get details from it
+ $api->callDoExpressCheckoutPayment();
+
+ $this->_importToPayment($api, $payment);
+ return $this;
+ }
+
+ /**
+ * Import payment info to payment
+ *
+ * @param Mage_Paypal_Model_Api_Nvp $api
+ * @param Mage_Sales_Model_Order_Payment $payment
+ */
+ protected function _importToPayment($api, $payment)
+ {
+ $payment->setTransactionId($api->getTransactionId())->setIsTransactionClosed(0)
+ ->setAdditionalInformation(
+ Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_REDIRECT,
+ $api->getRedirectRequired(),
+ );
+
+ if ($api->getBillingAgreementId()) {
+ $payment->setBillingAgreementData([
+ 'billing_agreement_id' => $api->getBillingAgreementId(),
+ 'method_code' => Mage_Paypal_Model_Config::METHOD_BILLING_AGREEMENT,
+ ]);
+ }
+
+ $this->_pro->importPaymentInfo($api, $payment);
+ }
+
/**
* Call DoAuthorize
*
diff --git a/app/code/core/Mage/Paypal/Model/Express/Checkout.php b/app/code/core/Mage/Paypal/Model/Express/Checkout.php
index 0ec6258ad76..2783a175739 100644
--- a/app/code/core/Mage/Paypal/Model/Express/Checkout.php
+++ b/app/code/core/Mage/Paypal/Model/Express/Checkout.php
@@ -630,20 +630,6 @@ public function place($token, $shippingMethodCode = null)
$this->_order = $order;
}
- /**
- * Make sure addresses will be saved without validation errors
- */
- private function _ignoreAddressValidation()
- {
- $this->_quote->getBillingAddress()->setShouldIgnoreValidation(true);
- if (!$this->_quote->getIsVirtual()) {
- $this->_quote->getShippingAddress()->setShouldIgnoreValidation(true);
- if (!$this->_config->requireBillingAddress && !$this->_quote->getBillingAddress()->getEmail()) {
- $this->_quote->getBillingAddress()->setSameAsBilling(1);
- }
- }
- }
-
/**
* Determine whether redirect somewhere specifically is required
*
@@ -704,6 +690,16 @@ public function getCheckoutMethod()
return $this->_quote->getCheckoutMethod();
}
+ /**
+ * Get customer session object
+ *
+ * @return Mage_Customer_Model_Session
+ */
+ public function getCustomerSession()
+ {
+ return $this->_customerSession;
+ }
+
/**
* Sets address data from exported address
*
@@ -1049,16 +1045,6 @@ protected function _involveNewCustomer()
return $this;
}
- /**
- * Get customer session object
- *
- * @return Mage_Customer_Model_Session
- */
- public function getCustomerSession()
- {
- return $this->_customerSession;
- }
-
/**
* Check if customer email exists
*
@@ -1080,4 +1066,18 @@ protected function _customerEmailExists($email)
return $result;
}
+
+ /**
+ * Make sure addresses will be saved without validation errors
+ */
+ private function _ignoreAddressValidation()
+ {
+ $this->_quote->getBillingAddress()->setShouldIgnoreValidation(true);
+ if (!$this->_quote->getIsVirtual()) {
+ $this->_quote->getShippingAddress()->setShouldIgnoreValidation(true);
+ if (!$this->_config->requireBillingAddress && !$this->_quote->getBillingAddress()->getEmail()) {
+ $this->_quote->getBillingAddress()->setSameAsBilling(1);
+ }
+ }
+ }
}
diff --git a/app/code/core/Mage/Paypal/Model/Hostedpro.php b/app/code/core/Mage/Paypal/Model/Hostedpro.php
index d36cc5941d7..fff76c1d546 100644
--- a/app/code/core/Mage/Paypal/Model/Hostedpro.php
+++ b/app/code/core/Mage/Paypal/Model/Hostedpro.php
@@ -145,6 +145,39 @@ public function initialize($paymentAction, $stateObject)
return $this;
}
+ /**
+ * Get return URL
+ *
+ * @param int $storeId
+ * @return string
+ */
+ public function getReturnUrl($storeId = null)
+ {
+ return $this->_getUrl('paypal/hostedpro/return', $storeId);
+ }
+
+ /**
+ * Get notify (IPN) URL
+ *
+ * @param int $storeId
+ * @return string
+ */
+ public function getNotifyUrl($storeId = null)
+ {
+ return $this->_getUrl('paypal/ipn', $storeId);
+ }
+
+ /**
+ * Get cancel URL
+ *
+ * @param int $storeId
+ * @return string
+ */
+ public function getCancelUrl($storeId = null)
+ {
+ return $this->_getUrl('paypal/hostedpro/cancel', $storeId);
+ }
+
/**
* Sends API request to PayPal to get form URL, then sets this URL to $payment object.
*/
@@ -200,39 +233,6 @@ protected function _buildBasicRequest()
return $request;
}
- /**
- * Get return URL
- *
- * @param int $storeId
- * @return string
- */
- public function getReturnUrl($storeId = null)
- {
- return $this->_getUrl('paypal/hostedpro/return', $storeId);
- }
-
- /**
- * Get notify (IPN) URL
- *
- * @param int $storeId
- * @return string
- */
- public function getNotifyUrl($storeId = null)
- {
- return $this->_getUrl('paypal/ipn', $storeId);
- }
-
- /**
- * Get cancel URL
- *
- * @param int $storeId
- * @return string
- */
- public function getCancelUrl($storeId = null)
- {
- return $this->_getUrl('paypal/hostedpro/cancel', $storeId);
- }
-
/**
* Build URL for store
*
diff --git a/app/code/core/Mage/Paypal/Model/Info.php b/app/code/core/Mage/Paypal/Model/Info.php
index 2233c98bf1a..1c74cfc9b79 100644
--- a/app/code/core/Mage/Paypal/Model/Info.php
+++ b/app/code/core/Mage/Paypal/Model/Info.php
@@ -61,39 +61,6 @@ class Mage_Paypal_Model_Info
public const BUYER_TAX_ID_TYPE_CPF = 'BR_CPF';
public const BUYER_TAX_ID_TYPE_CNPJ = 'BR_CNPJ';
- /**
- * All payment information map
- *
- * @var array
- */
- protected $_paymentMap = [
- self::PAYER_ID => 'paypal_payer_id',
- self::PAYER_EMAIL => 'paypal_payer_email',
- self::PAYER_STATUS => 'paypal_payer_status',
- self::ADDRESS_ID => 'paypal_address_id',
- self::ADDRESS_STATUS => 'paypal_address_status',
- self::PROTECTION_EL => 'paypal_protection_eligibility',
- self::FRAUD_FILTERS => 'paypal_fraud_filters',
- self::CORRELATION_ID => 'paypal_correlation_id',
- self::AVS_CODE => 'paypal_avs_code',
- self::CVV2_MATCH => 'paypal_cvv2_match',
- self::CENTINEL_VPAS => self::CENTINEL_VPAS,
- self::CENTINEL_ECI => self::CENTINEL_ECI,
- self::BUYER_TAX_ID => self::BUYER_TAX_ID,
- self::BUYER_TAX_ID_TYPE => self::BUYER_TAX_ID_TYPE,
- ];
-
- /**
- * System information map
- *
- * @var array
- */
- protected $_systemMap = [
- self::PAYMENT_STATUS => self::PAYMENT_STATUS_GLOBAL,
- self::PENDING_REASON => self::PENDING_REASON_GLOBAL,
- self::IS_FRAUD => self::IS_FRAUD_GLOBAL,
- ];
-
/**
* PayPal payment status possible values
*
@@ -134,6 +101,39 @@ class Mage_Paypal_Model_Info
*/
public const ORDER_STATUS_CANCELED_REVERSAL = 'paypal_canceled_reversal';
+ /**
+ * All payment information map
+ *
+ * @var array
+ */
+ protected $_paymentMap = [
+ self::PAYER_ID => 'paypal_payer_id',
+ self::PAYER_EMAIL => 'paypal_payer_email',
+ self::PAYER_STATUS => 'paypal_payer_status',
+ self::ADDRESS_ID => 'paypal_address_id',
+ self::ADDRESS_STATUS => 'paypal_address_status',
+ self::PROTECTION_EL => 'paypal_protection_eligibility',
+ self::FRAUD_FILTERS => 'paypal_fraud_filters',
+ self::CORRELATION_ID => 'paypal_correlation_id',
+ self::AVS_CODE => 'paypal_avs_code',
+ self::CVV2_MATCH => 'paypal_cvv2_match',
+ self::CENTINEL_VPAS => self::CENTINEL_VPAS,
+ self::CENTINEL_ECI => self::CENTINEL_ECI,
+ self::BUYER_TAX_ID => self::BUYER_TAX_ID,
+ self::BUYER_TAX_ID_TYPE => self::BUYER_TAX_ID_TYPE,
+ ];
+
+ /**
+ * System information map
+ *
+ * @var array
+ */
+ protected $_systemMap = [
+ self::PAYMENT_STATUS => self::PAYMENT_STATUS_GLOBAL,
+ self::PENDING_REASON => self::PENDING_REASON_GLOBAL,
+ self::IS_FRAUD => self::IS_FRAUD_GLOBAL,
+ ];
+
/**
* Map of payment information available to customer
*
@@ -386,6 +386,22 @@ public static function isReversalDisputable($code)
}
}
+ /**
+ * Get case type label
+ *
+ * @param string $key
+ * @return string
+ */
+ public static function getCaseTypeLabel($key)
+ {
+ $labels = [
+ 'chargeback' => Mage::helper('paypal')->__('Chargeback'),
+ 'complaint' => Mage::helper('paypal')->__('Complaint'),
+ 'dispute' => Mage::helper('paypal')->__('Dispute'),
+ ];
+ return (array_key_exists($key, $labels) && !empty($labels[$key])) ? $labels[$key] : '';
+ }
+
/**
* Render info item
*
@@ -461,22 +477,6 @@ protected function _getLabel($key)
return '';
}
- /**
- * Get case type label
- *
- * @param string $key
- * @return string
- */
- public static function getCaseTypeLabel($key)
- {
- $labels = [
- 'chargeback' => Mage::helper('paypal')->__('Chargeback'),
- 'complaint' => Mage::helper('paypal')->__('Complaint'),
- 'dispute' => Mage::helper('paypal')->__('Dispute'),
- ];
- return (array_key_exists($key, $labels) && !empty($labels[$key])) ? $labels[$key] : '';
- }
-
/**
* Apply a filter upon value getting
*
@@ -612,6 +612,26 @@ protected function _getCvv2Label($value)
}
}
+ /**
+ * Retrieve buyer id type value based on code received from PayPal (Brazil only)
+ *
+ * @param string $code
+ * @return string
+ */
+ protected function _getBuyerIdTypeValue($code)
+ {
+ $value = '';
+ switch ($code) {
+ case self::BUYER_TAX_ID_TYPE_CNPJ:
+ $value = Mage::helper('paypal')->__('CNPJ');
+ break;
+ case self::BUYER_TAX_ID_TYPE_CPF:
+ $value = Mage::helper('paypal')->__('CPF');
+ break;
+ }
+ return $value;
+ }
+
/**
* Attempt to convert centinel VPAS result into label
*
@@ -667,24 +687,4 @@ private function _getCentinelEciLabel($value)
return $value;
}
}
-
- /**
- * Retrieve buyer id type value based on code received from PayPal (Brazil only)
- *
- * @param string $code
- * @return string
- */
- protected function _getBuyerIdTypeValue($code)
- {
- $value = '';
- switch ($code) {
- case self::BUYER_TAX_ID_TYPE_CNPJ:
- $value = Mage::helper('paypal')->__('CNPJ');
- break;
- case self::BUYER_TAX_ID_TYPE_CPF:
- $value = Mage::helper('paypal')->__('CPF');
- break;
- }
- return $value;
- }
}
diff --git a/app/code/core/Mage/Paypal/Model/Ipn.php b/app/code/core/Mage/Paypal/Model/Ipn.php
index 28c687be827..7aafeda3039 100644
--- a/app/code/core/Mage/Paypal/Model/Ipn.php
+++ b/app/code/core/Mage/Paypal/Model/Ipn.php
@@ -116,6 +116,40 @@ public function processIpnRequest(array $request, ?Zend_Http_Client_Adapter_Inte
$this->_debug();
}
+ /**
+ * Process payment pending notification
+ *
+ * @throws Exception
+ */
+ public function _registerPaymentPending()
+ {
+ $reason = $this->getRequestData('pending_reason');
+ if ($reason === 'authorization') {
+ $this->_registerPaymentAuthorization();
+ return;
+ }
+ if ($reason === 'order') {
+ throw new Exception('The "order" authorizations are not implemented.');
+ }
+
+ // case when was placed using PayPal standard
+ if (Mage_Sales_Model_Order::STATE_PENDING_PAYMENT == $this->_order->getState()
+ && !$this->getRequestData('transaction_entity')
+ ) {
+ $this->_registerPaymentCapture();
+ return;
+ }
+
+ $this->_importPaymentInformation();
+
+ $this->_order->getPayment()
+ ->setPreparedMessage($this->_createIpnComment($this->_info::explainPendingReason($reason)))
+ ->setTransactionId($this->getRequestData('txn_id'))
+ ->setIsTransactionClosed(0)
+ ->registerPaymentReviewAction(Mage_Sales_Model_Order_Payment::REVIEW_ACTION_UPDATE, false);
+ $this->_order->save();
+ }
+
/**
* Post back to PayPal to check whether this request is a valid one
*
@@ -604,40 +638,6 @@ protected function _registerPaymentReversal()
->save();
}
- /**
- * Process payment pending notification
- *
- * @throws Exception
- */
- public function _registerPaymentPending()
- {
- $reason = $this->getRequestData('pending_reason');
- if ($reason === 'authorization') {
- $this->_registerPaymentAuthorization();
- return;
- }
- if ($reason === 'order') {
- throw new Exception('The "order" authorizations are not implemented.');
- }
-
- // case when was placed using PayPal standard
- if (Mage_Sales_Model_Order::STATE_PENDING_PAYMENT == $this->_order->getState()
- && !$this->getRequestData('transaction_entity')
- ) {
- $this->_registerPaymentCapture();
- return;
- }
-
- $this->_importPaymentInformation();
-
- $this->_order->getPayment()
- ->setPreparedMessage($this->_createIpnComment($this->_info::explainPendingReason($reason)))
- ->setTransactionId($this->getRequestData('txn_id'))
- ->setIsTransactionClosed(0)
- ->registerPaymentReviewAction(Mage_Sales_Model_Order_Payment::REVIEW_ACTION_UPDATE, false);
- $this->_order->save();
- }
-
/**
* Register authorized payment
*/
diff --git a/app/code/core/Mage/Paypal/Model/Method/Agreement.php b/app/code/core/Mage/Paypal/Model/Method/Agreement.php
index 192e74c3092..766d893e765 100644
--- a/app/code/core/Mage/Paypal/Model/Method/Agreement.php
+++ b/app/code/core/Mage/Paypal/Model/Method/Agreement.php
@@ -270,6 +270,17 @@ public function fetchTransactionInfo(Mage_Payment_Model_Info $payment, $transact
return $this->_pro->fetchTransactionInfo($payment, $transactionId);
}
+ /**
+ * Payment action getter compatible with payment model
+ *
+ * @see Mage_Sales_Model_Payment::place()
+ * @return string
+ */
+ public function getConfigPaymentAction()
+ {
+ return $this->_pro->getConfig()->getPaymentAction();
+ }
+
/**
* Place an order with authorization or capture action
*
@@ -319,15 +330,4 @@ protected function _isAvailable($quote)
{
return $this->_pro->getConfig()->isMethodAvailable($this->_code);
}
-
- /**
- * Payment action getter compatible with payment model
- *
- * @see Mage_Sales_Model_Payment::place()
- * @return string
- */
- public function getConfigPaymentAction()
- {
- return $this->_pro->getConfig()->getPaymentAction();
- }
}
diff --git a/app/code/core/Mage/Paypal/Model/Payflowlink.php b/app/code/core/Mage/Paypal/Model/Payflowlink.php
index f783ebcd1e0..ba0136b3d3c 100644
--- a/app/code/core/Mage/Paypal/Model/Payflowlink.php
+++ b/app/code/core/Mage/Paypal/Model/Payflowlink.php
@@ -32,6 +32,18 @@ class Mage_Paypal_Model_Payflowlink extends Mage_Paypal_Model_Payflowpro
*/
public const MOBILE_LAYOUT_TEMPLATE = 'mobile';
+ /**
+ * Gateway request URL
+ * @var string
+ */
+ public const TRANSACTION_PAYFLOW_URL = 'https://payflowlink.paypal.com/';
+
+ /**
+ * Error message
+ * @var string
+ */
+ public const RESPONSE_ERROR_MSG = 'Payment error. %s was not found.';
+
/**
* Controller for callback urls
*
@@ -89,18 +101,6 @@ class Mage_Paypal_Model_Payflowlink extends Mage_Paypal_Model_Payflowpro
*/
protected $_response;
- /**
- * Gateway request URL
- * @var string
- */
- public const TRANSACTION_PAYFLOW_URL = 'https://payflowlink.paypal.com/';
-
- /**
- * Error message
- * @var string
- */
- public const RESPONSE_ERROR_MSG = 'Payment error. %s was not found.';
-
/**
* Key for storing secure hash in additional information of payment model
*
@@ -250,6 +250,24 @@ public function process($responseData)
}
}
+ /**
+ * Check whether order review has enough data to initialize
+ *
+ * @deprecated since 1.6.2.0
+ * @param string $token
+ */
+ public function prepareOrderReview($token = null) {}
+
+ /**
+ * Get callback controller
+ *
+ * @return string
+ */
+ public function getCallbackController()
+ {
+ return $this->_callbackController;
+ }
+
/**
* Operate with order using information from silent post
*/
@@ -570,14 +588,6 @@ protected function _initialize(Varien_Object $payment, $amount)
return $this;
}
- /**
- * Check whether order review has enough data to initialize
- *
- * @deprecated since 1.6.2.0
- * @param string $token
- */
- public function prepareOrderReview($token = null) {}
-
/**
* Additional authorization logic for Account Verification
*
@@ -623,16 +633,6 @@ protected function _getDocumentFromResponse()
return null;
}
- /**
- * Get callback controller
- *
- * @return string
- */
- public function getCallbackController()
- {
- return $this->_callbackController;
- }
-
/**
* Get callback url
*
diff --git a/app/code/core/Mage/Paypal/Model/Payflowpro.php b/app/code/core/Mage/Paypal/Model/Payflowpro.php
index 0fcf420731d..ff6a4a4421f 100644
--- a/app/code/core/Mage/Paypal/Model/Payflowpro.php
+++ b/app/code/core/Mage/Paypal/Model/Payflowpro.php
@@ -163,20 +163,6 @@ public function authorize(Varien_Object $payment, $amount)
return $this;
}
- /**
- * Get capture amount
- *
- * @param float $amount
- * @return float
- */
- protected function _getCaptureAmount($amount)
- {
- $infoInstance = $this->getInfoInstance();
- $amountToPay = round($amount, 2);
- $authorizedAmount = round($infoInstance->getAmountAuthorized(), 2);
- return $amountToPay != $authorizedAmount ? $amountToPay : 0;
- }
-
/**
* Capture payment
*
@@ -327,6 +313,20 @@ public function fetchTransactionInfo(Mage_Payment_Model_Info $payment, $transact
return ($rawData) ? $rawData : [];
}
+ /**
+ * Get capture amount
+ *
+ * @param float $amount
+ * @return float
+ */
+ protected function _getCaptureAmount($amount)
+ {
+ $infoInstance = $this->getInfoInstance();
+ $amountToPay = round($amount, 2);
+ $authorizedAmount = round($infoInstance->getAmountAuthorized(), 2);
+ return $amountToPay != $authorizedAmount ? $amountToPay : 0;
+ }
+
/**
* Check whether the transaction is in payment review status
*
diff --git a/app/code/core/Mage/Paypal/Model/Payment/Transaction.php b/app/code/core/Mage/Paypal/Model/Payment/Transaction.php
index cd1dd38a34f..1586fa6e7d8 100644
--- a/app/code/core/Mage/Paypal/Model/Payment/Transaction.php
+++ b/app/code/core/Mage/Paypal/Model/Payment/Transaction.php
@@ -55,15 +55,6 @@ class Mage_Paypal_Model_Payment_Transaction extends Mage_Core_Model_Abstract
*/
protected $_orderWebsiteId = null;
- /**
- * Initialize resource model
- */
- protected function _construct()
- {
- $this->_init('paypal/payment_transaction');
- parent::_construct();
- }
-
/**
* Transaction ID setter
* @param string $txnId
@@ -75,20 +66,6 @@ public function setTxnId($txnId)
return $this->setData('txn_id', $txnId);
}
- /**
- * Check object before loading by by specified transaction ID
- * @param string $txnId
- * @return $this
- */
- protected function _beforeLoadByTxnId($txnId)
- {
- Mage::dispatchEvent(
- $this->_eventPrefix . '_load_by_txn_id_before',
- $this->_getEventData() + ['txn_id' => $txnId],
- );
- return $this;
- }
-
/**
* Load self by specified transaction ID. Requires the valid payment object to be set
* @param string $txnId
@@ -105,17 +82,6 @@ public function loadByTxnId($txnId)
return $this;
}
- /**
- * Check object after loading by by specified transaction ID
- *
- * @return $this
- */
- protected function _afterLoadByTxnId()
- {
- Mage::dispatchEvent($this->_eventPrefix . '_load_by_txn_id_after', $this->_getEventData());
- return $this;
- }
-
/**
* Additional information setter
* Updates data inside the 'additional_information' array
@@ -189,6 +155,40 @@ public function isFailsafe($setFailsafe = null)
return $this;
}
+ /**
+ * Initialize resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('paypal/payment_transaction');
+ parent::_construct();
+ }
+
+ /**
+ * Check object before loading by by specified transaction ID
+ * @param string $txnId
+ * @return $this
+ */
+ protected function _beforeLoadByTxnId($txnId)
+ {
+ Mage::dispatchEvent(
+ $this->_eventPrefix . '_load_by_txn_id_before',
+ $this->_getEventData() + ['txn_id' => $txnId],
+ );
+ return $this;
+ }
+
+ /**
+ * Check object after loading by by specified transaction ID
+ *
+ * @return $this
+ */
+ protected function _afterLoadByTxnId()
+ {
+ Mage::dispatchEvent($this->_eventPrefix . '_load_by_txn_id_after', $this->_getEventData());
+ return $this;
+ }
+
/**
* Verify data required for saving
* @return $this
diff --git a/app/code/core/Mage/Paypal/Model/Report/Settlement.php b/app/code/core/Mage/Paypal/Model/Report/Settlement.php
index 699006fdfb0..c9c3991f113 100644
--- a/app/code/core/Mage/Paypal/Model/Report/Settlement.php
+++ b/app/code/core/Mage/Paypal/Model/Report/Settlement.php
@@ -153,28 +153,6 @@ class Mage_Paypal_Model_Report_Settlement extends Mage_Core_Model_Abstract
],
];
- protected function _construct()
- {
- $this->_init('paypal/report_settlement');
- }
-
- /**
- * Stop saving process if file with same report date, account ID and last modified date was already ferched
- *
- * @return Mage_Core_Model_Abstract
- */
- protected function _beforeSave()
- {
- $this->_dataSaveAllowed = true;
- if ($this->getId()) {
- if ($this->getLastModified() == $this->getReportLastModified()) {
- $this->_dataSaveAllowed = false;
- }
- }
- $this->setLastModified($this->getReportLastModified());
- return parent::_beforeSave();
- }
-
/**
* Goes to specified host/path and fetches reports from there.
* Save reports to database.
@@ -407,6 +385,28 @@ public function getSftpCredentials($automaticMode = false)
return $configs;
}
+ protected function _construct()
+ {
+ $this->_init('paypal/report_settlement');
+ }
+
+ /**
+ * Stop saving process if file with same report date, account ID and last modified date was already ferched
+ *
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _beforeSave()
+ {
+ $this->_dataSaveAllowed = true;
+ if ($this->getId()) {
+ if ($this->getLastModified() == $this->getReportLastModified()) {
+ $this->_dataSaveAllowed = false;
+ }
+ }
+ $this->setLastModified($this->getReportLastModified());
+ return parent::_beforeSave();
+ }
+
/**
* Converts a filename to date of report.
*
diff --git a/app/code/core/Mage/Paypal/Model/Report/Settlement/Row.php b/app/code/core/Mage/Paypal/Model/Report/Settlement/Row.php
index 4beace06631..a61e8bb0b34 100644
--- a/app/code/core/Mage/Paypal/Model/Report/Settlement/Row.php
+++ b/app/code/core/Mage/Paypal/Model/Report/Settlement/Row.php
@@ -71,11 +71,6 @@ class Mage_Paypal_Model_Report_Settlement_Row extends Mage_Core_Model_Abstract
*/
protected $_castedAmounts = [];
- protected function _construct()
- {
- $this->_init('paypal/report_settlement_row');
- }
-
/**
* Return description of Reference ID Type
* If no code specified, return full list of codes with their description
@@ -179,6 +174,11 @@ public function _castAmount($key, $creditKey)
$this->_castedAmounts[$key] = true;
}
+ protected function _construct()
+ {
+ $this->_init('paypal/report_settlement_row');
+ }
+
/**
* Fill/translate and sort all event codes/labels
*/
diff --git a/app/code/core/Mage/Paypal/Model/Resource/Cert.php b/app/code/core/Mage/Paypal/Model/Resource/Cert.php
index af337e62046..b0114bb4c9e 100644
--- a/app/code/core/Mage/Paypal/Model/Resource/Cert.php
+++ b/app/code/core/Mage/Paypal/Model/Resource/Cert.php
@@ -22,22 +22,6 @@
*/
class Mage_Paypal_Model_Resource_Cert extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('paypal/cert', 'cert_id');
- }
-
- /**
- * Set date of last update
- *
- * @return Mage_Core_Model_Resource_Db_Abstract
- */
- protected function _beforeSave(Mage_Core_Model_Abstract $object)
- {
- $object->setUpdatedAt($this->formatDate(Mage::getSingleton('core/date')->gmtDate()));
- return parent::_beforeSave($object);
- }
-
/**
* Load model by website id
*
@@ -64,4 +48,19 @@ public function loadByWebsite($object, $strictLoad = true)
}
return $object;
}
+ protected function _construct()
+ {
+ $this->_init('paypal/cert', 'cert_id');
+ }
+
+ /**
+ * Set date of last update
+ *
+ * @return Mage_Core_Model_Resource_Db_Abstract
+ */
+ protected function _beforeSave(Mage_Core_Model_Abstract $object)
+ {
+ $object->setUpdatedAt($this->formatDate(Mage::getSingleton('core/date')->gmtDate()));
+ return parent::_beforeSave($object);
+ }
}
diff --git a/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction.php b/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction.php
index aa108b9bc65..bb4e75e9724 100644
--- a/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction.php
+++ b/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction.php
@@ -32,6 +32,20 @@ class Mage_Paypal_Model_Resource_Payment_Transaction extends Mage_Core_Model_Res
'additional_information' => [null, []],
];
+ /**
+ * Load the transaction object by specified txn_id
+ *
+ * @param string $txnId
+ */
+ public function loadObjectByTxnId(Mage_Paypal_Model_Payment_Transaction $transaction, $txnId)
+ {
+ $select = $this->_getLoadByUniqueKeySelect($txnId);
+ $data = $this->_getWriteAdapter()->fetchRow($select);
+ $transaction->setData($data);
+ $this->unserializeFields($transaction);
+ $this->_afterLoad($transaction);
+ }
+
/**
* Initialize main table and the primary key field name
*
@@ -61,20 +75,6 @@ protected function _unserializeField(Varien_Object $object, $field, $defaultValu
}
}
- /**
- * Load the transaction object by specified txn_id
- *
- * @param string $txnId
- */
- public function loadObjectByTxnId(Mage_Paypal_Model_Payment_Transaction $transaction, $txnId)
- {
- $select = $this->_getLoadByUniqueKeySelect($txnId);
- $data = $this->_getWriteAdapter()->fetchRow($select);
- $transaction->setData($data);
- $this->unserializeFields($transaction);
- $this->_afterLoad($transaction);
- }
-
/**
* Serialize additional information, if any
*
diff --git a/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction/Collection.php b/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction/Collection.php
index 1113f8ee8e6..d1c62b7488e 100644
--- a/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction/Collection.php
+++ b/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction/Collection.php
@@ -29,14 +29,6 @@ class Mage_Paypal_Model_Resource_Payment_Transaction_Collection extends Mage_Cor
* @var string
*/
protected $_createdBefore = '';
- /**
- * Initialize collection items factory class
- */
- protected function _construct()
- {
- $this->_init('paypal/payment_transaction');
- parent::_construct();
- }
/**
* CreatedAt filter setter
@@ -49,6 +41,14 @@ public function addCreatedBeforeFilter($date)
$this->_createdBefore = $date;
return $this;
}
+ /**
+ * Initialize collection items factory class
+ */
+ protected function _construct()
+ {
+ $this->_init('paypal/payment_transaction');
+ parent::_construct();
+ }
/**
* Prepare filters
diff --git a/app/code/core/Mage/Paypal/Model/Resource/Report/Settlement.php b/app/code/core/Mage/Paypal/Model/Resource/Report/Settlement.php
index eb819bbaa9a..8dfe9d3b505 100644
--- a/app/code/core/Mage/Paypal/Model/Resource/Report/Settlement.php
+++ b/app/code/core/Mage/Paypal/Model/Resource/Report/Settlement.php
@@ -29,6 +29,29 @@ class Mage_Paypal_Model_Resource_Report_Settlement extends Mage_Core_Model_Resou
*/
protected $_rowsTable;
+ /**
+ * Check if report with same account and report date already fetched
+ *
+ * @param string $accountId
+ * @param string $reportDate
+ * @return $this
+ */
+ public function loadByAccountAndDate(Mage_Paypal_Model_Report_Settlement $report, $accountId, $reportDate)
+ {
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from($this->getMainTable())
+ ->where('account_id = :account_id')
+ ->where('report_date = :report_date');
+
+ $data = $adapter->fetchRow($select, [':account_id' => $accountId, ':report_date' => $reportDate]);
+ if ($data) {
+ $report->addData($data);
+ }
+
+ return $this;
+ }
+
/**
* Init main table
*
@@ -87,27 +110,4 @@ protected function _afterSave(Mage_Core_Model_Abstract $object)
return $this;
}
-
- /**
- * Check if report with same account and report date already fetched
- *
- * @param string $accountId
- * @param string $reportDate
- * @return $this
- */
- public function loadByAccountAndDate(Mage_Paypal_Model_Report_Settlement $report, $accountId, $reportDate)
- {
- $adapter = $this->_getReadAdapter();
- $select = $adapter->select()
- ->from($this->getMainTable())
- ->where('account_id = :account_id')
- ->where('report_date = :report_date');
-
- $data = $adapter->fetchRow($select, [':account_id' => $accountId, ':report_date' => $reportDate]);
- if ($data) {
- $report->addData($data);
- }
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Paypal/Model/Resource/Report/Settlement/Row/Collection.php b/app/code/core/Mage/Paypal/Model/Resource/Report/Settlement/Row/Collection.php
index 424e0fbae85..3cc5e4bc3c1 100644
--- a/app/code/core/Mage/Paypal/Model/Resource/Report/Settlement/Row/Collection.php
+++ b/app/code/core/Mage/Paypal/Model/Resource/Report/Settlement/Row/Collection.php
@@ -22,6 +22,17 @@
*/
class Mage_Paypal_Model_Resource_Report_Settlement_Row_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
+ /**
+ * Filter items collection by account ID
+ *
+ * @param string $accountId
+ * @return $this
+ */
+ public function addAccountFilter($accountId)
+ {
+ $this->getSelect()->where('report.account_id = ?', $accountId);
+ return $this;
+ }
/**
* Resource initializing
*
@@ -47,16 +58,4 @@ protected function _initSelect()
);
return $this;
}
-
- /**
- * Filter items collection by account ID
- *
- * @param string $accountId
- * @return $this
- */
- public function addAccountFilter($accountId)
- {
- $this->getSelect()->where('report.account_id = ?', $accountId);
- return $this;
- }
}
diff --git a/app/code/core/Mage/Paypal/controllers/StandardController.php b/app/code/core/Mage/Paypal/controllers/StandardController.php
index b5455687a72..9de7b2192c1 100644
--- a/app/code/core/Mage/Paypal/controllers/StandardController.php
+++ b/app/code/core/Mage/Paypal/controllers/StandardController.php
@@ -37,19 +37,6 @@ public function getOrder()
return $this->_order;
}
- /**
- * Send expire header to ajax response
- *
- * @SuppressWarnings("PHPMD.ExitExpression")
- */
- protected function _expireAjax()
- {
- if (!Mage::getSingleton('checkout/session')->getQuote()->hasItems()) {
- $this->getResponse()->setHeader('HTTP/1.1', '403 Session Expired');
- exit;
- }
- }
-
/**
* Get singleton with PayPal standard order transaction information
*
@@ -103,4 +90,17 @@ public function successAction()
Mage::getSingleton('checkout/session')->getQuote()->setIsActive(false)->save();
$this->_redirect('checkout/onepage/success', ['_secure' => true]);
}
+
+ /**
+ * Send expire header to ajax response
+ *
+ * @SuppressWarnings("PHPMD.ExitExpression")
+ */
+ protected function _expireAjax()
+ {
+ if (!Mage::getSingleton('checkout/session')->getQuote()->hasItems()) {
+ $this->getResponse()->setHeader('HTTP/1.1', '403 Session Expired');
+ exit;
+ }
+ }
}
diff --git a/app/code/core/Mage/PaypalUk/Model/Api/Nvp.php b/app/code/core/Mage/PaypalUk/Model/Api/Nvp.php
index 1fc66915721..35a3f6312d3 100644
--- a/app/code/core/Mage/PaypalUk/Model/Api/Nvp.php
+++ b/app/code/core/Mage/PaypalUk/Model/Api/Nvp.php
@@ -395,6 +395,11 @@ public function getPaypalTransactionId()
return $this->getTransactionId();
}
+ /**
+ * "GetTransactionDetails" method does not exists in PaypalUK
+ */
+ public function callGetTransactionDetails() {}
+
/**
* Add method to request array
*
@@ -516,11 +521,6 @@ protected function getRequestId()
return Mage::helper('core')->uniqHash();
}
- /**
- * "GetTransactionDetails" method does not exists in PaypalUK
- */
- public function callGetTransactionDetails() {}
-
/**
* Get FMF results from response, if any
*/
diff --git a/app/code/core/Mage/PaypalUk/Model/Express.php b/app/code/core/Mage/PaypalUk/Model/Express.php
index 98043c07137..cb63b83b393 100644
--- a/app/code/core/Mage/PaypalUk/Model/Express.php
+++ b/app/code/core/Mage/PaypalUk/Model/Express.php
@@ -60,6 +60,18 @@ public function isAvailable($quote = null)
return $this->_ecInstance ? !$this->_ecInstance->isAvailable() : false;
}
+ /**
+ * Checkout redirect URL getter for onepage checkout (hardcode)
+ *
+ * @see Mage_Checkout_OnepageController::savePaymentAction()
+ * @see Mage_Sales_Model_Quote_Payment::getCheckoutRedirectUrl()
+ * @return string
+ */
+ public function getCheckoutRedirectUrl()
+ {
+ return Mage::getUrl('paypaluk/express/start');
+ }
+
/**
* Import payment info to payment
*
@@ -79,16 +91,4 @@ protected function _importToPayment($api, $payment)
$payment->setPreparedMessage(Mage::helper('paypaluk')->__('Payflow PNREF: #%s.', $api->getTransactionId()));
Mage::getModel('paypal/info')->importToPayment($api, $payment);
}
-
- /**
- * Checkout redirect URL getter for onepage checkout (hardcode)
- *
- * @see Mage_Checkout_OnepageController::savePaymentAction()
- * @see Mage_Sales_Model_Quote_Payment::getCheckoutRedirectUrl()
- * @return string
- */
- public function getCheckoutRedirectUrl()
- {
- return Mage::getUrl('paypaluk/express/start');
- }
}
diff --git a/app/code/core/Mage/PaypalUk/Model/Pro.php b/app/code/core/Mage/PaypalUk/Model/Pro.php
index fc0d3c24e44..15dabfcc163 100644
--- a/app/code/core/Mage/PaypalUk/Model/Pro.php
+++ b/app/code/core/Mage/PaypalUk/Model/Pro.php
@@ -25,25 +25,24 @@
class Mage_PaypalUk_Model_Pro extends Mage_Paypal_Model_Pro
{
/**
- * Api model type
+ * Payflow trx_id key in transaction info
*
* @var string
*/
- protected $_apiType = 'paypaluk/api_nvp';
-
+ public const TRANSPORT_PAYFLOW_TXN_ID = 'payflow_trxid';
/**
- * Config model type
+ * Api model type
*
* @var string
*/
- protected $_configType = 'paypal/config';
+ protected $_apiType = 'paypaluk/api_nvp';
/**
- * Payflow trx_id key in transaction info
+ * Config model type
*
* @var string
*/
- public const TRANSPORT_PAYFLOW_TXN_ID = 'payflow_trxid';
+ protected $_configType = 'paypal/config';
/**
* Refund a capture transaction
@@ -59,6 +58,20 @@ public function refund(Varien_Object $payment, $amount)
parent::refund($payment, $amount);
}
+ /**
+ * Fetch transaction details info method does not exists in PaypalUK
+ *
+ * @param string $transactionId
+ * @throws Mage_Core_Exception
+ * @return void
+ */
+ public function fetchTransactionInfo(Mage_Payment_Model_Info $payment, $transactionId)
+ {
+ Mage::throwException(
+ Mage::helper('paypaluk')->__('Fetch transaction details method does not exists in PaypalUK'),
+ );
+ }
+
/**
* Is capture request needed on this transaction
*
@@ -103,20 +116,6 @@ protected function _importCaptureResultToPayment($api, $payment)
Mage::getModel('paypal/info')->importToPayment($api, $payment);
}
- /**
- * Fetch transaction details info method does not exists in PaypalUK
- *
- * @param string $transactionId
- * @throws Mage_Core_Exception
- * @return void
- */
- public function fetchTransactionInfo(Mage_Payment_Model_Info $payment, $transactionId)
- {
- Mage::throwException(
- Mage::helper('paypaluk')->__('Fetch transaction details method does not exists in PaypalUK'),
- );
- }
-
/**
* Import refund results to payment
*
diff --git a/app/code/core/Mage/Persistent/Block/Form/Remember.php b/app/code/core/Mage/Persistent/Block/Form/Remember.php
index 97a230738d1..f9f54e3c29a 100644
--- a/app/code/core/Mage/Persistent/Block/Form/Remember.php
+++ b/app/code/core/Mage/Persistent/Block/Form/Remember.php
@@ -23,26 +23,25 @@
class Mage_Persistent_Block_Form_Remember extends Mage_Core_Block_Template
{
/**
- * Prevent rendering if Persistent disabled
+ * Is "Remember Me" checked
*
- * @return string
+ * @return bool
*/
- protected function _toHtml()
+ public function isRememberMeChecked()
{
/** @var Mage_Persistent_Helper_Data $helper */
$helper = Mage::helper('persistent');
- return ($helper->isEnabled() && $helper->isRememberMeEnabled()) ? parent::_toHtml() : '';
+ return $helper->isEnabled() && $helper->isRememberMeEnabled() && $helper->isRememberMeCheckedDefault();
}
-
/**
- * Is "Remember Me" checked
+ * Prevent rendering if Persistent disabled
*
- * @return bool
+ * @return string
*/
- public function isRememberMeChecked()
+ protected function _toHtml()
{
/** @var Mage_Persistent_Helper_Data $helper */
$helper = Mage::helper('persistent');
- return $helper->isEnabled() && $helper->isRememberMeEnabled() && $helper->isRememberMeCheckedDefault();
+ return ($helper->isEnabled() && $helper->isRememberMeEnabled()) ? parent::_toHtml() : '';
}
}
diff --git a/app/code/core/Mage/Persistent/Model/Observer.php b/app/code/core/Mage/Persistent/Model/Observer.php
index f3ae96c94e5..e740fc75920 100644
--- a/app/code/core/Mage/Persistent/Model/Observer.php
+++ b/app/code/core/Mage/Persistent/Model/Observer.php
@@ -110,16 +110,6 @@ public function emulateWelcomeBlock($block)
return $this;
}
- /**
- * Emulate 'account links' block with persistent data
- */
- protected function _applyAccountLinksPersistentData()
- {
- if (!Mage::app()->getLayout()->getBlock('header.additional')) {
- Mage::app()->getLayout()->addBlock('persistent/header_additional', 'header.additional');
- }
- }
-
/**
* Emulate 'account links' block with persistent data
*
@@ -255,27 +245,6 @@ public function makePersistentQuoteGuest($observer)
$this->setQuoteGuest(true);
}
- /**
- * Check if checkout session should NOT be cleared
- *
- * @param Varien_Event_Observer $observer
- * @return bool|Mage_Persistent_IndexController
- */
- protected function _checkClearCheckoutSessionNecessity($observer)
- {
- if (!$this->_isGuestShoppingCart()) {
- return false;
- }
-
- /** @var Mage_Persistent_IndexController $action */
- $action = $observer->getEvent()->getControllerAction();
- if ($action instanceof Mage_Persistent_IndexController) {
- return $action;
- }
-
- return false;
- }
-
/**
* Reset session data when customer re-authenticates
*
@@ -353,80 +322,6 @@ public function preventExpressCheckout($observer)
}
}
- /**
- * Retrieve persistent customer instance
- *
- * @return Mage_Customer_Model_Customer
- */
- protected function _getPersistentCustomer()
- {
- return Mage::getModel('customer/customer')->load(
- $this->_getPersistentHelper()->getSession()->getCustomerId(),
- );
- }
-
- /**
- * Retrieve persistent helper
- *
- * @return Mage_Persistent_Helper_Session
- */
- protected function _getPersistentHelper()
- {
- return Mage::helper('persistent/session');
- }
-
- /**
- * Return current active quote for persistent customer
- *
- * @return Mage_Sales_Model_Quote
- */
- protected function _getQuote()
- {
- $quote = Mage::getModel('sales/quote');
- $quote->loadByCustomer($this->_getPersistentCustomer());
- return $quote;
- }
-
- /**
- * Check whether shopping cart is persistent
- *
- * @return bool
- */
- protected function _isShoppingCartPersist()
- {
- return Mage::helper('persistent')->isShoppingCartPersist();
- }
-
- /**
- * Check whether persistent mode is running
- *
- * @return bool
- */
- protected function _isPersistent()
- {
- return $this->_getPersistentHelper()->isPersistent();
- }
-
- /**
- * Check if persistent mode is running and customer is logged out
- *
- * @return bool
- */
- protected function _isLoggedOut()
- {
- return $this->_isPersistent() && !Mage::getSingleton('customer/session')->isLoggedIn();
- }
-
- /**
- * Check if shopping cart is guest while persistent session and user is logged out
- *
- * @return bool
- */
- protected function _isGuestShoppingCart()
- {
- return $this->_isLoggedOut() && !Mage::helper('persistent')->isShoppingCartPersist();
- }
-
/**
* Make quote to be guest
*
@@ -487,25 +382,6 @@ public function checkExpirePersistentQuote(Varien_Event_Observer $observer)
$customerSession->setCustomerId(null)->setCustomerGroupId(null);
}
}
- /**
- * Active Persistent Sessions
- */
- protected function _expirePersistentSession()
- {
- /** @var Mage_Checkout_Model_Session $checkoutSession */
- $checkoutSession = Mage::getSingleton('checkout/session');
-
- $quote = $checkoutSession->setLoadInactive()->getQuote();
- if ($quote->getIsActive() && $quote->getCustomerId()) {
- $checkoutSession->setCustomer(null)->unsetAll();
- } else {
- $quote
- ->setIsActive(true)
- ->setIsPersistent(false)
- ->setCustomerId(null)
- ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
- }
- }
/**
* Clear expired persistent sessions
@@ -585,4 +461,128 @@ public function emulateCustomer($observer)
}
return $this;
}
+
+ /**
+ * Emulate 'account links' block with persistent data
+ */
+ protected function _applyAccountLinksPersistentData()
+ {
+ if (!Mage::app()->getLayout()->getBlock('header.additional')) {
+ Mage::app()->getLayout()->addBlock('persistent/header_additional', 'header.additional');
+ }
+ }
+
+ /**
+ * Check if checkout session should NOT be cleared
+ *
+ * @param Varien_Event_Observer $observer
+ * @return bool|Mage_Persistent_IndexController
+ */
+ protected function _checkClearCheckoutSessionNecessity($observer)
+ {
+ if (!$this->_isGuestShoppingCart()) {
+ return false;
+ }
+
+ /** @var Mage_Persistent_IndexController $action */
+ $action = $observer->getEvent()->getControllerAction();
+ if ($action instanceof Mage_Persistent_IndexController) {
+ return $action;
+ }
+
+ return false;
+ }
+
+ /**
+ * Retrieve persistent customer instance
+ *
+ * @return Mage_Customer_Model_Customer
+ */
+ protected function _getPersistentCustomer()
+ {
+ return Mage::getModel('customer/customer')->load(
+ $this->_getPersistentHelper()->getSession()->getCustomerId(),
+ );
+ }
+
+ /**
+ * Retrieve persistent helper
+ *
+ * @return Mage_Persistent_Helper_Session
+ */
+ protected function _getPersistentHelper()
+ {
+ return Mage::helper('persistent/session');
+ }
+
+ /**
+ * Return current active quote for persistent customer
+ *
+ * @return Mage_Sales_Model_Quote
+ */
+ protected function _getQuote()
+ {
+ $quote = Mage::getModel('sales/quote');
+ $quote->loadByCustomer($this->_getPersistentCustomer());
+ return $quote;
+ }
+
+ /**
+ * Check whether shopping cart is persistent
+ *
+ * @return bool
+ */
+ protected function _isShoppingCartPersist()
+ {
+ return Mage::helper('persistent')->isShoppingCartPersist();
+ }
+
+ /**
+ * Check whether persistent mode is running
+ *
+ * @return bool
+ */
+ protected function _isPersistent()
+ {
+ return $this->_getPersistentHelper()->isPersistent();
+ }
+
+ /**
+ * Check if persistent mode is running and customer is logged out
+ *
+ * @return bool
+ */
+ protected function _isLoggedOut()
+ {
+ return $this->_isPersistent() && !Mage::getSingleton('customer/session')->isLoggedIn();
+ }
+
+ /**
+ * Check if shopping cart is guest while persistent session and user is logged out
+ *
+ * @return bool
+ */
+ protected function _isGuestShoppingCart()
+ {
+ return $this->_isLoggedOut() && !Mage::helper('persistent')->isShoppingCartPersist();
+ }
+ /**
+ * Active Persistent Sessions
+ */
+ protected function _expirePersistentSession()
+ {
+ /** @var Mage_Checkout_Model_Session $checkoutSession */
+ $checkoutSession = Mage::getSingleton('checkout/session');
+
+ $quote = $checkoutSession->setLoadInactive()->getQuote();
+ if ($quote->getIsActive() && $quote->getCustomerId()) {
+ $checkoutSession->setCustomer(null)->unsetAll();
+ } else {
+ $quote
+ ->setIsActive(true)
+ ->setIsPersistent(false)
+ ->setCustomerId(null)
+ ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
+ }
+ }
}
diff --git a/app/code/core/Mage/Persistent/Model/Resource/Session.php b/app/code/core/Mage/Persistent/Model/Resource/Session.php
index 90b765b2cb6..b477785f14b 100644
--- a/app/code/core/Mage/Persistent/Model/Resource/Session.php
+++ b/app/code/core/Mage/Persistent/Model/Resource/Session.php
@@ -29,33 +29,6 @@ class Mage_Persistent_Model_Resource_Session extends Mage_Core_Model_Resource_Db
*/
protected $_useIsObjectNew = true;
- protected function _construct()
- {
- $this->_init('persistent/session', 'persistent_id');
- }
-
- /**
- * Add expiration date filter to select
- *
- * @param string $field
- * @param mixed $value
- * @param Mage_Persistent_Model_Session $object
- * @return Zend_Db_Select
- */
- protected function _getLoadSelect($field, $value, $object)
- {
- $select = parent::_getLoadSelect($field, $value, $object);
- if (!$object->getLoadExpired()) {
- $tableName = $this->getMainTable();
- $select->join(
- ['customer' => $this->getTable('customer/entity')],
- 'customer.entity_id = ' . $tableName . '.customer_id',
- )->where($tableName . '.updated_at >= ?', $object->getExpiredBefore());
- }
-
- return $select;
- }
-
/**
* Delete customer persistent session by customer id
*
@@ -99,4 +72,31 @@ public function deleteExpired($websiteId, $expiredBefore)
);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('persistent/session', 'persistent_id');
+ }
+
+ /**
+ * Add expiration date filter to select
+ *
+ * @param string $field
+ * @param mixed $value
+ * @param Mage_Persistent_Model_Session $object
+ * @return Zend_Db_Select
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ $select = parent::_getLoadSelect($field, $value, $object);
+ if (!$object->getLoadExpired()) {
+ $tableName = $this->getMainTable();
+ $select->join(
+ ['customer' => $this->getTable('customer/entity')],
+ 'customer.entity_id = ' . $tableName . '.customer_id',
+ )->where($tableName . '.updated_at >= ?', $object->getExpiredBefore());
+ }
+
+ return $select;
+ }
}
diff --git a/app/code/core/Mage/Persistent/Model/Session.php b/app/code/core/Mage/Persistent/Model/Session.php
index 3138355bd7e..82550060d87 100644
--- a/app/code/core/Mage/Persistent/Model/Session.php
+++ b/app/code/core/Mage/Persistent/Model/Session.php
@@ -48,14 +48,6 @@ class Mage_Persistent_Model_Session extends Mage_Core_Model_Abstract
*/
protected $_loadExpired = false;
- /**
- * Define resource model
- */
- protected function _construct()
- {
- $this->_init('persistent/session');
- }
-
/**
* Set if load expired persistent session
*
@@ -92,53 +84,6 @@ public function getExpiredBefore($store = null)
);
}
- /**
- * Serialize info for Resource Model to save
- * For new model check and set available cookie key
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
-
- // Setting info
- $info = [];
- foreach ($this->getData() as $index => $value) {
- if (!in_array($index, $this->_unserializableFields)) {
- $info[$index] = $value;
- }
- }
- $this->setInfo(Mage::helper('core')->jsonEncode($info));
-
- if ($this->isObjectNew()) {
- $this->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
- // Setting cookie key
- do {
- $this->setKey(Mage::helper('core')->getRandomString(self::KEY_LENGTH));
- } while (!$this->getResource()->isKeyAllowed($this->getKey()));
- }
-
- return $this;
- }
-
- /**
- * Set model data from info field
- *
- * @return $this
- */
- protected function _afterLoad()
- {
- parent::_afterLoad();
- $info = Mage::helper('core')->jsonDecode($this->getInfo());
- if (is_array($info)) {
- foreach ($info as $key => $value) {
- $this->setData($key, $value);
- }
- }
- return $this;
- }
-
/**
* Get persistent session by cookie key
*
@@ -224,24 +169,79 @@ public function deleteExpired($websiteId = null)
}
/**
- * Delete 'persistent' cookie
+ * Set `updated_at` to be always changed
*
* @inheritDoc
*/
- protected function _afterDeleteCommit()
+ public function save()
{
- Mage::getSingleton('core/cookie')->delete(Mage_Persistent_Model_Session::COOKIE_NAME);
- return parent::_afterDeleteCommit();
+ $this->setUpdatedAt(gmdate(Varien_Date::DATETIME_PHP_FORMAT));
+ return parent::save();
}
/**
- * Set `updated_at` to be always changed
+ * Define resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('persistent/session');
+ }
+
+ /**
+ * Serialize info for Resource Model to save
+ * For new model check and set available cookie key
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+
+ // Setting info
+ $info = [];
+ foreach ($this->getData() as $index => $value) {
+ if (!in_array($index, $this->_unserializableFields)) {
+ $info[$index] = $value;
+ }
+ }
+ $this->setInfo(Mage::helper('core')->jsonEncode($info));
+
+ if ($this->isObjectNew()) {
+ $this->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
+ // Setting cookie key
+ do {
+ $this->setKey(Mage::helper('core')->getRandomString(self::KEY_LENGTH));
+ } while (!$this->getResource()->isKeyAllowed($this->getKey()));
+ }
+
+ return $this;
+ }
+
+ /**
+ * Set model data from info field
+ *
+ * @return $this
+ */
+ protected function _afterLoad()
+ {
+ parent::_afterLoad();
+ $info = Mage::helper('core')->jsonDecode($this->getInfo());
+ if (is_array($info)) {
+ foreach ($info as $key => $value) {
+ $this->setData($key, $value);
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Delete 'persistent' cookie
*
* @inheritDoc
*/
- public function save()
+ protected function _afterDeleteCommit()
{
- $this->setUpdatedAt(gmdate(Varien_Date::DATETIME_PHP_FORMAT));
- return parent::save();
+ Mage::getSingleton('core/cookie')->delete(Mage_Persistent_Model_Session::COOKIE_NAME);
+ return parent::_afterDeleteCommit();
}
}
diff --git a/app/code/core/Mage/Persistent/controllers/IndexController.php b/app/code/core/Mage/Persistent/controllers/IndexController.php
index 24dc52ded3f..c1dcec68469 100644
--- a/app/code/core/Mage/Persistent/controllers/IndexController.php
+++ b/app/code/core/Mage/Persistent/controllers/IndexController.php
@@ -41,16 +41,6 @@ public function setClearCheckoutSession($clear = true)
return $this;
}
- /**
- * Retrieve 'persistent session' helper instance
- *
- * @return Mage_Persistent_Helper_Session
- */
- protected function _getHelper()
- {
- return Mage::helper('persistent/session');
- }
-
/**
* Unset persistent cookie action
*/
@@ -62,25 +52,6 @@ public function unsetCookieAction()
$this->_redirect('customer/account/login');
}
- /**
- * Revert all persistent data
- *
- * @return $this
- */
- protected function _cleanup()
- {
- Mage::dispatchEvent('persistent_session_expired');
- $customerSession = Mage::getSingleton('customer/session');
- $customerSession
- ->setCustomerId(null)
- ->setCustomerGroupId(null);
- if ($this->_clearCheckoutSession) {
- Mage::getSingleton('checkout/session')->unsetAll();
- }
- $this->_getHelper()->getSession()->removePersistentCookie();
- return $this;
- }
-
/**
* Save onepage checkout method to be register
*/
@@ -113,4 +84,33 @@ public function expressCheckoutAction()
);
$this->_redirect('checkout/cart');
}
+
+ /**
+ * Retrieve 'persistent session' helper instance
+ *
+ * @return Mage_Persistent_Helper_Session
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('persistent/session');
+ }
+
+ /**
+ * Revert all persistent data
+ *
+ * @return $this
+ */
+ protected function _cleanup()
+ {
+ Mage::dispatchEvent('persistent_session_expired');
+ $customerSession = Mage::getSingleton('customer/session');
+ $customerSession
+ ->setCustomerId(null)
+ ->setCustomerGroupId(null);
+ if ($this->_clearCheckoutSession) {
+ Mage::getSingleton('checkout/session')->unsetAll();
+ }
+ $this->_getHelper()->getSession()->removePersistentCookie();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/ProductAlert/Block/Email/Abstract.php b/app/code/core/Mage/ProductAlert/Block/Email/Abstract.php
index ec804a616c1..54cc2d6f135 100644
--- a/app/code/core/Mage/ProductAlert/Block/Email/Abstract.php
+++ b/app/code/core/Mage/ProductAlert/Block/Email/Abstract.php
@@ -109,19 +109,6 @@ public function getProducts()
return $this->_products;
}
- /**
- * Get store url params
- *
- * @return array
- */
- protected function _getUrlParams()
- {
- return [
- '_store' => $this->getStore(),
- '_store_to_url' => true,
- ];
- }
-
/**
* Get filtered product short description to be inserted into mail
*
@@ -135,4 +122,17 @@ public function _getFilteredProductShortDescription(Mage_Catalog_Model_Product $
}
return $shortDescription;
}
+
+ /**
+ * Get store url params
+ *
+ * @return array
+ */
+ protected function _getUrlParams()
+ {
+ return [
+ '_store' => $this->getStore(),
+ '_store_to_url' => true,
+ ];
+ }
}
diff --git a/app/code/core/Mage/ProductAlert/Model/Email.php b/app/code/core/Mage/ProductAlert/Model/Email.php
index 398cf8c46dc..313c6eaf633 100644
--- a/app/code/core/Mage/ProductAlert/Model/Email.php
+++ b/app/code/core/Mage/ProductAlert/Model/Email.php
@@ -177,34 +177,6 @@ public function addStockProduct(Mage_Catalog_Model_Product $product)
return $this;
}
- /**
- * Retrieve price block
- *
- * @return Mage_ProductAlert_Block_Email_Price
- */
- protected function _getPriceBlock()
- {
- if (is_null($this->_priceBlock)) {
- $this->_priceBlock = Mage::helper('productalert')
- ->createBlock('productalert/email_price');
- }
- return $this->_priceBlock;
- }
-
- /**
- * Retrieve stock block
- *
- * @return Mage_ProductAlert_Block_Email_Stock
- */
- protected function _getStockBlock()
- {
- if (is_null($this->_stockBlock)) {
- $this->_stockBlock = Mage::helper('productalert')
- ->createBlock('productalert/email_stock');
- }
- return $this->_stockBlock;
- }
-
/**
* Send customer email
*
@@ -281,4 +253,32 @@ public function send()
return true;
}
+
+ /**
+ * Retrieve price block
+ *
+ * @return Mage_ProductAlert_Block_Email_Price
+ */
+ protected function _getPriceBlock()
+ {
+ if (is_null($this->_priceBlock)) {
+ $this->_priceBlock = Mage::helper('productalert')
+ ->createBlock('productalert/email_price');
+ }
+ return $this->_priceBlock;
+ }
+
+ /**
+ * Retrieve stock block
+ *
+ * @return Mage_ProductAlert_Block_Email_Stock
+ */
+ protected function _getStockBlock()
+ {
+ if (is_null($this->_stockBlock)) {
+ $this->_stockBlock = Mage::helper('productalert')
+ ->createBlock('productalert/email_stock');
+ }
+ return $this->_stockBlock;
+ }
}
diff --git a/app/code/core/Mage/ProductAlert/Model/Observer.php b/app/code/core/Mage/ProductAlert/Model/Observer.php
index 7a35f2f79d7..ac07097f095 100644
--- a/app/code/core/Mage/ProductAlert/Model/Observer.php
+++ b/app/code/core/Mage/ProductAlert/Model/Observer.php
@@ -63,6 +63,21 @@ class Mage_ProductAlert_Model_Observer
*/
protected $_errors = [];
+ /**
+ * Run process send product alerts
+ *
+ * @return $this
+ */
+ public function process()
+ {
+ $email = Mage::getModel('productalert/email');
+ $this->_processPrice($email);
+ $this->_processStock($email);
+ $this->_sendErrorEmail();
+
+ return $this;
+ }
+
/**
* Retrieve website collection array
*
@@ -283,19 +298,4 @@ protected function _sendErrorEmail()
}
return $this;
}
-
- /**
- * Run process send product alerts
- *
- * @return $this
- */
- public function process()
- {
- $email = Mage::getModel('productalert/email');
- $this->_processPrice($email);
- $this->_processStock($email);
- $this->_sendErrorEmail();
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/ProductAlert/Model/Price.php b/app/code/core/Mage/ProductAlert/Model/Price.php
index e560b53e8c6..14a3e573cfd 100644
--- a/app/code/core/Mage/ProductAlert/Model/Price.php
+++ b/app/code/core/Mage/ProductAlert/Model/Price.php
@@ -43,11 +43,6 @@
*/
class Mage_ProductAlert_Model_Price extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('productalert/price');
- }
-
/**
* @return Mage_ProductAlert_Model_Resource_Price_Customer_Collection
*/
@@ -77,4 +72,8 @@ public function deleteCustomer($customerId, $websiteId = 0)
$this->getResource()->deleteCustomer($this, $customerId, $websiteId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('productalert/price');
+ }
}
diff --git a/app/code/core/Mage/ProductAlert/Model/Resource/Abstract.php b/app/code/core/Mage/ProductAlert/Model/Resource/Abstract.php
index 5eec667217d..8520c0c2b11 100644
--- a/app/code/core/Mage/ProductAlert/Model/Resource/Abstract.php
+++ b/app/code/core/Mage/ProductAlert/Model/Resource/Abstract.php
@@ -22,30 +22,6 @@
*/
abstract class Mage_ProductAlert_Model_Resource_Abstract extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Retrieve alert row by object parameters
- *
- * @return array|false
- */
- protected function _getAlertRow(Mage_Core_Model_Abstract $object)
- {
- $adapter = $this->_getReadAdapter();
- if ($object->getCustomerId() && $object->getProductId() && $object->getWebsiteId()) {
- $select = $adapter->select()
- ->from($this->getMainTable())
- ->where('customer_id = :customer_id')
- ->where('product_id = :product_id')
- ->where('website_id = :website_id');
- $bind = [
- ':customer_id' => $object->getCustomerId(),
- ':product_id' => $object->getProductId(),
- ':website_id' => $object->getWebsiteId(),
- ];
- return $adapter->fetchRow($select, $bind);
- }
- return false;
- }
-
/**
* Load object data by parameters
*
@@ -78,4 +54,27 @@ public function deleteCustomer(Mage_Core_Model_Abstract $object, $customerId, $w
$adapter->delete($this->getMainTable(), $where);
return $this;
}
+ /**
+ * Retrieve alert row by object parameters
+ *
+ * @return array|false
+ */
+ protected function _getAlertRow(Mage_Core_Model_Abstract $object)
+ {
+ $adapter = $this->_getReadAdapter();
+ if ($object->getCustomerId() && $object->getProductId() && $object->getWebsiteId()) {
+ $select = $adapter->select()
+ ->from($this->getMainTable())
+ ->where('customer_id = :customer_id')
+ ->where('product_id = :product_id')
+ ->where('website_id = :website_id');
+ $bind = [
+ ':customer_id' => $object->getCustomerId(),
+ ':product_id' => $object->getProductId(),
+ ':website_id' => $object->getWebsiteId(),
+ ];
+ return $adapter->fetchRow($select, $bind);
+ }
+ return false;
+ }
}
diff --git a/app/code/core/Mage/ProductAlert/Model/Resource/Price/Collection.php b/app/code/core/Mage/ProductAlert/Model/Resource/Price/Collection.php
index acfaa7e55e9..1fb14f61638 100644
--- a/app/code/core/Mage/ProductAlert/Model/Resource/Price/Collection.php
+++ b/app/code/core/Mage/ProductAlert/Model/Resource/Price/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_ProductAlert_Model_Resource_Price_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define price collection
- *
- */
- protected function _construct()
- {
- $this->_init('productalert/price');
- }
-
/**
* Add customer filter
*
@@ -83,4 +74,12 @@ public function setCustomerOrder($sort = 'ASC')
$this->getSelect()->order('customer_id ' . $sort);
return $this;
}
+ /**
+ * Define price collection
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('productalert/price');
+ }
}
diff --git a/app/code/core/Mage/ProductAlert/Model/Resource/Stock/Collection.php b/app/code/core/Mage/ProductAlert/Model/Resource/Stock/Collection.php
index ec107dc8871..46cc26821c6 100644
--- a/app/code/core/Mage/ProductAlert/Model/Resource/Stock/Collection.php
+++ b/app/code/core/Mage/ProductAlert/Model/Resource/Stock/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_ProductAlert_Model_Resource_Stock_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define stock collection
- *
- */
- protected function _construct()
- {
- $this->_init('productalert/stock');
- }
-
/**
* Add customer filter
*
@@ -98,4 +89,12 @@ public function setCustomerOrder($sort = 'ASC')
$this->getSelect()->order('customer_id ' . $sort);
return $this;
}
+ /**
+ * Define stock collection
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('productalert/stock');
+ }
}
diff --git a/app/code/core/Mage/ProductAlert/Model/Stock.php b/app/code/core/Mage/ProductAlert/Model/Stock.php
index 63506dcf013..ddba38da66b 100644
--- a/app/code/core/Mage/ProductAlert/Model/Stock.php
+++ b/app/code/core/Mage/ProductAlert/Model/Stock.php
@@ -41,11 +41,6 @@
*/
class Mage_ProductAlert_Model_Stock extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('productalert/stock');
- }
-
/**
* @return Mage_ProductAlert_Model_Resource_Stock_Customer_Collection
*/
@@ -75,4 +70,8 @@ public function deleteCustomer($customerId, $websiteId = 0)
$this->getResource()->deleteCustomer($this, $customerId, $websiteId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('productalert/stock');
+ }
}
diff --git a/app/code/core/Mage/Rating/Model/Rating.php b/app/code/core/Mage/Rating/Model/Rating.php
index 58a7d8ab94e..66a416ce1ea 100644
--- a/app/code/core/Mage/Rating/Model/Rating.php
+++ b/app/code/core/Mage/Rating/Model/Rating.php
@@ -59,14 +59,6 @@ class Mage_Rating_Model_Rating extends Mage_Core_Model_Abstract
public const ENTITY_PRODUCT_REVIEW_CODE = 'product_review';
public const ENTITY_REVIEW_CODE = 'review';
- /**
- * Define resource model
- */
- protected function _construct()
- {
- $this->_init('rating/rating');
- }
-
/**
* @param int $optionId
* @param string $entityPkValue
@@ -152,4 +144,12 @@ public function getEntityIdByCode($entityCode)
{
return $this->getResource()->getEntityIdByCode($entityCode);
}
+
+ /**
+ * Define resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('rating/rating');
+ }
}
diff --git a/app/code/core/Mage/Rating/Model/Rating/Entity.php b/app/code/core/Mage/Rating/Model/Rating/Entity.php
index 9bf4a40bc81..fa21e310971 100644
--- a/app/code/core/Mage/Rating/Model/Rating/Entity.php
+++ b/app/code/core/Mage/Rating/Model/Rating/Entity.php
@@ -27,11 +27,6 @@
*/
class Mage_Rating_Model_Rating_Entity extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('rating/rating_entity');
- }
-
/**
* @param string $entityCode
* @return int
@@ -40,4 +35,8 @@ public function getIdByCode($entityCode)
{
return $this->_getResource()->getIdByCode($entityCode);
}
+ protected function _construct()
+ {
+ $this->_init('rating/rating_entity');
+ }
}
diff --git a/app/code/core/Mage/Rating/Model/Rating/Option.php b/app/code/core/Mage/Rating/Model/Rating/Option.php
index 334ceeccfca..38870354b10 100644
--- a/app/code/core/Mage/Rating/Model/Rating/Option.php
+++ b/app/code/core/Mage/Rating/Model/Rating/Option.php
@@ -43,11 +43,6 @@
*/
class Mage_Rating_Model_Rating_Option extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('rating/rating_option');
- }
-
/**
* @return $this
* @throws Exception
@@ -67,4 +62,8 @@ public function setId($id)
$this->setOptionId($id);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('rating/rating_option');
+ }
}
diff --git a/app/code/core/Mage/Rating/Model/Resource/Rating.php b/app/code/core/Mage/Rating/Model/Resource/Rating.php
index b126713b904..60154b60c50 100644
--- a/app/code/core/Mage/Rating/Model/Resource/Rating.php
+++ b/app/code/core/Mage/Rating/Model/Resource/Rating.php
@@ -24,6 +24,190 @@ class Mage_Rating_Model_Resource_Rating extends Mage_Core_Model_Resource_Db_Abst
{
public const RATING_STATUS_APPROVED = 'Approved';
+ /**
+ * Retrieve store IDs related to given rating
+ *
+ * @param int $ratingId
+ * @return array
+ */
+ public function getStores($ratingId)
+ {
+ $select = $this->_getReadAdapter()->select()
+ ->from($this->getTable('rating/rating_store'), 'store_id')
+ ->where('rating_id = ?', $ratingId);
+ return $this->_getReadAdapter()->fetchCol($select);
+ }
+
+ /**
+ * Return array of rating summary
+ *
+ * @param Mage_Rating_Model_Rating $object
+ * @param bool $onlyForCurrentStore
+ * @return array|Mage_Rating_Model_Rating
+ */
+ public function getEntitySummary($object, $onlyForCurrentStore = true)
+ {
+ $data = $this->_getEntitySummaryData($object);
+
+ if ($onlyForCurrentStore) {
+ foreach ($data as $row) {
+ if ($row['store_id'] == Mage::app()->getStore()->getId()) {
+ $object->addData($row);
+ }
+ }
+ return $object;
+ }
+
+ $result = [];
+
+ //$stores = Mage::app()->getStore()->getResourceCollection()->load();
+ $stores = Mage::getModel('core/store')->getResourceCollection()->load();
+
+ foreach ($data as $row) {
+ $clone = clone $object;
+ $clone->addData($row);
+ $result[$clone->getStoreId()] = $clone;
+ }
+
+ $usedStoresId = array_keys($result);
+
+ /** @var Mage_Core_Model_Store $store */
+ foreach ($stores as $store) {
+ if (!in_array($store->getId(), $usedStoresId)) {
+ $clone = clone $object;
+ $clone->setCount(0);
+ $clone->setSum(0);
+ $clone->setStoreId($store->getId());
+ $result[$store->getId()] = $clone;
+ }
+ }
+
+ if (empty($result[0])) {
+ // when you unapprove the latest comment and save
+ // store_id = 0 is missing and not updated in review_entity_summary
+ $clone = clone $object;
+ $clone->setCount(0);
+ $clone->setSum(0);
+ $clone->setStoreId(0);
+ $result[0] = $clone;
+ }
+
+ return array_values($result);
+ }
+
+ /**
+ * Review summary
+ *
+ * @param Mage_Rating_Model_Rating $object
+ * @param bool $onlyForCurrentStore
+ * @return array|Mage_Rating_Model_Rating
+ */
+ public function getReviewSummary($object, $onlyForCurrentStore = true)
+ {
+ $adapter = $this->_getReadAdapter();
+
+ $sumColumn = new Zend_Db_Expr("SUM(rating_vote.{$adapter->quoteIdentifier('percent')})");
+ $countColumn = new Zend_Db_Expr('COUNT(*)');
+ $select = $adapter->select()
+ ->from(
+ ['rating_vote' => $this->getTable('rating/rating_option_vote')],
+ [
+ 'sum' => $sumColumn,
+ 'count' => $countColumn,
+ ],
+ )
+ ->joinLeft(
+ ['review_store' => $this->getTable('review/review_store')],
+ 'rating_vote.review_id = review_store.review_id',
+ ['review_store.store_id'],
+ )
+ ->join(
+ ['rating_store' => $this->getTable('rating/rating_store')],
+ 'rating_store.rating_id = rating_vote.rating_id AND rating_store.store_id = review_store.store_id',
+ [],
+ )
+ ->where('rating_vote.review_id = :review_id')
+ ->group('rating_vote.review_id')
+ ->group('review_store.store_id');
+
+ $data = $adapter->fetchAll($select, [':review_id' => $object->getReviewId()]);
+
+ if ($onlyForCurrentStore) {
+ foreach ($data as $row) {
+ if ($row['store_id'] == Mage::app()->getStore()->getId()) {
+ $object->addData($row);
+ }
+ }
+ return $object;
+ }
+
+ $result = [];
+
+ $stores = Mage::app()->getStore()->getResourceCollection()->load();
+
+ foreach ($data as $row) {
+ $clone = clone $object;
+ $clone->addData($row);
+ $result[$clone->getStoreId()] = $clone;
+ }
+
+ $usedStoresId = array_keys($result);
+
+ /** @var Mage_Core_Model_Store $store */
+ foreach ($stores as $store) {
+ if (!in_array($store->getId(), $usedStoresId)) {
+ $clone = clone $object;
+ $clone->setCount(0);
+ $clone->setSum(0);
+ $clone->setStoreId($store->getId());
+ $result[$store->getId()] = $clone;
+ }
+ }
+
+ return array_values($result);
+ }
+
+ /**
+ * Get rating entity type id by code
+ *
+ * @param string $entityCode
+ * @return int
+ */
+ public function getEntityIdByCode($entityCode)
+ {
+ $select = $this->_getReadAdapter()->select()
+ ->from($this->getTable('rating/rating_entity'), ['entity_id'])
+ ->where('entity_code = :entity_code');
+
+ return $this->_getReadAdapter()->fetchOne($select, [':entity_code' => $entityCode]);
+ }
+
+ /**
+ * Delete ratings by product id
+ *
+ * @param int $productId
+ * @return $this
+ */
+ public function deleteAggregatedRatingsByProductId($productId)
+ {
+ $entityId = $this->getEntityIdByCode(Mage_Rating_Model_Rating::ENTITY_PRODUCT_CODE);
+ $adapter = $this->_getWriteAdapter();
+ $select = $adapter->select()
+ ->from($this->getMainTable(), 'rating_id')
+ ->where('entity_id = :entity_id');
+ $ratingIds = $adapter->fetchCol($select, [':entity_id' => $entityId]);
+
+ if ($ratingIds) {
+ $where = [
+ 'entity_pk_value = ?' => (int) $productId,
+ 'rating_id IN(?)' => $ratingIds,
+ ];
+ $adapter->delete($this->getTable('rating/rating_vote_aggregated'), $where);
+ }
+
+ return $this;
+ }
+
protected function _construct()
{
$this->_init('rating/rating', 'rating_id');
@@ -100,20 +284,6 @@ protected function _afterLoad(Mage_Core_Model_Abstract $object)
return $this;
}
- /**
- * Retrieve store IDs related to given rating
- *
- * @param int $ratingId
- * @return array
- */
- public function getStores($ratingId)
- {
- $select = $this->_getReadAdapter()->select()
- ->from($this->getTable('rating/rating_store'), 'store_id')
- ->where('rating_id = ?', $ratingId);
- return $this->_getReadAdapter()->fetchCol($select);
- }
-
/**
* Actions after save
*
@@ -230,63 +400,6 @@ protected function _afterDelete(Mage_Core_Model_Abstract $object)
return $this;
}
- /**
- * Return array of rating summary
- *
- * @param Mage_Rating_Model_Rating $object
- * @param bool $onlyForCurrentStore
- * @return array|Mage_Rating_Model_Rating
- */
- public function getEntitySummary($object, $onlyForCurrentStore = true)
- {
- $data = $this->_getEntitySummaryData($object);
-
- if ($onlyForCurrentStore) {
- foreach ($data as $row) {
- if ($row['store_id'] == Mage::app()->getStore()->getId()) {
- $object->addData($row);
- }
- }
- return $object;
- }
-
- $result = [];
-
- //$stores = Mage::app()->getStore()->getResourceCollection()->load();
- $stores = Mage::getModel('core/store')->getResourceCollection()->load();
-
- foreach ($data as $row) {
- $clone = clone $object;
- $clone->addData($row);
- $result[$clone->getStoreId()] = $clone;
- }
-
- $usedStoresId = array_keys($result);
-
- /** @var Mage_Core_Model_Store $store */
- foreach ($stores as $store) {
- if (!in_array($store->getId(), $usedStoresId)) {
- $clone = clone $object;
- $clone->setCount(0);
- $clone->setSum(0);
- $clone->setStoreId($store->getId());
- $result[$store->getId()] = $clone;
- }
- }
-
- if (empty($result[0])) {
- // when you unapprove the latest comment and save
- // store_id = 0 is missing and not updated in review_entity_summary
- $clone = clone $object;
- $clone->setCount(0);
- $clone->setSum(0);
- $clone->setStoreId(0);
- $result[0] = $clone;
- }
-
- return array_values($result);
- }
-
/**
* Return data of rating summary
*
@@ -341,117 +454,4 @@ protected function _getEntitySummaryData($object)
return $adapter->fetchAll($select, $bind);
}
-
- /**
- * Review summary
- *
- * @param Mage_Rating_Model_Rating $object
- * @param bool $onlyForCurrentStore
- * @return array|Mage_Rating_Model_Rating
- */
- public function getReviewSummary($object, $onlyForCurrentStore = true)
- {
- $adapter = $this->_getReadAdapter();
-
- $sumColumn = new Zend_Db_Expr("SUM(rating_vote.{$adapter->quoteIdentifier('percent')})");
- $countColumn = new Zend_Db_Expr('COUNT(*)');
- $select = $adapter->select()
- ->from(
- ['rating_vote' => $this->getTable('rating/rating_option_vote')],
- [
- 'sum' => $sumColumn,
- 'count' => $countColumn,
- ],
- )
- ->joinLeft(
- ['review_store' => $this->getTable('review/review_store')],
- 'rating_vote.review_id = review_store.review_id',
- ['review_store.store_id'],
- )
- ->join(
- ['rating_store' => $this->getTable('rating/rating_store')],
- 'rating_store.rating_id = rating_vote.rating_id AND rating_store.store_id = review_store.store_id',
- [],
- )
- ->where('rating_vote.review_id = :review_id')
- ->group('rating_vote.review_id')
- ->group('review_store.store_id');
-
- $data = $adapter->fetchAll($select, [':review_id' => $object->getReviewId()]);
-
- if ($onlyForCurrentStore) {
- foreach ($data as $row) {
- if ($row['store_id'] == Mage::app()->getStore()->getId()) {
- $object->addData($row);
- }
- }
- return $object;
- }
-
- $result = [];
-
- $stores = Mage::app()->getStore()->getResourceCollection()->load();
-
- foreach ($data as $row) {
- $clone = clone $object;
- $clone->addData($row);
- $result[$clone->getStoreId()] = $clone;
- }
-
- $usedStoresId = array_keys($result);
-
- /** @var Mage_Core_Model_Store $store */
- foreach ($stores as $store) {
- if (!in_array($store->getId(), $usedStoresId)) {
- $clone = clone $object;
- $clone->setCount(0);
- $clone->setSum(0);
- $clone->setStoreId($store->getId());
- $result[$store->getId()] = $clone;
- }
- }
-
- return array_values($result);
- }
-
- /**
- * Get rating entity type id by code
- *
- * @param string $entityCode
- * @return int
- */
- public function getEntityIdByCode($entityCode)
- {
- $select = $this->_getReadAdapter()->select()
- ->from($this->getTable('rating/rating_entity'), ['entity_id'])
- ->where('entity_code = :entity_code');
-
- return $this->_getReadAdapter()->fetchOne($select, [':entity_code' => $entityCode]);
- }
-
- /**
- * Delete ratings by product id
- *
- * @param int $productId
- * @return $this
- */
- public function deleteAggregatedRatingsByProductId($productId)
- {
- $entityId = $this->getEntityIdByCode(Mage_Rating_Model_Rating::ENTITY_PRODUCT_CODE);
- $adapter = $this->_getWriteAdapter();
- $select = $adapter->select()
- ->from($this->getMainTable(), 'rating_id')
- ->where('entity_id = :entity_id');
- $ratingIds = $adapter->fetchCol($select, [':entity_id' => $entityId]);
-
- if ($ratingIds) {
- $where = [
- 'entity_pk_value = ?' => (int) $productId,
- 'rating_id IN(?)' => $ratingIds,
- ];
- $adapter->delete($this->getTable('rating/rating_vote_aggregated'), $where);
- }
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Rating/Model/Resource/Rating/Collection.php b/app/code/core/Mage/Rating/Model/Resource/Rating/Collection.php
index 15c859b3186..3306d3878fe 100644
--- a/app/code/core/Mage/Rating/Model/Resource/Rating/Collection.php
+++ b/app/code/core/Mage/Rating/Model/Resource/Rating/Collection.php
@@ -29,11 +29,6 @@ class Mage_Rating_Model_Resource_Rating_Collection extends Mage_Core_Model_Resou
*/
protected $_isStoreJoined = false;
- protected function _construct()
- {
- $this->_init('rating/rating');
- }
-
/**
* Add entity filter
*
@@ -257,4 +252,9 @@ public function addStoresToCollection()
}
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('rating/rating');
+ }
}
diff --git a/app/code/core/Mage/Rating/Model/Resource/Rating/Entity.php b/app/code/core/Mage/Rating/Model/Resource/Rating/Entity.php
index dfe44f4b344..e886bfea5d9 100644
--- a/app/code/core/Mage/Rating/Model/Resource/Rating/Entity.php
+++ b/app/code/core/Mage/Rating/Model/Resource/Rating/Entity.php
@@ -22,15 +22,6 @@
*/
class Mage_Rating_Model_Resource_Rating_Entity extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Rating entity resource initialization
- *
- */
- protected function _construct()
- {
- $this->_init('rating/rating_entity', 'entity_id');
- }
-
/**
* Return entity_id by entityCode
*
@@ -46,4 +37,12 @@ public function getIdByCode($entityCode)
->where('entity_code = :entity_code');
return $adapter->fetchOne($select, [':entity_code' => $entityCode]);
}
+ /**
+ * Rating entity resource initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('rating/rating_entity', 'entity_id');
+ }
}
diff --git a/app/code/core/Mage/Rating/Model/Resource/Rating/Option.php b/app/code/core/Mage/Rating/Model/Resource/Rating/Option.php
index 14ba4dc0b61..ca24d49cdb2 100644
--- a/app/code/core/Mage/Rating/Model/Resource/Rating/Option.php
+++ b/app/code/core/Mage/Rating/Model/Resource/Rating/Option.php
@@ -78,18 +78,6 @@ class Mage_Rating_Model_Resource_Rating_Option extends Mage_Core_Model_Resource_
*/
protected $_optionId;
- protected function _construct()
- {
- $this->_init('rating/rating_option', 'option_id');
-
- $this->_reviewTable = $this->getTable('review/review');
- $this->_ratingOptionTable = $this->getTable('rating/rating_option');
- $this->_ratingVoteTable = $this->getTable('rating/rating_option_vote');
- $this->_aggregateTable = $this->getTable('rating/rating_vote_aggregated');
- $this->_reviewStoreTable = $this->getTable('review/review_store');
- $this->_ratingStoreTable = $this->getTable('rating/rating_store');
- }
-
/**
* Add vote
*
@@ -257,4 +245,16 @@ public function loadDataById($optionId)
return $this->_optionData;
}
+
+ protected function _construct()
+ {
+ $this->_init('rating/rating_option', 'option_id');
+
+ $this->_reviewTable = $this->getTable('review/review');
+ $this->_ratingOptionTable = $this->getTable('rating/rating_option');
+ $this->_ratingVoteTable = $this->getTable('rating/rating_option_vote');
+ $this->_aggregateTable = $this->getTable('rating/rating_vote_aggregated');
+ $this->_reviewStoreTable = $this->getTable('review/review_store');
+ $this->_ratingStoreTable = $this->getTable('rating/rating_store');
+ }
}
diff --git a/app/code/core/Mage/Rating/Model/Resource/Rating/Option/Collection.php b/app/code/core/Mage/Rating/Model/Resource/Rating/Option/Collection.php
index 7dcff7956c3..8dc9e40870f 100644
--- a/app/code/core/Mage/Rating/Model/Resource/Rating/Option/Collection.php
+++ b/app/code/core/Mage/Rating/Model/Resource/Rating/Option/Collection.php
@@ -37,17 +37,6 @@ class Mage_Rating_Model_Resource_Rating_Option_Collection extends Mage_Core_Mode
*/
protected $_ratingVoteTable;
- /**
- * Define model
- *
- */
- protected function _construct()
- {
- $this->_init('rating/rating_option');
- $this->_ratingOptionTable = $this->getTable('rating/rating_option');
- $this->_ratingVoteTable = $this->getTable('rating/rating_option_vote');
- }
-
/**
* Add rating filter
*
@@ -75,4 +64,15 @@ public function setPositionOrder($dir = 'ASC')
$this->setOrder('main_table.position', $dir);
return $this;
}
+
+ /**
+ * Define model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('rating/rating_option');
+ $this->_ratingOptionTable = $this->getTable('rating/rating_option');
+ $this->_ratingVoteTable = $this->getTable('rating/rating_option_vote');
+ }
}
diff --git a/app/code/core/Mage/Rating/Model/Resource/Rating/Option/Vote/Collection.php b/app/code/core/Mage/Rating/Model/Resource/Rating/Option/Vote/Collection.php
index f0300ef7cc0..adc56fc0c1d 100644
--- a/app/code/core/Mage/Rating/Model/Resource/Rating/Option/Vote/Collection.php
+++ b/app/code/core/Mage/Rating/Model/Resource/Rating/Option/Vote/Collection.php
@@ -24,15 +24,6 @@
*/
class Mage_Rating_Model_Resource_Rating_Option_Vote_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Define model
- *
- */
- protected function _construct()
- {
- $this->_init('rating/rating_option_vote');
- }
-
/**
* Set review filter
*
@@ -164,4 +155,12 @@ public function addRatingOptions()
}
return $this;
}
+ /**
+ * Define model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('rating/rating_option_vote');
+ }
}
diff --git a/app/code/core/Mage/Reports/Block/Product/Abstract.php b/app/code/core/Mage/Reports/Block/Product/Abstract.php
index d7da626b2c6..4f32e738c64 100644
--- a/app/code/core/Mage/Reports/Block/Product/Abstract.php
+++ b/app/code/core/Mage/Reports/Block/Product/Abstract.php
@@ -73,34 +73,6 @@ public function getPageSize()
return 5;
}
- /**
- * Retrieve product ids, that must not be included in collection
- *
- * @return array
- */
- protected function _getProductsToSkip()
- {
- return [];
- }
-
- /**
- * Retrieve Product Index model instance
- *
- * @return Mage_Core_Model_Abstract|Mage_Reports_Model_Product_Index_Abstract
- */
- protected function _getModel()
- {
- if (is_null($this->_indexModel)) {
- if (is_null($this->_indexName)) {
- Mage::throwException(Mage::helper('reports')->__('Index model name must be defined'));
- }
-
- $this->_indexModel = Mage::getModel($this->_indexName);
- }
-
- return $this->_indexModel;
- }
-
/**
* Public method for retrieve Product Index model
*
@@ -180,6 +152,34 @@ public function getCount()
return $this->getItemsCollection()->count();
}
+ /**
+ * Retrieve product ids, that must not be included in collection
+ *
+ * @return array
+ */
+ protected function _getProductsToSkip()
+ {
+ return [];
+ }
+
+ /**
+ * Retrieve Product Index model instance
+ *
+ * @return Mage_Core_Model_Abstract|Mage_Reports_Model_Product_Index_Abstract
+ */
+ protected function _getModel()
+ {
+ if (is_null($this->_indexModel)) {
+ if (is_null($this->_indexName)) {
+ Mage::throwException(Mage::helper('reports')->__('Index model name must be defined'));
+ }
+
+ $this->_indexModel = Mage::getModel($this->_indexName);
+ }
+
+ return $this->_indexModel;
+ }
+
/**
* Get products collection and apply recent events log to it
*
diff --git a/app/code/core/Mage/Reports/Block/Product/Compared.php b/app/code/core/Mage/Reports/Block/Product/Compared.php
index 52e05f43cee..aa3601e4e7f 100644
--- a/app/code/core/Mage/Reports/Block/Product/Compared.php
+++ b/app/code/core/Mage/Reports/Block/Product/Compared.php
@@ -46,6 +46,19 @@ public function getPageSize()
return Mage::getStoreConfig(self::XML_PATH_RECENTLY_COMPARED_COUNT);
}
+ /**
+ * Retrieve block cache tags
+ *
+ * @return array
+ */
+ public function getCacheTags()
+ {
+ return array_merge(
+ parent::getCacheTags(),
+ $this->getItemsTags($this->getItemsCollection()),
+ );
+ }
+
/**
* Prepare to html
* Check has compared products
@@ -62,17 +75,4 @@ protected function _toHtml()
return parent::_toHtml();
}
-
- /**
- * Retrieve block cache tags
- *
- * @return array
- */
- public function getCacheTags()
- {
- return array_merge(
- parent::getCacheTags(),
- $this->getItemsTags($this->getItemsCollection()),
- );
- }
}
diff --git a/app/code/core/Mage/Reports/Block/Product/Viewed.php b/app/code/core/Mage/Reports/Block/Product/Viewed.php
index 1f0ba6a16c9..16c7cd04ed9 100644
--- a/app/code/core/Mage/Reports/Block/Product/Viewed.php
+++ b/app/code/core/Mage/Reports/Block/Product/Viewed.php
@@ -58,6 +58,19 @@ public function getCount()
return parent::getCount();
}
+ /**
+ * Retrieve block cache tags
+ *
+ * @return array
+ */
+ public function getCacheTags()
+ {
+ return array_merge(
+ parent::getCacheTags(),
+ $this->getItemsTags($this->getItemsCollection()),
+ );
+ }
+
/**
* Prepare to html
* check has viewed products
@@ -72,17 +85,4 @@ protected function _toHtml()
$this->setRecentlyViewedProducts($this->getItemsCollection());
return parent::_toHtml();
}
-
- /**
- * Retrieve block cache tags
- *
- * @return array
- */
- public function getCacheTags()
- {
- return array_merge(
- parent::getCacheTags(),
- $this->getItemsTags($this->getItemsCollection()),
- );
- }
}
diff --git a/app/code/core/Mage/Reports/Model/Event.php b/app/code/core/Mage/Reports/Model/Event.php
index 715c00b2ebb..657c52f2909 100644
--- a/app/code/core/Mage/Reports/Model/Event.php
+++ b/app/code/core/Mage/Reports/Model/Event.php
@@ -45,26 +45,6 @@ class Mage_Reports_Model_Event extends Mage_Core_Model_Abstract
public const EVENT_PRODUCT_TO_WISHLIST = 5;
public const EVENT_WISHLIST_SHARE = 6;
- /**
- * Initialize resource
- *
- */
- protected function _construct()
- {
- $this->_init('reports/event');
- }
-
- /**
- * Before Event save process
- *
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- $this->setLoggedAt(Mage::getModel('core/date')->gmtDate());
- return parent::_beforeSave();
- }
-
/**
* Update customer type after customer login
*
@@ -97,4 +77,24 @@ public function clean()
$this->getResource()->clean($this);
return $this;
}
+
+ /**
+ * Initialize resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('reports/event');
+ }
+
+ /**
+ * Before Event save process
+ *
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ $this->setLoggedAt(Mage::getModel('core/date')->gmtDate());
+ return parent::_beforeSave();
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Event/Observer.php b/app/code/core/Mage/Reports/Model/Event/Observer.php
index 60542a40562..0e605d33665 100644
--- a/app/code/core/Mage/Reports/Model/Event/Observer.php
+++ b/app/code/core/Mage/Reports/Model/Event/Observer.php
@@ -32,42 +32,6 @@ public function __construct()
$this->_enabledReports = Mage::helper('reports')->isReportsEnabled();
}
- /**
- * Abstract Event obeserver logic
- *
- * Save event
- *
- * @param int $eventTypeId
- * @param int $objectId
- * @param int $subjectId
- * @param int $subtype
- * @return $this
- */
- protected function _event($eventTypeId, $objectId, $subjectId = null, $subtype = 0)
- {
- if (is_null($subjectId)) {
- if (Mage::getSingleton('customer/session')->isLoggedIn()) {
- $customer = Mage::getSingleton('customer/session')->getCustomer();
- $subjectId = $customer->getId();
- } else {
- $subjectId = Mage::getSingleton('log/visitor')->getId();
- $subtype = 1;
- }
- }
-
- $eventModel = Mage::getModel('reports/event');
- $storeId = Mage::app()->getStore()->getId();
- $eventModel
- ->setEventTypeId($eventTypeId)
- ->setObjectId($objectId)
- ->setSubjectId($subjectId)
- ->setSubtype($subtype)
- ->setStoreId($storeId);
- $eventModel->save();
-
- return $this;
- }
-
/**
* Customer login action
*
@@ -277,4 +241,40 @@ public function eventClean(Varien_Event_Observer $observer)
return $this;
}
+
+ /**
+ * Abstract Event obeserver logic
+ *
+ * Save event
+ *
+ * @param int $eventTypeId
+ * @param int $objectId
+ * @param int $subjectId
+ * @param int $subtype
+ * @return $this
+ */
+ protected function _event($eventTypeId, $objectId, $subjectId = null, $subtype = 0)
+ {
+ if (is_null($subjectId)) {
+ if (Mage::getSingleton('customer/session')->isLoggedIn()) {
+ $customer = Mage::getSingleton('customer/session')->getCustomer();
+ $subjectId = $customer->getId();
+ } else {
+ $subjectId = Mage::getSingleton('log/visitor')->getId();
+ $subtype = 1;
+ }
+ }
+
+ $eventModel = Mage::getModel('reports/event');
+ $storeId = Mage::app()->getStore()->getId();
+ $eventModel
+ ->setEventTypeId($eventTypeId)
+ ->setObjectId($objectId)
+ ->setSubjectId($subjectId)
+ ->setSubtype($subtype)
+ ->setStoreId($storeId);
+ $eventModel->save();
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Product/Index/Abstract.php b/app/code/core/Mage/Reports/Model/Product/Index/Abstract.php
index 8ff5ff2606c..4a685f2ea70 100644
--- a/app/code/core/Mage/Reports/Model/Product/Index/Abstract.php
+++ b/app/code/core/Mage/Reports/Model/Product/Index/Abstract.php
@@ -146,16 +146,6 @@ public function purgeVisitorByCustomer()
return $this;
}
- /**
- * Retrieve Reports Session instance
- *
- * @return Mage_Reports_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('reports/session');
- }
-
/**
* Calculate count of product index items cache
*
@@ -234,4 +224,14 @@ public function registerIds($productIds)
$this->_getSession()->unsData($this->_countCacheKey);
return $this;
}
+
+ /**
+ * Retrieve Reports Session instance
+ *
+ * @return Mage_Reports_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('reports/session');
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Product/Index/Compared.php b/app/code/core/Mage/Reports/Model/Product/Index/Compared.php
index 4216ae1221f..b1192de4e04 100644
--- a/app/code/core/Mage/Reports/Model/Product/Index/Compared.php
+++ b/app/code/core/Mage/Reports/Model/Product/Index/Compared.php
@@ -39,11 +39,6 @@ class Mage_Reports_Model_Product_Index_Compared extends Mage_Reports_Model_Produ
*/
protected $_countCacheKey = 'product_index_compared_count';
- protected function _construct()
- {
- $this->_init('reports/product_index_compared');
- }
-
/**
* Retrieve Exclude Product Ids List for Collection
*
@@ -68,4 +63,9 @@ public function getExcludeProductIds()
return array_unique($productIds);
}
+
+ protected function _construct()
+ {
+ $this->_init('reports/product_index_compared');
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Product/Index/Viewed.php b/app/code/core/Mage/Reports/Model/Product/Index/Viewed.php
index e32caffcd5e..82d8e99881b 100644
--- a/app/code/core/Mage/Reports/Model/Product/Index/Viewed.php
+++ b/app/code/core/Mage/Reports/Model/Product/Index/Viewed.php
@@ -39,15 +39,6 @@ class Mage_Reports_Model_Product_Index_Viewed extends Mage_Reports_Model_Product
*/
protected $_countCacheKey = 'product_index_viewed_count';
- /**
- * Initialize resource model
- *
- */
- protected function _construct()
- {
- $this->_init('reports/product_index_viewed');
- }
-
/**
* Retrieve Exclude Product Ids List for Collection
*
@@ -63,4 +54,13 @@ public function getExcludeProductIds()
return $productIds;
}
+
+ /**
+ * Initialize resource model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('reports/product_index_viewed');
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Accounts/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Accounts/Collection.php
index 7bb80420cb2..f7571c73402 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Accounts/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Accounts/Collection.php
@@ -22,24 +22,6 @@
*/
class Mage_Reports_Model_Resource_Accounts_Collection extends Mage_Reports_Model_Resource_Customer_Collection
{
- /**
- * Join created_at and accounts fields
- *
- * @param string $from
- * @param string $to
- * @return $this
- */
- protected function _joinFields($from = '', $to = '')
- {
- $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
- $this->addAttributeToFilter('created_at', ['from' => $from, 'to' => $to, 'datetime' => true])
- ->addExpressionAttributeToSelect('accounts', 'COUNT({{entity_id}})', ['entity_id']);
-
- $this->getSelect()->having("{$this->_joinFields['accounts']['field']} > ?", 0);
-
- return $this;
- }
-
/**
* Set date range
*
@@ -67,4 +49,21 @@ public function setStoreIds($storeIds)
}
return $this;
}
+ /**
+ * Join created_at and accounts fields
+ *
+ * @param string $from
+ * @param string $to
+ * @return $this
+ */
+ protected function _joinFields($from = '', $to = '')
+ {
+ $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
+ $this->addAttributeToFilter('created_at', ['from' => $from, 'to' => $to, 'datetime' => true])
+ ->addExpressionAttributeToSelect('accounts', 'COUNT({{entity_id}})', ['entity_id']);
+
+ $this->getSelect()->having("{$this->_joinFields['accounts']['field']} > ?", 0);
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Customer/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Customer/Collection.php
index 31a56046d2e..06eeb870d38 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Customer/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Customer/Collection.php
@@ -191,6 +191,37 @@ public function addOrdersStatistics($isFilter = false)
return $this;
}
+ /**
+ * Order by customer registration
+ *
+ * @param string $dir
+ * @return $this
+ */
+ public function orderByCustomerRegistration($dir = self::SORT_ORDER_DESC)
+ {
+ $this->addAttributeToSort('entity_id', $dir);
+ return $this;
+ }
+
+ /**
+ * Get select count sql
+ *
+ * @return Varien_Db_Select
+ */
+ public function getSelectCountSql()
+ {
+ $countSelect = clone $this->getSelect();
+ $countSelect->reset(Zend_Db_Select::ORDER);
+ $countSelect->reset(Zend_Db_Select::LIMIT_COUNT);
+ $countSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
+ $countSelect->reset(Zend_Db_Select::COLUMNS);
+ $countSelect->reset(Zend_Db_Select::GROUP);
+ $countSelect->reset(Zend_Db_Select::HAVING);
+ $countSelect->columns('count(DISTINCT e.entity_id)');
+
+ return $countSelect;
+ }
+
/**
* Add orders statistics to collection items
*
@@ -245,35 +276,4 @@ protected function _afterLoad()
$this->_addOrdersStatistics();
return $this;
}
-
- /**
- * Order by customer registration
- *
- * @param string $dir
- * @return $this
- */
- public function orderByCustomerRegistration($dir = self::SORT_ORDER_DESC)
- {
- $this->addAttributeToSort('entity_id', $dir);
- return $this;
- }
-
- /**
- * Get select count sql
- *
- * @return Varien_Db_Select
- */
- public function getSelectCountSql()
- {
- $countSelect = clone $this->getSelect();
- $countSelect->reset(Zend_Db_Select::ORDER);
- $countSelect->reset(Zend_Db_Select::LIMIT_COUNT);
- $countSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
- $countSelect->reset(Zend_Db_Select::COLUMNS);
- $countSelect->reset(Zend_Db_Select::GROUP);
- $countSelect->reset(Zend_Db_Select::HAVING);
- $countSelect->columns('count(DISTINCT e.entity_id)');
-
- return $countSelect;
- }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Customer/Orders/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Customer/Orders/Collection.php
index 8ac785f3b53..a1b12148fd4 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Customer/Orders/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Customer/Orders/Collection.php
@@ -22,27 +22,6 @@
*/
class Mage_Reports_Model_Resource_Customer_Orders_Collection extends Mage_Reports_Model_Resource_Order_Collection
{
- protected function _construct()
- {
- parent::_construct();
- $this->_useAnalyticFunction = true;
- }
- /**
- * Join fields
- *
- * @param string $from
- * @param string $to
- * @return $this
- */
- protected function _joinFields($from = '', $to = '')
- {
- $this->joinCustomerName()
- ->groupByCustomer()
- ->addOrdersCount()
- ->addAttributeToFilter('created_at', ['from' => $from, 'to' => $to, 'datetime' => true]);
- return $this;
- }
-
/**
* Set date range
*
@@ -76,4 +55,24 @@ public function setStoreIds($storeIds)
return $this;
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_useAnalyticFunction = true;
+ }
+ /**
+ * Join fields
+ *
+ * @param string $from
+ * @param string $to
+ * @return $this
+ */
+ protected function _joinFields($from = '', $to = '')
+ {
+ $this->joinCustomerName()
+ ->groupByCustomer()
+ ->addOrdersCount()
+ ->addAttributeToFilter('created_at', ['from' => $from, 'to' => $to, 'datetime' => true]);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Customer/Totals/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Customer/Totals/Collection.php
index 399e38d31ad..4a773248447 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Customer/Totals/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Customer/Totals/Collection.php
@@ -22,27 +22,6 @@
*/
class Mage_Reports_Model_Resource_Customer_Totals_Collection extends Mage_Reports_Model_Resource_Order_Collection
{
- protected function _construct()
- {
- parent::_construct();
- $this->_useAnalyticFunction = true;
- }
- /**
- * Join fields
- *
- * @param string $from
- * @param string $to
- * @return $this
- */
- protected function _joinFields($from = '', $to = '')
- {
- $this->joinCustomerName()
- ->groupByCustomer()
- ->addOrdersCount()
- ->addAttributeToFilter('created_at', ['from' => $from, 'to' => $to, 'datetime' => true]);
- return $this;
- }
-
/**
* Set date range
*
@@ -76,4 +55,24 @@ public function setStoreIds($storeIds)
return $this;
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_useAnalyticFunction = true;
+ }
+ /**
+ * Join fields
+ *
+ * @param string $from
+ * @param string $to
+ * @return $this
+ */
+ protected function _joinFields($from = '', $to = '')
+ {
+ $this->joinCustomerName()
+ ->groupByCustomer()
+ ->addOrdersCount()
+ ->addAttributeToFilter('created_at', ['from' => $from, 'to' => $to, 'datetime' => true]);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Event.php b/app/code/core/Mage/Reports/Model/Resource/Event.php
index a01096ba97f..4fef4cdf895 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Event.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Event.php
@@ -22,15 +22,6 @@
*/
class Mage_Reports_Model_Resource_Event extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Initialize main table and identifier field.
- * Set main entity table name and primary key field name.
- */
- protected function _construct()
- {
- $this->_init('reports/event', 'event_id');
- }
-
/**
* Update customer type after customer login
*
@@ -174,4 +165,12 @@ public function clean(Mage_Reports_Model_Event $object)
}
return $this;
}
+ /**
+ * Initialize main table and identifier field.
+ * Set main entity table name and primary key field name.
+ */
+ protected function _construct()
+ {
+ $this->_init('reports/event', 'event_id');
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Event/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Event/Collection.php
index 79fa55e7179..7afdc3ff5be 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Event/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Event/Collection.php
@@ -40,11 +40,6 @@ class Mage_Reports_Model_Resource_Event_Collection extends Mage_Core_Model_Resou
*/
protected $_useAnalyticFunction = true;
- protected function _construct()
- {
- $this->_init('reports/event');
- }
-
/**
* Add store ids filter
*
@@ -85,4 +80,9 @@ public function addRecentlyFiler($typeId, $subjectId, $subtype = 0, $ignore = nu
->limit($limit);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('reports/event');
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Event/Type/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Event/Type/Collection.php
index ce9e8a31e3a..bf20a8354d2 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Event/Type/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Event/Type/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Reports_Model_Resource_Event_Type_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('reports/event_type');
- }
-
/**
* Return option array
*
@@ -36,4 +31,8 @@ public function toOptionArray()
{
return parent::_toOptionArray('event_type_id', 'event_name');
}
+ protected function _construct()
+ {
+ $this->_init('reports/event_type');
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Order/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Order/Collection.php
index 867ffd517af..89661906560 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Order/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Order/Collection.php
@@ -81,228 +81,6 @@ public function prepareSummary($range, $customStart, $customEnd, $isFilter = 0)
return $this;
}
- /**
- * Get sales amount expression
- *
- * @return string
- */
- protected function _getSalesAmountExpression()
- {
- if (is_null($this->_salesAmountExpression)) {
- $adapter = $this->getConnection();
- $expressionTransferObject = new Varien_Object([
- 'expression' => '%s - %s - %s - (%s - %s - %s)',
- 'arguments' => [
- $adapter->getIfNullSql('main_table.base_total_invoiced', 0),
- $adapter->getIfNullSql('main_table.base_tax_invoiced', 0),
- $adapter->getIfNullSql('main_table.base_shipping_invoiced', 0),
- $adapter->getIfNullSql('main_table.base_total_refunded', 0),
- $adapter->getIfNullSql('main_table.base_tax_refunded', 0),
- $adapter->getIfNullSql('main_table.base_shipping_refunded', 0),
- ],
- ]);
-
- Mage::dispatchEvent('sales_prepare_amount_expression', [
- 'collection' => $this,
- 'expression_object' => $expressionTransferObject,
- ]);
- $this->_salesAmountExpression = vsprintf(
- $expressionTransferObject->getExpression(),
- $expressionTransferObject->getArguments(),
- );
- }
-
- return $this->_salesAmountExpression;
- }
-
- /**
- * Prepare report summary from live data
- *
- * @param string $range
- * @param mixed $customStart
- * @param mixed $customEnd
- * @param int $isFilter
- * @return $this
- */
- protected function _prepareSummaryLive($range, $customStart, $customEnd, $isFilter = 0)
- {
- $this->setMainTable('sales/order');
- $adapter = $this->getConnection();
-
- /**
- * Reset all columns, because result will group only by 'created_at' field
- */
- $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
-
- $expression = $this->_getSalesAmountExpression();
- if ($isFilter == 0) {
- $this->getSelect()->columns([
- 'revenue' => new Zend_Db_Expr(
- sprintf(
- 'SUM((%s) * %s)',
- $expression,
- $adapter->getIfNullSql('main_table.base_to_global_rate', 0),
- ),
- ),
- ]);
- } else {
- $this->getSelect()->columns([
- 'revenue' => new Zend_Db_Expr(sprintf('SUM(%s)', $expression)),
- ]);
- }
-
- $dateRange = $this->getDateRange($range, $customStart, $customEnd);
-
- $tzRangeOffsetExpression = $this->_getTZRangeOffsetExpression(
- $range,
- 'created_at',
- $dateRange['from'],
- $dateRange['to'],
- );
-
- $this->getSelect()
- ->columns([
- 'quantity' => new Zend_Db_Expr('COUNT(main_table.entity_id)'),
- 'range' => $tzRangeOffsetExpression,
- ])
- ->where('main_table.state NOT IN (?)', [
- Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
- Mage_Sales_Model_Order::STATE_NEW])
- ->order('range ' . Zend_Db_Select::SQL_ASC)
- ->group($tzRangeOffsetExpression);
-
- $this->addFieldToFilter('created_at', $dateRange);
-
- return $this;
- }
-
- /**
- * Prepare report summary from aggregated data
- *
- * @param string $range
- * @param mixed $customStart
- * @param mixed $customEnd
- * @return $this
- */
- protected function _prepareSummaryAggregated($range, $customStart, $customEnd)
- {
- $this->setMainTable('sales/order_aggregated_created');
- /**
- * Reset all columns, because result will group only by 'created_at' field
- */
- $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
- $rangePeriod = $this->_getRangeExpressionForAttribute($range, 'main_table.period');
-
- $tableName = $this->getConnection()->quoteIdentifier('main_table.period');
- $rangePeriod2 = str_replace($tableName, "MIN($tableName)", $rangePeriod);
-
- $this->getSelect()->columns([
- 'revenue' => new Zend_Db_Expr('SUM(main_table.total_revenue_amount)'),
- 'quantity' => new Zend_Db_Expr('SUM(main_table.orders_count)'),
- 'range' => $rangePeriod2,
- ])
- ->order('range')
- ->group($rangePeriod);
-
- $this->getSelect()->where(
- $this->_getConditionSql('main_table.period', $this->getDateRange($range, $customStart, $customEnd)),
- );
-
- $statuses = Mage::getSingleton('sales/config')
- ->getOrderStatusesForState(Mage_Sales_Model_Order::STATE_CANCELED);
-
- if (empty($statuses)) {
- $statuses = [0];
- }
- $this->addFieldToFilter('main_table.order_status', ['nin' => $statuses]);
-
- return $this;
- }
-
- /**
- * Get range expression
- *
- * @param string $range
- * @return Zend_Db_Expr
- */
- protected function _getRangeExpression($range)
- {
- switch ($range) {
- case '24h':
- $expression = $this->getConnection()->getConcatSql([
- $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d %H:'),
- $this->getConnection()->quote('00'),
- ]);
- break;
- case '7d':
- case '1m':
- $expression = $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d');
- break;
- case '1y':
- case '2y':
- case 'custom':
- default:
- $expression = $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m');
- break;
- }
-
- return $expression;
- }
-
- /**
- * Retrieve range expression adapted for attribute
- *
- * @param string $range
- * @param string $attribute
- * @return string
- */
- protected function _getRangeExpressionForAttribute($range, $attribute)
- {
- $expression = $this->_getRangeExpression($range);
- return str_replace('{{attribute}}', $this->getConnection()->quoteIdentifier($attribute), $expression);
- }
-
- /**
- * Retrieve query for attribute with timezone conversion
- *
- * @param string $range
- * @param string $attribute
- * @param mixed $from
- * @param mixed $to
- * @return string
- */
- protected function _getTZRangeOffsetExpression($range, $attribute, $from = null, $to = null)
- {
- return str_replace(
- '{{attribute}}',
- Mage::getResourceModel('sales/report_order')
- ->getStoreTZOffsetQuery($this->getMainTable(), $attribute, $from, $to),
- $this->_getRangeExpression($range),
- );
- }
-
- /**
- * Retrieve range expression with timezone conversion adapted for attribute
- *
- * @param string $range
- * @param string $attribute
- * @param string $tzFrom
- * @param string $tzTo
- * @return string
- */
- protected function _getTZRangeExpressionForAttribute($range, $attribute, $tzFrom = '+00:00', $tzTo = null)
- {
- if ($tzTo == null) {
- $tzTo = Mage::app()->getLocale()->storeDate()->toString(Zend_Date::GMT_DIFF_SEP);
- }
- $adapter = $this->getConnection();
- $expression = $this->_getRangeExpression($range);
- $attribute = $adapter->quoteIdentifier($attribute);
- $periodExpr = $adapter->getDateAddSql($attribute, $tzTo, Varien_Db_Adapter_Interface::INTERVAL_HOUR);
-
- return str_replace('{{attribute}}', $periodExpr, $expression);
- }
-
/**
* Calculate From and To dates (or times) by given period
*
@@ -401,114 +179,33 @@ public function calculateTotals($isFilter = 0)
}
/**
- * Calculate totals live report
+ * Calculate lifitime sales
*
- * @param int $isFilter
+ * @param bool|int $isFilter
* @return $this
*/
- protected function _calculateTotalsLive($isFilter = 0)
+ public function calculateSales($isFilter = 0)
{
- $this->setMainTable('sales/order');
- $this->removeAllFieldsFromSelect();
+ $statuses = Mage::getSingleton('sales/config')
+ ->getOrderStatusesForState(Mage_Sales_Model_Order::STATE_CANCELED);
+ if (empty($statuses)) {
+ $statuses = [0];
+ }
$adapter = $this->getConnection();
- $baseTaxInvoiced = $adapter->getIfNullSql('main_table.base_tax_invoiced', 0);
- $baseTaxRefunded = $adapter->getIfNullSql('main_table.base_tax_refunded', 0);
- $baseShippingInvoiced = $adapter->getIfNullSql('main_table.base_shipping_invoiced', 0);
- $baseShippingRefunded = $adapter->getIfNullSql('main_table.base_shipping_refunded', 0);
-
- $revenueExp = $this->_getSalesAmountExpression();
- $taxExp = sprintf('%s - %s', $baseTaxInvoiced, $baseTaxRefunded);
- $shippingExp = sprintf('%s - %s', $baseShippingInvoiced, $baseShippingRefunded);
-
- if ($isFilter == 0) {
- $rateExp = $adapter->getIfNullSql('main_table.base_to_global_rate', 0);
- $this->getSelect()->columns(
- [
- 'revenue' => new Zend_Db_Expr(sprintf('SUM((%s) * %s)', $revenueExp, $rateExp)),
- 'tax' => new Zend_Db_Expr(sprintf('SUM((%s) * %s)', $taxExp, $rateExp)),
- 'shipping' => new Zend_Db_Expr(sprintf('SUM((%s) * %s)', $shippingExp, $rateExp)),
- ],
- );
- } else {
- $this->getSelect()->columns(
- [
- 'revenue' => new Zend_Db_Expr(sprintf('SUM(%s)', $revenueExp)),
- 'tax' => new Zend_Db_Expr(sprintf('SUM(%s)', $taxExp)),
- 'shipping' => new Zend_Db_Expr(sprintf('SUM(%s)', $shippingExp)),
- ],
- );
- }
-
- $this->getSelect()->columns([
- 'quantity' => 'COUNT(main_table.entity_id)',
- ])
- ->where('main_table.state NOT IN (?)', [
- Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
- Mage_Sales_Model_Order::STATE_NEW]);
-
- return $this;
- }
-
- /**
- * Calculate totals aggregated report
- *
- * @param int $isFilter
- * @return $this
- */
- protected function _calculateTotalsAggregated($isFilter = 0)
- {
- $this->setMainTable('sales/order_aggregated_created');
- $this->removeAllFieldsFromSelect();
-
- $this->getSelect()->columns([
- 'revenue' => 'SUM(main_table.total_revenue_amount)',
- 'tax' => 'SUM(main_table.total_tax_amount_actual)',
- 'shipping' => 'SUM(main_table.total_shipping_amount_actual)',
- 'quantity' => 'SUM(orders_count)',
- ]);
-
- $statuses = Mage::getSingleton('sales/config')
- ->getOrderStatusesForState(Mage_Sales_Model_Order::STATE_CANCELED);
-
- if (empty($statuses)) {
- $statuses = [0];
- }
-
- $this->getSelect()->where('main_table.order_status NOT IN(?)', $statuses);
-
- return $this;
- }
-
- /**
- * Calculate lifitime sales
- *
- * @param bool|int $isFilter
- * @return $this
- */
- public function calculateSales($isFilter = 0)
- {
- $statuses = Mage::getSingleton('sales/config')
- ->getOrderStatusesForState(Mage_Sales_Model_Order::STATE_CANCELED);
-
- if (empty($statuses)) {
- $statuses = [0];
- }
- $adapter = $this->getConnection();
-
- if (Mage::getStoreConfig('sales/dashboard/use_aggregated_data')) {
- $this->setMainTable('sales/order_aggregated_created');
- $this->removeAllFieldsFromSelect();
- $averageExpr = $adapter->getCheckSql(
- 'SUM(main_table.orders_count) > 0',
- 'SUM(main_table.total_revenue_amount)/SUM(main_table.orders_count)',
- '0',
- );
- $this->getSelect()->columns([
- 'lifetime' => new Zend_Db_Expr('SUM(main_table.total_revenue_amount)'),
- 'average' => $averageExpr,
- ]);
+ if (Mage::getStoreConfig('sales/dashboard/use_aggregated_data')) {
+ $this->setMainTable('sales/order_aggregated_created');
+ $this->removeAllFieldsFromSelect();
+ $averageExpr = $adapter->getCheckSql(
+ 'SUM(main_table.orders_count) > 0',
+ 'SUM(main_table.total_revenue_amount)/SUM(main_table.orders_count)',
+ '0',
+ );
+ $this->getSelect()->columns([
+ 'lifetime' => new Zend_Db_Expr('SUM(main_table.total_revenue_amount)'),
+ 'average' => $averageExpr,
+ ]);
if (!$isFilter) {
$this->addFieldToFilter(
@@ -778,17 +475,6 @@ public function getSelectCountSql()
return $countSelect;
}
- /**
- * Initialize initial fields to select
- *
- * @return $this
- */
- protected function _initInitialFieldsToSelect()
- {
- // No fields should be initialized
- return $this;
- }
-
/**
* Add period filter by created_at attribute
*
@@ -814,4 +500,318 @@ public function addCreateAtPeriodFilter($period)
return $this;
}
+
+ /**
+ * Get sales amount expression
+ *
+ * @return string
+ */
+ protected function _getSalesAmountExpression()
+ {
+ if (is_null($this->_salesAmountExpression)) {
+ $adapter = $this->getConnection();
+ $expressionTransferObject = new Varien_Object([
+ 'expression' => '%s - %s - %s - (%s - %s - %s)',
+ 'arguments' => [
+ $adapter->getIfNullSql('main_table.base_total_invoiced', 0),
+ $adapter->getIfNullSql('main_table.base_tax_invoiced', 0),
+ $adapter->getIfNullSql('main_table.base_shipping_invoiced', 0),
+ $adapter->getIfNullSql('main_table.base_total_refunded', 0),
+ $adapter->getIfNullSql('main_table.base_tax_refunded', 0),
+ $adapter->getIfNullSql('main_table.base_shipping_refunded', 0),
+ ],
+ ]);
+
+ Mage::dispatchEvent('sales_prepare_amount_expression', [
+ 'collection' => $this,
+ 'expression_object' => $expressionTransferObject,
+ ]);
+ $this->_salesAmountExpression = vsprintf(
+ $expressionTransferObject->getExpression(),
+ $expressionTransferObject->getArguments(),
+ );
+ }
+
+ return $this->_salesAmountExpression;
+ }
+
+ /**
+ * Prepare report summary from live data
+ *
+ * @param string $range
+ * @param mixed $customStart
+ * @param mixed $customEnd
+ * @param int $isFilter
+ * @return $this
+ */
+ protected function _prepareSummaryLive($range, $customStart, $customEnd, $isFilter = 0)
+ {
+ $this->setMainTable('sales/order');
+ $adapter = $this->getConnection();
+
+ /**
+ * Reset all columns, because result will group only by 'created_at' field
+ */
+ $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
+
+ $expression = $this->_getSalesAmountExpression();
+ if ($isFilter == 0) {
+ $this->getSelect()->columns([
+ 'revenue' => new Zend_Db_Expr(
+ sprintf(
+ 'SUM((%s) * %s)',
+ $expression,
+ $adapter->getIfNullSql('main_table.base_to_global_rate', 0),
+ ),
+ ),
+ ]);
+ } else {
+ $this->getSelect()->columns([
+ 'revenue' => new Zend_Db_Expr(sprintf('SUM(%s)', $expression)),
+ ]);
+ }
+
+ $dateRange = $this->getDateRange($range, $customStart, $customEnd);
+
+ $tzRangeOffsetExpression = $this->_getTZRangeOffsetExpression(
+ $range,
+ 'created_at',
+ $dateRange['from'],
+ $dateRange['to'],
+ );
+
+ $this->getSelect()
+ ->columns([
+ 'quantity' => new Zend_Db_Expr('COUNT(main_table.entity_id)'),
+ 'range' => $tzRangeOffsetExpression,
+ ])
+ ->where('main_table.state NOT IN (?)', [
+ Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
+ Mage_Sales_Model_Order::STATE_NEW])
+ ->order('range ' . Zend_Db_Select::SQL_ASC)
+ ->group($tzRangeOffsetExpression);
+
+ $this->addFieldToFilter('created_at', $dateRange);
+
+ return $this;
+ }
+
+ /**
+ * Prepare report summary from aggregated data
+ *
+ * @param string $range
+ * @param mixed $customStart
+ * @param mixed $customEnd
+ * @return $this
+ */
+ protected function _prepareSummaryAggregated($range, $customStart, $customEnd)
+ {
+ $this->setMainTable('sales/order_aggregated_created');
+ /**
+ * Reset all columns, because result will group only by 'created_at' field
+ */
+ $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
+ $rangePeriod = $this->_getRangeExpressionForAttribute($range, 'main_table.period');
+
+ $tableName = $this->getConnection()->quoteIdentifier('main_table.period');
+ $rangePeriod2 = str_replace($tableName, "MIN($tableName)", $rangePeriod);
+
+ $this->getSelect()->columns([
+ 'revenue' => new Zend_Db_Expr('SUM(main_table.total_revenue_amount)'),
+ 'quantity' => new Zend_Db_Expr('SUM(main_table.orders_count)'),
+ 'range' => $rangePeriod2,
+ ])
+ ->order('range')
+ ->group($rangePeriod);
+
+ $this->getSelect()->where(
+ $this->_getConditionSql('main_table.period', $this->getDateRange($range, $customStart, $customEnd)),
+ );
+
+ $statuses = Mage::getSingleton('sales/config')
+ ->getOrderStatusesForState(Mage_Sales_Model_Order::STATE_CANCELED);
+
+ if (empty($statuses)) {
+ $statuses = [0];
+ }
+ $this->addFieldToFilter('main_table.order_status', ['nin' => $statuses]);
+
+ return $this;
+ }
+
+ /**
+ * Get range expression
+ *
+ * @param string $range
+ * @return Zend_Db_Expr
+ */
+ protected function _getRangeExpression($range)
+ {
+ switch ($range) {
+ case '24h':
+ $expression = $this->getConnection()->getConcatSql([
+ $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d %H:'),
+ $this->getConnection()->quote('00'),
+ ]);
+ break;
+ case '7d':
+ case '1m':
+ $expression = $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d');
+ break;
+ case '1y':
+ case '2y':
+ case 'custom':
+ default:
+ $expression = $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m');
+ break;
+ }
+
+ return $expression;
+ }
+
+ /**
+ * Retrieve range expression adapted for attribute
+ *
+ * @param string $range
+ * @param string $attribute
+ * @return string
+ */
+ protected function _getRangeExpressionForAttribute($range, $attribute)
+ {
+ $expression = $this->_getRangeExpression($range);
+ return str_replace('{{attribute}}', $this->getConnection()->quoteIdentifier($attribute), $expression);
+ }
+
+ /**
+ * Retrieve query for attribute with timezone conversion
+ *
+ * @param string $range
+ * @param string $attribute
+ * @param mixed $from
+ * @param mixed $to
+ * @return string
+ */
+ protected function _getTZRangeOffsetExpression($range, $attribute, $from = null, $to = null)
+ {
+ return str_replace(
+ '{{attribute}}',
+ Mage::getResourceModel('sales/report_order')
+ ->getStoreTZOffsetQuery($this->getMainTable(), $attribute, $from, $to),
+ $this->_getRangeExpression($range),
+ );
+ }
+
+ /**
+ * Retrieve range expression with timezone conversion adapted for attribute
+ *
+ * @param string $range
+ * @param string $attribute
+ * @param string $tzFrom
+ * @param string $tzTo
+ * @return string
+ */
+ protected function _getTZRangeExpressionForAttribute($range, $attribute, $tzFrom = '+00:00', $tzTo = null)
+ {
+ if ($tzTo == null) {
+ $tzTo = Mage::app()->getLocale()->storeDate()->toString(Zend_Date::GMT_DIFF_SEP);
+ }
+ $adapter = $this->getConnection();
+ $expression = $this->_getRangeExpression($range);
+ $attribute = $adapter->quoteIdentifier($attribute);
+ $periodExpr = $adapter->getDateAddSql($attribute, $tzTo, Varien_Db_Adapter_Interface::INTERVAL_HOUR);
+
+ return str_replace('{{attribute}}', $periodExpr, $expression);
+ }
+
+ /**
+ * Calculate totals live report
+ *
+ * @param int $isFilter
+ * @return $this
+ */
+ protected function _calculateTotalsLive($isFilter = 0)
+ {
+ $this->setMainTable('sales/order');
+ $this->removeAllFieldsFromSelect();
+
+ $adapter = $this->getConnection();
+
+ $baseTaxInvoiced = $adapter->getIfNullSql('main_table.base_tax_invoiced', 0);
+ $baseTaxRefunded = $adapter->getIfNullSql('main_table.base_tax_refunded', 0);
+ $baseShippingInvoiced = $adapter->getIfNullSql('main_table.base_shipping_invoiced', 0);
+ $baseShippingRefunded = $adapter->getIfNullSql('main_table.base_shipping_refunded', 0);
+
+ $revenueExp = $this->_getSalesAmountExpression();
+ $taxExp = sprintf('%s - %s', $baseTaxInvoiced, $baseTaxRefunded);
+ $shippingExp = sprintf('%s - %s', $baseShippingInvoiced, $baseShippingRefunded);
+
+ if ($isFilter == 0) {
+ $rateExp = $adapter->getIfNullSql('main_table.base_to_global_rate', 0);
+ $this->getSelect()->columns(
+ [
+ 'revenue' => new Zend_Db_Expr(sprintf('SUM((%s) * %s)', $revenueExp, $rateExp)),
+ 'tax' => new Zend_Db_Expr(sprintf('SUM((%s) * %s)', $taxExp, $rateExp)),
+ 'shipping' => new Zend_Db_Expr(sprintf('SUM((%s) * %s)', $shippingExp, $rateExp)),
+ ],
+ );
+ } else {
+ $this->getSelect()->columns(
+ [
+ 'revenue' => new Zend_Db_Expr(sprintf('SUM(%s)', $revenueExp)),
+ 'tax' => new Zend_Db_Expr(sprintf('SUM(%s)', $taxExp)),
+ 'shipping' => new Zend_Db_Expr(sprintf('SUM(%s)', $shippingExp)),
+ ],
+ );
+ }
+
+ $this->getSelect()->columns([
+ 'quantity' => 'COUNT(main_table.entity_id)',
+ ])
+ ->where('main_table.state NOT IN (?)', [
+ Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
+ Mage_Sales_Model_Order::STATE_NEW]);
+
+ return $this;
+ }
+
+ /**
+ * Calculate totals aggregated report
+ *
+ * @param int $isFilter
+ * @return $this
+ */
+ protected function _calculateTotalsAggregated($isFilter = 0)
+ {
+ $this->setMainTable('sales/order_aggregated_created');
+ $this->removeAllFieldsFromSelect();
+
+ $this->getSelect()->columns([
+ 'revenue' => 'SUM(main_table.total_revenue_amount)',
+ 'tax' => 'SUM(main_table.total_tax_amount_actual)',
+ 'shipping' => 'SUM(main_table.total_shipping_amount_actual)',
+ 'quantity' => 'SUM(orders_count)',
+ ]);
+
+ $statuses = Mage::getSingleton('sales/config')
+ ->getOrderStatusesForState(Mage_Sales_Model_Order::STATE_CANCELED);
+
+ if (empty($statuses)) {
+ $statuses = [0];
+ }
+
+ $this->getSelect()->where('main_table.order_status NOT IN(?)', $statuses);
+
+ return $this;
+ }
+
+ /**
+ * Initialize initial fields to select
+ *
+ * @return $this
+ */
+ protected function _initInitialFieldsToSelect()
+ {
+ // No fields should be initialized
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Product/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Product/Collection.php
index 915f3ad6aaf..21502225e32 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Product/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Product/Collection.php
@@ -143,20 +143,6 @@ public function getProductEntityTypeId()
return $this->_productEntityTypeId;
}
- /**
- * Join fields
- *
- * @return $this
- */
- protected function _joinFields()
- {
- $this->addAttributeToSelect('entity_id')
- ->addAttributeToSelect('name')
- ->addAttributeToSelect('price');
-
- return $this;
- }
-
/**
* Get select count sql
*
@@ -381,24 +367,6 @@ public function addViewsCount($from = '', $to = '')
return $this;
}
- /**
- * Prepare between sql
- *
- * @param string $fieldName Field name with table suffix ('created_at' or 'main_table.created_at')
- * @param string $from
- * @param string $to
- * @return string Formatted sql string
- */
- protected function _prepareBetweenSql($fieldName, $from, $to)
- {
- return sprintf(
- '(%s BETWEEN %s AND %s)',
- $fieldName,
- $this->getConnection()->quote($from),
- $this->getConnection()->quote($to),
- );
- }
-
/**
* Add store restrictions to product collection
*
@@ -428,4 +396,36 @@ public function addStoreRestrictions($storeIds, $websiteIds)
return $this;
}
+
+ /**
+ * Join fields
+ *
+ * @return $this
+ */
+ protected function _joinFields()
+ {
+ $this->addAttributeToSelect('entity_id')
+ ->addAttributeToSelect('name')
+ ->addAttributeToSelect('price');
+
+ return $this;
+ }
+
+ /**
+ * Prepare between sql
+ *
+ * @param string $fieldName Field name with table suffix ('created_at' or 'main_table.created_at')
+ * @param string $from
+ * @param string $to
+ * @return string Formatted sql string
+ */
+ protected function _prepareBetweenSql($fieldName, $from, $to)
+ {
+ return sprintf(
+ '(%s BETWEEN %s AND %s)',
+ $fieldName,
+ $this->getConnection()->quote($from),
+ $this->getConnection()->quote($to),
+ );
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Product/Index/Collection/Abstract.php b/app/code/core/Mage/Reports/Model/Resource/Product/Index/Collection/Abstract.php
index 7d2589e6531..8fa125f180c 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Product/Index/Collection/Abstract.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Product/Index/Collection/Abstract.php
@@ -37,35 +37,6 @@ abstract class Mage_Reports_Model_Resource_Product_Index_Collection_Abstract ext
*/
protected $_sortIds = [];
- /**
- * Retrieve Product Index table name
- *
- */
- abstract protected function _getTableName();
-
- /**
- * Join index table
- *
- * @return Mage_Reports_Model_Resource_Product_Index_Collection_Abstract
- */
- protected function _joinIdxTable()
- {
- if (!$this->getFlag('is_idx_table_joined')) {
- $this->joinTable(
- ['idx_table' => $this->_getTableName()],
- 'product_id=entity_id',
- [
- 'product_id' => 'product_id',
- 'item_store_id' => 'store_id',
- 'added_at' => 'added_at',
- ],
- $this->_getWhereCondition(),
- );
- $this->setFlag('is_idx_table_joined', true);
- }
- return $this;
- }
-
/**
* Add Viewed Products Index to Collection
*
@@ -96,26 +67,6 @@ public function addFilterByIds($ids)
return $this;
}
- /**
- * Retrieve Where Condition to Index table
- *
- * @return array
- */
- protected function _getWhereCondition()
- {
- $condition = [];
-
- if (Mage::getSingleton('customer/session')->isLoggedIn()) {
- $condition['customer_id'] = Mage::getSingleton('customer/session')->getCustomerId();
- } elseif ($this->_customerId) {
- $condition['customer_id'] = $this->_customerId;
- } else {
- $condition['visitor_id'] = Mage::getSingleton('log/visitor')->getId();
- }
-
- return $condition;
- }
-
/**
* Set customer id, that will be used in 'whereCondition'
*
@@ -153,6 +104,71 @@ public function setSortIds(array $ids)
return $this;
}
+ /**
+ * Add exclude Product Ids
+ *
+ * @param int|array $productIds
+ * @return Mage_Reports_Model_Resource_Product_Index_Collection_Abstract
+ */
+ public function excludeProductIds($productIds)
+ {
+ if (empty($productIds)) {
+ return $this;
+ }
+ $this->_joinIdxTable();
+ $this->getSelect()->where('idx_table.product_id NOT IN(?)', $productIds);
+ return $this;
+ }
+
+ /**
+ * Retrieve Product Index table name
+ *
+ */
+ abstract protected function _getTableName();
+
+ /**
+ * Join index table
+ *
+ * @return Mage_Reports_Model_Resource_Product_Index_Collection_Abstract
+ */
+ protected function _joinIdxTable()
+ {
+ if (!$this->getFlag('is_idx_table_joined')) {
+ $this->joinTable(
+ ['idx_table' => $this->_getTableName()],
+ 'product_id=entity_id',
+ [
+ 'product_id' => 'product_id',
+ 'item_store_id' => 'store_id',
+ 'added_at' => 'added_at',
+ ],
+ $this->_getWhereCondition(),
+ );
+ $this->setFlag('is_idx_table_joined', true);
+ }
+ return $this;
+ }
+
+ /**
+ * Retrieve Where Condition to Index table
+ *
+ * @return array
+ */
+ protected function _getWhereCondition()
+ {
+ $condition = [];
+
+ if (Mage::getSingleton('customer/session')->isLoggedIn()) {
+ $condition['customer_id'] = Mage::getSingleton('customer/session')->getCustomerId();
+ } elseif ($this->_customerId) {
+ $condition['customer_id'] = $this->_customerId;
+ } else {
+ $condition['visitor_id'] = Mage::getSingleton('log/visitor')->getId();
+ }
+
+ return $condition;
+ }
+
/**
* Sort loaded collection by predefined items ids
*
@@ -183,20 +199,4 @@ protected function _afterLoad()
$this->_sort();
return $result;
}
-
- /**
- * Add exclude Product Ids
- *
- * @param int|array $productIds
- * @return Mage_Reports_Model_Resource_Product_Index_Collection_Abstract
- */
- public function excludeProductIds($productIds)
- {
- if (empty($productIds)) {
- return $this;
- }
- $this->_joinIdxTable();
- $this->getSelect()->where('idx_table.product_id NOT IN(?)', $productIds);
- return $this;
- }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Product/Lowstock/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Product/Lowstock/Collection.php
index a4122f7f5e5..0a8ec125a08 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Product/Lowstock/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Product/Lowstock/Collection.php
@@ -43,86 +43,6 @@ class Mage_Reports_Model_Resource_Product_Lowstock_Collection extends Mage_Repor
*/
protected $_inventoryItemTableAlias = 'lowstock_inventory_item';
- /**
- * Retrieve CatalogInventory Stock Item Resource instance
- *
- * @return Mage_CatalogInventory_Model_Resource_Stock_Item
- */
- protected function _getInventoryItemResource()
- {
- if ($this->_inventoryItemResource === null) {
- $this->_inventoryItemResource = Mage::getResourceSingleton('cataloginventory/stock_item');
- }
- return $this->_inventoryItemResource;
- }
-
- /**
- * Retrieve CatalogInventory Stock Item Table
- *
- * @return string
- */
- protected function _getInventoryItemTable()
- {
- return $this->_getInventoryItemResource()->getMainTable();
- }
-
- /**
- * Retrieve CatalogInventory Stock Item Table Id field name
- *
- * @return string
- */
- protected function _getInventoryItemIdField()
- {
- return $this->_getInventoryItemResource()->getIdFieldName();
- }
-
- /**
- * Retrieve alias for CatalogInventory Stock Item Table
- *
- * @return string
- */
- protected function _getInventoryItemTableAlias()
- {
- return $this->_inventoryItemTableAlias;
- }
-
- /**
- * Add catalog inventory stock item field to select
- *
- * @param string $field
- * @param string $alias
- * @return $this
- */
- protected function _addInventoryItemFieldToSelect($field, $alias = null)
- {
- if (empty($alias)) {
- $alias = $field;
- }
-
- if (isset($this->_joinFields[$alias])) {
- return $this;
- }
-
- $this->_joinFields[$alias] = [
- 'table' => $this->_getInventoryItemTableAlias(),
- 'field' => $field,
- ];
-
- $this->getSelect()->columns([$alias => $field], $this->_getInventoryItemTableAlias());
- return $this;
- }
-
- /**
- * Retrieve catalog inventory stock item field correlation name
- *
- * @param string $field
- * @return string
- */
- protected function _getInventoryItemField($field)
- {
- return sprintf('%s.%s', $this->_getInventoryItemTableAlias(), $field);
- }
-
/**
* Join catalog inventory stock item table for further stock_item values filters
*
@@ -229,4 +149,84 @@ public function useNotifyStockQtyFilter($storeId = null)
$this->getSelect()->where('qty < ?', $notifyStockExpr);
return $this;
}
+
+ /**
+ * Retrieve CatalogInventory Stock Item Resource instance
+ *
+ * @return Mage_CatalogInventory_Model_Resource_Stock_Item
+ */
+ protected function _getInventoryItemResource()
+ {
+ if ($this->_inventoryItemResource === null) {
+ $this->_inventoryItemResource = Mage::getResourceSingleton('cataloginventory/stock_item');
+ }
+ return $this->_inventoryItemResource;
+ }
+
+ /**
+ * Retrieve CatalogInventory Stock Item Table
+ *
+ * @return string
+ */
+ protected function _getInventoryItemTable()
+ {
+ return $this->_getInventoryItemResource()->getMainTable();
+ }
+
+ /**
+ * Retrieve CatalogInventory Stock Item Table Id field name
+ *
+ * @return string
+ */
+ protected function _getInventoryItemIdField()
+ {
+ return $this->_getInventoryItemResource()->getIdFieldName();
+ }
+
+ /**
+ * Retrieve alias for CatalogInventory Stock Item Table
+ *
+ * @return string
+ */
+ protected function _getInventoryItemTableAlias()
+ {
+ return $this->_inventoryItemTableAlias;
+ }
+
+ /**
+ * Add catalog inventory stock item field to select
+ *
+ * @param string $field
+ * @param string $alias
+ * @return $this
+ */
+ protected function _addInventoryItemFieldToSelect($field, $alias = null)
+ {
+ if (empty($alias)) {
+ $alias = $field;
+ }
+
+ if (isset($this->_joinFields[$alias])) {
+ return $this;
+ }
+
+ $this->_joinFields[$alias] = [
+ 'table' => $this->_getInventoryItemTableAlias(),
+ 'field' => $field,
+ ];
+
+ $this->getSelect()->columns([$alias => $field], $this->_getInventoryItemTableAlias());
+ return $this;
+ }
+
+ /**
+ * Retrieve catalog inventory stock item field correlation name
+ *
+ * @param string $field
+ * @return string
+ */
+ protected function _getInventoryItemField($field)
+ {
+ return sprintf('%s.%s', $this->_getInventoryItemTableAlias(), $field);
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Product/Ordered/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Product/Ordered/Collection.php
index 66fd53aa588..65cbb6cab7c 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Product/Ordered/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Product/Ordered/Collection.php
@@ -22,22 +22,6 @@
*/
class Mage_Reports_Model_Resource_Product_Ordered_Collection extends Mage_Reports_Model_Resource_Product_Collection
{
- /**
- * Join fields
- *
- * @param string $from
- * @param string $to
- * @return $this
- */
- protected function _joinFields($from = '', $to = '')
- {
- $this->addAttributeToSelect('*')
- ->addOrderedQty($from, $to)
- ->setOrder('ordered_qty', self::SORT_ORDER_DESC);
-
- return $this;
- }
-
/**
* @param int $from
* @param int $to
@@ -63,4 +47,19 @@ public function setStoreIds($storeIds)
$this->addStoreFilter($storeId);
return $this;
}
+ /**
+ * Join fields
+ *
+ * @param string $from
+ * @param string $to
+ * @return $this
+ */
+ protected function _joinFields($from = '', $to = '')
+ {
+ $this->addAttributeToSelect('*')
+ ->addOrderedQty($from, $to)
+ ->setOrder('ordered_qty', self::SORT_ORDER_DESC);
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Product/Sold/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Product/Sold/Collection.php
index d34b20df032..0124f9a10fa 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Product/Sold/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Product/Sold/Collection.php
@@ -22,17 +22,6 @@
*/
class Mage_Reports_Model_Resource_Product_Sold_Collection extends Mage_Reports_Model_Resource_Product_Collection
{
- /**
- * Initialize resources
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_useAnalyticFunction = true;
- // skip adding stock information to collection for performance reasons
- $this->setFlag('no_stock_data', true);
- }
/**
* Set Date range to collection
*
@@ -61,6 +50,17 @@ public function setStoreIds($storeIds)
}
return $this;
}
+ /**
+ * Initialize resources
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_useAnalyticFunction = true;
+ // skip adding stock information to collection for performance reasons
+ $this->setFlag('no_stock_data', true);
+ }
/**
* Add website product limitation
diff --git a/app/code/core/Mage/Reports/Model/Resource/Product/Viewed/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Product/Viewed/Collection.php
index b686cdfbb5d..70c3e02cde8 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Product/Viewed/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Product/Viewed/Collection.php
@@ -29,20 +29,6 @@ class Mage_Reports_Model_Resource_Product_Viewed_Collection extends Mage_Reports
*/
protected $_storeIds = [];
- /**
- * Join fields
- *
- * @param string $from
- * @param string $to
- * @return $this
- */
- protected function _joinFields($from = '', $to = '')
- {
- $this->addAttributeToSelect('*')
- ->addViewsCount($from, $to);
- return $this;
- }
-
/**
* Set date range
*
@@ -88,6 +74,20 @@ public function addStoreIds($storeIds)
return $this;
}
+ /**
+ * Join fields
+ *
+ * @param string $from
+ * @param string $to
+ * @return $this
+ */
+ protected function _joinFields($from = '', $to = '')
+ {
+ $this->addAttributeToSelect('*')
+ ->addViewsCount($from, $to);
+ return $this;
+ }
+
/**
* Apply store filter
*
diff --git a/app/code/core/Mage/Reports/Model/Resource/Quote/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Quote/Collection.php
index d6c7631f949..7483ed7c546 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Quote/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Quote/Collection.php
@@ -52,15 +52,6 @@ public function setSelectCountSqlType($type)
return $this;
}
- protected function _construct()
- {
- parent::_construct();
- /**
- * Allow to use analytic function
- */
- $this->_useAnalyticFunction = true;
- }
-
/**
* Prepare for abandoned report
*
@@ -296,4 +287,13 @@ public function getSelectCountSql()
return $countSelect;
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ /**
+ * Allow to use analytic function
+ */
+ $this->_useAnalyticFunction = true;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Report/Abstract.php b/app/code/core/Mage/Reports/Model/Resource/Report/Abstract.php
index 71b1a6713cf..ea5a3d01f5d 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Report/Abstract.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Report/Abstract.php
@@ -29,6 +29,57 @@ abstract class Mage_Reports_Model_Resource_Report_Abstract extends Mage_Core_Mod
*/
protected $_flag = null;
+ /**
+ * Retrieve query for attribute with timezone conversion
+ *
+ * @param string|array $table
+ * @param string $column
+ * @param mixed $from
+ * @param mixed $to
+ * @param int|string|Mage_Core_Model_Store|null $store
+ * @return string
+ */
+ public function getStoreTZOffsetQuery($table, $column, $from = null, $to = null, $store = null)
+ {
+ $column = $this->_getWriteAdapter()->quoteIdentifier($column);
+
+ if (is_null($from)) {
+ $selectOldest = $this->_getWriteAdapter()->select()
+ ->from(
+ $table,
+ ["MIN($column)"],
+ );
+ $from = $this->_getWriteAdapter()->fetchOne($selectOldest);
+ }
+
+ $periods = $this->_getTZOffsetTransitions(
+ Mage::app()->getLocale()->storeDate($store)->toString(Zend_Date::TIMEZONE_NAME),
+ $from,
+ $to,
+ );
+ if (empty($periods)) {
+ return $column;
+ }
+
+ $query = '';
+ $periodsCount = count($periods);
+
+ $i = 0;
+ foreach ($periods as $offset => $timestamps) {
+ $subParts = [];
+ foreach ($timestamps as $ts) {
+ $subParts[] = "($column between {$ts['from']} and {$ts['to']})";
+ }
+
+ $then = $this->_getWriteAdapter()
+ ->getDateAddSql($column, $offset, Varien_Db_Adapter_Interface::INTERVAL_SECOND);
+
+ $query .= (++$i == $periodsCount) ? $then : 'CASE WHEN ' . implode(' OR ', $subParts) . " THEN $then ELSE ";
+ }
+
+ return $query . str_repeat('END ', count($periods) - 1);
+ }
+
/**
* Retrieve flag object
*
@@ -343,57 +394,6 @@ protected function _checkDates(&$from, &$to)
return $this;
}
- /**
- * Retrieve query for attribute with timezone conversion
- *
- * @param string|array $table
- * @param string $column
- * @param mixed $from
- * @param mixed $to
- * @param int|string|Mage_Core_Model_Store|null $store
- * @return string
- */
- public function getStoreTZOffsetQuery($table, $column, $from = null, $to = null, $store = null)
- {
- $column = $this->_getWriteAdapter()->quoteIdentifier($column);
-
- if (is_null($from)) {
- $selectOldest = $this->_getWriteAdapter()->select()
- ->from(
- $table,
- ["MIN($column)"],
- );
- $from = $this->_getWriteAdapter()->fetchOne($selectOldest);
- }
-
- $periods = $this->_getTZOffsetTransitions(
- Mage::app()->getLocale()->storeDate($store)->toString(Zend_Date::TIMEZONE_NAME),
- $from,
- $to,
- );
- if (empty($periods)) {
- return $column;
- }
-
- $query = '';
- $periodsCount = count($periods);
-
- $i = 0;
- foreach ($periods as $offset => $timestamps) {
- $subParts = [];
- foreach ($timestamps as $ts) {
- $subParts[] = "($column between {$ts['from']} and {$ts['to']})";
- }
-
- $then = $this->_getWriteAdapter()
- ->getDateAddSql($column, $offset, Varien_Db_Adapter_Interface::INTERVAL_SECOND);
-
- $query .= (++$i == $periodsCount) ? $then : 'CASE WHEN ' . implode(' OR ', $subParts) . " THEN $then ELSE ";
- }
-
- return $query . str_repeat('END ', count($periods) - 1);
- }
-
/**
* Retrieve transitions for offsets of given timezone
*
diff --git a/app/code/core/Mage/Reports/Model/Resource/Report/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Report/Collection.php
index ac754b5b074..aece9e0b61b 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Report/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Report/Collection.php
@@ -71,8 +71,6 @@ class Mage_Reports_Model_Resource_Report_Collection
*/
protected $_storeIds;
- protected function _construct() {}
-
/**
* Set period
*
@@ -290,4 +288,6 @@ public function timeShift($datetime)
->utcDate(null, $datetime, true, Varien_Date::DATETIME_INTERNAL_FORMAT)
->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
}
+
+ protected function _construct() {}
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Report/Collection/Abstract.php b/app/code/core/Mage/Reports/Model/Resource/Report/Collection/Abstract.php
index b502f0a6e38..8f79c5a99c5 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Report/Collection/Abstract.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Report/Collection/Abstract.php
@@ -125,24 +125,6 @@ public function setPeriod($period)
return $this;
}
- /**
- * Apply date range filter
- *
- * @return $this
- */
- protected function _applyDateRangeFilter()
- {
- // Remember that field PERIOD is a DATE(YYYY-MM-DD) in all databases including Oracle
- if ($this->_from !== null) {
- $this->getSelect()->where('period >= ?', $this->_from);
- }
- if ($this->_to !== null) {
- $this->getSelect()->where('period <= ?', $this->_to);
- }
-
- return $this;
- }
-
/**
* Set store ids
*
@@ -155,48 +137,6 @@ public function addStoreFilter($storeIds)
return $this;
}
- /**
- * Apply stores filter to select object
- *
- * @return $this
- */
- protected function _applyStoresFilterToSelect(Zend_Db_Select $select)
- {
- $nullCheck = false;
- $storeIds = $this->_storesIds;
-
- if (!is_array($storeIds)) {
- $storeIds = [$storeIds];
- }
-
- $storeIds = array_unique($storeIds);
-
- if ($index = array_search(null, $storeIds)) {
- unset($storeIds[$index]);
- $nullCheck = true;
- }
-
- $storeIds[0] = ($storeIds[0] == '') ? 0 : $storeIds[0];
-
- if ($nullCheck) {
- $select->where('store_id IN(?) OR store_id IS NULL', $storeIds);
- } else {
- $select->where('store_id IN(?)', $storeIds);
- }
-
- return $this;
- }
-
- /**
- * Apply stores filter
- *
- * @return $this
- */
- protected function _applyStoresFilter()
- {
- return $this->_applyStoresFilterToSelect($this->getSelect());
- }
-
/**
* Set apply filters flag
*
@@ -239,16 +179,6 @@ public function isSubTotals($flag = null)
return $this;
}
- /**
- * Custom filters application ability
- *
- * @return $this
- */
- protected function _applyCustomFilter()
- {
- return $this;
- }
-
/**
* Load data
* Redeclare parent load method just for adding method _beforeLoad
@@ -268,4 +198,74 @@ public function load($printQuery = false, $logQuery = false)
}
return parent::load($printQuery, $logQuery);
}
+
+ /**
+ * Apply date range filter
+ *
+ * @return $this
+ */
+ protected function _applyDateRangeFilter()
+ {
+ // Remember that field PERIOD is a DATE(YYYY-MM-DD) in all databases including Oracle
+ if ($this->_from !== null) {
+ $this->getSelect()->where('period >= ?', $this->_from);
+ }
+ if ($this->_to !== null) {
+ $this->getSelect()->where('period <= ?', $this->_to);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Apply stores filter to select object
+ *
+ * @return $this
+ */
+ protected function _applyStoresFilterToSelect(Zend_Db_Select $select)
+ {
+ $nullCheck = false;
+ $storeIds = $this->_storesIds;
+
+ if (!is_array($storeIds)) {
+ $storeIds = [$storeIds];
+ }
+
+ $storeIds = array_unique($storeIds);
+
+ if ($index = array_search(null, $storeIds)) {
+ unset($storeIds[$index]);
+ $nullCheck = true;
+ }
+
+ $storeIds[0] = ($storeIds[0] == '') ? 0 : $storeIds[0];
+
+ if ($nullCheck) {
+ $select->where('store_id IN(?) OR store_id IS NULL', $storeIds);
+ } else {
+ $select->where('store_id IN(?)', $storeIds);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Apply stores filter
+ *
+ * @return $this
+ */
+ protected function _applyStoresFilter()
+ {
+ return $this->_applyStoresFilterToSelect($this->getSelect());
+ }
+
+ /**
+ * Custom filters application ability
+ *
+ * @return $this
+ */
+ protected function _applyCustomFilter()
+ {
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed.php b/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed.php
index 6ef0b3d2ab1..0ef41e81149 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed.php
@@ -26,11 +26,6 @@ class Mage_Reports_Model_Resource_Report_Product_Viewed extends Mage_Sales_Model
public const AGGREGATION_MONTHLY = 'reports/viewed_aggregated_monthly';
public const AGGREGATION_YEARLY = 'reports/viewed_aggregated_yearly';
- protected function _construct()
- {
- $this->_init(self::AGGREGATION_DAILY, 'id');
- }
-
/**
* Aggregate products view data
*
@@ -212,4 +207,9 @@ public function aggregate($from = null, $to = null)
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init(self::AGGREGATION_DAILY, 'id');
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed/Collection.php
index dbe8d77391d..ea378c07b4a 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed/Collection.php
@@ -51,6 +51,45 @@ public function __construct()
$this->_applyFilters = false;
}
+ /**
+ * Get SQL for get record count
+ *
+ * @return Varien_Db_Select
+ */
+ public function getSelectCountSql()
+ {
+ $this->_renderFilters();
+ $select = clone $this->getSelect();
+ $select->reset(Zend_Db_Select::ORDER);
+ return $this->getConnection()->select()->from($select, 'COUNT(*)');
+ }
+
+ /**
+ * Set ids for store restrictions
+ *
+ * @param array $storeIds
+ * @return $this
+ */
+ public function addStoreRestrictions($storeIds)
+ {
+ if (!is_array($storeIds)) {
+ $storeIds = [$storeIds];
+ }
+ $currentStoreIds = $this->_storesIds;
+ if (isset($currentStoreIds) && $currentStoreIds != Mage_Core_Model_App::ADMIN_STORE_ID
+ && $currentStoreIds != [Mage_Core_Model_App::ADMIN_STORE_ID]
+ ) {
+ if (!is_array($currentStoreIds)) {
+ $currentStoreIds = [$currentStoreIds];
+ }
+ $this->_storesIds = array_intersect($currentStoreIds, $storeIds);
+ } else {
+ $this->_storesIds = $storeIds;
+ }
+
+ return $this;
+ }
+
/**
* Retrieve selected columns
*
@@ -157,45 +196,6 @@ protected function _initSelect()
return $this;
}
- /**
- * Get SQL for get record count
- *
- * @return Varien_Db_Select
- */
- public function getSelectCountSql()
- {
- $this->_renderFilters();
- $select = clone $this->getSelect();
- $select->reset(Zend_Db_Select::ORDER);
- return $this->getConnection()->select()->from($select, 'COUNT(*)');
- }
-
- /**
- * Set ids for store restrictions
- *
- * @param array $storeIds
- * @return $this
- */
- public function addStoreRestrictions($storeIds)
- {
- if (!is_array($storeIds)) {
- $storeIds = [$storeIds];
- }
- $currentStoreIds = $this->_storesIds;
- if (isset($currentStoreIds) && $currentStoreIds != Mage_Core_Model_App::ADMIN_STORE_ID
- && $currentStoreIds != [Mage_Core_Model_App::ADMIN_STORE_ID]
- ) {
- if (!is_array($currentStoreIds)) {
- $currentStoreIds = [$currentStoreIds];
- }
- $this->_storesIds = array_intersect($currentStoreIds, $storeIds);
- } else {
- $this->_storesIds = $storeIds;
- }
-
- return $this;
- }
-
/**
* Redeclare parent method for applying filters after parent method
* but before adding unions and calculating totals
diff --git a/app/code/core/Mage/Reports/Model/Resource/Review/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Review/Collection.php
index 125751e9e26..d65ebcd0cce 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Review/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Review/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Reports_Model_Resource_Review_Collection extends Mage_Review_Model_Resource_Review_Collection
{
- protected function _construct()
- {
- $this->_init('review/review');
- }
-
/**
* @param string|int $productId
* @return $this
@@ -84,4 +79,8 @@ public function setOrder($attribute, $dir = self::SORT_ORDER_DESC)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('review/review');
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Review/Product/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Review/Product/Collection.php
index bd278c7e146..0bca92cbf31 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Review/Product/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Review/Product/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Reports_Model_Resource_Review_Product_Collection extends Mage_Catalog_Model_Resource_Product_Collection
{
- protected function _construct()
- {
- parent::_construct();
- $this->_useAnalyticFunction = true;
- }
/**
* Join review table to result
*
@@ -116,4 +111,9 @@ public function getSelectCountSql()
return $countSelect;
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_useAnalyticFunction = true;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Shopcart/Product/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Shopcart/Product/Collection.php
index 3d56c8c1dfc..d1422f5bacc 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Shopcart/Product/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Shopcart/Product/Collection.php
@@ -23,30 +23,29 @@
class Mage_Reports_Model_Resource_Shopcart_Product_Collection extends Mage_Reports_Model_Resource_Product_Collection
{
/**
- * Join fields
+ * Set date range
*
+ * @param string $from
+ * @param string $to
* @return $this
*/
- protected function _joinFields()
+ public function setDateRange($from, $to)
{
- parent::_joinFields();
- $this->addAttributeToSelect('price')
- ->addCartsCount()
- ->addOrdersCount();
-
+ $this->getSelect()->reset();
return $this;
}
-
/**
- * Set date range
+ * Join fields
*
- * @param string $from
- * @param string $to
* @return $this
*/
- public function setDateRange($from, $to)
+ protected function _joinFields()
{
- $this->getSelect()->reset();
+ parent::_joinFields();
+ $this->addAttributeToSelect('price')
+ ->addCartsCount()
+ ->addOrdersCount();
+
return $this;
}
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Tag/Customer/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Tag/Customer/Collection.php
index 998ac3a7f5f..8cd77fd492b 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Tag/Customer/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Tag/Customer/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Reports_Model_Resource_Tag_Customer_Collection extends Mage_Tag_Model_Resource_Customer_Collection
{
- protected function _construct()
- {
- parent::_construct();
- $this->_useAnalyticFunction = true;
- }
/**
* Add target count
*
@@ -56,4 +51,9 @@ public function getSelectCountSql()
return $countSelect;
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_useAnalyticFunction = true;
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Tag/Product/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Tag/Product/Collection.php
index b225dedf8d7..9b9ed83a7b5 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Tag/Product/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Tag/Product/Collection.php
@@ -22,14 +22,6 @@
*/
class Mage_Reports_Model_Resource_Tag_Product_Collection extends Mage_Tag_Model_Resource_Product_Collection
{
- protected function _construct()
- {
- parent::_construct();
- /**
- * Allow to use analytic function
- */
- $this->_useAnalyticFunction = true;
- }
/**
* Add unique target count to result
*
@@ -131,6 +123,14 @@ public function setOrder($attribute, $dir = self::SORT_ORDER_DESC)
return $this;
}
+ protected function _construct()
+ {
+ parent::_construct();
+ /**
+ * Allow to use analytic function
+ */
+ $this->_useAnalyticFunction = true;
+ }
/**
* Join fields
diff --git a/app/code/core/Mage/Reports/Model/Resource/Wishlist/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Wishlist/Collection.php
index 89527da9aaa..a63a7b5e95f 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Wishlist/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Wishlist/Collection.php
@@ -28,12 +28,6 @@ class Mage_Reports_Model_Resource_Wishlist_Collection extends Mage_Core_Model_Re
* @var string
*/
protected $_wishlistTable;
-
- protected function _construct()
- {
- $this->_init('wishlist/wishlist');
- $this->setWishlistTable($this->getTable('wishlist/wishlist'));
- }
/**
* Set wishlist table name
*
@@ -102,4 +96,10 @@ public function getSharedCount()
->group('wt.wishlist_id');
return $countSelect->getAdapter()->fetchOne($countSelect);
}
+
+ protected function _construct()
+ {
+ $this->_init('wishlist/wishlist');
+ $this->setWishlistTable($this->getTable('wishlist/wishlist'));
+ }
}
diff --git a/app/code/core/Mage/Reports/Model/Resource/Wishlist/Product/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Wishlist/Product/Collection.php
index eb7cff24923..f46d6b750c3 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Wishlist/Product/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Wishlist/Product/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Reports_Model_Resource_Wishlist_Product_Collection extends Mage_Wishlist_Model_Resource_Product_Collection
{
- protected function _construct()
- {
- $this->_init('wishlist/wishlist');
- }
-
/**
* @return $this
*/
@@ -106,4 +101,8 @@ public function setOrder($attribute, $dir = self::SORT_ORDER_DESC)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('wishlist/wishlist');
+ }
}
diff --git a/app/code/core/Mage/Review/Block/Customer/List.php b/app/code/core/Mage/Review/Block/Customer/List.php
index 435624b02a0..48e5b22db8b 100644
--- a/app/code/core/Mage/Review/Block/Customer/List.php
+++ b/app/code/core/Mage/Review/Block/Customer/List.php
@@ -29,18 +29,6 @@ class Mage_Review_Block_Customer_List extends Mage_Customer_Block_Account_Dashbo
*/
protected $_collection;
- /**
- * Initializes collection
- */
- protected function _construct()
- {
- $this->_collection = Mage::getModel('review/review')->getProductCollection();
- $this->_collection
- ->addStoreFilter(Mage::app()->getStore()->getId())
- ->addCustomerFilter(Mage::getSingleton('customer/session')->getCustomerId())
- ->setDateOrder();
- }
-
/**
* Gets collection items count
*
@@ -61,30 +49,6 @@ public function getToolbarHtml()
return $this->getChildHtml('toolbar');
}
- /**
- * Initializes toolbar
- *
- * @return Mage_Core_Block_Abstract
- */
- protected function _prepareLayout()
- {
- $toolbar = $this->getLayout()->createBlock('page/html_pager', 'customer_review_list.toolbar')
- ->setCollection($this->getCollection());
-
- $this->setChild('toolbar', $toolbar);
- return parent::_prepareLayout();
- }
-
- /**
- * Get collection
- *
- * @return Mage_Review_Model_Resource_Review_Product_Collection
- */
- protected function _getCollection()
- {
- return $this->_collection;
- }
-
/**
* Get collection
*
@@ -126,6 +90,42 @@ public function dateFormat($date)
return $this->formatDate($date, Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
}
+ /**
+ * Initializes collection
+ */
+ protected function _construct()
+ {
+ $this->_collection = Mage::getModel('review/review')->getProductCollection();
+ $this->_collection
+ ->addStoreFilter(Mage::app()->getStore()->getId())
+ ->addCustomerFilter(Mage::getSingleton('customer/session')->getCustomerId())
+ ->setDateOrder();
+ }
+
+ /**
+ * Initializes toolbar
+ *
+ * @return Mage_Core_Block_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ $toolbar = $this->getLayout()->createBlock('page/html_pager', 'customer_review_list.toolbar')
+ ->setCollection($this->getCollection());
+
+ $this->setChild('toolbar', $toolbar);
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * Get collection
+ *
+ * @return Mage_Review_Model_Resource_Review_Product_Collection
+ */
+ protected function _getCollection()
+ {
+ return $this->_collection;
+ }
+
/**
* @return Mage_Core_Block_Abstract
*/
diff --git a/app/code/core/Mage/Review/Block/Customer/Recent.php b/app/code/core/Mage/Review/Block/Customer/Recent.php
index 8be5f909d59..9f2910929d8 100644
--- a/app/code/core/Mage/Review/Block/Customer/Recent.php
+++ b/app/code/core/Mage/Review/Block/Customer/Recent.php
@@ -51,14 +51,6 @@ public function count()
return $this->_collection->getSize();
}
- /**
- * @return Mage_Review_Model_Resource_Review_Product_Collection
- */
- protected function _getCollection()
- {
- return $this->_collection;
- }
-
/**
* @return Mage_Review_Model_Resource_Review_Product_Collection
*/
@@ -108,4 +100,12 @@ public function getReviewUrl($id)
{
return Mage::getUrl('review/customer/view', ['id' => $id]);
}
+
+ /**
+ * @return Mage_Review_Model_Resource_Review_Product_Collection
+ */
+ protected function _getCollection()
+ {
+ return $this->_collection;
+ }
}
diff --git a/app/code/core/Mage/Review/Block/Product/View.php b/app/code/core/Mage/Review/Block/Product/View.php
index 3bc9638c625..c9cfba8f4e1 100644
--- a/app/code/core/Mage/Review/Block/Product/View.php
+++ b/app/code/core/Mage/Review/Block/Product/View.php
@@ -24,19 +24,6 @@ class Mage_Review_Block_Product_View extends Mage_Catalog_Block_Product_View
{
protected $_reviewsCollection;
- /**
- * Render block HTML
- *
- * @inheritDoc
- * @throws Mage_Core_Exception
- */
- protected function _toHtml()
- {
- $this->getProduct()->setShortDescription(null);
-
- return parent::_toHtml();
- }
-
/**
* Replace review summary html with more detailed review summary
* Reviews collection count will be jerked here
@@ -86,4 +73,17 @@ public function hasOptions()
{
return false;
}
+
+ /**
+ * Render block HTML
+ *
+ * @inheritDoc
+ * @throws Mage_Core_Exception
+ */
+ protected function _toHtml()
+ {
+ $this->getProduct()->setShortDescription(null);
+
+ return parent::_toHtml();
+ }
}
diff --git a/app/code/core/Mage/Review/Block/Product/View/List.php b/app/code/core/Mage/Review/Block/Product/View/List.php
index 6866a5205fc..4c94dadfabd 100644
--- a/app/code/core/Mage/Review/Block/Product/View/List.php
+++ b/app/code/core/Mage/Review/Block/Product/View/List.php
@@ -32,6 +32,15 @@ public function getProductId()
return Mage::registry('product')->getId();
}
+ /**
+ * @param int $id
+ * @return string
+ */
+ public function getReviewUrl($id)
+ {
+ return Mage::getUrl('review/product/view', ['id' => $id]);
+ }
+
/**
* @return $this
* @throws Mage_Core_Model_Store_Exception
@@ -59,13 +68,4 @@ protected function _beforeToHtml()
->addRateVotes();
return parent::_beforeToHtml();
}
-
- /**
- * @param int $id
- * @return string
- */
- public function getReviewUrl($id)
- {
- return Mage::getUrl('review/product/view', ['id' => $id]);
- }
}
diff --git a/app/code/core/Mage/Review/Model/Resource/Review.php b/app/code/core/Mage/Review/Model/Resource/Review.php
index 5bf7e3b039b..fe29b4d1f4f 100644
--- a/app/code/core/Mage/Review/Model/Resource/Review.php
+++ b/app/code/core/Mage/Review/Model/Resource/Review.php
@@ -72,6 +72,189 @@ class Mage_Review_Model_Resource_Review extends Mage_Core_Model_Resource_Db_Abst
// phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
private $_deleteCache = [];
+ /**
+ * Perform actions after object delete
+ *
+ * @return $this
+ */
+ public function afterDeleteCommit(Mage_Core_Model_Abstract $object)
+ {
+ $readAdapter = $this->_getReadAdapter();
+ $select = $readAdapter->select()
+ ->from(
+ $this->_reviewTable,
+ [
+ 'review_count' => new Zend_Db_Expr('COUNT(*)'),
+ ],
+ )
+ ->where('entity_id = ?', $object->getEntityId())
+ ->where('entity_pk_value = ?', $object->getEntityPkValue());
+ $totalReviews = $readAdapter->fetchOne($select);
+ if ($totalReviews == 0) {
+ $this->_getWriteAdapter()->delete($this->_aggregateTable, [
+ 'entity_type = ?' => $object->getEntityId(),
+ 'entity_pk_value = ?' => $object->getEntityPkValue(),
+ ]);
+ return $this;
+ }
+
+ $this->aggregate($object);
+
+ // re-aggregate ratings, that depended on this review
+ $this->_aggregateRatings(
+ $this->_deleteCache['ratingIds'],
+ $this->_deleteCache['entityPkValue'],
+ );
+ $this->_deleteCache = [];
+
+ return $this;
+ }
+
+ /**
+ * Retrieves total reviews
+ *
+ * @param int $entityPkValue
+ * @param bool $approvedOnly
+ * @param int $storeId
+ * @return int
+ */
+ public function getTotalReviews($entityPkValue, $approvedOnly = false, $storeId = 0)
+ {
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from(
+ $this->_reviewTable,
+ [
+ 'review_count' => new Zend_Db_Expr('COUNT(*)'),
+ ],
+ )
+ ->where("{$this->_reviewTable}.entity_pk_value = :pk_value");
+ $bind = [':pk_value' => $entityPkValue];
+ if ($storeId > 0) {
+ $select->join(
+ ['store' => $this->_reviewStoreTable],
+ $this->_reviewTable . '.review_id=store.review_id AND store.store_id = :store_id',
+ [],
+ );
+ $bind[':store_id'] = (int) $storeId;
+ }
+ if ($approvedOnly) {
+ $select->where("{$this->_reviewTable}.status_id = :status_id");
+ $bind[':status_id'] = Mage_Review_Model_Review::STATUS_APPROVED;
+ }
+ return $adapter->fetchOne($select, $bind);
+ }
+
+ /**
+ * Aggregate
+ *
+ * @param Mage_Core_Model_Abstract|Mage_Review_Model_Review $object
+ */
+ public function aggregate($object)
+ {
+ $readAdapter = $this->_getReadAdapter();
+ $writeAdapter = $this->_getWriteAdapter();
+ $ratingModel = Mage::getModel('rating/rating');
+
+ if (!$object->getEntityPkValue() && $object->getId()) {
+ $object->load($object->getReviewId());
+ }
+
+ $ratingSummaries = $ratingModel->getEntitySummary($object->getEntityPkValue(), false);
+
+ foreach ($ratingSummaries as $ratingSummaryObject) {
+ if ($ratingSummaryObject->getCount()) {
+ $ratingSummary = round($ratingSummaryObject->getSum() / $ratingSummaryObject->getCount());
+ } else {
+ $ratingSummary = $ratingSummaryObject->getSum();
+ }
+
+ $reviewsCount = $this->getTotalReviews(
+ $object->getEntityPkValue(),
+ true,
+ $ratingSummaryObject->getStoreId(),
+ );
+ $select = $readAdapter->select()
+ ->from($this->_aggregateTable)
+ ->where('entity_pk_value = :pk_value')
+ ->where('entity_type = :entity_type')
+ ->where('store_id = :store_id');
+ $bind = [
+ ':pk_value' => $object->getEntityPkValue(),
+ ':entity_type' => $object->getEntityId(),
+ ':store_id' => $ratingSummaryObject->getStoreId(),
+ ];
+ $oldData = $readAdapter->fetchRow($select, $bind);
+
+ $data = new Varien_Object();
+
+ $data->setReviewsCount($reviewsCount)
+ ->setEntityPkValue($object->getEntityPkValue())
+ ->setEntityType($object->getEntityId())
+ ->setRatingSummary(($ratingSummary > 0) ? $ratingSummary : 0)
+ ->setStoreId($ratingSummaryObject->getStoreId());
+
+ $writeAdapter->beginTransaction();
+ try {
+ if (isset($oldData['primary_id']) && $oldData['primary_id'] > 0) {
+ $condition = ["{$this->_aggregateTable}.primary_id = ?" => $oldData['primary_id']];
+ $writeAdapter->update($this->_aggregateTable, $data->getData(), $condition);
+ } else {
+ $writeAdapter->insert($this->_aggregateTable, $data->getData());
+ }
+ $writeAdapter->commit();
+ } catch (Exception $e) {
+ $writeAdapter->rollBack();
+ }
+ }
+ }
+
+ /**
+ * Reaggregate this review's ratings.
+ *
+ * @param int $reviewId
+ * @param int $entityPkValue
+ */
+ public function reAggregateReview($reviewId, $entityPkValue)
+ {
+ $this->_aggregateRatings($this->_loadVotedRatingIds($reviewId), $entityPkValue);
+ }
+
+ /**
+ * Get review entity type id by code
+ *
+ * @param string $entityCode
+ * @return int|bool
+ */
+ public function getEntityIdByCode($entityCode)
+ {
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from($this->_reviewEntityTable, ['entity_id'])
+ ->where('entity_code = :entity_code');
+ return $adapter->fetchOne($select, [':entity_code' => $entityCode]);
+ }
+
+ /**
+ * Delete reviews by product id.
+ * Better to call this method in transaction, because operation performed on two separated tables
+ *
+ * @param int $productId
+ * @return $this
+ */
+ public function deleteReviewsByProductId($productId)
+ {
+ $this->_getWriteAdapter()->delete($this->_reviewTable, [
+ 'entity_pk_value=?' => $productId,
+ 'entity_id=?' => $this->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE),
+ ]);
+ $this->_getWriteAdapter()->delete($this->getTable('review/review_aggregate'), [
+ 'entity_pk_value=?' => $productId,
+ 'entity_type=?' => $this->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE),
+ ]);
+ return $this;
+ }
+
/**
* Define main table. Define other tables name
*/
@@ -224,143 +407,6 @@ protected function _beforeDelete(Mage_Core_Model_Abstract $object)
return $this;
}
- /**
- * Perform actions after object delete
- *
- * @return $this
- */
- public function afterDeleteCommit(Mage_Core_Model_Abstract $object)
- {
- $readAdapter = $this->_getReadAdapter();
- $select = $readAdapter->select()
- ->from(
- $this->_reviewTable,
- [
- 'review_count' => new Zend_Db_Expr('COUNT(*)'),
- ],
- )
- ->where('entity_id = ?', $object->getEntityId())
- ->where('entity_pk_value = ?', $object->getEntityPkValue());
- $totalReviews = $readAdapter->fetchOne($select);
- if ($totalReviews == 0) {
- $this->_getWriteAdapter()->delete($this->_aggregateTable, [
- 'entity_type = ?' => $object->getEntityId(),
- 'entity_pk_value = ?' => $object->getEntityPkValue(),
- ]);
- return $this;
- }
-
- $this->aggregate($object);
-
- // re-aggregate ratings, that depended on this review
- $this->_aggregateRatings(
- $this->_deleteCache['ratingIds'],
- $this->_deleteCache['entityPkValue'],
- );
- $this->_deleteCache = [];
-
- return $this;
- }
-
- /**
- * Retrieves total reviews
- *
- * @param int $entityPkValue
- * @param bool $approvedOnly
- * @param int $storeId
- * @return int
- */
- public function getTotalReviews($entityPkValue, $approvedOnly = false, $storeId = 0)
- {
- $adapter = $this->_getReadAdapter();
- $select = $adapter->select()
- ->from(
- $this->_reviewTable,
- [
- 'review_count' => new Zend_Db_Expr('COUNT(*)'),
- ],
- )
- ->where("{$this->_reviewTable}.entity_pk_value = :pk_value");
- $bind = [':pk_value' => $entityPkValue];
- if ($storeId > 0) {
- $select->join(
- ['store' => $this->_reviewStoreTable],
- $this->_reviewTable . '.review_id=store.review_id AND store.store_id = :store_id',
- [],
- );
- $bind[':store_id'] = (int) $storeId;
- }
- if ($approvedOnly) {
- $select->where("{$this->_reviewTable}.status_id = :status_id");
- $bind[':status_id'] = Mage_Review_Model_Review::STATUS_APPROVED;
- }
- return $adapter->fetchOne($select, $bind);
- }
-
- /**
- * Aggregate
- *
- * @param Mage_Core_Model_Abstract|Mage_Review_Model_Review $object
- */
- public function aggregate($object)
- {
- $readAdapter = $this->_getReadAdapter();
- $writeAdapter = $this->_getWriteAdapter();
- $ratingModel = Mage::getModel('rating/rating');
-
- if (!$object->getEntityPkValue() && $object->getId()) {
- $object->load($object->getReviewId());
- }
-
- $ratingSummaries = $ratingModel->getEntitySummary($object->getEntityPkValue(), false);
-
- foreach ($ratingSummaries as $ratingSummaryObject) {
- if ($ratingSummaryObject->getCount()) {
- $ratingSummary = round($ratingSummaryObject->getSum() / $ratingSummaryObject->getCount());
- } else {
- $ratingSummary = $ratingSummaryObject->getSum();
- }
-
- $reviewsCount = $this->getTotalReviews(
- $object->getEntityPkValue(),
- true,
- $ratingSummaryObject->getStoreId(),
- );
- $select = $readAdapter->select()
- ->from($this->_aggregateTable)
- ->where('entity_pk_value = :pk_value')
- ->where('entity_type = :entity_type')
- ->where('store_id = :store_id');
- $bind = [
- ':pk_value' => $object->getEntityPkValue(),
- ':entity_type' => $object->getEntityId(),
- ':store_id' => $ratingSummaryObject->getStoreId(),
- ];
- $oldData = $readAdapter->fetchRow($select, $bind);
-
- $data = new Varien_Object();
-
- $data->setReviewsCount($reviewsCount)
- ->setEntityPkValue($object->getEntityPkValue())
- ->setEntityType($object->getEntityId())
- ->setRatingSummary(($ratingSummary > 0) ? $ratingSummary : 0)
- ->setStoreId($ratingSummaryObject->getStoreId());
-
- $writeAdapter->beginTransaction();
- try {
- if (isset($oldData['primary_id']) && $oldData['primary_id'] > 0) {
- $condition = ["{$this->_aggregateTable}.primary_id = ?" => $oldData['primary_id']];
- $writeAdapter->update($this->_aggregateTable, $data->getData(), $condition);
- } else {
- $writeAdapter->insert($this->_aggregateTable, $data->getData());
- }
- $writeAdapter->commit();
- } catch (Exception $e) {
- $writeAdapter->rollBack();
- }
- }
- }
-
/**
* Get rating IDs from review votes
*
@@ -405,50 +451,4 @@ protected function _aggregateRatings($ratingIds, $entityPkValue)
}
return $this;
}
-
- /**
- * Reaggregate this review's ratings.
- *
- * @param int $reviewId
- * @param int $entityPkValue
- */
- public function reAggregateReview($reviewId, $entityPkValue)
- {
- $this->_aggregateRatings($this->_loadVotedRatingIds($reviewId), $entityPkValue);
- }
-
- /**
- * Get review entity type id by code
- *
- * @param string $entityCode
- * @return int|bool
- */
- public function getEntityIdByCode($entityCode)
- {
- $adapter = $this->_getReadAdapter();
- $select = $adapter->select()
- ->from($this->_reviewEntityTable, ['entity_id'])
- ->where('entity_code = :entity_code');
- return $adapter->fetchOne($select, [':entity_code' => $entityCode]);
- }
-
- /**
- * Delete reviews by product id.
- * Better to call this method in transaction, because operation performed on two separated tables
- *
- * @param int $productId
- * @return $this
- */
- public function deleteReviewsByProductId($productId)
- {
- $this->_getWriteAdapter()->delete($this->_reviewTable, [
- 'entity_pk_value=?' => $productId,
- 'entity_id=?' => $this->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE),
- ]);
- $this->_getWriteAdapter()->delete($this->getTable('review/review_aggregate'), [
- 'entity_pk_value=?' => $productId,
- 'entity_type=?' => $this->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE),
- ]);
- return $this;
- }
}
diff --git a/app/code/core/Mage/Review/Model/Resource/Review/Collection.php b/app/code/core/Mage/Review/Model/Resource/Review/Collection.php
index f0e333d1f36..029e2436364 100644
--- a/app/code/core/Mage/Review/Model/Resource/Review/Collection.php
+++ b/app/code/core/Mage/Review/Model/Resource/Review/Collection.php
@@ -65,37 +65,6 @@ class Mage_Review_Model_Resource_Review_Collection extends Mage_Core_Model_Resou
*/
protected $_addStoreDataFlag = false;
- /**
- * Define module
- *
- */
- protected function _construct()
- {
- $this->_init('review/review');
- $this->_reviewTable = $this->getTable('review/review');
- $this->_reviewDetailTable = $this->getTable('review/review_detail');
- $this->_reviewStatusTable = $this->getTable('review/review_status');
- $this->_reviewEntityTable = $this->getTable('review/review_entity');
- $this->_reviewStoreTable = $this->getTable('review/review_store');
- }
-
- /**
- * init select
- *
- * @return Mage_Review_Model_Resource_Review_Collection
- */
- protected function _initSelect()
- {
- parent::_initSelect();
- $this->getSelect()
- ->join(
- ['detail' => $this->_reviewDetailTable],
- 'main_table.review_id = detail.review_id',
- ['detail_id', 'title', 'detail', 'nickname', 'customer_id'],
- );
- return $this;
- }
-
/**
* @param int $customerId
* @return $this
@@ -273,6 +242,37 @@ public function load($printQuery = false, $logQuery = false)
return $this;
}
+ /**
+ * Define module
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('review/review');
+ $this->_reviewTable = $this->getTable('review/review');
+ $this->_reviewDetailTable = $this->getTable('review/review_detail');
+ $this->_reviewStatusTable = $this->getTable('review/review_status');
+ $this->_reviewEntityTable = $this->getTable('review/review_entity');
+ $this->_reviewStoreTable = $this->getTable('review/review_store');
+ }
+
+ /**
+ * init select
+ *
+ * @return Mage_Review_Model_Resource_Review_Collection
+ */
+ protected function _initSelect()
+ {
+ parent::_initSelect();
+ $this->getSelect()
+ ->join(
+ ['detail' => $this->_reviewDetailTable],
+ 'main_table.review_id = detail.review_id',
+ ['detail_id', 'title', 'detail', 'nickname', 'customer_id'],
+ );
+ return $this;
+ }
+
/**
* Add store data
*
diff --git a/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php b/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php
index d4a4b646583..f5b9223d47d 100644
--- a/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php
+++ b/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php
@@ -50,30 +50,6 @@ class Mage_Review_Model_Resource_Review_Product_Collection extends Mage_Catalog_
*/
protected $_storesIds = [];
- /**
- * Define module
- *
- */
- protected function _construct()
- {
- $this->_init('catalog/product');
- $this->setRowIdFieldName('review_id');
- $this->_reviewStoreTable = Mage::getSingleton('core/resource')->getTableName('review/review_store');
- $this->_initTables();
- }
-
- /**
- * init select
- *
- * @return $this
- */
- protected function _initSelect()
- {
- parent::_initSelect();
- $this->_joinFields();
- return $this;
- }
-
/**
* Adds store filter into array
*
@@ -126,44 +102,6 @@ public function setStoreFilter($storeId)
return $this;
}
- /**
- * Applies all store filters in one place to prevent multiple joins in select
- *
- * @return $this
- */
- protected function _applyStoresFilterToSelect(?Zend_Db_Select $select = null)
- {
- $adapter = $this->getConnection();
- $storesIds = $this->_storesIds;
- if (is_null($select)) {
- $select = $this->getSelect();
- }
-
- if (is_array($storesIds) && (count($storesIds) == 1)) {
- $storesIds = array_shift($storesIds);
- }
-
- if (is_array($storesIds) && !empty($storesIds)) {
- $inCond = $adapter->prepareSqlCondition('store.store_id', ['in' => $storesIds]);
- $select->join(
- ['store' => $this->_reviewStoreTable],
- 'rt.review_id=store.review_id AND ' . $inCond,
- [],
- )
- ->group('rt.review_id');
-
- $this->_useAnalyticFunction = true;
- } else {
- $select->join(
- ['store' => $this->_reviewStoreTable],
- $adapter->quoteInto('rt.review_id=store.review_id AND store.store_id = ?', (int) $storesIds),
- [],
- );
- }
-
- return $this;
- }
-
/**
* Add stores data
*
@@ -259,33 +197,6 @@ public function addRateVotes()
return $this;
}
- /**
- * join fields to entity
- *
- * @return $this
- */
- protected function _joinFields()
- {
- $reviewTable = Mage::getSingleton('core/resource')->getTableName('review/review');
- $reviewDetailTable = Mage::getSingleton('core/resource')->getTableName('review/review_detail');
-
- $this->addAttributeToSelect('name')
- ->addAttributeToSelect('sku');
-
- $this->getSelect()
- ->join(
- ['rt' => $reviewTable],
- 'rt.entity_pk_value = e.entity_id',
- ['rt.review_id', 'review_created_at' => 'rt.created_at', 'rt.entity_pk_value', 'rt.status_id'],
- )
- ->join(
- ['rdt' => $reviewDetailTable],
- 'rdt.review_id = rt.review_id',
- ['rdt.title','rdt.nickname', 'rdt.detail', 'rdt.customer_id', 'rdt.store_id'],
- );
- return $this;
- }
-
/**
* Retrieve all ids for collection
*
@@ -411,6 +322,95 @@ public function getColumnValues($colName)
return $col;
}
+ /**
+ * Define module
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/product');
+ $this->setRowIdFieldName('review_id');
+ $this->_reviewStoreTable = Mage::getSingleton('core/resource')->getTableName('review/review_store');
+ $this->_initTables();
+ }
+
+ /**
+ * init select
+ *
+ * @return $this
+ */
+ protected function _initSelect()
+ {
+ parent::_initSelect();
+ $this->_joinFields();
+ return $this;
+ }
+
+ /**
+ * Applies all store filters in one place to prevent multiple joins in select
+ *
+ * @return $this
+ */
+ protected function _applyStoresFilterToSelect(?Zend_Db_Select $select = null)
+ {
+ $adapter = $this->getConnection();
+ $storesIds = $this->_storesIds;
+ if (is_null($select)) {
+ $select = $this->getSelect();
+ }
+
+ if (is_array($storesIds) && (count($storesIds) == 1)) {
+ $storesIds = array_shift($storesIds);
+ }
+
+ if (is_array($storesIds) && !empty($storesIds)) {
+ $inCond = $adapter->prepareSqlCondition('store.store_id', ['in' => $storesIds]);
+ $select->join(
+ ['store' => $this->_reviewStoreTable],
+ 'rt.review_id=store.review_id AND ' . $inCond,
+ [],
+ )
+ ->group('rt.review_id');
+
+ $this->_useAnalyticFunction = true;
+ } else {
+ $select->join(
+ ['store' => $this->_reviewStoreTable],
+ $adapter->quoteInto('rt.review_id=store.review_id AND store.store_id = ?', (int) $storesIds),
+ [],
+ );
+ }
+
+ return $this;
+ }
+
+ /**
+ * join fields to entity
+ *
+ * @return $this
+ */
+ protected function _joinFields()
+ {
+ $reviewTable = Mage::getSingleton('core/resource')->getTableName('review/review');
+ $reviewDetailTable = Mage::getSingleton('core/resource')->getTableName('review/review_detail');
+
+ $this->addAttributeToSelect('name')
+ ->addAttributeToSelect('sku');
+
+ $this->getSelect()
+ ->join(
+ ['rt' => $reviewTable],
+ 'rt.entity_pk_value = e.entity_id',
+ ['rt.review_id', 'review_created_at' => 'rt.created_at', 'rt.entity_pk_value', 'rt.status_id'],
+ )
+ ->join(
+ ['rdt' => $reviewDetailTable],
+ 'rdt.review_id = rt.review_id',
+ ['rdt.title','rdt.nickname', 'rdt.detail', 'rdt.customer_id', 'rdt.store_id'],
+ );
+ return $this;
+ }
+
/**
* Action after load
*
diff --git a/app/code/core/Mage/Review/Model/Resource/Review/Status/Collection.php b/app/code/core/Mage/Review/Model/Resource/Review/Status/Collection.php
index bb03a956cc9..e3216e5c661 100644
--- a/app/code/core/Mage/Review/Model/Resource/Review/Status/Collection.php
+++ b/app/code/core/Mage/Review/Model/Resource/Review/Status/Collection.php
@@ -30,21 +30,21 @@ class Mage_Review_Model_Resource_Review_Status_Collection extends Mage_Core_Mode
protected $_reviewStatusTable;
/**
- * Collection model initialization
+ * Convert items array to array for select options
*
+ * @return array
*/
- protected function _construct()
+ public function toOptionArray()
{
- $this->_init('review/review_status');
+ return parent::_toOptionArray('status_id', 'status_code');
}
/**
- * Convert items array to array for select options
+ * Collection model initialization
*
- * @return array
*/
- public function toOptionArray()
+ protected function _construct()
{
- return parent::_toOptionArray('status_id', 'status_code');
+ $this->_init('review/review_status');
}
}
diff --git a/app/code/core/Mage/Review/Model/Resource/Review/Summary.php b/app/code/core/Mage/Review/Model/Resource/Review/Summary.php
index d7277fd7e35..d5a1e36c830 100644
--- a/app/code/core/Mage/Review/Model/Resource/Review/Summary.php
+++ b/app/code/core/Mage/Review/Model/Resource/Review/Summary.php
@@ -22,30 +22,6 @@
*/
class Mage_Review_Model_Resource_Review_Summary extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Define module
- *
- */
- protected function _construct()
- {
- $this->_init('review/review_aggregate', 'entity_pk_value');
- }
-
- /**
- * Retrieve select object for load object data
- *
- * @param string $field
- * @param mixed $value
- * @param Mage_Core_Model_Abstract $object
- * @return Varien_Db_Select
- */
- protected function _getLoadSelect($field, $value, $object)
- {
- $select = parent::_getLoadSelect($field, $value, $object);
- $select->where('store_id = ?', (int) $object->getStoreId());
- return $select;
- }
-
/**
* Reaggregate all data by rating summary
*
@@ -84,4 +60,27 @@ public function reAggregate($summary)
}
return $this;
}
+ /**
+ * Define module
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('review/review_aggregate', 'entity_pk_value');
+ }
+
+ /**
+ * Retrieve select object for load object data
+ *
+ * @param string $field
+ * @param mixed $value
+ * @param Mage_Core_Model_Abstract $object
+ * @return Varien_Db_Select
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ $select = parent::_getLoadSelect($field, $value, $object);
+ $select->where('store_id = ?', (int) $object->getStoreId());
+ return $select;
+ }
}
diff --git a/app/code/core/Mage/Review/Model/Review.php b/app/code/core/Mage/Review/Model/Review.php
index a20d94d943b..14b97a5bd4d 100644
--- a/app/code/core/Mage/Review/Model/Review.php
+++ b/app/code/core/Mage/Review/Model/Review.php
@@ -45,13 +45,6 @@
*/
class Mage_Review_Model_Review extends Mage_Core_Model_Abstract
{
- /**
- * Event prefix for observer
- *
- * @var string
- */
- protected $_eventPrefix = 'review';
-
/**
* @deprecated after 1.3.2.4
*
@@ -69,11 +62,12 @@ class Mage_Review_Model_Review extends Mage_Core_Model_Abstract
public const STATUS_APPROVED = 1;
public const STATUS_PENDING = 2;
public const STATUS_NOT_APPROVED = 3;
-
- protected function _construct()
- {
- $this->_init('review/review');
- }
+ /**
+ * Event prefix for observer
+ *
+ * @var string
+ */
+ protected $_eventPrefix = 'review';
/**
* @return Mage_Review_Model_Resource_Review_Product_Collection
@@ -162,17 +156,6 @@ public function validate()
return $errors;
}
- /**
- * Perform actions after object delete
- *
- * @return Mage_Core_Model_Abstract
- */
- protected function _afterDeleteCommit()
- {
- $this->getResource()->afterDeleteCommit($this);
- return parent::_afterDeleteCommit();
- }
-
/**
* Append review summary to product collection
*
@@ -205,16 +188,6 @@ public function appendSummary($collection)
return $this;
}
- /**
- * @return Mage_Core_Model_Abstract
- * @throws Mage_Core_Exception
- */
- protected function _beforeDelete()
- {
- $this->_protectFromNonAdmin();
- return parent::_beforeDelete();
- }
-
/**
* Check if current review approved or not
*
@@ -251,4 +224,30 @@ public function getEntityIdByCode($entityCode)
{
return $this->getResource()->getEntityIdByCode($entityCode);
}
+
+ protected function _construct()
+ {
+ $this->_init('review/review');
+ }
+
+ /**
+ * Perform actions after object delete
+ *
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _afterDeleteCommit()
+ {
+ $this->getResource()->afterDeleteCommit($this);
+ return parent::_afterDeleteCommit();
+ }
+
+ /**
+ * @return Mage_Core_Model_Abstract
+ * @throws Mage_Core_Exception
+ */
+ protected function _beforeDelete()
+ {
+ $this->_protectFromNonAdmin();
+ return parent::_beforeDelete();
+ }
}
diff --git a/app/code/core/Mage/Review/controllers/CustomerController.php b/app/code/core/Mage/Review/controllers/CustomerController.php
index 4590121ea55..12956208328 100644
--- a/app/code/core/Mage/Review/controllers/CustomerController.php
+++ b/app/code/core/Mage/Review/controllers/CustomerController.php
@@ -36,28 +36,6 @@ public function preDispatch()
return $this;
}
- /**
- * Load review model with data by passed id.
- * Return false if review was not loaded or was not created by customer
- *
- * @param int $reviewId
- * @return bool|Mage_Review_Model_Review
- */
- protected function _loadReview($reviewId)
- {
- if (!$reviewId) {
- return false;
- }
-
- /** @var Mage_Review_Model_Review $review */
- $review = Mage::getModel('review/review')->load($reviewId);
- if (!$review->getId() || $review->getCustomerId() != Mage::getSingleton('customer/session')->getCustomerId()) {
- return false;
- }
-
- return $review;
- }
-
public function indexAction()
{
$this->loadLayout();
@@ -90,4 +68,26 @@ public function viewAction()
$this->getLayout()->getBlock('head')->setTitle($this->__('Review Details'));
$this->renderLayout();
}
+
+ /**
+ * Load review model with data by passed id.
+ * Return false if review was not loaded or was not created by customer
+ *
+ * @param int $reviewId
+ * @return bool|Mage_Review_Model_Review
+ */
+ protected function _loadReview($reviewId)
+ {
+ if (!$reviewId) {
+ return false;
+ }
+
+ /** @var Mage_Review_Model_Review $review */
+ $review = Mage::getModel('review/review')->load($reviewId);
+ if (!$review->getId() || $review->getCustomerId() != Mage::getSingleton('customer/session')->getCustomerId()) {
+ return false;
+ }
+
+ return $review;
+ }
}
diff --git a/app/code/core/Mage/Review/controllers/ProductController.php b/app/code/core/Mage/Review/controllers/ProductController.php
index c389c97602d..240f44bddd5 100644
--- a/app/code/core/Mage/Review/controllers/ProductController.php
+++ b/app/code/core/Mage/Review/controllers/ProductController.php
@@ -54,91 +54,6 @@ public function preDispatch()
return $this;
}
- /**
- * Initialize and check product
- *
- * @return Mage_Catalog_Model_Product|false
- */
- protected function _initProduct()
- {
- Mage::dispatchEvent('review_controller_product_init_before', ['controller_action' => $this]);
- $categoryId = (int) $this->getRequest()->getParam('category', false);
- $productId = (int) $this->getRequest()->getParam('id');
-
- $product = $this->_loadProduct($productId);
- if (!$product) {
- return false;
- }
-
- if ($categoryId) {
- $category = Mage::getModel('catalog/category')->load($categoryId);
- Mage::register('current_category', $category);
- }
-
- try {
- Mage::dispatchEvent('review_controller_product_init', ['product' => $product]);
- Mage::dispatchEvent('review_controller_product_init_after', [
- 'product' => $product,
- 'controller_action' => $this,
- ]);
- } catch (Mage_Core_Exception $e) {
- Mage::logException($e);
- return false;
- }
-
- return $product;
- }
-
- /**
- * Load product model with data by passed id.
- * Return false if product was not loaded or has incorrect status.
- *
- * @param int $productId
- * @return bool|Mage_Catalog_Model_Product
- */
- protected function _loadProduct($productId)
- {
- if (!$productId) {
- return false;
- }
-
- $product = Mage::getModel('catalog/product')
- ->setStoreId(Mage::app()->getStore()->getId())
- ->load($productId);
- /** @var Mage_Catalog_Model_Product $product */
- if (!$product->getId() || !$product->isVisibleInCatalog() || !$product->isVisibleInSiteVisibility()) {
- return false;
- }
-
- Mage::register('current_product', $product);
- Mage::register('product', $product);
-
- return $product;
- }
-
- /**
- * Load review model with data by passed id.
- * Return false if review was not loaded or review is not approved.
- *
- * @param int $reviewId
- * @return bool|Mage_Review_Model_Review
- */
- protected function _loadReview($reviewId)
- {
- if (!$reviewId) {
- return false;
- }
-
- $review = Mage::getModel('review/review')->load($reviewId);
- /** @var Mage_Review_Model_Review $review */
- if (!$review->getId() || !$review->isApproved() || !$review->isAvailableOnStore(Mage::app()->getStore())) {
- return false;
- }
-
- Mage::register('current_review', $review);
-
- return $review;
- }
/**
* Submit new review action
@@ -269,6 +184,91 @@ public function viewAction()
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
+ /**
+ * Initialize and check product
+ *
+ * @return Mage_Catalog_Model_Product|false
+ */
+ protected function _initProduct()
+ {
+ Mage::dispatchEvent('review_controller_product_init_before', ['controller_action' => $this]);
+ $categoryId = (int) $this->getRequest()->getParam('category', false);
+ $productId = (int) $this->getRequest()->getParam('id');
+
+ $product = $this->_loadProduct($productId);
+ if (!$product) {
+ return false;
+ }
+
+ if ($categoryId) {
+ $category = Mage::getModel('catalog/category')->load($categoryId);
+ Mage::register('current_category', $category);
+ }
+
+ try {
+ Mage::dispatchEvent('review_controller_product_init', ['product' => $product]);
+ Mage::dispatchEvent('review_controller_product_init_after', [
+ 'product' => $product,
+ 'controller_action' => $this,
+ ]);
+ } catch (Mage_Core_Exception $e) {
+ Mage::logException($e);
+ return false;
+ }
+
+ return $product;
+ }
+
+ /**
+ * Load product model with data by passed id.
+ * Return false if product was not loaded or has incorrect status.
+ *
+ * @param int $productId
+ * @return bool|Mage_Catalog_Model_Product
+ */
+ protected function _loadProduct($productId)
+ {
+ if (!$productId) {
+ return false;
+ }
+
+ $product = Mage::getModel('catalog/product')
+ ->setStoreId(Mage::app()->getStore()->getId())
+ ->load($productId);
+ /** @var Mage_Catalog_Model_Product $product */
+ if (!$product->getId() || !$product->isVisibleInCatalog() || !$product->isVisibleInSiteVisibility()) {
+ return false;
+ }
+
+ Mage::register('current_product', $product);
+ Mage::register('product', $product);
+
+ return $product;
+ }
+
+ /**
+ * Load review model with data by passed id.
+ * Return false if review was not loaded or review is not approved.
+ *
+ * @param int $reviewId
+ * @return bool|Mage_Review_Model_Review
+ */
+ protected function _loadReview($reviewId)
+ {
+ if (!$reviewId) {
+ return false;
+ }
+
+ $review = Mage::getModel('review/review')->load($reviewId);
+ /** @var Mage_Review_Model_Review $review */
+ if (!$review->getId() || !$review->isApproved() || !$review->isAvailableOnStore(Mage::app()->getStore())) {
+ return false;
+ }
+
+ Mage::register('current_review', $review);
+
+ return $review;
+ }
/**
* Load specific layout handles by product type id
diff --git a/app/code/core/Mage/Rss/Block/Catalog/Abstract.php b/app/code/core/Mage/Rss/Block/Catalog/Abstract.php
index 07c386494e7..6f60aedccd9 100644
--- a/app/code/core/Mage/Rss/Block/Catalog/Abstract.php
+++ b/app/code/core/Mage/Rss/Block/Catalog/Abstract.php
@@ -52,42 +52,6 @@ class Mage_Rss_Block_Catalog_Abstract extends Mage_Rss_Block_Abstract
*/
protected $_mapRenderer = 'msrp_rss';
- /**
- * Return Price Block renderer for specified product type
- *
- * @param string $productTypeId Catalog Product type
- * @return Mage_Core_Block_Abstract
- */
- protected function _getPriceBlock($productTypeId)
- {
- if (!isset($this->_priceBlock[$productTypeId])) {
- $block = $this->_priceBlockDefaultType;
- if (isset($this->_priceBlockTypes[$productTypeId])) {
- if ($this->_priceBlockTypes[$productTypeId]['block'] != '') {
- $block = $this->_priceBlockTypes[$productTypeId]['block'];
- }
- }
- $this->_priceBlock[$productTypeId] = $this->getLayout()->createBlock($block);
- }
- return $this->_priceBlock[$productTypeId];
- }
-
- /**
- * Return template for Price Block renderer
- *
- * @param string $productTypeId Catalog Product type
- * @return string
- */
- protected function _getPriceBlockTemplate($productTypeId)
- {
- if (isset($this->_priceBlockTypes[$productTypeId])) {
- if ($this->_priceBlockTypes[$productTypeId]['template'] != '') {
- return $this->_priceBlockTypes[$productTypeId]['template'];
- }
- }
- return $this->_priceBlockDefaultTemplate;
- }
-
/**
* Returns product price html for RSS feed
*
@@ -128,4 +92,40 @@ public function addPriceBlockType($type, $block = '', $template = '')
];
}
}
+
+ /**
+ * Return Price Block renderer for specified product type
+ *
+ * @param string $productTypeId Catalog Product type
+ * @return Mage_Core_Block_Abstract
+ */
+ protected function _getPriceBlock($productTypeId)
+ {
+ if (!isset($this->_priceBlock[$productTypeId])) {
+ $block = $this->_priceBlockDefaultType;
+ if (isset($this->_priceBlockTypes[$productTypeId])) {
+ if ($this->_priceBlockTypes[$productTypeId]['block'] != '') {
+ $block = $this->_priceBlockTypes[$productTypeId]['block'];
+ }
+ }
+ $this->_priceBlock[$productTypeId] = $this->getLayout()->createBlock($block);
+ }
+ return $this->_priceBlock[$productTypeId];
+ }
+
+ /**
+ * Return template for Price Block renderer
+ *
+ * @param string $productTypeId Catalog Product type
+ * @return string
+ */
+ protected function _getPriceBlockTemplate($productTypeId)
+ {
+ if (isset($this->_priceBlockTypes[$productTypeId])) {
+ if ($this->_priceBlockTypes[$productTypeId]['template'] != '') {
+ return $this->_priceBlockTypes[$productTypeId]['template'];
+ }
+ }
+ return $this->_priceBlockDefaultTemplate;
+ }
}
diff --git a/app/code/core/Mage/Rss/Block/Catalog/Category.php b/app/code/core/Mage/Rss/Block/Catalog/Category.php
index ec5a5f8f9b8..3aafb89a86a 100644
--- a/app/code/core/Mage/Rss/Block/Catalog/Category.php
+++ b/app/code/core/Mage/Rss/Block/Catalog/Category.php
@@ -22,6 +22,46 @@
*/
class Mage_Rss_Block_Catalog_Category extends Mage_Rss_Block_Catalog_Abstract
{
+ /**
+ * Preparing data and adding to rss object
+ *
+ * @param array $args
+ */
+ public function addNewItemXmlCallback($args)
+ {
+ $product = $args['product'];
+ $product->setAllowedInRss(true);
+ $product->setAllowedPriceInRss(true);
+
+ Mage::dispatchEvent('rss_catalog_category_xml_callback', $args);
+
+ if (!$product->getAllowedInRss()) {
+ return;
+ }
+
+ /** @var Mage_Catalog_Helper_Image $helper */
+ $helper = $this->helper('catalog/image');
+
+ $description = ''
+ . '->resize(75, 75)
+ . ') | '
+ . '' . $product->getDescription();
+
+ if ($product->getAllowedPriceInRss()) {
+ $description .= $this->getPriceHtml($product, true);
+ }
+
+ $description .= ' |
';
+ $rssObj = $args['rssObj'];
+ $data = [
+ 'title' => $product->getName(),
+ 'link' => $product->getProductUrl(),
+ 'description' => $description,
+ ];
+
+ $rssObj->_addEntry($data);
+ }
/**
* @throws Exception
*/
@@ -104,45 +144,4 @@ protected function _toHtml()
}
return $rssObj->createRssXml();
}
-
- /**
- * Preparing data and adding to rss object
- *
- * @param array $args
- */
- public function addNewItemXmlCallback($args)
- {
- $product = $args['product'];
- $product->setAllowedInRss(true);
- $product->setAllowedPriceInRss(true);
-
- Mage::dispatchEvent('rss_catalog_category_xml_callback', $args);
-
- if (!$product->getAllowedInRss()) {
- return;
- }
-
- /** @var Mage_Catalog_Helper_Image $helper */
- $helper = $this->helper('catalog/image');
-
- $description = ''
- . '->resize(75, 75)
- . ') | '
- . '' . $product->getDescription();
-
- if ($product->getAllowedPriceInRss()) {
- $description .= $this->getPriceHtml($product, true);
- }
-
- $description .= ' |
';
- $rssObj = $args['rssObj'];
- $data = [
- 'title' => $product->getName(),
- 'link' => $product->getProductUrl(),
- 'description' => $description,
- ];
-
- $rssObj->_addEntry($data);
- }
}
diff --git a/app/code/core/Mage/Rss/Block/Catalog/New.php b/app/code/core/Mage/Rss/Block/Catalog/New.php
index e970ff22bf3..ad677096623 100644
--- a/app/code/core/Mage/Rss/Block/Catalog/New.php
+++ b/app/code/core/Mage/Rss/Block/Catalog/New.php
@@ -22,6 +22,51 @@
*/
class Mage_Rss_Block_Catalog_New extends Mage_Rss_Block_Catalog_Abstract
{
+ /**
+ * Preparing data and adding to rss object
+ *
+ * @param array $args
+ */
+ public function addNewItemXmlCallback($args)
+ {
+ $product = $args['product'];
+
+ $product->setAllowedInRss(true);
+ $product->setAllowedPriceInRss(true);
+ Mage::dispatchEvent('rss_catalog_new_xml_callback', $args);
+
+ if (!$product->getAllowedInRss()) {
+ //Skip adding product to RSS
+ return;
+ }
+
+ $allowedPriceInRss = $product->getAllowedPriceInRss();
+
+ /** @var Mage_Catalog_Helper_Image $helper */
+ $helper = $this->helper('catalog/image');
+
+ $product->setData($args['row']);
+ $description = ''
+ . '->resize(75, 75)
+ . ') | ' .
+ '' . $product->getDescription();
+
+ if ($allowedPriceInRss) {
+ $description .= $this->getPriceHtml($product, true);
+ }
+
+ $description .= ' | ' .
+ '
';
+
+ $rssObj = $args['rssObj'];
+ $data = [
+ 'title' => $product->getName(),
+ 'link' => $product->getProductUrl(),
+ 'description' => $description,
+ ];
+ $rssObj->_addEntry($data);
+ }
protected function _construct() {}
/**
@@ -101,50 +146,4 @@ protected function _toHtml()
return $rssObj->createRssXml();
}
-
- /**
- * Preparing data and adding to rss object
- *
- * @param array $args
- */
- public function addNewItemXmlCallback($args)
- {
- $product = $args['product'];
-
- $product->setAllowedInRss(true);
- $product->setAllowedPriceInRss(true);
- Mage::dispatchEvent('rss_catalog_new_xml_callback', $args);
-
- if (!$product->getAllowedInRss()) {
- //Skip adding product to RSS
- return;
- }
-
- $allowedPriceInRss = $product->getAllowedPriceInRss();
-
- /** @var Mage_Catalog_Helper_Image $helper */
- $helper = $this->helper('catalog/image');
-
- $product->setData($args['row']);
- $description = ''
- . '->resize(75, 75)
- . ') | ' .
- '' . $product->getDescription();
-
- if ($allowedPriceInRss) {
- $description .= $this->getPriceHtml($product, true);
- }
-
- $description .= ' | ' .
- '
';
-
- $rssObj = $args['rssObj'];
- $data = [
- 'title' => $product->getName(),
- 'link' => $product->getProductUrl(),
- 'description' => $description,
- ];
- $rssObj->_addEntry($data);
- }
}
diff --git a/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php b/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php
index 94b723f4882..a34dd043a0b 100644
--- a/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php
+++ b/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php
@@ -29,6 +29,30 @@ class Mage_Rss_Block_Catalog_NotifyStock extends Mage_Rss_Block_Abstract
*/
public const CACHE_TAG = 'block_html_rss_catalog_notifystock';
+ /**
+ * Adds single product to feed
+ *
+ * @param array $args
+ */
+ public function addNotifyItemXmlCallback($args)
+ {
+ $product = $args['product'];
+ $product->setData($args['row']);
+ $url = Mage::helper('adminhtml')->getUrl(
+ 'adminhtml/catalog_product/edit/',
+ ['id' => $product->getId(), '_secure' => true, '_nosecret' => true],
+ );
+ $qty = 1 * $product->getQty();
+ $description = Mage::helper('rss')->__('%s has reached a quantity of %s.', $product->getName(), $qty);
+ $rssObj = $args['rssObj'];
+ $data = [
+ 'title' => $product->getName(),
+ 'link' => $url,
+ 'description' => $description,
+ ];
+ $rssObj->_addEntry($data);
+ }
+
protected function _construct()
{
$this->setCacheTags([self::CACHE_TAG]);
@@ -92,28 +116,4 @@ protected function _toHtml()
return $rssObj->createRssXml();
}
-
- /**
- * Adds single product to feed
- *
- * @param array $args
- */
- public function addNotifyItemXmlCallback($args)
- {
- $product = $args['product'];
- $product->setData($args['row']);
- $url = Mage::helper('adminhtml')->getUrl(
- 'adminhtml/catalog_product/edit/',
- ['id' => $product->getId(), '_secure' => true, '_nosecret' => true],
- );
- $qty = 1 * $product->getQty();
- $description = Mage::helper('rss')->__('%s has reached a quantity of %s.', $product->getName(), $qty);
- $rssObj = $args['rssObj'];
- $data = [
- 'title' => $product->getName(),
- 'link' => $url,
- 'description' => $description,
- ];
- $rssObj->_addEntry($data);
- }
}
diff --git a/app/code/core/Mage/Rss/Block/Catalog/Review.php b/app/code/core/Mage/Rss/Block/Catalog/Review.php
index c458c6a25a1..15a6540549f 100644
--- a/app/code/core/Mage/Rss/Block/Catalog/Review.php
+++ b/app/code/core/Mage/Rss/Block/Catalog/Review.php
@@ -29,6 +29,40 @@ class Mage_Rss_Block_Catalog_Review extends Mage_Rss_Block_Abstract
*/
public const CACHE_TAG = 'block_html_rss_catalog_review';
+ /**
+ * Format single RSS element
+ *
+ * @param array $args
+ */
+ public function addReviewItemXmlCallback($args)
+ {
+ $rssObj = $args['rssObj'];
+ $row = $args['row'];
+
+ $store = Mage::app()->getStore($row['store_id']);
+ $urlModel = Mage::getModel('core/url')->setStore($store);
+ $productUrl = $urlModel->getUrl('catalog/product/view', ['id' => $row['entity_id']]);
+ $reviewUrl = Mage::helper('adminhtml')->getUrl(
+ 'adminhtml/catalog_product_review/edit/',
+ ['id' => $row['review_id'], '_secure' => true, '_nosecret' => true],
+ );
+ $storeName = $store->getName();
+
+ $description = ''
+ . $this->__('Product: %s
', $productUrl, $row['name'])
+ . $this->__('Summary of review: %s
', $row['title'])
+ . $this->__('Review: %s
', $row['detail'])
+ . $this->__('Store: %s
', $storeName)
+ . $this->__('click here to view the review', $reviewUrl)
+ . '
';
+ $data = [
+ 'title' => $this->__('Product: "%s" review By: %s', $row['name'], $row['nickname']),
+ 'link' => 'test',
+ 'description' => $description,
+ ];
+ $rssObj->_addEntry($data);
+ }
+
/**
* Initialize cache
*/
@@ -78,38 +112,4 @@ protected function _toHtml()
);
return $rssObj->createRssXml();
}
-
- /**
- * Format single RSS element
- *
- * @param array $args
- */
- public function addReviewItemXmlCallback($args)
- {
- $rssObj = $args['rssObj'];
- $row = $args['row'];
-
- $store = Mage::app()->getStore($row['store_id']);
- $urlModel = Mage::getModel('core/url')->setStore($store);
- $productUrl = $urlModel->getUrl('catalog/product/view', ['id' => $row['entity_id']]);
- $reviewUrl = Mage::helper('adminhtml')->getUrl(
- 'adminhtml/catalog_product_review/edit/',
- ['id' => $row['review_id'], '_secure' => true, '_nosecret' => true],
- );
- $storeName = $store->getName();
-
- $description = ''
- . $this->__('Product: %s
', $productUrl, $row['name'])
- . $this->__('Summary of review: %s
', $row['title'])
- . $this->__('Review: %s
', $row['detail'])
- . $this->__('Store: %s
', $storeName)
- . $this->__('click here to view the review', $reviewUrl)
- . '
';
- $data = [
- 'title' => $this->__('Product: "%s" review By: %s', $row['name'], $row['nickname']),
- 'link' => 'test',
- 'description' => $description,
- ];
- $rssObj->_addEntry($data);
- }
}
diff --git a/app/code/core/Mage/Rss/Block/Catalog/Special.php b/app/code/core/Mage/Rss/Block/Catalog/Special.php
index 977de87dc80..9f33295daca 100644
--- a/app/code/core/Mage/Rss/Block/Catalog/Special.php
+++ b/app/code/core/Mage/Rss/Block/Catalog/Special.php
@@ -29,6 +29,54 @@ class Mage_Rss_Block_Catalog_Special extends Mage_Rss_Block_Catalog_Abstract
*/
protected static $_currentDate = null;
+ /**
+ * Preparing data and adding to rss object
+ *
+ * @param array $args
+ * @throws Zend_Date_Exception
+ */
+ public function addSpecialXmlCallback($args)
+ {
+ if (!isset(self::$_currentDate)) {
+ self::$_currentDate = new Zend_Date();
+ }
+
+ // dispatch event to determine whether the product will eventually get to the result
+ $product = new Varien_Object(['allowed_in_rss' => true, 'allowed_price_in_rss' => true]);
+ $args['product'] = $product;
+ Mage::dispatchEvent('rss_catalog_special_xml_callback', $args);
+ if (!$product->getAllowedInRss()) {
+ return;
+ }
+
+ // add row to result and determine whether special price is active (less or equal to the final price)
+ $row = $args['row'];
+ $row['use_special'] = false;
+ $row['allowed_price_in_rss'] = $product->getAllowedPriceInRss();
+ if (isset($row['special_to_date']) && $row['final_price'] <= $row['special_price']
+ && $row['allowed_price_in_rss']
+ ) {
+ $compareDate = self::$_currentDate->compareDate($row['special_to_date'], Varien_Date::DATE_INTERNAL_FORMAT);
+ if ($compareDate === -1 || $compareDate === 0) {
+ $row['use_special'] = true;
+ }
+ }
+
+ $args['results'][] = $row;
+ }
+
+ /**
+ * Function for comparing two items in collection
+ *
+ * @param Varien_Object $a
+ * @param Varien_Object $b
+ * @return int
+ */
+ public function sortByStartDate($a, $b)
+ {
+ return $a['start_date'] > $b['start_date'] ? -1 : ($a['start_date'] < $b['start_date'] ? 1 : 0);
+ }
+
/**
* @throws Mage_Core_Model_Store_Exception
* @throws Exception
@@ -154,52 +202,4 @@ protected function _toHtml()
}
return $rssObj->createRssXml();
}
-
- /**
- * Preparing data and adding to rss object
- *
- * @param array $args
- * @throws Zend_Date_Exception
- */
- public function addSpecialXmlCallback($args)
- {
- if (!isset(self::$_currentDate)) {
- self::$_currentDate = new Zend_Date();
- }
-
- // dispatch event to determine whether the product will eventually get to the result
- $product = new Varien_Object(['allowed_in_rss' => true, 'allowed_price_in_rss' => true]);
- $args['product'] = $product;
- Mage::dispatchEvent('rss_catalog_special_xml_callback', $args);
- if (!$product->getAllowedInRss()) {
- return;
- }
-
- // add row to result and determine whether special price is active (less or equal to the final price)
- $row = $args['row'];
- $row['use_special'] = false;
- $row['allowed_price_in_rss'] = $product->getAllowedPriceInRss();
- if (isset($row['special_to_date']) && $row['final_price'] <= $row['special_price']
- && $row['allowed_price_in_rss']
- ) {
- $compareDate = self::$_currentDate->compareDate($row['special_to_date'], Varien_Date::DATE_INTERNAL_FORMAT);
- if ($compareDate === -1 || $compareDate === 0) {
- $row['use_special'] = true;
- }
- }
-
- $args['results'][] = $row;
- }
-
- /**
- * Function for comparing two items in collection
- *
- * @param Varien_Object $a
- * @param Varien_Object $b
- * @return int
- */
- public function sortByStartDate($a, $b)
- {
- return $a['start_date'] > $b['start_date'] ? -1 : ($a['start_date'] < $b['start_date'] ? 1 : 0);
- }
}
diff --git a/app/code/core/Mage/Rss/Block/Catalog/Tag.php b/app/code/core/Mage/Rss/Block/Catalog/Tag.php
index 297f4ab9fa1..c6512fb29db 100644
--- a/app/code/core/Mage/Rss/Block/Catalog/Tag.php
+++ b/app/code/core/Mage/Rss/Block/Catalog/Tag.php
@@ -22,6 +22,49 @@
*/
class Mage_Rss_Block_Catalog_Tag extends Mage_Rss_Block_Catalog_Abstract
{
+ /**
+ * Preparing data and adding to rss object
+ *
+ * @param array $args
+ */
+ public function addTaggedItemXml($args)
+ {
+ $product = $args['product'];
+
+ $product->setAllowedInRss(true);
+ $product->setAllowedPriceInRss(true);
+ Mage::dispatchEvent('rss_catalog_tagged_item_xml_callback', $args);
+
+ if (!$product->getAllowedInRss()) {
+ //Skip adding product to RSS
+ return;
+ }
+
+ $allowedPriceInRss = $product->getAllowedPriceInRss();
+
+ /** @var Mage_Catalog_Helper_Image $helper */
+ $helper = $this->helper('catalog/image');
+
+ $product->unsetData()->load($args['row']['entity_id']);
+ $description = ''
+ . '->resize(75, 75)
+ . ') | '
+ . '' . $product->getDescription();
+
+ if ($allowedPriceInRss) {
+ $description .= $this->getPriceHtml($product, true);
+ }
+
+ $description .= ' |
';
+
+ $rssObj = $args['rssObj'];
+ $data = [
+ 'title' => $product->getName(),
+ 'link' => $product->getProductUrl(),
+ 'description' => $description,
+ ];
+ $rssObj->_addEntry($data);
+ }
protected function _construct()
{
/*
@@ -75,48 +118,4 @@ protected function _toHtml()
return $rssObj->createRssXml();
}
-
- /**
- * Preparing data and adding to rss object
- *
- * @param array $args
- */
- public function addTaggedItemXml($args)
- {
- $product = $args['product'];
-
- $product->setAllowedInRss(true);
- $product->setAllowedPriceInRss(true);
- Mage::dispatchEvent('rss_catalog_tagged_item_xml_callback', $args);
-
- if (!$product->getAllowedInRss()) {
- //Skip adding product to RSS
- return;
- }
-
- $allowedPriceInRss = $product->getAllowedPriceInRss();
-
- /** @var Mage_Catalog_Helper_Image $helper */
- $helper = $this->helper('catalog/image');
-
- $product->unsetData()->load($args['row']['entity_id']);
- $description = ''
- . '->resize(75, 75)
- . ') | '
- . '' . $product->getDescription();
-
- if ($allowedPriceInRss) {
- $description .= $this->getPriceHtml($product, true);
- }
-
- $description .= ' |
';
-
- $rssObj = $args['rssObj'];
- $data = [
- 'title' => $product->getName(),
- 'link' => $product->getProductUrl(),
- 'description' => $description,
- ];
- $rssObj->_addEntry($data);
- }
}
diff --git a/app/code/core/Mage/Rss/Block/List.php b/app/code/core/Mage/Rss/Block/List.php
index 00fecd43992..6e31a337213 100644
--- a/app/code/core/Mage/Rss/Block/List.php
+++ b/app/code/core/Mage/Rss/Block/List.php
@@ -26,25 +26,6 @@ class Mage_Rss_Block_List extends Mage_Core_Block_Template
protected $_rssFeeds = [];
- /**
- * Add Link elements to head
- *
- * @return $this
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Head $head */
- $head = $this->getLayout()->getBlock('head');
- $feeds = $this->getRssMiscFeeds();
- if ($head && !empty($feeds)) {
- foreach ($feeds as $feed) {
- $head->addItem('rss', $feed['url'], 'title="' . $feed['label'] . '"');
- }
- }
- return parent::_prepareLayout();
- }
-
/**
* Retrieve rss feeds
*
@@ -196,4 +177,23 @@ public function categoriesRssFeed()
}
}
}
+
+ /**
+ * Add Link elements to head
+ *
+ * @return $this
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Head $head */
+ $head = $this->getLayout()->getBlock('head');
+ $feeds = $this->getRssMiscFeeds();
+ if ($head && !empty($feeds)) {
+ foreach ($feeds as $feed) {
+ $head->addItem('rss', $feed['url'], 'title="' . $feed['label'] . '"');
+ }
+ }
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Rss/Block/Order/New.php b/app/code/core/Mage/Rss/Block/Order/New.php
index e070359aae6..e5fe4e5acc9 100644
--- a/app/code/core/Mage/Rss/Block/Order/New.php
+++ b/app/code/core/Mage/Rss/Block/Order/New.php
@@ -29,6 +29,28 @@ class Mage_Rss_Block_Order_New extends Mage_Core_Block_Template
*/
public const CACHE_TAG = 'block_html_rss_order_new';
+ /**
+ * @param array $args
+ */
+ public function addNewOrderXmlCallback($args)
+ {
+ $rssObj = $args['rssObj'];
+ $order = $args['order'];
+ $detailBlock = $args['detailBlock'];
+ $order->reset()->load($args['row']['entity_id']);
+ if ($order && $order->getId()) {
+ $title = Mage::helper('rss')->__('Order #%s created at %s', $order->getIncrementId(), $this->formatDate($order->getCreatedAt()));
+ $url = Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', ['_secure' => true, 'order_id' => $order->getId(), '_nosecret' => true]);
+ $detailBlock->setOrder($order);
+ $data = [
+ 'title' => $title,
+ 'link' => $url,
+ 'description' => $detailBlock->toHtml(),
+ ];
+ $rssObj->_addEntry($data);
+ }
+ }
+
protected function _construct()
{
$this->setCacheTags([self::CACHE_TAG]);
@@ -81,26 +103,4 @@ protected function _toHtml()
return $rssObj->createRssXml();
}
-
- /**
- * @param array $args
- */
- public function addNewOrderXmlCallback($args)
- {
- $rssObj = $args['rssObj'];
- $order = $args['order'];
- $detailBlock = $args['detailBlock'];
- $order->reset()->load($args['row']['entity_id']);
- if ($order && $order->getId()) {
- $title = Mage::helper('rss')->__('Order #%s created at %s', $order->getIncrementId(), $this->formatDate($order->getCreatedAt()));
- $url = Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', ['_secure' => true, 'order_id' => $order->getId(), '_nosecret' => true]);
- $detailBlock->setOrder($order);
- $data = [
- 'title' => $title,
- 'link' => $url,
- 'description' => $detailBlock->toHtml(),
- ];
- $rssObj->_addEntry($data);
- }
- }
}
diff --git a/app/code/core/Mage/Rss/Block/Wishlist.php b/app/code/core/Mage/Rss/Block/Wishlist.php
index aa650f287ee..08c22de2728 100644
--- a/app/code/core/Mage/Rss/Block/Wishlist.php
+++ b/app/code/core/Mage/Rss/Block/Wishlist.php
@@ -36,6 +36,36 @@ class Mage_Rss_Block_Wishlist extends Mage_Wishlist_Block_Abstract
*/
protected $_mapRenderer = 'msrp_rss';
+ /**
+ * Retrieve Product View URL
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @param array $additional
+ * @return string
+ */
+ public function getProductUrl($product, $additional = [])
+ {
+ $additional['_rss'] = true;
+ return parent::getProductUrl($product, $additional);
+ }
+
+ /**
+ * Adding customized price template for product type, used as action in layouts
+ *
+ * @param string $type Catalog Product Type
+ * @param string $block Block Type
+ * @param string $template Template
+ */
+ public function addPriceBlockType($type, $block = '', $template = '')
+ {
+ if ($type) {
+ $this->_priceBlockTypes[$type] = [
+ 'block' => $block,
+ 'template' => $template,
+ ];
+ }
+ }
+
/**
* Retrieve Wishlist model
*
@@ -178,34 +208,4 @@ protected function _toHtml()
return $rssObj->createRssXml();
}
-
- /**
- * Retrieve Product View URL
- *
- * @param Mage_Catalog_Model_Product $product
- * @param array $additional
- * @return string
- */
- public function getProductUrl($product, $additional = [])
- {
- $additional['_rss'] = true;
- return parent::getProductUrl($product, $additional);
- }
-
- /**
- * Adding customized price template for product type, used as action in layouts
- *
- * @param string $type Catalog Product Type
- * @param string $block Block Type
- * @param string $template Template
- */
- public function addPriceBlockType($type, $block = '', $template = '')
- {
- if ($type) {
- $this->_priceBlockTypes[$type] = [
- 'block' => $block,
- 'template' => $template,
- ];
- }
- }
}
diff --git a/app/code/core/Mage/Rule/Model/Abstract.php b/app/code/core/Mage/Rule/Model/Abstract.php
index 4a8a6d6eea8..c62d09a551f 100644
--- a/app/code/core/Mage/Rule/Model/Abstract.php
+++ b/app/code/core/Mage/Rule/Model/Abstract.php
@@ -103,58 +103,6 @@ public function getProductFlatSelect($storeId)
return $resource->getProductFlatSelect($storeId, $this->getConditions());
}
- /**
- * Prepare data before saving
- *
- * @return Mage_Rule_Model_Abstract
- */
- protected function _beforeSave()
- {
- // Check if discount amount not negative
- if ($this->hasDiscountAmount()) {
- if ((int) $this->getDiscountAmount() < 0) {
- Mage::throwException(Mage::helper('rule')->__('Invalid discount amount.'));
- }
- }
-
- // Serialize conditions
- if ($this->getConditions()) {
- $this->setConditionsSerialized(serialize($this->getConditions()->asArray()));
- $this->unsConditions();
- }
-
- // Serialize actions
- if ($this->getActions()) {
- $this->setActionsSerialized(serialize($this->getActions()->asArray()));
- $this->unsActions();
- }
-
- /**
- * Prepare website Ids if applicable and if they were set as string in comma separated format.
- * Backwards compatibility.
- */
- if ($this->hasWebsiteIds()) {
- $websiteIds = $this->getWebsiteIds();
- if (is_string($websiteIds) && !empty($websiteIds)) {
- $this->setWebsiteIds(explode(',', $websiteIds));
- }
- }
-
- /**
- * Prepare customer group Ids if applicable and if they were set as string in comma separated format.
- * Backwards compatibility.
- */
- if ($this->hasCustomerGroupIds()) {
- $groupIds = $this->getCustomerGroupIds();
- if (is_string($groupIds) && !empty($groupIds)) {
- $this->setCustomerGroupIds(explode(',', $groupIds));
- }
- }
-
- parent::_beforeSave();
- return $this;
- }
-
/**
* Set rule combine conditions model
*
@@ -233,42 +181,6 @@ public function getActions()
return $this->_actions;
}
- /**
- * Reset rule combine conditions
- *
- * @param null|Mage_Rule_Model_Condition_Combine $conditions
- *
- * @return Mage_Rule_Model_Abstract
- */
- protected function _resetConditions($conditions = null)
- {
- if (is_null($conditions)) {
- $conditions = $this->getConditionsInstance();
- }
- $conditions->setRule($this)->setId('1')->setPrefix('conditions');
- $this->setConditions($conditions);
-
- return $this;
- }
-
- /**
- * Reset rule actions
- *
- * @param null|Mage_Rule_Model_Action_Collection $actions
- *
- * @return Mage_Rule_Model_Abstract
- */
- protected function _resetActions($actions = null)
- {
- if (is_null($actions)) {
- $actions = $this->getActionsInstance();
- }
- $actions->setRule($this)->setId('1')->setPrefix('actions');
- $this->setActions($actions);
-
- return $this;
- }
-
/**
* Rule form getter
*
@@ -301,48 +213,6 @@ public function loadPost(array $data)
return $this;
}
- /**
- * Set specified data to current rule.
- * Set conditions and actions recursively.
- * Convert dates into Zend_Date.
- *
- *
- * @return array
- */
- protected function _convertFlatToRecursive(array $data)
- {
- $arr = [];
- foreach ($data as $key => $value) {
- if (($key === 'conditions' || $key === 'actions') && is_array($value)) {
- foreach ($value as $id => $data) {
- $path = explode('--', $id);
- $node = & $arr;
- for ($i = 0, $l = count($path); $i < $l; $i++) {
- $node = & $node[$key][$path[$i]] ?? [];
- }
- foreach ($data as $k => $v) {
- $node[$k] = $v;
- }
- }
- } else {
- /**
- * Convert dates into Zend_Date
- */
- if (in_array($key, ['from_date', 'to_date']) && $value) {
- $value = Mage::app()->getLocale()->date(
- $value,
- Varien_Date::DATE_INTERNAL_FORMAT,
- null,
- false,
- );
- }
- $this->setData($key, $value);
- }
- }
-
- return $arr;
- }
-
/**
* Validate rule conditions to determine if rule can run
*
@@ -490,6 +360,136 @@ public function asArray(array $arrAttributes = [])
return [];
}
+ /**
+ * Prepare data before saving
+ *
+ * @return Mage_Rule_Model_Abstract
+ */
+ protected function _beforeSave()
+ {
+ // Check if discount amount not negative
+ if ($this->hasDiscountAmount()) {
+ if ((int) $this->getDiscountAmount() < 0) {
+ Mage::throwException(Mage::helper('rule')->__('Invalid discount amount.'));
+ }
+ }
+
+ // Serialize conditions
+ if ($this->getConditions()) {
+ $this->setConditionsSerialized(serialize($this->getConditions()->asArray()));
+ $this->unsConditions();
+ }
+
+ // Serialize actions
+ if ($this->getActions()) {
+ $this->setActionsSerialized(serialize($this->getActions()->asArray()));
+ $this->unsActions();
+ }
+
+ /**
+ * Prepare website Ids if applicable and if they were set as string in comma separated format.
+ * Backwards compatibility.
+ */
+ if ($this->hasWebsiteIds()) {
+ $websiteIds = $this->getWebsiteIds();
+ if (is_string($websiteIds) && !empty($websiteIds)) {
+ $this->setWebsiteIds(explode(',', $websiteIds));
+ }
+ }
+
+ /**
+ * Prepare customer group Ids if applicable and if they were set as string in comma separated format.
+ * Backwards compatibility.
+ */
+ if ($this->hasCustomerGroupIds()) {
+ $groupIds = $this->getCustomerGroupIds();
+ if (is_string($groupIds) && !empty($groupIds)) {
+ $this->setCustomerGroupIds(explode(',', $groupIds));
+ }
+ }
+
+ parent::_beforeSave();
+ return $this;
+ }
+
+ /**
+ * Reset rule combine conditions
+ *
+ * @param null|Mage_Rule_Model_Condition_Combine $conditions
+ *
+ * @return Mage_Rule_Model_Abstract
+ */
+ protected function _resetConditions($conditions = null)
+ {
+ if (is_null($conditions)) {
+ $conditions = $this->getConditionsInstance();
+ }
+ $conditions->setRule($this)->setId('1')->setPrefix('conditions');
+ $this->setConditions($conditions);
+
+ return $this;
+ }
+
+ /**
+ * Reset rule actions
+ *
+ * @param null|Mage_Rule_Model_Action_Collection $actions
+ *
+ * @return Mage_Rule_Model_Abstract
+ */
+ protected function _resetActions($actions = null)
+ {
+ if (is_null($actions)) {
+ $actions = $this->getActionsInstance();
+ }
+ $actions->setRule($this)->setId('1')->setPrefix('actions');
+ $this->setActions($actions);
+
+ return $this;
+ }
+
+ /**
+ * Set specified data to current rule.
+ * Set conditions and actions recursively.
+ * Convert dates into Zend_Date.
+ *
+ *
+ * @return array
+ */
+ protected function _convertFlatToRecursive(array $data)
+ {
+ $arr = [];
+ foreach ($data as $key => $value) {
+ if (($key === 'conditions' || $key === 'actions') && is_array($value)) {
+ foreach ($value as $id => $data) {
+ $path = explode('--', $id);
+ $node = & $arr;
+ for ($i = 0, $l = count($path); $i < $l; $i++) {
+ $node = & $node[$key][$path[$i]] ?? [];
+ }
+ foreach ($data as $k => $v) {
+ $node[$k] = $v;
+ }
+ }
+ } else {
+ /**
+ * Convert dates into Zend_Date
+ */
+ if (in_array($key, ['from_date', 'to_date']) && $value) {
+ $value = Mage::app()->getLocale()->date(
+ $value,
+ Varien_Date::DATE_INTERNAL_FORMAT,
+ null,
+ false,
+ );
+ }
+ $this->setData($key, $value);
+ }
+ }
+
+ return $arr;
+ }
+
/**
* Combine website ids to string
*
diff --git a/app/code/core/Mage/Rule/Model/Condition/Abstract.php b/app/code/core/Mage/Rule/Model/Condition/Abstract.php
index 6971636b985..24fb686c1a6 100644
--- a/app/code/core/Mage/Rule/Model/Condition/Abstract.php
+++ b/app/code/core/Mage/Rule/Model/Condition/Abstract.php
@@ -811,6 +811,24 @@ public function validateAttribute($validatedValue)
return $result;
}
+ /**
+ * @return bool
+ */
+ public function validate(Varien_Object $object)
+ {
+ return $this->validateAttribute($object->getData($this->getAttribute()));
+ }
+
+ /**
+ * Retrieve operator for php validation
+ *
+ * @return string
+ */
+ public function getOperatorForValidate()
+ {
+ return $this->getOperator();
+ }
+
/**
* Case and type insensitive comparison of values
*
@@ -832,22 +850,4 @@ protected function _compareValues($validatedValue, $value, $strict = true)
return (bool) preg_match('~' . $validatePattern . '~iu', $value);
}
}
-
- /**
- * @return bool
- */
- public function validate(Varien_Object $object)
- {
- return $this->validateAttribute($object->getData($this->getAttribute()));
- }
-
- /**
- * Retrieve operator for php validation
- *
- * @return string
- */
- public function getOperatorForValidate()
- {
- return $this->getOperator();
- }
}
diff --git a/app/code/core/Mage/Rule/Model/Condition/Combine.php b/app/code/core/Mage/Rule/Model/Condition/Combine.php
index a462a0fc075..a603c60e0bd 100644
--- a/app/code/core/Mage/Rule/Model/Condition/Combine.php
+++ b/app/code/core/Mage/Rule/Model/Condition/Combine.php
@@ -36,6 +36,24 @@ class Mage_Rule_Model_Condition_Combine extends Mage_Rule_Model_Condition_Abstra
*/
protected static $_conditionModels = [];
+ public function __construct()
+ {
+ parent::__construct();
+ $this->setType('rule/condition_combine')
+ ->setAggregator('all')
+ ->setValue(true)
+ ->setConditions([])
+ ->setActions([]);
+
+ $this->loadAggregatorOptions();
+ if ($options = $this->getAggregatorOptions()) {
+ foreach (array_keys($options) as $aggregator) {
+ $this->setAggregator($aggregator);
+ break;
+ }
+ }
+ }
+
/**
* Prepare sql where by condition
*
@@ -55,53 +73,6 @@ public function prepareConditionSql()
$delimiter = $this->getAggregator() == 'all' ? ' AND ' : ' OR ';
return ' (' . implode($delimiter, $wheres) . ') ';
}
-
- /**
- * Retrieve new object for each requested model.
- * If model is requested first time, store it at static array.
- *
- * It's made by performance reasons to avoid initialization of same models each time when rules are being processed.
- *
- * @param string $modelClass
- * @return Mage_Rule_Model_Condition_Abstract|bool
- */
- protected function _getNewConditionModelInstance($modelClass)
- {
- if (empty($modelClass)) {
- return false;
- }
-
- if (!array_key_exists($modelClass, self::$_conditionModels)) {
- $model = Mage::getModel($modelClass);
- self::$_conditionModels[$modelClass] = $model;
- } else {
- $model = self::$_conditionModels[$modelClass];
- }
-
- if (!$model) {
- return false;
- }
-
- return clone $model;
- }
-
- public function __construct()
- {
- parent::__construct();
- $this->setType('rule/condition_combine')
- ->setAggregator('all')
- ->setValue(true)
- ->setConditions([])
- ->setActions([]);
-
- $this->loadAggregatorOptions();
- if ($options = $this->getAggregatorOptions()) {
- foreach (array_keys($options) as $aggregator) {
- $this->setAggregator($aggregator);
- break;
- }
- }
- }
/* start aggregator methods */
/**
* @return $this
@@ -414,6 +385,35 @@ public function setConditions($conditions)
return $this->setData($key, $conditions);
}
+ /**
+ * Retrieve new object for each requested model.
+ * If model is requested first time, store it at static array.
+ *
+ * It's made by performance reasons to avoid initialization of same models each time when rules are being processed.
+ *
+ * @param string $modelClass
+ * @return Mage_Rule_Model_Condition_Abstract|bool
+ */
+ protected function _getNewConditionModelInstance($modelClass)
+ {
+ if (empty($modelClass)) {
+ return false;
+ }
+
+ if (!array_key_exists($modelClass, self::$_conditionModels)) {
+ $model = Mage::getModel($modelClass);
+ self::$_conditionModels[$modelClass] = $model;
+ } else {
+ $model = self::$_conditionModels[$modelClass];
+ }
+
+ if (!$model) {
+ return false;
+ }
+
+ return clone $model;
+ }
+
/**
* Getter for "Conditions Combination" select option for recursive combines
*/
diff --git a/app/code/core/Mage/Rule/Model/Condition/Product/Abstract.php b/app/code/core/Mage/Rule/Model/Condition/Product/Abstract.php
index db1d868e1e4..6b331724d51 100644
--- a/app/code/core/Mage/Rule/Model/Condition/Product/Abstract.php
+++ b/app/code/core/Mage/Rule/Model/Condition/Product/Abstract.php
@@ -153,15 +153,6 @@ public function getAttributeObject()
return $obj;
}
- /**
- * Add special attributes
- */
- protected function _addSpecialAttributes(array &$attributes)
- {
- $attributes['attribute_set_id'] = Mage::helper('catalogrule')->__('Attribute Set');
- $attributes['category_ids'] = Mage::helper('catalogrule')->__('Category');
- }
-
/**
* Load attribute options
*
@@ -192,65 +183,6 @@ public function loadAttributeOptions()
return $this;
}
- /**
- * Prepares values options to be used as select options or hashed array
- * Result is stored in following keys:
- * 'value_select_options' - normal select array: array(array('value' => $value, 'label' => $label), ...)
- * 'value_option' - hashed array: array($value => $label, ...),
- *
- * @return $this
- */
- protected function _prepareValueOptions()
- {
- // Check that both keys exist. Maybe somehow only one was set not in this routine, but externally.
- $selectReady = $this->getData('value_select_options');
- $hashedReady = $this->getData('value_option');
- if ($selectReady && $hashedReady) {
- return $this;
- }
-
- // Get array of select options. It will be used as source for hashed options
- $selectOptions = null;
- if ($this->getAttribute() === 'attribute_set_id') {
- $entityTypeId = Mage::getSingleton('eav/config')
- ->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getId();
- $selectOptions = Mage::getResourceModel('eav/entity_attribute_set_collection')
- ->setEntityTypeFilter($entityTypeId)
- ->load()
- ->toOptionArray();
- } elseif (is_object($this->getAttributeObject())) {
- $attributeObject = $this->getAttributeObject();
- if ($attributeObject->usesSource()) {
- if ($attributeObject->getFrontendInput() == 'multiselect') {
- $addEmptyOption = false;
- } else {
- $addEmptyOption = true;
- }
- $selectOptions = $attributeObject->getSource()->getAllOptions($addEmptyOption);
- }
- }
-
- // Set new values only if we really got them
- if ($selectOptions !== null) {
- // Overwrite only not already existing values
- if (!$selectReady) {
- $this->setData('value_select_options', $selectOptions);
- }
- if (!$hashedReady) {
- $hashedOptions = [];
- foreach ($selectOptions as $o) {
- if (is_array($o['value'])) {
- continue; // We cannot use array as index
- }
- $hashedOptions[$o['value']] = $o['label'];
- }
- $this->setData('value_option', $hashedOptions);
- }
- }
-
- return $this;
- }
-
/**
* Retrieve value by option
*
@@ -588,4 +520,72 @@ public function correctOperator($operator, $inputType)
return $operator;
}
+
+ /**
+ * Add special attributes
+ */
+ protected function _addSpecialAttributes(array &$attributes)
+ {
+ $attributes['attribute_set_id'] = Mage::helper('catalogrule')->__('Attribute Set');
+ $attributes['category_ids'] = Mage::helper('catalogrule')->__('Category');
+ }
+
+ /**
+ * Prepares values options to be used as select options or hashed array
+ * Result is stored in following keys:
+ * 'value_select_options' - normal select array: array(array('value' => $value, 'label' => $label), ...)
+ * 'value_option' - hashed array: array($value => $label, ...),
+ *
+ * @return $this
+ */
+ protected function _prepareValueOptions()
+ {
+ // Check that both keys exist. Maybe somehow only one was set not in this routine, but externally.
+ $selectReady = $this->getData('value_select_options');
+ $hashedReady = $this->getData('value_option');
+ if ($selectReady && $hashedReady) {
+ return $this;
+ }
+
+ // Get array of select options. It will be used as source for hashed options
+ $selectOptions = null;
+ if ($this->getAttribute() === 'attribute_set_id') {
+ $entityTypeId = Mage::getSingleton('eav/config')
+ ->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getId();
+ $selectOptions = Mage::getResourceModel('eav/entity_attribute_set_collection')
+ ->setEntityTypeFilter($entityTypeId)
+ ->load()
+ ->toOptionArray();
+ } elseif (is_object($this->getAttributeObject())) {
+ $attributeObject = $this->getAttributeObject();
+ if ($attributeObject->usesSource()) {
+ if ($attributeObject->getFrontendInput() == 'multiselect') {
+ $addEmptyOption = false;
+ } else {
+ $addEmptyOption = true;
+ }
+ $selectOptions = $attributeObject->getSource()->getAllOptions($addEmptyOption);
+ }
+ }
+
+ // Set new values only if we really got them
+ if ($selectOptions !== null) {
+ // Overwrite only not already existing values
+ if (!$selectReady) {
+ $this->setData('value_select_options', $selectOptions);
+ }
+ if (!$hashedReady) {
+ $hashedOptions = [];
+ foreach ($selectOptions as $o) {
+ if (is_array($o['value'])) {
+ continue; // We cannot use array as index
+ }
+ $hashedOptions[$o['value']] = $o['label'];
+ }
+ $this->setData('value_option', $hashedOptions);
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Rule/Model/Resource/Rule/Collection/Abstract.php b/app/code/core/Mage/Rule/Model/Resource/Rule/Collection/Abstract.php
index 1d911f71dc5..141c8997cce 100644
--- a/app/code/core/Mage/Rule/Model/Resource/Rule/Collection/Abstract.php
+++ b/app/code/core/Mage/Rule/Model/Resource/Rule/Collection/Abstract.php
@@ -53,24 +53,6 @@ abstract class Mage_Rule_Model_Resource_Rule_Collection_Abstract extends Mage_Co
*/
protected $_env;
- /**
- * Add website ids to rules data
- *
- * @return Mage_Rule_Model_Resource_Rule_Collection_Abstract
- */
- protected function _afterLoad()
- {
- parent::_afterLoad();
- if ($this->getFlag('add_websites_to_result') && $this->_items) {
- /** @var Mage_Rule_Model_Abstract $item */
- foreach ($this->_items as $item) {
- $item->afterLoad();
- }
- }
-
- return $this;
- }
-
/**
* Init flag for adding rule website ids to collection result
*
@@ -146,26 +128,6 @@ public function addIsActiveFilter($isActive = 1)
return $this;
}
- /**
- * Retrieve correspondent entity information (associations table name, columns names)
- * of rule's associated entity by specified entity type
- *
- * @param string $entityType
- *
- * @return array
- */
- protected function _getAssociatedEntityInfo($entityType)
- {
- if (isset($this->_associatedEntitiesMap[$entityType])) {
- return $this->_associatedEntitiesMap[$entityType];
- }
-
- throw Mage::exception(
- 'Mage_Core',
- Mage::helper('rule')->__('There is no information about associated entity type "%s".', $entityType),
- );
- }
-
/**
* Set environment for all rules in collection
*
@@ -214,4 +176,42 @@ public function process()
{
return $this;
}
+
+ /**
+ * Add website ids to rules data
+ *
+ * @return Mage_Rule_Model_Resource_Rule_Collection_Abstract
+ */
+ protected function _afterLoad()
+ {
+ parent::_afterLoad();
+ if ($this->getFlag('add_websites_to_result') && $this->_items) {
+ /** @var Mage_Rule_Model_Abstract $item */
+ foreach ($this->_items as $item) {
+ $item->afterLoad();
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Retrieve correspondent entity information (associations table name, columns names)
+ * of rule's associated entity by specified entity type
+ *
+ * @param string $entityType
+ *
+ * @return array
+ */
+ protected function _getAssociatedEntityInfo($entityType)
+ {
+ if (isset($this->_associatedEntitiesMap[$entityType])) {
+ return $this->_associatedEntitiesMap[$entityType];
+ }
+
+ throw Mage::exception(
+ 'Mage_Core',
+ Mage::helper('rule')->__('There is no information about associated entity type "%s".', $entityType),
+ );
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/View/Tab/Info.php b/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/View/Tab/Info.php
index 520a89c23b2..9e42f21a814 100644
--- a/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/View/Tab/Info.php
+++ b/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/View/Tab/Info.php
@@ -29,15 +29,6 @@
*/
class Mage_Sales_Block_Adminhtml_Billing_Agreement_View_Tab_Info extends Mage_Adminhtml_Block_Abstract implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
- /**
- * Set custom template
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('sales/billing/agreement/view/tab/info.phtml');
- }
-
/**
* Return Tab label
*
@@ -77,6 +68,14 @@ public function isHidden()
{
return false;
}
+ /**
+ * Set custom template
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('sales/billing/agreement/view/tab/info.phtml');
+ }
/**
* Retrieve billing agreement model
diff --git a/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/View/Tab/Orders.php b/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/View/Tab/Orders.php
index ac7b94d9c5c..f332c8aa7c7 100644
--- a/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/View/Tab/Orders.php
+++ b/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/View/Tab/Orders.php
@@ -32,19 +32,6 @@ public function __construct()
$this->setId('billing_agreement_orders');
}
- /**
- * Prepare related orders collection
- *
- * @return Mage_Adminhtml_Block_Widget_Grid
- */
- protected function _prepareCollection()
- {
- $collection = Mage::getResourceModel('sales/order_grid_collection');
- $collection->addBillingAgreementsFilter(Mage::registry('current_billing_agreement')->getId());
- $this->setCollection($collection);
- return Mage_Adminhtml_Block_Widget_Grid::_prepareCollection();
- }
-
/**
* Return Tab label
*
@@ -105,6 +92,19 @@ public function getExportTypes()
return false;
}
+ /**
+ * Prepare related orders collection
+ *
+ * @return Mage_Adminhtml_Block_Widget_Grid
+ */
+ protected function _prepareCollection()
+ {
+ $collection = Mage::getResourceModel('sales/order_grid_collection');
+ $collection->addBillingAgreementsFilter(Mage::registry('current_billing_agreement')->getId());
+ $this->setCollection($collection);
+ return Mage_Adminhtml_Block_Widget_Grid::_prepareCollection();
+ }
+
/**
* Disable massaction in grid
*
diff --git a/app/code/core/Mage/Sales/Block/Adminhtml/Customer/Edit/Tab/Recurring/Profile.php b/app/code/core/Mage/Sales/Block/Adminhtml/Customer/Edit/Tab/Recurring/Profile.php
index c079412e0bb..3242974cdaa 100644
--- a/app/code/core/Mage/Sales/Block/Adminhtml/Customer/Edit/Tab/Recurring/Profile.php
+++ b/app/code/core/Mage/Sales/Block/Adminhtml/Customer/Edit/Tab/Recurring/Profile.php
@@ -73,22 +73,6 @@ public function isHidden()
return false;
}
- /**
- * Prepare collection for grid
- *
- * @return Mage_Adminhtml_Block_Widget_Grid
- */
- protected function _prepareCollection()
- {
- $collection = Mage::getResourceModel('sales/recurring_profile_collection')
- ->addFieldToFilter('customer_id', Mage::registry('current_customer')->getId());
- if (!$this->getParam($this->getVarNameSort())) {
- $collection->setOrder('profile_id', 'desc');
- }
- $this->setCollection($collection);
- return Mage_Adminhtml_Block_Widget_Grid::_prepareCollection();
- }
-
/**
* Defines after which tab, this tab should be rendered
*
@@ -108,4 +92,20 @@ public function getGridUrl()
{
return $this->getUrl('*/sales_recurring_profile/customerGrid', ['_current' => true]);
}
+
+ /**
+ * Prepare collection for grid
+ *
+ * @return Mage_Adminhtml_Block_Widget_Grid
+ */
+ protected function _prepareCollection()
+ {
+ $collection = Mage::getResourceModel('sales/recurring_profile_collection')
+ ->addFieldToFilter('customer_id', Mage::registry('current_customer')->getId());
+ if (!$this->getParam($this->getVarNameSort())) {
+ $collection->setOrder('profile_id', 'desc');
+ }
+ $this->setCollection($collection);
+ return Mage_Adminhtml_Block_Widget_Grid::_prepareCollection();
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/Edit/Form.php b/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/Edit/Form.php
index 6a45277464e..c55177cd3b3 100644
--- a/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/Edit/Form.php
+++ b/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/Edit/Form.php
@@ -72,6 +72,28 @@ public function setProductEntity(Mage_Catalog_Model_Product $product)
return $this;
}
+ /**
+ * Set readonly flag
+ *
+ * @param bool $isReadonly
+ * @return $this
+ */
+ public function setIsReadonly($isReadonly)
+ {
+ $this->_isReadOnly = $isReadonly;
+ return $this;
+ }
+
+ /**
+ * Get readonly flag
+ *
+ * @return bool
+ */
+ public function getIsReadonly()
+ {
+ return $this->_isReadOnly;
+ }
+
/**
* Instantiate a recurring payment profile to use it as a helper
*/
@@ -215,26 +237,4 @@ protected function _getPeriodUnitOptions($emptyLabel)
$this->_profile->getAllPeriodUnits(),
);
}
-
- /**
- * Set readonly flag
- *
- * @param bool $isReadonly
- * @return $this
- */
- public function setIsReadonly($isReadonly)
- {
- $this->_isReadOnly = $isReadonly;
- return $this;
- }
-
- /**
- * Get readonly flag
- *
- * @return bool
- */
- public function getIsReadonly()
- {
- return $this->_isReadOnly;
- }
}
diff --git a/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/Grid.php b/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/Grid.php
index 022799e9782..e4213a93e85 100644
--- a/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/Grid.php
+++ b/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/Grid.php
@@ -31,6 +31,27 @@ public function __construct()
$this->setSaveParametersInSession(true);
}
+ /**
+ * Return row url for js event handlers
+ *
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/sales_recurring_profile/view', ['profile' => $row->getId()]);
+ }
+
+ /**
+ * Return grid url
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', ['_current' => true]);
+ }
+
/**
* Prepare grid collection object
*
@@ -113,25 +134,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Return row url for js event handlers
- *
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/sales_recurring_profile/view', ['profile' => $row->getId()]);
- }
-
- /**
- * Return grid url
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getUrl('*/*/grid', ['_current' => true]);
- }
}
diff --git a/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/View/Items.php b/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/View/Items.php
index ebaf38f772c..bbb3ffd7468 100644
--- a/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/View/Items.php
+++ b/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/View/Items.php
@@ -22,17 +22,6 @@
*/
class Mage_Adminhtml_Block_Sales_Recurring_Profile_View_Items extends Mage_Adminhtml_Block_Sales_Items_Abstract
{
- /**
- * Retrieve required options from parent
- */
- protected function _beforeToHtml()
- {
- if (!$this->getParentBlock()) {
- Mage::throwException(Mage::helper('adminhtml')->__('Invalid parent block for this block'));
- }
- return parent::_beforeToHtml();
- }
-
/**
* Return current recurring profile
*
@@ -64,4 +53,14 @@ public function formatPrice($value)
$store = Mage::app()->getStore($this->_getRecurringProfile()->getStore());
return $store->formatPrice($value);
}
+ /**
+ * Retrieve required options from parent
+ */
+ protected function _beforeToHtml()
+ {
+ if (!$this->getParentBlock()) {
+ Mage::throwException(Mage::helper('adminhtml')->__('Invalid parent block for this block'));
+ }
+ return parent::_beforeToHtml();
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/View/Tab/Orders.php b/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/View/Tab/Orders.php
index 556d89085a4..106117262fa 100644
--- a/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/View/Tab/Orders.php
+++ b/app/code/core/Mage/Sales/Block/Adminhtml/Recurring/Profile/View/Tab/Orders.php
@@ -34,6 +34,83 @@ public function __construct()
;
}
+ /**
+ * Return row url for js event handlers
+ *
+ * @param Varien_Object $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
+ }
+
+ /**
+ * Url for ajax grid submission
+ *
+ * @return string
+ */
+ public function getGridUrl()
+ {
+ return $this->getTabUrl();
+ }
+
+ /**
+ * Url for ajax tab
+ *
+ * @return string
+ */
+ public function getTabUrl()
+ {
+ return $this->getUrl('*/*/orders', ['profile' => Mage::registry('current_recurring_profile')->getId()]);
+ }
+
+ /**
+ * Class for ajax tab
+ *
+ * @return string
+ */
+ public function getTabClass()
+ {
+ return 'ajax';
+ }
+
+ /**
+ * Label getter
+ *
+ * @return string
+ */
+ public function getTabLabel()
+ {
+ return Mage::helper('sales')->__('Related Orders');
+ }
+
+ /**
+ * Same as label getter
+ *
+ * @return string
+ */
+ public function getTabTitle()
+ {
+ return $this->getTabLabel();
+ }
+
+ /**
+ * @return bool
+ */
+ public function canShowTab()
+ {
+ return true;
+ }
+
+ /**
+ * @return bool
+ */
+ public function isHidden()
+ {
+ return false;
+ }
+
/**
* Prepare grid collection object
*
@@ -132,81 +209,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Return row url for js event handlers
- *
- * @param Varien_Object $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/sales_order/view', ['order_id' => $row->getId()]);
- }
-
- /**
- * Url for ajax grid submission
- *
- * @return string
- */
- public function getGridUrl()
- {
- return $this->getTabUrl();
- }
-
- /**
- * Url for ajax tab
- *
- * @return string
- */
- public function getTabUrl()
- {
- return $this->getUrl('*/*/orders', ['profile' => Mage::registry('current_recurring_profile')->getId()]);
- }
-
- /**
- * Class for ajax tab
- *
- * @return string
- */
- public function getTabClass()
- {
- return 'ajax';
- }
-
- /**
- * Label getter
- *
- * @return string
- */
- public function getTabLabel()
- {
- return Mage::helper('sales')->__('Related Orders');
- }
-
- /**
- * Same as label getter
- *
- * @return string
- */
- public function getTabTitle()
- {
- return $this->getTabLabel();
- }
-
- /**
- * @return bool
- */
- public function canShowTab()
- {
- return true;
- }
-
- /**
- * @return bool
- */
- public function isHidden()
- {
- return false;
- }
}
diff --git a/app/code/core/Mage/Sales/Block/Billing/Agreements.php b/app/code/core/Mage/Sales/Block/Billing/Agreements.php
index 0acb7e2029f..c71fff57cc8 100644
--- a/app/code/core/Mage/Sales/Block/Billing/Agreements.php
+++ b/app/code/core/Mage/Sales/Block/Billing/Agreements.php
@@ -37,22 +37,6 @@ class Mage_Sales_Block_Billing_Agreements extends Mage_Core_Block_Template
*/
protected $_billingAgreements = null;
- /**
- * Set Billing Agreement instance
- *
- * @return Mage_Core_Block_Abstract
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
- $pager = $this->getLayout()->createBlock('page/html_pager')
- ->setCollection($this->getBillingAgreements())->setIsOutputRequired(false);
- $this->setChild('pager', $pager)
- ->setBackUrl($this->getUrl('customer/account/'));
- $this->getBillingAgreements()->load();
- return $this;
- }
-
/**
* Retrieve billing agreements collection
*
@@ -98,23 +82,6 @@ public function getItemValue(Mage_Sales_Model_Billing_Agreement $item, $key)
return $this->escapeHtml($value);
}
- /**
- * Load available billing agreement methods
- *
- * @return array
- */
- protected function _loadPaymentMethods()
- {
- if (!$this->_paymentMethods) {
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
- foreach ($helper->getBillingAgreementMethods() as $paymentMethod) {
- $this->_paymentMethods[$paymentMethod->getCode()] = $paymentMethod->getTitle();
- }
- }
- return $this->_paymentMethods;
- }
-
/**
* Retrieve wizard payment options array
*
@@ -133,6 +100,39 @@ public function getWizardPaymentMethodOptions()
return $paymentMethodOptions;
}
+ /**
+ * Set Billing Agreement instance
+ *
+ * @return Mage_Core_Block_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+ $pager = $this->getLayout()->createBlock('page/html_pager')
+ ->setCollection($this->getBillingAgreements())->setIsOutputRequired(false);
+ $this->setChild('pager', $pager)
+ ->setBackUrl($this->getUrl('customer/account/'));
+ $this->getBillingAgreements()->load();
+ return $this;
+ }
+
+ /**
+ * Load available billing agreement methods
+ *
+ * @return array
+ */
+ protected function _loadPaymentMethods()
+ {
+ if (!$this->_paymentMethods) {
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+ foreach ($helper->getBillingAgreementMethods() as $paymentMethod) {
+ $this->_paymentMethods[$paymentMethod->getCode()] = $paymentMethod->getTitle();
+ }
+ }
+ return $this->_paymentMethods;
+ }
+
/**
* Set data to block
*
diff --git a/app/code/core/Mage/Sales/Block/Items/Abstract.php b/app/code/core/Mage/Sales/Block/Items/Abstract.php
index a707d029736..493e3ebad21 100644
--- a/app/code/core/Mage/Sales/Block/Items/Abstract.php
+++ b/app/code/core/Mage/Sales/Block/Items/Abstract.php
@@ -32,15 +32,6 @@ class Mage_Sales_Block_Items_Abstract extends Mage_Core_Block_Template
*/
protected $_itemRenders = [];
- /**
- * Initialize default item renderer
- */
- protected function _construct()
- {
- parent::_construct();
- $this->addItemRender('default', 'checkout/cart_item_renderer', 'checkout/cart/item/default.phtml');
- }
-
/**
* Add renderer for item product type
*
@@ -81,6 +72,30 @@ public function getItemRenderer($type)
return $this->_itemRenders[$type]['renderer'];
}
+ /**
+ * Get item row html
+ *
+ * @return string
+ */
+ public function getItemHtml(Varien_Object $item)
+ {
+ $type = $this->_getItemType($item);
+
+ $block = $this->getItemRenderer($type)
+ ->setItem($item);
+ $this->_prepareItem($block);
+ return $block->toHtml();
+ }
+
+ /**
+ * Initialize default item renderer
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->addItemRender('default', 'checkout/cart_item_renderer', 'checkout/cart/item/default.phtml');
+ }
+
/**
* Prepare item before output
*
@@ -107,19 +122,4 @@ protected function _getItemType(Varien_Object $item)
}
return $type;
}
-
- /**
- * Get item row html
- *
- * @return string
- */
- public function getItemHtml(Varien_Object $item)
- {
- $type = $this->_getItemType($item);
-
- $block = $this->getItemRenderer($type)
- ->setItem($item);
- $this->_prepareItem($block);
- return $block->toHtml();
- }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Creditmemo.php b/app/code/core/Mage/Sales/Block/Order/Creditmemo.php
index cb5a195e537..56460ebf8cc 100644
--- a/app/code/core/Mage/Sales/Block/Order/Creditmemo.php
+++ b/app/code/core/Mage/Sales/Block/Order/Creditmemo.php
@@ -22,33 +22,6 @@
*/
class Mage_Sales_Block_Order_Creditmemo extends Mage_Sales_Block_Order_Creditmemo_Items
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('sales/order/creditmemo.phtml');
- }
-
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
- }
-
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
- $this->setChild(
- 'payment_info',
- $helper->getInfoBlock($this->getOrder()->getPayment()),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -147,4 +120,30 @@ public function canDisplayGiftmessage(): bool
$helper = $this->helper('giftmessage/message');
return $helper->getIsMessagesAvailable($helper::TYPE_ORDER, $this->getOrder());
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('sales/order/creditmemo.phtml');
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
+ }
+
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+ $this->setChild(
+ 'payment_info',
+ $helper->getInfoBlock($this->getOrder()->getPayment()),
+ );
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/History.php b/app/code/core/Mage/Sales/Block/Order/History.php
index 11bb4e93155..c6f88d9a045 100644
--- a/app/code/core/Mage/Sales/Block/Order/History.php
+++ b/app/code/core/Mage/Sales/Block/Order/History.php
@@ -42,20 +42,6 @@ public function __construct()
Mage::app()->getFrontController()->getAction()->getLayout()->getBlock('root')->setHeaderTitle(Mage::helper('sales')->__('My Orders'));
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
-
- $pager = $this->getLayout()->createBlock('page/html_pager', 'sales.order.history.pager')
- ->setCollection($this->getOrders());
- $this->setChild('pager', $pager);
- $this->getOrders()->load();
- return $this;
- }
-
/**
* @return string
*/
@@ -98,4 +84,18 @@ public function getBackUrl()
{
return $this->getUrl('customer/account/');
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+
+ $pager = $this->getLayout()->createBlock('page/html_pager', 'sales.order.history.pager')
+ ->setCollection($this->getOrders());
+ $this->setChild('pager', $pager);
+ $this->getOrders()->load();
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Info.php b/app/code/core/Mage/Sales/Block/Order/Info.php
index 1d8cbffdab0..b57c6ba9267 100644
--- a/app/code/core/Mage/Sales/Block/Order/Info.php
+++ b/app/code/core/Mage/Sales/Block/Order/Info.php
@@ -24,33 +24,6 @@ class Mage_Sales_Block_Order_Info extends Mage_Core_Block_Template
{
protected $_links = [];
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('sales/order/info.phtml');
- }
-
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
- }
-
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
- $this->setChild(
- 'payment_info',
- $helper->getInfoBlock($this->getOrder()->getPayment()),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -108,20 +81,6 @@ public function getLinks()
return $this->_links;
}
- private function checkLinks()
- {
- $order = $this->getOrder();
- if (!$order->hasInvoices()) {
- unset($this->_links['invoice']);
- }
- if (!$order->hasShipments()) {
- unset($this->_links['shipment']);
- }
- if (!$order->hasCreditmemos()) {
- unset($this->_links['creditmemo']);
- }
- }
-
/**
* Get url for reorder action
*
@@ -151,4 +110,45 @@ public function getPrintUrl($order)
}
return $this->getUrl('sales/order/print', ['order_id' => $order->getId()]);
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('sales/order/info.phtml');
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
+ }
+
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+ $this->setChild(
+ 'payment_info',
+ $helper->getInfoBlock($this->getOrder()->getPayment()),
+ );
+
+ return parent::_prepareLayout();
+ }
+
+ private function checkLinks()
+ {
+ $order = $this->getOrder();
+ if (!$order->hasInvoices()) {
+ unset($this->_links['invoice']);
+ }
+ if (!$order->hasShipments()) {
+ unset($this->_links['shipment']);
+ }
+ if (!$order->hasCreditmemos()) {
+ unset($this->_links['creditmemo']);
+ }
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Info/Buttons.php b/app/code/core/Mage/Sales/Block/Order/Info/Buttons.php
index 89ad7145e14..540438e08de 100644
--- a/app/code/core/Mage/Sales/Block/Order/Info/Buttons.php
+++ b/app/code/core/Mage/Sales/Block/Order/Info/Buttons.php
@@ -22,12 +22,6 @@
*/
class Mage_Sales_Block_Order_Info_Buttons extends Mage_Core_Block_Template
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('sales/order/info/buttons.phtml');
- }
-
/**
* Retrieve current order model instance
*
@@ -65,4 +59,9 @@ public function getReorderUrl($order)
}
return $this->getUrl('sales/order/reorder', ['order_id' => $order->getId()]);
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('sales/order/info/buttons.phtml');
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Invoice.php b/app/code/core/Mage/Sales/Block/Order/Invoice.php
index 48c3d8e82eb..e51a19738b5 100644
--- a/app/code/core/Mage/Sales/Block/Order/Invoice.php
+++ b/app/code/core/Mage/Sales/Block/Order/Invoice.php
@@ -22,33 +22,6 @@
*/
class Mage_Sales_Block_Order_Invoice extends Mage_Sales_Block_Order_Invoice_Items
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('sales/order/invoice.phtml');
- }
-
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
- }
-
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
- $this->setChild(
- 'payment_info',
- $helper->getInfoBlock($this->getOrder()->getPayment()),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -147,4 +120,30 @@ public function canDisplayGiftmessage(): bool
$helper = $this->helper('giftmessage/message');
return $helper->getIsMessagesAvailable($helper::TYPE_ORDER, $this->getOrder());
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('sales/order/invoice.phtml');
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
+ }
+
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+ $this->setChild(
+ 'payment_info',
+ $helper->getInfoBlock($this->getOrder()->getPayment()),
+ );
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Print.php b/app/code/core/Mage/Sales/Block/Order/Print.php
index d07b5f07fc3..7f2efb5bf61 100644
--- a/app/code/core/Mage/Sales/Block/Order/Print.php
+++ b/app/code/core/Mage/Sales/Block/Order/Print.php
@@ -22,6 +22,21 @@
*/
class Mage_Sales_Block_Order_Print extends Mage_Sales_Block_Items_Abstract
{
+ /**
+ * @return string
+ */
+ public function getPaymentInfoHtml()
+ {
+ return $this->getChildHtml('payment_info');
+ }
+
+ /**
+ * @return Mage_Sales_Model_Order
+ */
+ public function getOrder()
+ {
+ return Mage::registry('current_order');
+ }
/**
* @inheritDoc
*/
@@ -43,22 +58,6 @@ protected function _prepareLayout()
return parent::_prepareLayout();
}
- /**
- * @return string
- */
- public function getPaymentInfoHtml()
- {
- return $this->getChildHtml('payment_info');
- }
-
- /**
- * @return Mage_Sales_Model_Order
- */
- public function getOrder()
- {
- return Mage::registry('current_order');
- }
-
/**
* @return Mage_Sales_Block_Items_Abstract
*/
diff --git a/app/code/core/Mage/Sales/Block/Order/Print/Creditmemo.php b/app/code/core/Mage/Sales/Block/Order/Print/Creditmemo.php
index eac0b07407f..33aedf423a1 100644
--- a/app/code/core/Mage/Sales/Block/Order/Print/Creditmemo.php
+++ b/app/code/core/Mage/Sales/Block/Order/Print/Creditmemo.php
@@ -22,27 +22,6 @@
*/
class Mage_Sales_Block_Order_Print_Creditmemo extends Mage_Sales_Block_Items_Abstract
{
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
- }
-
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
- $this->setChild(
- 'payment_info',
- $helper->getInfoBlock($this->getOrder()->getPayment()),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -83,15 +62,6 @@ public function getCreditmemo()
return Mage::registry('current_creditmemo');
}
- /**
- * @return Mage_Sales_Block_Items_Abstract
- */
- protected function _prepareItem(Mage_Core_Block_Abstract $renderer)
- {
- $renderer->setPrintStatus(true);
- return parent::_prepareItem($renderer);
- }
-
/**
* Get Creditmemo totals block html gor specific creditmemo
*
@@ -108,4 +78,33 @@ public function getTotalsHtml($creditmemo)
}
return $html;
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
+ }
+
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+ $this->setChild(
+ 'payment_info',
+ $helper->getInfoBlock($this->getOrder()->getPayment()),
+ );
+
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * @return Mage_Sales_Block_Items_Abstract
+ */
+ protected function _prepareItem(Mage_Core_Block_Abstract $renderer)
+ {
+ $renderer->setPrintStatus(true);
+ return parent::_prepareItem($renderer);
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Print/Invoice.php b/app/code/core/Mage/Sales/Block/Order/Print/Invoice.php
index 6abf66c693e..27c313a5fb1 100644
--- a/app/code/core/Mage/Sales/Block/Order/Print/Invoice.php
+++ b/app/code/core/Mage/Sales/Block/Order/Print/Invoice.php
@@ -22,27 +22,6 @@
*/
class Mage_Sales_Block_Order_Print_Invoice extends Mage_Sales_Block_Items_Abstract
{
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
- }
-
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
- $this->setChild(
- 'payment_info',
- $helper->getInfoBlock($this->getOrder()->getPayment()),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -83,15 +62,6 @@ public function getInvoice()
return Mage::registry('current_invoice');
}
- /**
- * @return Mage_Sales_Block_Items_Abstract
- */
- protected function _prepareItem(Mage_Core_Block_Abstract $renderer)
- {
- $renderer->setPrintStatus(true);
- return parent::_prepareItem($renderer);
- }
-
/**
* Get html of invoice totlas block
*
@@ -108,4 +78,33 @@ public function getInvoiceTotalsHtml($invoice)
}
return $html;
}
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
+ }
+
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+ $this->setChild(
+ 'payment_info',
+ $helper->getInfoBlock($this->getOrder()->getPayment()),
+ );
+
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * @return Mage_Sales_Block_Items_Abstract
+ */
+ protected function _prepareItem(Mage_Core_Block_Abstract $renderer)
+ {
+ $renderer->setPrintStatus(true);
+ return parent::_prepareItem($renderer);
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Print/Shipment.php b/app/code/core/Mage/Sales/Block/Order/Print/Shipment.php
index d50a6b35d8d..f2f1c0db5c5 100644
--- a/app/code/core/Mage/Sales/Block/Order/Print/Shipment.php
+++ b/app/code/core/Mage/Sales/Block/Order/Print/Shipment.php
@@ -36,51 +36,6 @@ class Mage_Sales_Block_Order_Print_Shipment extends Mage_Sales_Block_Items_Abstr
*/
protected $_shipmentsCollection;
- /**
- * Load all tracks and save it to local cache by shipments
- *
- * @inheritDoc
- */
- protected function _beforeToHtml()
- {
- $tracksCollection = $this->getOrder()->getTracksCollection();
-
- foreach ($tracksCollection->getItems() as $track) {
- $shipmentId = $track->getParentId();
- $this->_tracks[$shipmentId][] = $track;
- }
-
- $shipment = Mage::registry('current_shipment');
- if ($shipment) {
- $this->_shipmentsCollection = [$shipment];
- } else {
- $this->_shipmentsCollection = $this->getOrder()->getShipmentsCollection();
- }
-
- return parent::_beforeToHtml();
- }
-
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
- }
-
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
- $this->setChild(
- 'payment_info',
- $helper->getInfoBlock($this->getOrder()->getPayment()),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -121,16 +76,6 @@ public function getShipment()
return Mage::registry('current_shipment');
}
- /**
- * @inheritDoc
- */
- protected function _prepareItem(Mage_Core_Block_Abstract $renderer)
- {
- $renderer->setPrintStatus(true);
-
- return parent::_prepareItem($renderer);
- }
-
/**
* Retrieve order shipments collection
*
@@ -202,4 +147,59 @@ public function getShipmentItems($shipment)
}
return $res;
}
+
+ /**
+ * Load all tracks and save it to local cache by shipments
+ *
+ * @inheritDoc
+ */
+ protected function _beforeToHtml()
+ {
+ $tracksCollection = $this->getOrder()->getTracksCollection();
+
+ foreach ($tracksCollection->getItems() as $track) {
+ $shipmentId = $track->getParentId();
+ $this->_tracks[$shipmentId][] = $track;
+ }
+
+ $shipment = Mage::registry('current_shipment');
+ if ($shipment) {
+ $this->_shipmentsCollection = [$shipment];
+ } else {
+ $this->_shipmentsCollection = $this->getOrder()->getShipmentsCollection();
+ }
+
+ return parent::_beforeToHtml();
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
+ }
+
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+ $this->setChild(
+ 'payment_info',
+ $helper->getInfoBlock($this->getOrder()->getPayment()),
+ );
+
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareItem(Mage_Core_Block_Abstract $renderer)
+ {
+ $renderer->setPrintStatus(true);
+
+ return parent::_prepareItem($renderer);
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Recent.php b/app/code/core/Mage/Sales/Block/Order/Recent.php
index 1304ad5f721..6d7f56860a2 100644
--- a/app/code/core/Mage/Sales/Block/Order/Recent.php
+++ b/app/code/core/Mage/Sales/Block/Order/Recent.php
@@ -88,22 +88,22 @@ public function getTrackUrl($order)
}
/**
+ * @param Mage_Sales_Model_Order $order
* @return string
*/
- protected function _toHtml()
+ public function getReorderUrl($order)
{
- if ($this->getOrders()->getSize() > 0) {
- return parent::_toHtml();
- }
- return '';
+ return $this->getUrl('sales/order/reorder', ['order_id' => $order->getId()]);
}
/**
- * @param Mage_Sales_Model_Order $order
* @return string
*/
- public function getReorderUrl($order)
+ protected function _toHtml()
{
- return $this->getUrl('sales/order/reorder', ['order_id' => $order->getId()]);
+ if ($this->getOrders()->getSize() > 0) {
+ return parent::_toHtml();
+ }
+ return '';
}
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Shipment.php b/app/code/core/Mage/Sales/Block/Order/Shipment.php
index c64c583e8ad..060342fb15e 100644
--- a/app/code/core/Mage/Sales/Block/Order/Shipment.php
+++ b/app/code/core/Mage/Sales/Block/Order/Shipment.php
@@ -22,33 +22,6 @@
*/
class Mage_Sales_Block_Order_Shipment extends Mage_Core_Block_Template
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('sales/order/shipment.phtml');
- }
-
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
- }
-
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
- $this->setChild(
- 'payment_info',
- $helper->getInfoBlock($this->getOrder()->getPayment()),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -147,4 +120,30 @@ public function canDisplayGiftmessage(): bool
$helper = $this->helper('giftmessage/message');
return $helper->getIsMessagesAvailable($helper::TYPE_ORDER, $this->getOrder());
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('sales/order/shipment.phtml');
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
+ }
+
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+ $this->setChild(
+ 'payment_info',
+ $helper->getInfoBlock($this->getOrder()->getPayment()),
+ );
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/Totals.php b/app/code/core/Mage/Sales/Block/Order/Totals.php
index 8da72dca755..8f9340ef505 100644
--- a/app/code/core/Mage/Sales/Block/Order/Totals.php
+++ b/app/code/core/Mage/Sales/Block/Order/Totals.php
@@ -31,22 +31,6 @@ class Mage_Sales_Block_Order_Totals extends Mage_Core_Block_Template
protected $_totals;
protected $_order = null;
- /**
- * Initialize self totals and children blocks totals before html building
- *
- * @inheritDoc
- */
- protected function _beforeToHtml()
- {
- $this->_initTotals();
- foreach ($this->getChild() as $child) {
- if (method_exists($child, 'initTotals')) {
- $child->initTotals();
- }
- }
- return parent::_beforeToHtml();
- }
-
/**
* Get order object
*
@@ -86,73 +70,6 @@ public function getSource()
return $this->getOrder();
}
- /**
- * Initialize order totals array
- *
- * @return $this
- */
- protected function _initTotals()
- {
- $source = $this->getSource();
-
- $this->_totals = [];
- $this->_totals['subtotal'] = new Varien_Object([
- 'code' => 'subtotal',
- 'value' => $source->getSubtotal(),
- 'label' => $this->__('Subtotal'),
- ]);
-
- /**
- * Add shipping
- */
- if (!$source->getIsVirtual() && ((float) $source->getShippingAmount() || $source->getShippingDescription())) {
- $this->_totals['shipping'] = new Varien_Object([
- 'code' => 'shipping',
- 'field' => 'shipping_amount',
- 'value' => $this->getSource()->getShippingAmount(),
- 'label' => $this->__('Shipping & Handling'),
- ]);
- }
-
- /**
- * Add discount
- */
- if ((float) $this->getSource()->getDiscountAmount() != 0) {
- if ($this->getSource()->getDiscountDescription()) {
- $discountLabel = $this->__('Discount (%s)', $source->getDiscountDescription());
- } else {
- $discountLabel = $this->__('Discount');
- }
- $this->_totals['discount'] = new Varien_Object([
- 'code' => 'discount',
- 'field' => 'discount_amount',
- 'value' => $source->getDiscountAmount(),
- 'label' => $discountLabel,
- ]);
- }
-
- $this->_totals['grand_total'] = new Varien_Object([
- 'code' => 'grand_total',
- 'field' => 'grand_total',
- 'strong' => true,
- 'value' => $source->getGrandTotal(),
- 'label' => $this->__('Grand Total'),
- ]);
-
- /**
- * Base grandtotal
- */
- if ($this->getOrder()->isCurrencyDifferent()) {
- $this->_totals['base_grandtotal'] = new Varien_Object([
- 'code' => 'base_grandtotal',
- 'value' => $this->getOrder()->formatBasePrice($source->getBaseGrandTotal()),
- 'label' => $this->__('Grand Total to be Charged'),
- 'is_formated' => true,
- ]);
- }
- return $this;
- }
-
/**
* Add new total to totals array after specific total or before last total by default
*
@@ -302,4 +219,87 @@ public function formatValue($total)
}
return $total->getValue();
}
+
+ /**
+ * Initialize self totals and children blocks totals before html building
+ *
+ * @inheritDoc
+ */
+ protected function _beforeToHtml()
+ {
+ $this->_initTotals();
+ foreach ($this->getChild() as $child) {
+ if (method_exists($child, 'initTotals')) {
+ $child->initTotals();
+ }
+ }
+ return parent::_beforeToHtml();
+ }
+
+ /**
+ * Initialize order totals array
+ *
+ * @return $this
+ */
+ protected function _initTotals()
+ {
+ $source = $this->getSource();
+
+ $this->_totals = [];
+ $this->_totals['subtotal'] = new Varien_Object([
+ 'code' => 'subtotal',
+ 'value' => $source->getSubtotal(),
+ 'label' => $this->__('Subtotal'),
+ ]);
+
+ /**
+ * Add shipping
+ */
+ if (!$source->getIsVirtual() && ((float) $source->getShippingAmount() || $source->getShippingDescription())) {
+ $this->_totals['shipping'] = new Varien_Object([
+ 'code' => 'shipping',
+ 'field' => 'shipping_amount',
+ 'value' => $this->getSource()->getShippingAmount(),
+ 'label' => $this->__('Shipping & Handling'),
+ ]);
+ }
+
+ /**
+ * Add discount
+ */
+ if ((float) $this->getSource()->getDiscountAmount() != 0) {
+ if ($this->getSource()->getDiscountDescription()) {
+ $discountLabel = $this->__('Discount (%s)', $source->getDiscountDescription());
+ } else {
+ $discountLabel = $this->__('Discount');
+ }
+ $this->_totals['discount'] = new Varien_Object([
+ 'code' => 'discount',
+ 'field' => 'discount_amount',
+ 'value' => $source->getDiscountAmount(),
+ 'label' => $discountLabel,
+ ]);
+ }
+
+ $this->_totals['grand_total'] = new Varien_Object([
+ 'code' => 'grand_total',
+ 'field' => 'grand_total',
+ 'strong' => true,
+ 'value' => $source->getGrandTotal(),
+ 'label' => $this->__('Grand Total'),
+ ]);
+
+ /**
+ * Base grandtotal
+ */
+ if ($this->getOrder()->isCurrencyDifferent()) {
+ $this->_totals['base_grandtotal'] = new Varien_Object([
+ 'code' => 'base_grandtotal',
+ 'value' => $this->getOrder()->formatBasePrice($source->getBaseGrandTotal()),
+ 'label' => $this->__('Grand Total to be Charged'),
+ 'is_formated' => true,
+ ]);
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Order/View.php b/app/code/core/Mage/Sales/Block/Order/View.php
index 76aa4b43742..a49c0bb8bdf 100644
--- a/app/code/core/Mage/Sales/Block/Order/View.php
+++ b/app/code/core/Mage/Sales/Block/Order/View.php
@@ -22,33 +22,6 @@
*/
class Mage_Sales_Block_Order_View extends Mage_Core_Block_Template
{
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('sales/order/view.phtml');
- }
-
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- /** @var Mage_Page_Block_Html_Head $headBlock */
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
- }
-
- /** @var Mage_Payment_Helper_Data $helper */
- $helper = $this->helper('payment');
- $this->setChild(
- 'payment_info',
- $helper->getInfoBlock($this->getOrder()->getPayment()),
- );
-
- return parent::_prepareLayout();
- }
-
/**
* @return string
*/
@@ -142,4 +115,30 @@ public function canDisplayGiftmessageOrder(): bool
$this->getOrder(),
) && $this->getOrder()->getGiftMessageId();
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('sales/order/view.phtml');
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ /** @var Mage_Page_Block_Html_Head $headBlock */
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('Order # %s', $this->getOrder()->getRealOrderId()));
+ }
+
+ /** @var Mage_Payment_Helper_Data $helper */
+ $helper = $this->helper('payment');
+ $this->setChild(
+ 'payment_info',
+ $helper->getInfoBlock($this->getOrder()->getPayment()),
+ );
+
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Sales/Block/Reorder/Sidebar.php b/app/code/core/Mage/Sales/Block/Reorder/Sidebar.php
index 43f330533b7..5ed9665fe71 100644
--- a/app/code/core/Mage/Sales/Block/Reorder/Sidebar.php
+++ b/app/code/core/Mage/Sales/Block/Reorder/Sidebar.php
@@ -124,6 +124,19 @@ public function getLastOrder()
return false;
}
+ /**
+ * Retrieve block cache tags
+ *
+ * @return array
+ */
+ public function getCacheTags()
+ {
+ return array_merge(
+ parent::getCacheTags(),
+ $this->getItemsTags($this->_getItemProducts()),
+ );
+ }
+
/**
* Render "My Orders" sidebar block
*
@@ -144,19 +157,6 @@ protected function _getCustomerSession()
return Mage::getSingleton('customer/session');
}
- /**
- * Retrieve block cache tags
- *
- * @return array
- */
- public function getCacheTags()
- {
- return array_merge(
- parent::getCacheTags(),
- $this->getItemsTags($this->_getItemProducts()),
- );
- }
-
/**
* Retrieve products list from items
*
diff --git a/app/code/core/Mage/Sales/Block/Widget/Guest/Form.php b/app/code/core/Mage/Sales/Block/Widget/Guest/Form.php
index a7241658f87..f97cbc78dbb 100644
--- a/app/code/core/Mage/Sales/Block/Widget/Guest/Form.php
+++ b/app/code/core/Mage/Sales/Block/Widget/Guest/Form.php
@@ -50,6 +50,16 @@ public function getTypeSelectHtml()
return $select->getHtml();
}
+ /**
+ * Return quick search form action url
+ *
+ * @return string
+ */
+ public function getActionUrl()
+ {
+ return $this->getUrl('sales/guest/view', ['_secure' => $this->_isSecure()]);
+ }
+
/**
* Get Form Options for Guest
*
@@ -73,14 +83,4 @@ protected function _getFormOptions()
return $options;
}
-
- /**
- * Return quick search form action url
- *
- * @return string
- */
- public function getActionUrl()
- {
- return $this->getUrl('sales/guest/view', ['_secure' => $this->_isSecure()]);
- }
}
diff --git a/app/code/core/Mage/Sales/Controller/Abstract.php b/app/code/core/Mage/Sales/Controller/Abstract.php
index 318f4389fad..53e4181ad02 100644
--- a/app/code/core/Mage/Sales/Controller/Abstract.php
+++ b/app/code/core/Mage/Sales/Controller/Abstract.php
@@ -22,70 +22,6 @@
*/
abstract class Mage_Sales_Controller_Abstract extends Mage_Core_Controller_Front_Action
{
- /**
- * Check order view availability
- *
- * @param Mage_Sales_Model_Order $order
- * @return bool
- */
- protected function _canViewOrder($order)
- {
- $customerId = Mage::getSingleton('customer/session')->getCustomerId();
- $availableStates = Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates();
- if ($order->getId() && $order->getCustomerId() && ($order->getCustomerId() == $customerId)
- && in_array($order->getState(), $availableStates, $strict = true)
- ) {
- return true;
- }
- return false;
- }
-
- /**
- * Init layout, messages and set active block for customer
- */
- protected function _viewAction()
- {
- if (!$this->_loadValidOrder()) {
- return;
- }
-
- $this->loadLayout();
- $this->_initLayoutMessages('catalog/session');
-
- $navigationBlock = $this->getLayout()->getBlock('customer_account_navigation');
- if ($navigationBlock) {
- $navigationBlock->setActive('sales/order/history');
- }
- $this->renderLayout();
- }
-
- /**
- * Try to load valid order by order_id and register it
- *
- * @param int $orderId
- * @return bool
- */
- protected function _loadValidOrder($orderId = null)
- {
- if ($orderId === null) {
- $orderId = (int) $this->getRequest()->getParam('order_id');
- }
- if (!$orderId) {
- $this->_forward('noRoute');
- return false;
- }
-
- $order = Mage::getModel('sales/order')->load($orderId);
-
- if ($this->_canViewOrder($order)) {
- Mage::register('current_order', $order);
- return true;
- } else {
- $this->_redirect('*/*/history');
- }
- return false;
- }
-
/**
* Order view page
*/
@@ -254,4 +190,67 @@ public function printCreditmemoAction()
}
}
}
+ /**
+ * Check order view availability
+ *
+ * @param Mage_Sales_Model_Order $order
+ * @return bool
+ */
+ protected function _canViewOrder($order)
+ {
+ $customerId = Mage::getSingleton('customer/session')->getCustomerId();
+ $availableStates = Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates();
+ if ($order->getId() && $order->getCustomerId() && ($order->getCustomerId() == $customerId)
+ && in_array($order->getState(), $availableStates, $strict = true)
+ ) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Init layout, messages and set active block for customer
+ */
+ protected function _viewAction()
+ {
+ if (!$this->_loadValidOrder()) {
+ return;
+ }
+
+ $this->loadLayout();
+ $this->_initLayoutMessages('catalog/session');
+
+ $navigationBlock = $this->getLayout()->getBlock('customer_account_navigation');
+ if ($navigationBlock) {
+ $navigationBlock->setActive('sales/order/history');
+ }
+ $this->renderLayout();
+ }
+
+ /**
+ * Try to load valid order by order_id and register it
+ *
+ * @param int $orderId
+ * @return bool
+ */
+ protected function _loadValidOrder($orderId = null)
+ {
+ if ($orderId === null) {
+ $orderId = (int) $this->getRequest()->getParam('order_id');
+ }
+ if (!$orderId) {
+ $this->_forward('noRoute');
+ return false;
+ }
+
+ $order = Mage::getModel('sales/order')->load($orderId);
+
+ if ($this->_canViewOrder($order)) {
+ Mage::register('current_order', $order);
+ return true;
+ } else {
+ $this->_redirect('*/*/history');
+ }
+ return false;
+ }
}
diff --git a/app/code/core/Mage/Sales/Helper/Guest.php b/app/code/core/Mage/Sales/Helper/Guest.php
index c3de548655c..2cda76ede56 100644
--- a/app/code/core/Mage/Sales/Helper/Guest.php
+++ b/app/code/core/Mage/Sales/Helper/Guest.php
@@ -150,6 +150,16 @@ public function getBreadcrumbs($controller)
);
}
+ /**
+ * Getter for $this->_cookieName
+ *
+ * @return string
+ */
+ public function getCookieName()
+ {
+ return $this->_cookieName;
+ }
+
/**
* Try to load order by cookie hash
*
@@ -175,14 +185,4 @@ protected function _loadOrderByCookie($cookie = null)
}
return null;
}
-
- /**
- * Getter for $this->_cookieName
- *
- * @return string
- */
- public function getCookieName()
- {
- return $this->_cookieName;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Api2/Order.php b/app/code/core/Mage/Sales/Model/Api2/Order.php
index c29a0c65068..d1aeeaaf350 100644
--- a/app/code/core/Mage/Sales/Model/Api2/Order.php
+++ b/app/code/core/Mage/Sales/Model/Api2/Order.php
@@ -31,6 +31,56 @@ class Mage_Sales_Model_Api2_Order extends Mage_Api2_Model_Resource
public const PARAM_TAX_NAME = '_tax_name';
public const PARAM_TAX_RATE = '_tax_rate';
+ /**
+ * Check gift messages information is allowed
+ *
+ * @return bool
+ */
+ public function _isGiftMessageAllowed()
+ {
+ return in_array(self::PARAM_GIFT_MESSAGE, $this->getFilter()->getAllowedAttributes());
+ }
+
+ /**
+ * Check order comments information is allowed
+ *
+ * @return bool
+ */
+ public function _isOrderCommentsAllowed()
+ {
+ return in_array(self::PARAM_ORDER_COMMENTS, $this->getFilter()->getAllowedAttributes());
+ }
+
+ /**
+ * Check payment method information is allowed
+ *
+ * @return bool
+ */
+ public function _isPaymentMethodAllowed()
+ {
+ return in_array(self::PARAM_PAYMENT_METHOD, $this->getFilter()->getAllowedAttributes());
+ }
+
+ /**
+ * Check tax name information is allowed
+ *
+ * @return bool
+ */
+ public function _isTaxNameAllowed()
+ {
+ return in_array(self::PARAM_TAX_NAME, $this->getFilter()->getAllowedAttributes());
+ }
+
+ /**
+ * Check tax rate information is allowed
+ *
+ * @return bool
+ */
+ public function _isTaxRateAllowed()
+ {
+ return in_array(self::PARAM_TAX_RATE, $this->getFilter()->getAllowedAttributes());
+ }
+
/**
* Add gift message info to select
*
@@ -213,56 +263,6 @@ protected function _getItems(array $orderIds)
return $items;
}
- /**
- * Check gift messages information is allowed
- *
- * @return bool
- */
- public function _isGiftMessageAllowed()
- {
- return in_array(self::PARAM_GIFT_MESSAGE, $this->getFilter()->getAllowedAttributes());
- }
-
- /**
- * Check order comments information is allowed
- *
- * @return bool
- */
- public function _isOrderCommentsAllowed()
- {
- return in_array(self::PARAM_ORDER_COMMENTS, $this->getFilter()->getAllowedAttributes());
- }
-
- /**
- * Check payment method information is allowed
- *
- * @return bool
- */
- public function _isPaymentMethodAllowed()
- {
- return in_array(self::PARAM_PAYMENT_METHOD, $this->getFilter()->getAllowedAttributes());
- }
-
- /**
- * Check tax name information is allowed
- *
- * @return bool
- */
- public function _isTaxNameAllowed()
- {
- return in_array(self::PARAM_TAX_NAME, $this->getFilter()->getAllowedAttributes());
- }
-
- /**
- * Check tax rate information is allowed
- *
- * @return bool
- */
- public function _isTaxRateAllowed()
- {
- return in_array(self::PARAM_TAX_RATE, $this->getFilter()->getAllowedAttributes());
- }
-
/**
* Get orders list
*
diff --git a/app/code/core/Mage/Sales/Model/Billing/Agreement.php b/app/code/core/Mage/Sales/Model/Billing/Agreement.php
index 1d1e21c583c..4e821bdaf9c 100644
--- a/app/code/core/Mage/Sales/Model/Billing/Agreement.php
+++ b/app/code/core/Mage/Sales/Model/Billing/Agreement.php
@@ -62,43 +62,6 @@ class Mage_Sales_Model_Billing_Agreement extends Mage_Payment_Model_Billing_Agre
*/
protected $_relatedOrders = [];
- /**
- * Init model
- */
- protected function _construct()
- {
- $this->_init('sales/billing_agreement');
- }
-
- /**
- * Set created_at parameter
- *
- * @inheritdoc
- */
- protected function _beforeSave()
- {
- $date = Mage::getModel('core/date')->gmtDate();
- if ($this->isObjectNew() && !$this->getCreatedAt()) {
- $this->setCreatedAt($date);
- } else {
- $this->setUpdatedAt($date);
- }
- return parent::_beforeSave();
- }
-
- /**
- * Save agreement order relations
- *
- * @return Mage_Core_Model_Abstract
- */
- protected function _afterSave()
- {
- if (!empty($this->_relatedOrders)) {
- $this->_saveOrderRelations();
- }
- return parent::_afterSave();
- }
-
/**
* Retrieve billing agreement status label
*
@@ -289,6 +252,43 @@ public function addOrderRelation($orderId)
return $this;
}
+ /**
+ * Init model
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/billing_agreement');
+ }
+
+ /**
+ * Set created_at parameter
+ *
+ * @inheritdoc
+ */
+ protected function _beforeSave()
+ {
+ $date = Mage::getModel('core/date')->gmtDate();
+ if ($this->isObjectNew() && !$this->getCreatedAt()) {
+ $this->setCreatedAt($date);
+ } else {
+ $this->setUpdatedAt($date);
+ }
+ return parent::_beforeSave();
+ }
+
+ /**
+ * Save agreement order relations
+ *
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _afterSave()
+ {
+ if (!empty($this->_relatedOrders)) {
+ $this->_saveOrderRelations();
+ }
+ return parent::_afterSave();
+ }
+
/**
* Save related orders
*/
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Address/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Address/Collection.php
index 4fff197f5ef..2db2c25beba 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Address/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Address/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Address_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_address');
- }
-
/**
* @param int $orderId
* @return $this
@@ -36,4 +31,8 @@ public function setOrderFilter($orderId)
$this->addAttributeToFilter('parent_id', $orderId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_address');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Collection.php
index 2b08f332df9..a6284967286 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order');
- }
-
/**
* @return $this
* @throws Mage_Core_Exception
@@ -43,4 +38,8 @@ public function addItemCountExpr()
->group('e.entity_id');
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Collection.php
index a77672eec0a..c73991353b6 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Creditmemo_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_creditmemo');
- }
-
/**
* @param Mage_Sales_Model_Order $order
* @return $this
@@ -41,4 +36,8 @@ public function setOrderFilter($order)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_creditmemo');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Comment/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Comment/Collection.php
index d5aa2ca14f6..1a061c0a9a7 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Comment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Comment/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Creditmemo_Comment_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_creditmemo_comment');
- }
-
/**
* @param int $creditmemoId
* @return $this
@@ -46,4 +41,8 @@ public function setCreatedAtOrder($order = 'desc')
$this->setOrder('created_at', $order);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_creditmemo_comment');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Item/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Item/Collection.php
index c919bba7b2e..54f8ea15e9c 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Creditmemo/Item/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Creditmemo_Item_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_creditmemo_item');
- }
-
/**
* @param int $creditmemoId
* @return $this
@@ -36,4 +31,8 @@ public function setCreditmemoFilter($creditmemoId)
$this->addAttributeToFilter('parent_id', $creditmemoId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_creditmemo_item');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Collection.php
index bc358105ee0..9cbddf57067 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Invoice_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_invoice');
- }
-
/**
* @param Mage_Sales_Model_Order $order
* @return $this
@@ -41,4 +36,8 @@ public function setOrderFilter($order)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_invoice');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Comment/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Comment/Collection.php
index 3af1ffaef83..c2da348e8d2 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Comment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Comment/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Invoice_Comment_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_invoice_comment');
- }
-
/**
* @param int $invoiceId
* @return $this
@@ -46,4 +41,8 @@ public function setCreatedAtOrder($order = 'desc')
$this->setOrder('created_at', $order);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_invoice_comment');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Item/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Item/Collection.php
index d81edc8d80b..deadc94cba0 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Invoice/Item/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Invoice_Item_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_invoice_item');
- }
-
/**
* @param int $invoiceId
* @return $this
@@ -36,4 +31,8 @@ public function setInvoiceFilter($invoiceId)
$this->addAttributeToFilter('parent_id', $invoiceId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_invoice_item');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Payment/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Payment/Collection.php
index e540967f3f4..e4bfb2e4adb 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Payment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Payment/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Payment_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_payment');
- }
-
/**
* @param int $orderId
* @return $this
@@ -36,4 +31,8 @@ public function setOrderFilter($orderId)
$this->addAttributeToFilter('parent_id', $orderId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_payment');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Collection.php
index 1ad46d64a25..70765b732d6 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Shipment_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_shipment');
- }
-
/**
* @param Mage_Sales_Model_Order $order
* @return $this
@@ -41,4 +36,8 @@ public function setOrderFilter($order)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_shipment');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Comment/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Comment/Collection.php
index 48aa0350eb6..5132eb2a7f0 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Comment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Comment/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Shipment_Comment_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_shipment_comment');
- }
-
/**
* @param int $shipmentId
* @return $this
@@ -46,4 +41,8 @@ public function setCreatedAtOrder($order = 'desc')
$this->setOrder('created_at', $order);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_shipment_comment');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Item/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Item/Collection.php
index 3d0327c210f..97a22f85797 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Item/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Shipment_Item_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_shipment_item');
- }
-
/**
* @param int $shipmentId
* @return $this
@@ -36,4 +31,8 @@ public function setShipmentFilter($shipmentId)
$this->addAttributeToFilter('parent_id', $shipmentId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_shipment_item');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Order/Status/History/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Order/Status/History/Collection.php
index 2064fad930f..e4681c42285 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Order/Status/History/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Order/Status/History/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Order_Status_History_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_status_history');
- }
-
/**
* @param int $orderId
* @return $this
@@ -36,4 +31,8 @@ public function setOrderFilter($orderId)
$this->addAttributeToFilter('parent_id', $orderId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_status_history');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Quote.php b/app/code/core/Mage/Sales/Model/Entity/Quote.php
index 46766a38111..4cfb533820a 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Quote.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Quote.php
@@ -31,22 +31,6 @@ public function __construct()
);
}
- /**
- * Retrieve select object for loading base entity row
- *
- * @param Varien_Object|Mage_Sales_Model_Quote $object
- * @param int $rowId
- * @return Zend_Db_Select
- */
- protected function _getLoadRowSelect($object, $rowId)
- {
- $select = parent::_getLoadRowSelect($object, $rowId);
- if ($object->getSharedStoreIds()) {
- $select->where('store_id IN (?)', $object->getSharedStoreIds());
- }
- return $select;
- }
-
/**
* Loading quote by customer identifier
*
@@ -112,4 +96,20 @@ public function getReservedOrderId($quote)
{
return Mage::getSingleton('eav/config')->getEntityType(Mage_Sales_Model_Order::ENTITY)->fetchNewIncrementId($quote->getStoreId());
}
+
+ /**
+ * Retrieve select object for loading base entity row
+ *
+ * @param Varien_Object|Mage_Sales_Model_Quote $object
+ * @param int $rowId
+ * @return Zend_Db_Select
+ */
+ protected function _getLoadRowSelect($object, $rowId)
+ {
+ $select = parent::_getLoadRowSelect($object, $rowId);
+ if ($object->getSharedStoreIds()) {
+ $select->where('store_id IN (?)', $object->getSharedStoreIds());
+ }
+ return $select;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Collection.php
index 5b414bd55fd..4613d0600e7 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Quote_Address_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/quote_address');
- }
-
/**
* @param int $quoteId
* @return $this
@@ -36,4 +31,8 @@ public function setQuoteFilter($quoteId)
$this->addAttributeToFilter('parent_id', $quoteId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote_address');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Item/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Item/Collection.php
index e6ef2271822..97c7390f802 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Item/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Quote_Address_Item_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/quote_address_item');
- }
-
/**
* @param int $addressId
* @return $this
@@ -36,4 +31,8 @@ public function setAddressFilter($addressId)
$this->addAttributeToFilter('parent_id', $addressId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote_address_item');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Rate/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Rate/Collection.php
index 4bfcf5f4d7d..87a9cbfe93c 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Rate/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Quote/Address/Rate/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Quote_Address_Rate_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/quote_address_rate');
- }
-
/**
* @param int $addressId
* @return $this
@@ -36,4 +31,8 @@ public function setAddressFilter($addressId)
$this->addAttributeToFilter('parent_id', $addressId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote_address_rate');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Entity/Quote/Item/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Quote/Item/Collection.php
index 2f64ad50256..0c297fb7f58 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Quote/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Quote/Item/Collection.php
@@ -29,11 +29,6 @@ class Mage_Sales_Model_Entity_Quote_Item_Collection extends Mage_Eav_Model_Entit
*/
protected $_quote;
- protected function _construct()
- {
- $this->_init('sales/quote_item');
- }
-
/**
* @return int
*/
@@ -53,6 +48,11 @@ public function setQuote($quote)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote_item');
+ }
+
/**
* @return $this
*/
diff --git a/app/code/core/Mage/Sales/Model/Entity/Quote/Payment/Collection.php b/app/code/core/Mage/Sales/Model/Entity/Quote/Payment/Collection.php
index 628ade38b1e..5259ce15a6a 100644
--- a/app/code/core/Mage/Sales/Model/Entity/Quote/Payment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Entity/Quote/Payment/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Entity_Quote_Payment_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/quote_payment');
- }
-
/**
* @param int $quoteId
* @return $this
@@ -36,4 +31,8 @@ public function setQuoteFilter($quoteId)
$this->addAttributeToFilter('parent_id', $quoteId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote_payment');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Observer.php b/app/code/core/Mage/Sales/Model/Observer.php
index 6863e0111bc..d62766efec8 100644
--- a/app/code/core/Mage/Sales/Model/Observer.php
+++ b/app/code/core/Mage/Sales/Model/Observer.php
@@ -374,47 +374,6 @@ public function addVatRequestParamsOrderComment(Varien_Event_Observer $observer)
}
}
- /**
- * Retrieve sales address (order or quote) on which tax calculation must be based
- *
- * @param Mage_Core_Model_Abstract $salesModel
- * @param Mage_Core_Model_Store|string|int|null $store
- * @return Mage_Customer_Model_Address_Abstract|null
- */
- protected function _getVatRequiredSalesAddress($salesModel, $store = null)
- {
- $configAddressType = Mage::helper('customer/address')->getTaxCalculationAddressType($store);
- $requiredAddress = null;
- switch ($configAddressType) {
- case Mage_Customer_Model_Address_Abstract::TYPE_SHIPPING:
- $requiredAddress = $salesModel->getShippingAddress();
- break;
- default:
- $requiredAddress = $salesModel->getBillingAddress();
- }
- return $requiredAddress;
- }
-
- /**
- * Retrieve customer address (default billing or default shipping) ID on which tax calculation must be based
- *
- * @param Mage_Core_Model_Store|string|int|null $store
- * @return int|string
- */
- protected function _getVatRequiredCustomerAddress(Mage_Customer_Model_Customer $customer, $store = null)
- {
- $configAddressType = Mage::helper('customer/address')->getTaxCalculationAddressType($store);
- $requiredAddress = null;
- switch ($configAddressType) {
- case Mage_Customer_Model_Address_Abstract::TYPE_SHIPPING:
- $requiredAddress = $customer->getDefaultShipping();
- break;
- default:
- $requiredAddress = $customer->getDefaultBilling();
- }
- return $requiredAddress;
- }
-
/**
* Handle customer VAT number if needed on collect_totals_before event of quote address
*/
@@ -531,4 +490,45 @@ public function restoreQuoteCustomerGroupId($observer)
$quoteAddress->unsPrevQuoteCustomerGroupId();
}
}
+
+ /**
+ * Retrieve sales address (order or quote) on which tax calculation must be based
+ *
+ * @param Mage_Core_Model_Abstract $salesModel
+ * @param Mage_Core_Model_Store|string|int|null $store
+ * @return Mage_Customer_Model_Address_Abstract|null
+ */
+ protected function _getVatRequiredSalesAddress($salesModel, $store = null)
+ {
+ $configAddressType = Mage::helper('customer/address')->getTaxCalculationAddressType($store);
+ $requiredAddress = null;
+ switch ($configAddressType) {
+ case Mage_Customer_Model_Address_Abstract::TYPE_SHIPPING:
+ $requiredAddress = $salesModel->getShippingAddress();
+ break;
+ default:
+ $requiredAddress = $salesModel->getBillingAddress();
+ }
+ return $requiredAddress;
+ }
+
+ /**
+ * Retrieve customer address (default billing or default shipping) ID on which tax calculation must be based
+ *
+ * @param Mage_Core_Model_Store|string|int|null $store
+ * @return int|string
+ */
+ protected function _getVatRequiredCustomerAddress(Mage_Customer_Model_Customer $customer, $store = null)
+ {
+ $configAddressType = Mage::helper('customer/address')->getTaxCalculationAddressType($store);
+ $requiredAddress = null;
+ switch ($configAddressType) {
+ case Mage_Customer_Model_Address_Abstract::TYPE_SHIPPING:
+ $requiredAddress = $customer->getDefaultShipping();
+ break;
+ default:
+ $requiredAddress = $customer->getDefaultBilling();
+ }
+ return $requiredAddress;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Order.php b/app/code/core/Mage/Sales/Model/Order.php
index 46cd0b0c403..903c0d439ef 100644
--- a/app/code/core/Mage/Sales/Model/Order.php
+++ b/app/code/core/Mage/Sales/Model/Order.php
@@ -499,28 +499,6 @@ class Mage_Sales_Model_Order extends Mage_Sales_Model_Abstract
*/
protected $_historyEntityName = self::HISTORY_ENTITY_NAME;
- protected function _construct()
- {
- $this->_init('sales/order');
- }
-
- /**
- * Init mapping array of short fields to
- * its full names
- *
- * @return Varien_Object
- */
- protected function _initOldFieldsMap()
- {
- // pre 1.6 fields names, old => new
- $this->_oldFieldsMap = [
- 'payment_authorization_expiration' => 'payment_auth_expiration',
- 'forced_do_shipment_with_invoice' => 'forced_shipment_with_invoice',
- 'base_shipping_hidden_tax_amount' => 'base_shipping_hidden_tax_amnt',
- ];
- return $this;
- }
-
/**
* Clear order object data
*
@@ -675,19 +653,6 @@ public function canVoidPayment()
return $this->_canVoidOrder() ? $this->getPayment()->canVoid($this->getPayment()) : false;
}
- /**
- * Check whether order could be canceled by states and flags
- *
- * @return bool
- */
- protected function _canVoidOrder()
- {
- if ($this->canUnhold() || $this->isPaymentReview()) {
- return false;
- }
- return true;
- }
-
/**
* Retrieve order invoice availability
*
@@ -873,61 +838,6 @@ public function canReorderIgnoreSalable()
return $this->_canReorder(true);
}
- /**
- * Retrieve order reorder availability
- *
- * @param bool $ignoreSalable
- * @return bool
- */
- protected function _canReorder($ignoreSalable = false)
- {
- if ($this->canUnhold() || $this->isPaymentReview()) {
- return false;
- }
-
- if ($this->getActionFlag(self::ACTION_FLAG_REORDER) === false) {
- return false;
- }
-
- $products = [];
- foreach ($this->getItemsCollection() as $item) {
- $products[] = $item->getProductId();
- }
-
- if (!empty($products)) {
- /*
- * @TODO ACPAOC: Use product collection here, but ensure that product
- * is loaded with order store id, otherwise there'll be problems with isSalable()
- * for configurables, bundles and other composites
- *
- */
- /*
- $productsCollection = Mage::getModel('catalog/product')->getCollection()
- ->setStoreId($this->getStoreId())
- ->addIdFilter($products)
- ->addAttributeToSelect('status')
- ->load();
-
- foreach ($productsCollection as $product) {
- if (!$product->isSalable()) {
- return false;
- }
- }
- */
-
- foreach ($products as $productId) {
- $product = Mage::getModel('catalog/product')
- ->setStoreId($this->getStoreId())
- ->load($productId);
- if (!$product->getId() || (!$ignoreSalable && !$product->isSalable())) {
- return false;
- }
- }
- }
-
- return true;
- }
-
/**
* Check whether the payment is in payment review state
* In this state order cannot be normally processed. Possible actions can be:
@@ -971,17 +881,6 @@ public function getConfig()
return Mage::getSingleton('sales/order_config');
}
- /**
- * Place order payments
- *
- * @return $this
- */
- protected function _placePayment()
- {
- $this->getPayment()->place();
- return $this;
- }
-
/**
* Retrieve order payment model object
*
@@ -1073,47 +972,6 @@ public function setState($state, $status = false, $comment = '', $isCustomerNoti
return $this->_setState($state, $status, $comment, $isCustomerNotified, true);
}
- /**
- * Order state protected setter.
- * By default allows to set any state. Can also update status to default or specified value
- * Сomplete and closed states are encapsulated intentionally, see the _checkState()
- *
- * @param string $state
- * @param string|bool $status
- * @param string $comment
- * @param bool $isCustomerNotified
- * @param bool $shouldProtectState
- * @return $this
- */
- protected function _setState(
- $state,
- $status = false,
- $comment = '',
- $isCustomerNotified = null,
- $shouldProtectState = false
- ) {
- // attempt to set the specified state
- if ($shouldProtectState) {
- if ($this->isStateProtected($state)) {
- Mage::throwException(
- Mage::helper('sales')->__('The Order State "%s" must not be set manually.', $state),
- );
- }
- }
- $this->setData('state', $state);
-
- // add status history
- if ($status) {
- if ($status === true) {
- $status = $this->getConfig()->getStateDefaultStatus($state);
- }
- $this->setStatus($status);
- $history = $this->addStatusHistoryComment($comment, false); // no sense to set $status again
- $history->setIsCustomerNotified($isCustomerNotified); // for backwards compatibility
- }
- return $this;
- }
-
/**
* Whether specified state can be set from outside
* @param string $state
@@ -1586,19 +1444,6 @@ public function sendOrderUpdateEmail($notifyCustomer = true, $comment = '')
return $this;
}
- /**
- * @param string $configPath
- * @return array|false
- */
- protected function _getEmails($configPath)
- {
- $data = Mage::getStoreConfig($configPath, $this->getStoreId());
- if (!empty($data)) {
- return explode(',', $data);
- }
- return false;
- }
-
/*********************** ADDRESSES ***************************/
/**
@@ -1696,47 +1541,6 @@ public function getParentItemsRandomCollection($limit = 1)
return $this->_getItemsRandomCollection($limit, true);
}
- /**
- * Get random items collection with or without related children
- *
- * @param int $limit
- * @param bool $nonChildrenOnly
- * @return Mage_Sales_Model_Resource_Order_Item_Collection
- */
- protected function _getItemsRandomCollection($limit, $nonChildrenOnly = false)
- {
- $collection = Mage::getModel('sales/order_item')->getCollection()
- ->setOrderFilter($this)
- ->setRandomOrder();
-
- if ($nonChildrenOnly) {
- $collection->filterByParent();
- }
- $products = [];
- /** @var Mage_Sales_Model_Order_Item $item */
- foreach ($collection as $item) {
- $products[] = $item->getProductId();
- }
-
- $productsCollection = Mage::getModel('catalog/product')
- ->getCollection()
- ->addIdFilter($products)
- ->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInSiteIds())
- /* Price data is added to consider item stock status using price index */
- ->addPriceData()
- ->setPageSize($limit)
- ->load();
-
- foreach ($collection as $item) {
- $product = $productsCollection->getItemById($item->getProductId());
- if ($product) {
- $item->setProduct($product);
- }
- }
-
- return $collection;
- }
-
/**
* @return Mage_Sales_Model_Order_Item[]
*/
@@ -2315,43 +2119,325 @@ public function getEmailCustomerNote()
}
/**
- * Processing object before save data
- *
- * @return Mage_Core_Model_Abstract
+ * @return string
*/
- protected function _beforeSave()
+ public function getStoreGroupName()
{
- parent::_beforeSave();
- $this->_checkState();
- if (!$this->getId()) {
- $store = $this->getStore();
- $name = [$store->getWebsite()->getName(),$store->getGroup()->getName(),$store->getName()];
- $this->setStoreName(implode("\n", $name));
+ $storeId = $this->getStoreId();
+ if (is_null($storeId)) {
+ return $this->getStoreName(1); // 0 - website name, 1 - store group name, 2 - store name
}
+ return $this->getStore()->getGroup()->getName();
+ }
- if (!$this->getIncrementId()) {
- $incrementId = Mage::getSingleton('eav/config')
- ->getEntityType('order')
- ->fetchNewIncrementId($this->getStoreId());
- $this->setIncrementId($incrementId);
- }
+ /**
+ * Resets all data in object
+ * so after another load it will be complete new object
+ *
+ * @return $this
+ */
+ public function reset()
+ {
+ $this->unsetData();
+ $this->_actionFlag = [];
+ $this->_addresses = null;
+ $this->_items = null;
+ $this->_payments = null;
+ $this->_statusHistory = null;
+ $this->_invoices = null;
+ $this->_tracks = null;
+ $this->_shipments = null;
+ $this->_creditmemos = null;
+ $this->_relatedObjects = [];
+ $this->_orderCurrency = null;
+ $this->_baseCurrency = null;
- /**
- * Process items dependency for new order
- */
- if (!$this->getId()) {
- $itemsCount = 0;
- foreach ($this->getAllItems() as $item) {
- $parent = $item->getQuoteParentItemId();
- if ($parent && !$item->getParentItem()) {
- $item->setParentItem($this->getItemByQuoteItemId($parent));
- } elseif (!$parent) {
- $itemsCount++;
- }
- }
- // Set items count
- $this->setTotalItemCount($itemsCount);
- }
+ return $this;
+ }
+
+ /**
+ * @return bool
+ */
+ public function getIsNotVirtual()
+ {
+ return !$this->getIsVirtual();
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getFullTaxInfo()
+ {
+ $rates = Mage::getModel('tax/sales_order_tax')->getCollection()->loadByOrder($this)->toArray();
+ return Mage::getSingleton('tax/calculation')->reproduceProcess($rates['items']);
+ }
+
+ /**
+ * Create new invoice with maximum qty for invoice for each item
+ *
+ * @param array $qtys
+ * @return Mage_Sales_Model_Order_Invoice
+ */
+ public function prepareInvoice($qtys = [])
+ {
+ return Mage::getModel('sales/service_order', $this)->prepareInvoice($qtys);
+ }
+
+ /**
+ * Create new shipment with maximum qty for shipping for each item
+ *
+ * @param array $qtys
+ * @return Mage_Sales_Model_Order_Shipment
+ */
+ public function prepareShipment($qtys = [])
+ {
+ return Mage::getModel('sales/service_order', $this)->prepareShipment($qtys);
+ }
+
+ /**
+ * Check whether order is canceled
+ *
+ * @return bool
+ */
+ public function isCanceled()
+ {
+ return ($this->getState() === self::STATE_CANCELED);
+ }
+
+ protected function _construct()
+ {
+ $this->_init('sales/order');
+ }
+
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return Varien_Object
+ */
+ protected function _initOldFieldsMap()
+ {
+ // pre 1.6 fields names, old => new
+ $this->_oldFieldsMap = [
+ 'payment_authorization_expiration' => 'payment_auth_expiration',
+ 'forced_do_shipment_with_invoice' => 'forced_shipment_with_invoice',
+ 'base_shipping_hidden_tax_amount' => 'base_shipping_hidden_tax_amnt',
+ ];
+ return $this;
+ }
+
+ /**
+ * Check whether order could be canceled by states and flags
+ *
+ * @return bool
+ */
+ protected function _canVoidOrder()
+ {
+ if ($this->canUnhold() || $this->isPaymentReview()) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Retrieve order reorder availability
+ *
+ * @param bool $ignoreSalable
+ * @return bool
+ */
+ protected function _canReorder($ignoreSalable = false)
+ {
+ if ($this->canUnhold() || $this->isPaymentReview()) {
+ return false;
+ }
+
+ if ($this->getActionFlag(self::ACTION_FLAG_REORDER) === false) {
+ return false;
+ }
+
+ $products = [];
+ foreach ($this->getItemsCollection() as $item) {
+ $products[] = $item->getProductId();
+ }
+
+ if (!empty($products)) {
+ /*
+ * @TODO ACPAOC: Use product collection here, but ensure that product
+ * is loaded with order store id, otherwise there'll be problems with isSalable()
+ * for configurables, bundles and other composites
+ *
+ */
+ /*
+ $productsCollection = Mage::getModel('catalog/product')->getCollection()
+ ->setStoreId($this->getStoreId())
+ ->addIdFilter($products)
+ ->addAttributeToSelect('status')
+ ->load();
+
+ foreach ($productsCollection as $product) {
+ if (!$product->isSalable()) {
+ return false;
+ }
+ }
+ */
+
+ foreach ($products as $productId) {
+ $product = Mage::getModel('catalog/product')
+ ->setStoreId($this->getStoreId())
+ ->load($productId);
+ if (!$product->getId() || (!$ignoreSalable && !$product->isSalable())) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Place order payments
+ *
+ * @return $this
+ */
+ protected function _placePayment()
+ {
+ $this->getPayment()->place();
+ return $this;
+ }
+
+ /**
+ * Order state protected setter.
+ * By default allows to set any state. Can also update status to default or specified value
+ * Сomplete and closed states are encapsulated intentionally, see the _checkState()
+ *
+ * @param string $state
+ * @param string|bool $status
+ * @param string $comment
+ * @param bool $isCustomerNotified
+ * @param bool $shouldProtectState
+ * @return $this
+ */
+ protected function _setState(
+ $state,
+ $status = false,
+ $comment = '',
+ $isCustomerNotified = null,
+ $shouldProtectState = false
+ ) {
+ // attempt to set the specified state
+ if ($shouldProtectState) {
+ if ($this->isStateProtected($state)) {
+ Mage::throwException(
+ Mage::helper('sales')->__('The Order State "%s" must not be set manually.', $state),
+ );
+ }
+ }
+ $this->setData('state', $state);
+
+ // add status history
+ if ($status) {
+ if ($status === true) {
+ $status = $this->getConfig()->getStateDefaultStatus($state);
+ }
+ $this->setStatus($status);
+ $history = $this->addStatusHistoryComment($comment, false); // no sense to set $status again
+ $history->setIsCustomerNotified($isCustomerNotified); // for backwards compatibility
+ }
+ return $this;
+ }
+
+ /**
+ * @param string $configPath
+ * @return array|false
+ */
+ protected function _getEmails($configPath)
+ {
+ $data = Mage::getStoreConfig($configPath, $this->getStoreId());
+ if (!empty($data)) {
+ return explode(',', $data);
+ }
+ return false;
+ }
+
+ /**
+ * Get random items collection with or without related children
+ *
+ * @param int $limit
+ * @param bool $nonChildrenOnly
+ * @return Mage_Sales_Model_Resource_Order_Item_Collection
+ */
+ protected function _getItemsRandomCollection($limit, $nonChildrenOnly = false)
+ {
+ $collection = Mage::getModel('sales/order_item')->getCollection()
+ ->setOrderFilter($this)
+ ->setRandomOrder();
+
+ if ($nonChildrenOnly) {
+ $collection->filterByParent();
+ }
+ $products = [];
+ /** @var Mage_Sales_Model_Order_Item $item */
+ foreach ($collection as $item) {
+ $products[] = $item->getProductId();
+ }
+
+ $productsCollection = Mage::getModel('catalog/product')
+ ->getCollection()
+ ->addIdFilter($products)
+ ->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInSiteIds())
+ /* Price data is added to consider item stock status using price index */
+ ->addPriceData()
+ ->setPageSize($limit)
+ ->load();
+
+ foreach ($collection as $item) {
+ $product = $productsCollection->getItemById($item->getProductId());
+ if ($product) {
+ $item->setProduct($product);
+ }
+ }
+
+ return $collection;
+ }
+
+ /**
+ * Processing object before save data
+ *
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ $this->_checkState();
+ if (!$this->getId()) {
+ $store = $this->getStore();
+ $name = [$store->getWebsite()->getName(),$store->getGroup()->getName(),$store->getName()];
+ $this->setStoreName(implode("\n", $name));
+ }
+
+ if (!$this->getIncrementId()) {
+ $incrementId = Mage::getSingleton('eav/config')
+ ->getEntityType('order')
+ ->fetchNewIncrementId($this->getStoreId());
+ $this->setIncrementId($incrementId);
+ }
+
+ /**
+ * Process items dependency for new order
+ */
+ if (!$this->getId()) {
+ $itemsCount = 0;
+ foreach ($this->getAllItems() as $item) {
+ $parent = $item->getQuoteParentItemId();
+ if ($parent && !$item->getParentItem()) {
+ $item->setParentItem($this->getItemByQuoteItemId($parent));
+ } elseif (!$parent) {
+ $itemsCount++;
+ }
+ }
+ // Set items count
+ $this->setTotalItemCount($itemsCount);
+ }
if ($this->getCustomer()) {
$this->setCustomerId($this->getCustomer()->getId());
}
@@ -2455,92 +2541,6 @@ protected function _afterSave()
return parent::_afterSave();
}
- /**
- * @return string
- */
- public function getStoreGroupName()
- {
- $storeId = $this->getStoreId();
- if (is_null($storeId)) {
- return $this->getStoreName(1); // 0 - website name, 1 - store group name, 2 - store name
- }
- return $this->getStore()->getGroup()->getName();
- }
-
- /**
- * Resets all data in object
- * so after another load it will be complete new object
- *
- * @return $this
- */
- public function reset()
- {
- $this->unsetData();
- $this->_actionFlag = [];
- $this->_addresses = null;
- $this->_items = null;
- $this->_payments = null;
- $this->_statusHistory = null;
- $this->_invoices = null;
- $this->_tracks = null;
- $this->_shipments = null;
- $this->_creditmemos = null;
- $this->_relatedObjects = [];
- $this->_orderCurrency = null;
- $this->_baseCurrency = null;
-
- return $this;
- }
-
- /**
- * @return bool
- */
- public function getIsNotVirtual()
- {
- return !$this->getIsVirtual();
- }
-
- /**
- * @return mixed
- */
- public function getFullTaxInfo()
- {
- $rates = Mage::getModel('tax/sales_order_tax')->getCollection()->loadByOrder($this)->toArray();
- return Mage::getSingleton('tax/calculation')->reproduceProcess($rates['items']);
- }
-
- /**
- * Create new invoice with maximum qty for invoice for each item
- *
- * @param array $qtys
- * @return Mage_Sales_Model_Order_Invoice
- */
- public function prepareInvoice($qtys = [])
- {
- return Mage::getModel('sales/service_order', $this)->prepareInvoice($qtys);
- }
-
- /**
- * Create new shipment with maximum qty for shipping for each item
- *
- * @param array $qtys
- * @return Mage_Sales_Model_Order_Shipment
- */
- public function prepareShipment($qtys = [])
- {
- return Mage::getModel('sales/service_order', $this)->prepareShipment($qtys);
- }
-
- /**
- * Check whether order is canceled
- *
- * @return bool
- */
- public function isCanceled()
- {
- return ($this->getState() === self::STATE_CANCELED);
- }
-
/**
* Protect order delete from not admin scope
* @inheritDoc
diff --git a/app/code/core/Mage/Sales/Model/Order/Address.php b/app/code/core/Mage/Sales/Model/Order/Address.php
index 2552e88d8af..138d0947429 100644
--- a/app/code/core/Mage/Sales/Model/Order/Address.php
+++ b/app/code/core/Mage/Sales/Model/Order/Address.php
@@ -86,24 +86,6 @@ class Mage_Sales_Model_Order_Address extends Mage_Customer_Model_Address_Abstrac
protected $_eventPrefix = 'sales_order_address';
protected $_eventObject = 'address';
- /**
- * Initialize resource
- */
- protected function _construct()
- {
- $this->_init('sales/order_address');
- }
-
- /**
- * Init mapping array of short fields to its full names
- *
- * @return $this
- */
- protected function _initOldFieldsMap()
- {
- return $this;
- }
-
/**
* Set order
*
@@ -128,6 +110,24 @@ public function getOrder()
return $this->_order;
}
+ /**
+ * Initialize resource
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/order_address');
+ }
+
+ /**
+ * Init mapping array of short fields to its full names
+ *
+ * @return $this
+ */
+ protected function _initOldFieldsMap()
+ {
+ return $this;
+ }
+
/**
* Before object save manipulations
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Api.php b/app/code/core/Mage/Sales/Model/Order/Api.php
index 1e6cc562857..138c6e5ad94 100644
--- a/app/code/core/Mage/Sales/Model/Order/Api.php
+++ b/app/code/core/Mage/Sales/Model/Order/Api.php
@@ -34,27 +34,6 @@ public function __construct()
];
}
- /**
- * Initialize basic order model
- *
- * @param mixed $orderIncrementId
- * @return Mage_Sales_Model_Order
- */
- protected function _initOrder($orderIncrementId)
- {
- $order = Mage::getModel('sales/order');
-
- /** @var Mage_Sales_Model_Order $order */
-
- $order->loadByIncrementId($orderIncrementId);
-
- if (!$order->getId()) {
- $this->_fault('not_exists');
- }
-
- return $order;
- }
-
/**
* Retrieve list of orders. Filtration could be applied
*
@@ -267,4 +246,25 @@ public function cancel($orderIncrementId)
}
return true;
}
+
+ /**
+ * Initialize basic order model
+ *
+ * @param mixed $orderIncrementId
+ * @return Mage_Sales_Model_Order
+ */
+ protected function _initOrder($orderIncrementId)
+ {
+ $order = Mage::getModel('sales/order');
+
+ /** @var Mage_Sales_Model_Order $order */
+
+ $order->loadByIncrementId($orderIncrementId);
+
+ if (!$order->getId()) {
+ $this->_fault('not_exists');
+ }
+
+ return $order;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Config.php b/app/code/core/Mage/Sales/Model/Order/Config.php
index 8c692e89d5d..8b8ecf1bd4c 100644
--- a/app/code/core/Mage/Sales/Model/Order/Config.php
+++ b/app/code/core/Mage/Sales/Model/Order/Config.php
@@ -48,24 +48,6 @@ public function __construct()
parent::__construct(Mage::getConfig()->getNode('global/sales/order'));
}
- /**
- * @param string $status
- * @return Varien_Simplexml_Element
- */
- protected function _getStatus($status)
- {
- return $this->getNode('statuses/' . $status);
- }
-
- /**
- * @param string $state
- * @return Varien_Simplexml_Element
- */
- protected function _getState($state)
- {
- return $this->getNode('states/' . $state);
- }
-
/**
* Retrieve default status for state
*
@@ -225,6 +207,24 @@ public function getInvisibleOnFrontStates()
return $this->_states['invisible'];
}
+ /**
+ * @param string $status
+ * @return Varien_Simplexml_Element
+ */
+ protected function _getStatus($status)
+ {
+ return $this->getNode('statuses/' . $status);
+ }
+
+ /**
+ * @param string $state
+ * @return Varien_Simplexml_Element
+ */
+ protected function _getState($state)
+ {
+ return $this->getNode('states/' . $state);
+ }
+
/**
* If not yet initialized, loads the "_states" array object.
*/
diff --git a/app/code/core/Mage/Sales/Model/Order/Creditmemo.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo.php
index 1e41b6915ab..a429404e202 100644
--- a/app/code/core/Mage/Sales/Model/Order/Creditmemo.php
+++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo.php
@@ -199,24 +199,6 @@ class Mage_Sales_Model_Order_Creditmemo extends Mage_Sales_Model_Abstract
protected $_eventPrefix = 'sales_order_creditmemo';
protected $_eventObject = 'creditmemo';
- /**
- * Initialize creditmemo resource model
- */
- protected function _construct()
- {
- $this->_init('sales/order_creditmemo');
- }
-
- /**
- * Init mapping array of short fields to its full names
- *
- * @return $this
- */
- protected function _initOldFieldsMap()
- {
- return $this;
- }
-
/**
* Retrieve Creditmemo configuration model
*
@@ -906,6 +888,50 @@ public function sendUpdateEmail($notifyCustomer = true, $comment = '')
return $this;
}
+ /**
+ * Get creditmemos collection filtered by $filter
+ *
+ * @param array|null $filter
+ * @return Mage_Sales_Model_Resource_Order_Creditmemo_Collection
+ */
+ public function getFilteredCollectionItems($filter = null)
+ {
+ return $this->getResourceCollection()->getFiltered($filter);
+ }
+
+ /**
+ * Checking if the credit memo is last
+ *
+ * @return bool
+ */
+ public function isLast()
+ {
+ foreach ($this->getAllItems() as $item) {
+ if (!$item->isLast()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Initialize creditmemo resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/order_creditmemo');
+ }
+
+ /**
+ * Init mapping array of short fields to its full names
+ *
+ * @return $this
+ */
+ protected function _initOldFieldsMap()
+ {
+ return $this;
+ }
+
/**
* @param string $configPath
* @return array|bool
@@ -967,30 +993,4 @@ protected function _beforeSave()
return $this;
}
-
- /**
- * Get creditmemos collection filtered by $filter
- *
- * @param array|null $filter
- * @return Mage_Sales_Model_Resource_Order_Creditmemo_Collection
- */
- public function getFilteredCollectionItems($filter = null)
- {
- return $this->getResourceCollection()->getFiltered($filter);
- }
-
- /**
- * Checking if the credit memo is last
- *
- * @return bool
- */
- public function isLast()
- {
- foreach ($this->getAllItems() as $item) {
- if (!$item->isLast()) {
- return false;
- }
- }
- return true;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api.php
index 3649df842f9..697073dccf2 100644
--- a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api.php
+++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api.php
@@ -59,27 +59,6 @@ public function items($filters = null)
return $creditmemos;
}
- /**
- * Make filter of appropriate format for list method
- *
- * @deprecated since 1.7.0.1
- * @param array|null $filter
- * @return array|null
- */
- protected function _prepareListFilter($filter = null)
- {
- // prepare filter, map field creditmemo_id to entity_id
- if (is_array($filter)) {
- foreach ($filter as $field => $value) {
- if (isset($this->_attributesMap['creditmemo'][$field])) {
- $filter[$this->_attributesMap['creditmemo'][$field]] = $value;
- unset($filter[$field]);
- }
- }
- }
- return $filter;
- }
-
/**
* Retrieve credit memo information
*
@@ -225,6 +204,27 @@ public function cancel($creditmemoIncrementId)
return true;
}
+ /**
+ * Make filter of appropriate format for list method
+ *
+ * @deprecated since 1.7.0.1
+ * @param array|null $filter
+ * @return array|null
+ */
+ protected function _prepareListFilter($filter = null)
+ {
+ // prepare filter, map field creditmemo_id to entity_id
+ if (is_array($filter)) {
+ foreach ($filter as $field => $value) {
+ if (isset($this->_attributesMap['creditmemo'][$field])) {
+ $filter[$this->_attributesMap['creditmemo'][$field]] = $value;
+ unset($filter[$field]);
+ }
+ }
+ }
+ return $filter;
+ }
+
/**
* Hook method, could be replaced in derived classes
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Comment.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Comment.php
index 822d99bf1cb..4e2ce7ebc43 100644
--- a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Comment.php
+++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Comment.php
@@ -41,11 +41,6 @@ class Mage_Sales_Model_Order_Creditmemo_Comment extends Mage_Sales_Model_Abstrac
*/
protected $_creditmemo;
- protected function _construct()
- {
- $this->_init('sales/order_creditmemo_comment');
- }
-
/**
* Declare Creditmemo instance
*
@@ -80,6 +75,11 @@ public function getStore()
return Mage::app()->getStore();
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_creditmemo_comment');
+ }
+
/**
* Before object save
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Item.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Item.php
index 7f12752de69..02843c291ec 100644
--- a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Item.php
+++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Item.php
@@ -128,21 +128,6 @@ public function setCreditmemo(Mage_Sales_Model_Order_Creditmemo $creditmemo)
return $this;
}
- /**
- * Init mapping array of short fields to
- * its full names
- *
- * @return Varien_Object
- */
- protected function _initOldFieldsMap()
- {
- // pre 1.6 fields names, old => new
- $this->_oldFieldsMap = [
- 'base_weee_tax_applied_row_amount' => 'base_weee_tax_applied_row_amnt',
- ];
- return $this;
- }
-
/**
* Retrieve creditmemo instance
*
@@ -305,6 +290,21 @@ public function isLast()
return false;
}
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return Varien_Object
+ */
+ protected function _initOldFieldsMap()
+ {
+ // pre 1.6 fields names, old => new
+ $this->_oldFieldsMap = [
+ 'base_weee_tax_applied_row_amount' => 'base_weee_tax_applied_row_amnt',
+ ];
+ return $this;
+ }
+
/**
* Before object save
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Invoice.php b/app/code/core/Mage/Sales/Model/Order/Invoice.php
index 6198f7d434f..836342219ce 100644
--- a/app/code/core/Mage/Sales/Model/Order/Invoice.php
+++ b/app/code/core/Mage/Sales/Model/Order/Invoice.php
@@ -194,24 +194,6 @@ public function destruct()
}
}
- /**
- * Initialize invoice resource model
- */
- protected function _construct()
- {
- $this->_init('sales/order_invoice');
- }
-
- /**
- * Init mapping array of short fields to its full names
- *
- * @return $this
- */
- protected function _initOldFieldsMap()
- {
- return $this;
- }
-
/**
* Load invoice by increment id
*
@@ -938,6 +920,41 @@ public function sendUpdateEmail($notifyCustomer = true, $comment = '')
return $this;
}
+ /**
+ * Reset invoice object
+ *
+ * @return $this
+ */
+ public function reset()
+ {
+ $this->unsetData();
+ $this->_origData = null;
+ $this->_items = null;
+ $this->_comments = null;
+ $this->_order = null;
+ $this->_saveBeforeDestruct = false;
+ $this->_wasPayCalled = false;
+ return $this;
+ }
+
+ /**
+ * Initialize invoice resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/order_invoice');
+ }
+
+ /**
+ * Init mapping array of short fields to its full names
+ *
+ * @return $this
+ */
+ protected function _initOldFieldsMap()
+ {
+ return $this;
+ }
+
/**
* @param string $configPath
* @return array|bool
@@ -961,23 +978,6 @@ protected function _beforeDelete()
return parent::_beforeDelete();
}
- /**
- * Reset invoice object
- *
- * @return $this
- */
- public function reset()
- {
- $this->unsetData();
- $this->_origData = null;
- $this->_items = null;
- $this->_comments = null;
- $this->_order = null;
- $this->_saveBeforeDestruct = false;
- $this->_wasPayCalled = false;
- return $this;
- }
-
/**
* Before object save manipulations
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Invoice/Comment.php b/app/code/core/Mage/Sales/Model/Order/Invoice/Comment.php
index ae7035dfc54..14e005f5401 100644
--- a/app/code/core/Mage/Sales/Model/Order/Invoice/Comment.php
+++ b/app/code/core/Mage/Sales/Model/Order/Invoice/Comment.php
@@ -41,11 +41,6 @@ class Mage_Sales_Model_Order_Invoice_Comment extends Mage_Sales_Model_Abstract
*/
protected $_invoice;
- protected function _construct()
- {
- $this->_init('sales/order_invoice_comment');
- }
-
/**
* Declare invoice instance
*
@@ -80,6 +75,11 @@ public function getStore()
return Mage::app()->getStore();
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_invoice_comment');
+ }
+
/**
* Before object save
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Invoice/Item.php b/app/code/core/Mage/Sales/Model/Order/Invoice/Item.php
index 3ee7ab5916d..8f95bf9490c 100644
--- a/app/code/core/Mage/Sales/Model/Order/Invoice/Item.php
+++ b/app/code/core/Mage/Sales/Model/Order/Invoice/Item.php
@@ -104,21 +104,6 @@ public function _construct()
{
$this->_init('sales/order_invoice_item');
}
-
- /**
- * Init mapping array of short fields to
- * its full names
- *
- * @return $this
- */
- protected function _initOldFieldsMap()
- {
- // pre 1.6 fields names, old => new
- $this->_oldFieldsMap = [
- 'base_weee_tax_applied_row_amount' => 'base_weee_tax_applied_row_amnt',
- ];
- return $this;
- }
/**
* Declare invoice instance
*
@@ -292,6 +277,21 @@ public function isLast()
return false;
}
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return $this
+ */
+ protected function _initOldFieldsMap()
+ {
+ // pre 1.6 fields names, old => new
+ $this->_oldFieldsMap = [
+ 'base_weee_tax_applied_row_amount' => 'base_weee_tax_applied_row_amnt',
+ ];
+ return $this;
+ }
+
/**
* Before object save
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Item.php b/app/code/core/Mage/Sales/Model/Order/Item.php
index 79c3e5f4bd1..712722d0cac 100644
--- a/app/code/core/Mage/Sales/Model/Order/Item.php
+++ b/app/code/core/Mage/Sales/Model/Order/Item.php
@@ -219,46 +219,6 @@ class Mage_Sales_Model_Order_Item extends Mage_Core_Model_Abstract
protected $_parentItem = null;
protected $_children = [];
- /**
- * Init resource model
- */
- protected function _construct()
- {
- $this->_init('sales/order_item');
- }
-
- /**
- * Init mapping array of short fields to
- * its full names
- *
- * @return Varien_Object
- */
- protected function _initOldFieldsMap()
- {
- // pre 1.6 fields names, old => new
- $this->_oldFieldsMap = [
- 'base_weee_tax_applied_row_amount' => 'base_weee_tax_applied_row_amnt',
- ];
- return $this;
- }
-
- /**
- * Prepare data before save
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
- if (!$this->getOrderId() && $this->getOrder()) {
- $this->setOrderId($this->getOrder()->getId());
- }
- if ($this->getParentItem()) {
- $this->setParentItemId($this->getParentItem()->getId());
- }
- return $this;
- }
-
/**
* Set parent item
*
@@ -501,21 +461,6 @@ public function getStatusId()
return self::STATUS_MIXED;
}
- /**
- * Retrieve backordered qty of children items
- *
- * @return float|null
- */
- protected function _getQtyChildrenBackordered()
- {
- $backordered = null;
- foreach ($this->_children as $childItem) {
- $backordered += (float) $childItem->getQtyBackordered();
- }
-
- return $backordered;
- }
-
/**
* Retrieve status
*
@@ -856,4 +801,59 @@ public function getDiscountAppliedForWeeeTax()
}
return $totalDiscount;
}
+
+ /**
+ * Init resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/order_item');
+ }
+
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return Varien_Object
+ */
+ protected function _initOldFieldsMap()
+ {
+ // pre 1.6 fields names, old => new
+ $this->_oldFieldsMap = [
+ 'base_weee_tax_applied_row_amount' => 'base_weee_tax_applied_row_amnt',
+ ];
+ return $this;
+ }
+
+ /**
+ * Prepare data before save
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ if (!$this->getOrderId() && $this->getOrder()) {
+ $this->setOrderId($this->getOrder()->getId());
+ }
+ if ($this->getParentItem()) {
+ $this->setParentItemId($this->getParentItem()->getId());
+ }
+ return $this;
+ }
+
+ /**
+ * Retrieve backordered qty of children items
+ *
+ * @return float|null
+ */
+ protected function _getQtyChildrenBackordered()
+ {
+ $backordered = null;
+ foreach ($this->_children as $childItem) {
+ $backordered += (float) $childItem->getQtyBackordered();
+ }
+
+ return $backordered;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Payment.php b/app/code/core/Mage/Sales/Model/Order/Payment.php
index 08fb53a7556..52c1730dc4f 100644
--- a/app/code/core/Mage/Sales/Model/Order/Payment.php
+++ b/app/code/core/Mage/Sales/Model/Order/Payment.php
@@ -256,11 +256,6 @@ class Mage_Sales_Model_Order_Payment extends Mage_Payment_Model_Info
*/
protected $_transactionAdditionalInfo = [];
- protected function _construct()
- {
- $this->_init('sales/order_payment');
- }
-
/**
* Declare order model object
*
@@ -628,25 +623,6 @@ public function cancelInvoice($invoice)
return $this;
}
- /**
- * Create new invoice with maximum qty for invoice for each item
- * register this invoice and capture
- *
- * @return Mage_Sales_Model_Order_Invoice
- */
- protected function _invoice()
- {
- $invoice = $this->getOrder()->prepareInvoice();
-
- $invoice->register();
- if ($this->getMethodInstance()->canCapture()) {
- $invoice->capture();
- }
-
- $this->getOrder()->addRelatedObject($invoice);
- return $invoice;
- }
-
/**
* Check order payment void availability
*
@@ -1055,6 +1031,168 @@ public function registerPaymentReviewAction($action, $isOnline)
return $this;
}
+ /**
+ * Public access to _authorize method
+ * @param bool $isOnline
+ * @param float $amount
+ * @return $this
+ */
+ public function authorize($isOnline, $amount)
+ {
+ return $this->_authorize($isOnline, $amount);
+ }
+
+ /**
+ * Public access to _addTransaction method
+ *
+ * @param string $type
+ * @param Mage_Sales_Model_Abstract $salesDocument
+ * @param bool $failsafe
+ * @param string|false $message
+ * @return null|Mage_Sales_Model_Order_Payment_Transaction
+ */
+ public function addTransaction($type, $salesDocument = null, $failsafe = false, $message = false)
+ {
+ $transaction = $this->_addTransaction($type, $salesDocument, $failsafe);
+
+ if ($message) {
+ $order = $this->getOrder();
+ $message = $this->_appendTransactionToMessage($transaction, $message);
+ $order->addStatusHistoryComment($message);
+ }
+
+ return $transaction;
+ }
+
+ /**
+ * Import details data of specified transaction
+ *
+ * @return $this
+ */
+ public function importTransactionInfo(Mage_Sales_Model_Order_Payment_Transaction $transactionTo)
+ {
+ $data = $this->getMethodInstance()
+ ->setStore($this->getOrder()->getStoreId())
+ ->fetchTransactionInfo($this, $transactionTo->getTxnId());
+ if ($data) {
+ $transactionTo->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $data);
+ }
+ return $this;
+ }
+
+ /**
+ * Get the billing agreement, if any
+ *
+ * @return Mage_Sales_Model_Billing_Agreement|null
+ */
+ public function getBillingAgreement()
+ {
+ return $this->_billingAgreement;
+ }
+
+ /**
+ * Find one transaction by ID or type
+ * @param string|false $txnId
+ * @param string|false $txnType
+ * @return Mage_Sales_Model_Order_Payment_Transaction|false
+ */
+ public function lookupTransaction($txnId, $txnType = false)
+ {
+ return $this->_lookupTransaction($txnId, $txnType);
+ }
+
+ /**
+ * Lookup an authorization transaction using parent transaction id, if set
+ * @return Mage_Sales_Model_Order_Payment_Transaction|false
+ */
+ public function getAuthorizationTransaction()
+ {
+ if ($this->getParentTransactionId()) {
+ $txn = $this->_lookupTransaction($this->getParentTransactionId());
+ } else {
+ $txn = false;
+ }
+
+ if (!$txn) {
+ $txn = $this->_lookupTransaction(false, Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH);
+ }
+ return $txn;
+ }
+
+ /**
+ * Lookup the transaction by id
+ * @param string $transactionId
+ * @return Mage_Sales_Model_Order_Payment_Transaction|false
+ */
+ public function getTransaction($transactionId)
+ {
+ return $this->_lookupTransaction($transactionId);
+ }
+
+ /**
+ * Additional transaction info setter
+ *
+ * @param string $key
+ * @param string $value
+ */
+ public function setTransactionAdditionalInfo($key, $value)
+ {
+ if (is_array($key)) {
+ $this->_transactionAdditionalInfo = $key;
+ } else {
+ $this->_transactionAdditionalInfo[$key] = $value;
+ }
+ }
+
+ /**
+ * Additional transaction info getter
+ *
+ * @param string $key
+ * @return mixed
+ */
+ public function getTransactionAdditionalInfo($key = null)
+ {
+ if (is_null($key)) {
+ return $this->_transactionAdditionalInfo;
+ }
+ return $this->_transactionAdditionalInfo[$key] ?? null;
+ }
+
+ /**
+ * Reset transaction additional info property
+ *
+ * @return $this
+ */
+ public function resetTransactionAdditionalInfo()
+ {
+ $this->_transactionAdditionalInfo = [];
+ return $this;
+ }
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_payment');
+ }
+
+ /**
+ * Create new invoice with maximum qty for invoice for each item
+ * register this invoice and capture
+ *
+ * @return Mage_Sales_Model_Order_Invoice
+ */
+ protected function _invoice()
+ {
+ $invoice = $this->getOrder()->prepareInvoice();
+
+ $invoice->register();
+ if ($this->getMethodInstance()->canCapture()) {
+ $invoice->capture();
+ }
+
+ $this->getOrder()->addRelatedObject($invoice);
+ return $invoice;
+ }
+
/**
* Order payment either online
* Updates transactions hierarchy, if required
@@ -1160,17 +1298,6 @@ protected function _authorize($isOnline, $amount)
return $this;
}
- /**
- * Public access to _authorize method
- * @param bool $isOnline
- * @param float $amount
- * @return $this
- */
- public function authorize($isOnline, $amount)
- {
- return $this->_authorize($isOnline, $amount);
- }
-
/**
* Void payment either online or offline (process void notification)
* NOTE: that in some cases authorization can be voided after a capture. In such case it makes sense to use
@@ -1316,54 +1443,6 @@ protected function _addTransaction($type, $salesDocument = null, $failsafe = fal
}
}
- /**
- * Public access to _addTransaction method
- *
- * @param string $type
- * @param Mage_Sales_Model_Abstract $salesDocument
- * @param bool $failsafe
- * @param string|false $message
- * @return null|Mage_Sales_Model_Order_Payment_Transaction
- */
- public function addTransaction($type, $salesDocument = null, $failsafe = false, $message = false)
- {
- $transaction = $this->_addTransaction($type, $salesDocument, $failsafe);
-
- if ($message) {
- $order = $this->getOrder();
- $message = $this->_appendTransactionToMessage($transaction, $message);
- $order->addStatusHistoryComment($message);
- }
-
- return $transaction;
- }
-
- /**
- * Import details data of specified transaction
- *
- * @return $this
- */
- public function importTransactionInfo(Mage_Sales_Model_Order_Payment_Transaction $transactionTo)
- {
- $data = $this->getMethodInstance()
- ->setStore($this->getOrder()->getStoreId())
- ->fetchTransactionInfo($this, $transactionTo->getTxnId());
- if ($data) {
- $transactionTo->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $data);
- }
- return $this;
- }
-
- /**
- * Get the billing agreement, if any
- *
- * @return Mage_Sales_Model_Billing_Agreement|null
- */
- public function getBillingAgreement()
- {
- return $this->_billingAgreement;
- }
-
/**
* Totals updater utility method
* Updates self totals by keys in data array('key' => $delta)
@@ -1517,45 +1596,6 @@ protected function _lookupTransaction($txnId, $txnType = false)
return $this->_transactionsLookup[$txnId];
}
- /**
- * Find one transaction by ID or type
- * @param string|false $txnId
- * @param string|false $txnType
- * @return Mage_Sales_Model_Order_Payment_Transaction|false
- */
- public function lookupTransaction($txnId, $txnType = false)
- {
- return $this->_lookupTransaction($txnId, $txnType);
- }
-
- /**
- * Lookup an authorization transaction using parent transaction id, if set
- * @return Mage_Sales_Model_Order_Payment_Transaction|false
- */
- public function getAuthorizationTransaction()
- {
- if ($this->getParentTransactionId()) {
- $txn = $this->_lookupTransaction($this->getParentTransactionId());
- } else {
- $txn = false;
- }
-
- if (!$txn) {
- $txn = $this->_lookupTransaction(false, Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH);
- }
- return $txn;
- }
-
- /**
- * Lookup the transaction by id
- * @param string $transactionId
- * @return Mage_Sales_Model_Order_Payment_Transaction|false
- */
- public function getTransaction($transactionId)
- {
- return $this->_lookupTransaction($transactionId);
- }
-
/**
* Update transaction ids for further processing
* If no transactions were set before invoking, may generate an "offline" transaction id
@@ -1640,46 +1680,6 @@ protected function _createBillingAgreement()
}
}
- /**
- * Additional transaction info setter
- *
- * @param string $key
- * @param string $value
- */
- public function setTransactionAdditionalInfo($key, $value)
- {
- if (is_array($key)) {
- $this->_transactionAdditionalInfo = $key;
- } else {
- $this->_transactionAdditionalInfo[$key] = $value;
- }
- }
-
- /**
- * Additional transaction info getter
- *
- * @param string $key
- * @return mixed
- */
- public function getTransactionAdditionalInfo($key = null)
- {
- if (is_null($key)) {
- return $this->_transactionAdditionalInfo;
- }
- return $this->_transactionAdditionalInfo[$key] ?? null;
- }
-
- /**
- * Reset transaction additional info property
- *
- * @return $this
- */
- public function resetTransactionAdditionalInfo()
- {
- $this->_transactionAdditionalInfo = [];
- return $this;
- }
-
/**
* Return invoice model for transaction
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Payment/Transaction.php b/app/code/core/Mage/Sales/Model/Order/Payment/Transaction.php
index 66807a4cb48..d02b73376e5 100644
--- a/app/code/core/Mage/Sales/Model/Order/Payment/Transaction.php
+++ b/app/code/core/Mage/Sales/Model/Order/Payment/Transaction.php
@@ -128,12 +128,6 @@ class Mage_Sales_Model_Order_Payment_Transaction extends Mage_Core_Model_Abstrac
*/
protected $_orderWebsiteId = null;
- protected function _construct()
- {
- $this->_init('sales/order_payment_transaction');
- parent::_construct();
- }
-
/**
* Payment instance setter
* @return $this
@@ -387,21 +381,6 @@ public function hasChildTransaction($whetherHasChild = null)
return $this->_hasChild;
}
- /**
- * Check object before loading by by specified transaction ID
- * @param int $txnId
- * @return $this
- */
- protected function _beforeLoadByTxnId($txnId)
- {
- $this->_verifyPaymentObject();
- Mage::dispatchEvent(
- $this->_eventPrefix . '_load_by_txn_id_before',
- $this->_getEventData() + ['txn_id' => $txnId],
- );
- return $this;
- }
-
/**
* Load self by specified transaction ID. Requires the valid payment object to be set
* @param string $txnId
@@ -420,16 +399,6 @@ public function loadByTxnId($txnId)
return $this;
}
- /**
- * Check object after loading by by specified transaction ID
- * @return $this
- */
- protected function _afterLoadByTxnId()
- {
- Mage::dispatchEvent($this->_eventPrefix . '_load_by_txn_id_after', $this->_getEventData());
- return $this;
- }
-
/**
* Additional information setter
* Updates data inside the 'additional_information' array
@@ -612,6 +581,86 @@ public function isFailsafe($setFailsafe = null)
return $this;
}
+ /**
+ * Check whether this transaction is voided
+ * @return bool
+ */
+ public function isVoided()
+ {
+ return $this->_isVoided();
+ }
+
+ /**
+ * Retrieve transaction types
+ *
+ * @return array
+ */
+ public function getTransactionTypes()
+ {
+ return [
+ self::TYPE_ORDER => Mage::helper('sales')->__('Order'),
+ self::TYPE_AUTH => Mage::helper('sales')->__('Authorization'),
+ self::TYPE_CAPTURE => Mage::helper('sales')->__('Capture'),
+ self::TYPE_VOID => Mage::helper('sales')->__('Void'),
+ self::TYPE_REFUND => Mage::helper('sales')->__('Refund'),
+ ];
+ }
+
+ /**
+ * Retrieve order website id
+ *
+ * @return int
+ */
+ public function getOrderWebsiteId()
+ {
+ if (is_null($this->_orderWebsiteId)) {
+ $this->_orderWebsiteId = (int) $this->getResource()->getOrderWebsiteId($this->getOrderId());
+ }
+ return $this->_orderWebsiteId;
+ }
+
+ /**
+ * Get HTML format for transaction id
+ *
+ * @return string
+ */
+ public function getHtmlTxnId()
+ {
+ Mage::dispatchEvent('sales_html_txn_id', ['transaction' => $this, 'payment' => $this->_paymentObject]);
+ return $this->_data['html_txn_id'] ?? $this->getTxnId();
+ }
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_payment_transaction');
+ parent::_construct();
+ }
+
+ /**
+ * Check object before loading by by specified transaction ID
+ * @param int $txnId
+ * @return $this
+ */
+ protected function _beforeLoadByTxnId($txnId)
+ {
+ $this->_verifyPaymentObject();
+ Mage::dispatchEvent(
+ $this->_eventPrefix . '_load_by_txn_id_before',
+ $this->_getEventData() + ['txn_id' => $txnId],
+ );
+ return $this;
+ }
+
+ /**
+ * Check object after loading by by specified transaction ID
+ * @return $this
+ */
+ protected function _afterLoadByTxnId()
+ {
+ Mage::dispatchEvent($this->_eventPrefix . '_load_by_txn_id_after', $this->_getEventData());
+ return $this;
+ }
+
/**
* Verify data required for saving
* @inheritDoc
@@ -699,44 +748,6 @@ protected function _isVoided()
&& (bool) count($this->getChildTransactions(self::TYPE_VOID));
}
- /**
- * Check whether this transaction is voided
- * @return bool
- */
- public function isVoided()
- {
- return $this->_isVoided();
- }
-
- /**
- * Retrieve transaction types
- *
- * @return array
- */
- public function getTransactionTypes()
- {
- return [
- self::TYPE_ORDER => Mage::helper('sales')->__('Order'),
- self::TYPE_AUTH => Mage::helper('sales')->__('Authorization'),
- self::TYPE_CAPTURE => Mage::helper('sales')->__('Capture'),
- self::TYPE_VOID => Mage::helper('sales')->__('Void'),
- self::TYPE_REFUND => Mage::helper('sales')->__('Refund'),
- ];
- }
-
- /**
- * Retrieve order website id
- *
- * @return int
- */
- public function getOrderWebsiteId()
- {
- if (is_null($this->_orderWebsiteId)) {
- $this->_orderWebsiteId = (int) $this->getResource()->getOrderWebsiteId($this->getOrderId());
- }
- return $this->_orderWebsiteId;
- }
-
/**
* Check whether specified or set transaction type is supported
* @param string $txnType
@@ -801,15 +812,4 @@ protected function _verifyThisTransactionExists()
}
$this->_verifyTxnType();
}
-
- /**
- * Get HTML format for transaction id
- *
- * @return string
- */
- public function getHtmlTxnId()
- {
- Mage::dispatchEvent('sales_html_txn_id', ['transaction' => $this, 'payment' => $this->_paymentObject]);
- return $this->_data['html_txn_id'] ?? $this->getTxnId();
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php
index f4552a9a245..caacd475fe1 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php
@@ -22,6 +22,12 @@
*/
abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
{
+ /**
+ * Predefined constants
+ */
+ public const XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID = 'sales_pdf/invoice/put_order_id';
+ public const XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID = 'sales_pdf/shipment/put_order_id';
+ public const XML_PATH_SALES_PDF_CREDITMEMO_PUT_ORDER_ID = 'sales_pdf/creditmemo/put_order_id';
/**
* Y coordinate
*
@@ -39,13 +45,6 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
*/
protected $_renderers = [];
- /**
- * Predefined constants
- */
- public const XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID = 'sales_pdf/invoice/put_order_id';
- public const XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID = 'sales_pdf/shipment/put_order_id';
- public const XML_PATH_SALES_PDF_CREDITMEMO_PUT_ORDER_ID = 'sales_pdf/creditmemo/put_order_id';
-
/**
* Zend PDF object
*
@@ -129,6 +128,185 @@ public function getAlignCenter($string, $x, $columnWidth, Zend_Pdf_Resource_Font
return $x + round(($columnWidth - $width) / 2);
}
+ /**
+ * Insert title and number for concrete document type
+ *
+ * @param string $text
+ */
+ public function insertDocumentNumber(Zend_Pdf_Page $page, $text)
+ {
+ $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
+ $this->_setFontRegular($page, 10);
+ $docHeader = $this->getDocHeaderCoordinates();
+ $page->drawText($text, 35, $docHeader[1] - 15, 'UTF-8');
+ }
+
+ /**
+ * Public method of protected @see _getRenderer()
+ *
+ * Retrieve renderer model
+ *
+ * @param string $type
+ * @return Mage_Sales_Model_Order_Pdf_Items_Abstract
+ */
+ public function getRenderer($type)
+ {
+ return $this->_getRenderer($type);
+ }
+
+ /**
+ * Render item
+ *
+ * @param Mage_Sales_Model_Order_Pdf_Items_Abstract $renderer
+ *
+ * @return Mage_Sales_Model_Order_Pdf_Abstract
+ */
+ public function renderItem(Varien_Object $item, Zend_Pdf_Page $page, Mage_Sales_Model_Order $order, $renderer)
+ {
+ $renderer->setOrder($order)
+ ->setItem($item)
+ ->setPdf($this)
+ ->setPage($page)
+ ->setRenderedModel($this)
+ ->draw();
+
+ return $this;
+ }
+
+ /**
+ * Create new page and assign to PDF object
+ *
+ * @return Zend_Pdf_Page
+ */
+ public function newPage(array $settings = [])
+ {
+ $pageSize = !empty($settings['page_size']) ? $settings['page_size'] : Zend_Pdf_Page::SIZE_A4;
+ $page = $this->_getPdf()->newPage($pageSize);
+ $this->_getPdf()->pages[] = $page;
+ $this->y = 800;
+
+ return $page;
+ }
+
+ /**
+ * Draw lines
+ *
+ * draw items array format:
+ * lines array;array of line blocks (required)
+ * shift int; full line height (optional)
+ * height int;line spacing (default 10)
+ *
+ * line block has line columns array
+ *
+ * column array format
+ * text string|array; draw text (required)
+ * feed int; x position (required)
+ * font string; font style, optional: bold, italic, regular
+ * font_file string; path to font file (optional for use your custom font)
+ * font_size int; font size (default 7)
+ * align string; text align (also see feed parameter), optional left, right
+ * height int;line spacing (default 10)
+ *
+ * @throws Mage_Core_Exception
+ * @return Zend_Pdf_Page
+ */
+ public function drawLineBlocks(Zend_Pdf_Page $page, array $draw, array $pageSettings = [])
+ {
+ foreach ($draw as $itemsProp) {
+ if (!isset($itemsProp['lines']) || !is_array($itemsProp['lines'])) {
+ Mage::throwException(Mage::helper('sales')->__('Invalid draw line data. Please define "lines" array.'));
+ }
+ $lines = $itemsProp['lines'];
+ $height = $itemsProp['height'] ?? 10;
+
+ if (empty($itemsProp['shift'])) {
+ $shift = 0;
+ foreach ($lines as $line) {
+ $maxHeight = 0;
+ foreach ($line as $column) {
+ $lineSpacing = !empty($column['height']) ? $column['height'] : $height;
+ if (!is_array($column['text'])) {
+ $column['text'] = [$column['text']];
+ }
+ $top = 0;
+ foreach ($column['text'] as $part) {
+ $top += $lineSpacing;
+ }
+
+ $maxHeight = $top > $maxHeight ? $top : $maxHeight;
+ }
+ $shift += $maxHeight;
+ }
+ $itemsProp['shift'] = $shift;
+ }
+
+ if ($this->y - $itemsProp['shift'] < 15) {
+ $page = $this->newPage($pageSettings);
+ }
+
+ foreach ($lines as $line) {
+ $maxHeight = 0;
+ foreach ($line as $column) {
+ $fontSize = empty($column['font_size']) ? 10 : $column['font_size'];
+ if (!empty($column['font_file'])) {
+ $font = Zend_Pdf_Font::fontWithPath($column['font_file']);
+ $page->setFont($font, $fontSize);
+ } else {
+ $fontStyle = empty($column['font']) ? 'regular' : $column['font'];
+ switch ($fontStyle) {
+ case 'bold':
+ $font = $this->_setFontBold($page, $fontSize);
+ break;
+ case 'italic':
+ $font = $this->_setFontItalic($page, $fontSize);
+ break;
+ default:
+ $font = $this->_setFontRegular($page, $fontSize);
+ break;
+ }
+ }
+
+ if (!is_array($column['text'])) {
+ $column['text'] = [$column['text']];
+ }
+
+ $lineSpacing = !empty($column['height']) ? $column['height'] : $height;
+ $top = 0;
+ foreach ($column['text'] as $part) {
+ if ($this->y - $lineSpacing < 15) {
+ $page = $this->newPage($pageSettings);
+ }
+
+ $feed = $column['feed'];
+ $textAlign = empty($column['align']) ? 'left' : $column['align'];
+ $width = empty($column['width']) ? 0 : $column['width'];
+ switch ($textAlign) {
+ case 'right':
+ if ($width) {
+ $feed = $this->getAlignRight($part, $feed, $width, $font, $fontSize);
+ } else {
+ $feed = $feed - $this->widthForStringUsingFontSize($part, $font, $fontSize);
+ }
+ break;
+ case 'center':
+ if ($width) {
+ $feed = $this->getAlignCenter($part, $feed, $width, $font, $fontSize);
+ }
+ break;
+ }
+ $page->drawText($part, $feed, $this->y - $top, 'UTF-8');
+ $top += $lineSpacing;
+ }
+
+ $maxHeight = $top > $maxHeight ? $top : $maxHeight;
+ }
+ $this->y -= $maxHeight;
+ }
+ }
+
+ return $page;
+ }
+
/**
* Insert logo to pdf page
*
@@ -495,19 +673,6 @@ protected function insertOrder(&$page, $obj, $putOrderId = true)
}
}
- /**
- * Insert title and number for concrete document type
- *
- * @param string $text
- */
- public function insertDocumentNumber(Zend_Pdf_Page $page, $text)
- {
- $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
- $this->_setFontRegular($page, 10);
- $docHeader = $this->getDocHeaderCoordinates();
- $page->drawText($text, 35, $docHeader[1] - 15, 'UTF-8');
- }
-
/**
* Sort totals list
*
@@ -708,38 +873,6 @@ protected function _getRenderer($type)
return $this->_renderers[$type]['renderer'];
}
- /**
- * Public method of protected @see _getRenderer()
- *
- * Retrieve renderer model
- *
- * @param string $type
- * @return Mage_Sales_Model_Order_Pdf_Items_Abstract
- */
- public function getRenderer($type)
- {
- return $this->_getRenderer($type);
- }
-
- /**
- * Render item
- *
- * @param Mage_Sales_Model_Order_Pdf_Items_Abstract $renderer
- *
- * @return Mage_Sales_Model_Order_Pdf_Abstract
- */
- public function renderItem(Varien_Object $item, Zend_Pdf_Page $page, Mage_Sales_Model_Order $order, $renderer)
- {
- $renderer->setOrder($order)
- ->setItem($item)
- ->setPdf($this)
- ->setPage($page)
- ->setRenderedModel($this)
- ->draw();
-
- return $this;
- }
-
/**
* Draw Item process
*
@@ -836,138 +969,4 @@ protected function _getPdf()
return $this->_pdf;
}
-
- /**
- * Create new page and assign to PDF object
- *
- * @return Zend_Pdf_Page
- */
- public function newPage(array $settings = [])
- {
- $pageSize = !empty($settings['page_size']) ? $settings['page_size'] : Zend_Pdf_Page::SIZE_A4;
- $page = $this->_getPdf()->newPage($pageSize);
- $this->_getPdf()->pages[] = $page;
- $this->y = 800;
-
- return $page;
- }
-
- /**
- * Draw lines
- *
- * draw items array format:
- * lines array;array of line blocks (required)
- * shift int; full line height (optional)
- * height int;line spacing (default 10)
- *
- * line block has line columns array
- *
- * column array format
- * text string|array; draw text (required)
- * feed int; x position (required)
- * font string; font style, optional: bold, italic, regular
- * font_file string; path to font file (optional for use your custom font)
- * font_size int; font size (default 7)
- * align string; text align (also see feed parameter), optional left, right
- * height int;line spacing (default 10)
- *
- * @throws Mage_Core_Exception
- * @return Zend_Pdf_Page
- */
- public function drawLineBlocks(Zend_Pdf_Page $page, array $draw, array $pageSettings = [])
- {
- foreach ($draw as $itemsProp) {
- if (!isset($itemsProp['lines']) || !is_array($itemsProp['lines'])) {
- Mage::throwException(Mage::helper('sales')->__('Invalid draw line data. Please define "lines" array.'));
- }
- $lines = $itemsProp['lines'];
- $height = $itemsProp['height'] ?? 10;
-
- if (empty($itemsProp['shift'])) {
- $shift = 0;
- foreach ($lines as $line) {
- $maxHeight = 0;
- foreach ($line as $column) {
- $lineSpacing = !empty($column['height']) ? $column['height'] : $height;
- if (!is_array($column['text'])) {
- $column['text'] = [$column['text']];
- }
- $top = 0;
- foreach ($column['text'] as $part) {
- $top += $lineSpacing;
- }
-
- $maxHeight = $top > $maxHeight ? $top : $maxHeight;
- }
- $shift += $maxHeight;
- }
- $itemsProp['shift'] = $shift;
- }
-
- if ($this->y - $itemsProp['shift'] < 15) {
- $page = $this->newPage($pageSettings);
- }
-
- foreach ($lines as $line) {
- $maxHeight = 0;
- foreach ($line as $column) {
- $fontSize = empty($column['font_size']) ? 10 : $column['font_size'];
- if (!empty($column['font_file'])) {
- $font = Zend_Pdf_Font::fontWithPath($column['font_file']);
- $page->setFont($font, $fontSize);
- } else {
- $fontStyle = empty($column['font']) ? 'regular' : $column['font'];
- switch ($fontStyle) {
- case 'bold':
- $font = $this->_setFontBold($page, $fontSize);
- break;
- case 'italic':
- $font = $this->_setFontItalic($page, $fontSize);
- break;
- default:
- $font = $this->_setFontRegular($page, $fontSize);
- break;
- }
- }
-
- if (!is_array($column['text'])) {
- $column['text'] = [$column['text']];
- }
-
- $lineSpacing = !empty($column['height']) ? $column['height'] : $height;
- $top = 0;
- foreach ($column['text'] as $part) {
- if ($this->y - $lineSpacing < 15) {
- $page = $this->newPage($pageSettings);
- }
-
- $feed = $column['feed'];
- $textAlign = empty($column['align']) ? 'left' : $column['align'];
- $width = empty($column['width']) ? 0 : $column['width'];
- switch ($textAlign) {
- case 'right':
- if ($width) {
- $feed = $this->getAlignRight($part, $feed, $width, $font, $fontSize);
- } else {
- $feed = $feed - $this->widthForStringUsingFontSize($part, $font, $fontSize);
- }
- break;
- case 'center':
- if ($width) {
- $feed = $this->getAlignCenter($part, $feed, $width, $font, $fontSize);
- }
- break;
- }
- $page->drawText($part, $feed, $this->y - $top, 'UTF-8');
- $top += $lineSpacing;
- }
-
- $maxHeight = $top > $maxHeight ? $top : $maxHeight;
- }
- $this->y -= $maxHeight;
- }
- }
-
- return $page;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Creditmemo.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Creditmemo.php
index bceb1dc959c..6cb5cfb12ba 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Creditmemo.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Creditmemo.php
@@ -22,75 +22,6 @@
*/
class Mage_Sales_Model_Order_Pdf_Creditmemo extends Mage_Sales_Model_Order_Pdf_Abstract
{
- /**
- * Draw table header for product items
- */
- protected function _drawHeader(Zend_Pdf_Page $page)
- {
- $this->_setFontRegular($page, 10);
- $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
- $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
- $page->setLineWidth(0.5);
- $page->drawRectangle(25, $this->y, 570, $this->y - 30);
- $this->y -= 10;
- $page->setFillColor(new Zend_Pdf_Color_Rgb(0, 0, 0));
-
- //columns headers
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('Products'),
- 'feed' => 35,
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('SKU'), 12, true, true),
- 'feed' => 255,
- 'align' => 'right',
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Total (ex)'), 12, true, true),
- 'feed' => 330,
- 'align' => 'right',
- //'width' => 50,
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Discount'), 12, true, true),
- 'feed' => 380,
- 'align' => 'right',
- //'width' => 50,
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Qty'), 12, true, true),
- 'feed' => 445,
- 'align' => 'right',
- //'width' => 30,
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Tax'), 12, true, true),
- 'feed' => 495,
- 'align' => 'right',
- //'width' => 45,
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Total (inc)'), 12, true, true),
- 'feed' => 565,
- 'align' => 'right',
- ];
-
- $lineBlock = [
- 'lines' => $lines,
- 'height' => 10,
- ];
-
- $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
- $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
- $this->y -= 20;
- }
-
/**
* Return PDF document
*
@@ -163,4 +94,72 @@ public function newPage(array $settings = [])
}
return $page;
}
+ /**
+ * Draw table header for product items
+ */
+ protected function _drawHeader(Zend_Pdf_Page $page)
+ {
+ $this->_setFontRegular($page, 10);
+ $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
+ $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
+ $page->setLineWidth(0.5);
+ $page->drawRectangle(25, $this->y, 570, $this->y - 30);
+ $this->y -= 10;
+ $page->setFillColor(new Zend_Pdf_Color_Rgb(0, 0, 0));
+
+ //columns headers
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('Products'),
+ 'feed' => 35,
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('SKU'), 12, true, true),
+ 'feed' => 255,
+ 'align' => 'right',
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Total (ex)'), 12, true, true),
+ 'feed' => 330,
+ 'align' => 'right',
+ //'width' => 50,
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Discount'), 12, true, true),
+ 'feed' => 380,
+ 'align' => 'right',
+ //'width' => 50,
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Qty'), 12, true, true),
+ 'feed' => 445,
+ 'align' => 'right',
+ //'width' => 30,
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Tax'), 12, true, true),
+ 'feed' => 495,
+ 'align' => 'right',
+ //'width' => 45,
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('core/string')->str_split(Mage::helper('sales')->__('Total (inc)'), 12, true, true),
+ 'feed' => 565,
+ 'align' => 'right',
+ ];
+
+ $lineBlock = [
+ 'lines' => $lines,
+ 'height' => 10,
+ ];
+
+ $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
+ $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
+ $this->y -= 20;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php
index f61ff4de214..5d7e7550422 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php
@@ -22,66 +22,6 @@
*/
class Mage_Sales_Model_Order_Pdf_Invoice extends Mage_Sales_Model_Order_Pdf_Abstract
{
- /**
- * Draw header for item table
- */
- protected function _drawHeader(Zend_Pdf_Page $page)
- {
- /* Add table head */
- $this->_setFontRegular($page, 10);
- $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
- $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
- $page->setLineWidth(0.5);
- $page->drawRectangle(25, $this->y, 570, $this->y - 15);
- $this->y -= 10;
- $page->setFillColor(new Zend_Pdf_Color_Rgb(0, 0, 0));
-
- //columns headers
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('Products'),
- 'feed' => 35,
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('SKU'),
- 'feed' => 290,
- 'align' => 'right',
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('Qty'),
- 'feed' => 435,
- 'align' => 'right',
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('Price'),
- 'feed' => 360,
- 'align' => 'right',
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('Tax'),
- 'feed' => 495,
- 'align' => 'right',
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('Subtotal'),
- 'feed' => 565,
- 'align' => 'right',
- ];
-
- $lineBlock = [
- 'lines' => $lines,
- 'height' => 5,
- ];
-
- $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
- $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
- $this->y -= 20;
- }
-
/**
* Return PDF document
*
@@ -157,4 +97,63 @@ public function newPage(array $settings = [])
}
return $page;
}
+ /**
+ * Draw header for item table
+ */
+ protected function _drawHeader(Zend_Pdf_Page $page)
+ {
+ /* Add table head */
+ $this->_setFontRegular($page, 10);
+ $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
+ $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
+ $page->setLineWidth(0.5);
+ $page->drawRectangle(25, $this->y, 570, $this->y - 15);
+ $this->y -= 10;
+ $page->setFillColor(new Zend_Pdf_Color_Rgb(0, 0, 0));
+
+ //columns headers
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('Products'),
+ 'feed' => 35,
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('SKU'),
+ 'feed' => 290,
+ 'align' => 'right',
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('Qty'),
+ 'feed' => 435,
+ 'align' => 'right',
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('Price'),
+ 'feed' => 360,
+ 'align' => 'right',
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('Tax'),
+ 'feed' => 495,
+ 'align' => 'right',
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('Subtotal'),
+ 'feed' => 565,
+ 'align' => 'right',
+ ];
+
+ $lineBlock = [
+ 'lines' => $lines,
+ 'height' => 5,
+ ];
+
+ $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
+ $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
+ $this->y -= 20;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Abstract.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Abstract.php
index 9ea021eca78..7bf4e6d3ea4 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Abstract.php
@@ -188,48 +188,6 @@ public function getPage()
*/
abstract public function draw();
- /**
- * Format option value process
- *
- * @param array|string $value
- * @return string
- */
- protected function _formatOptionValue($value)
- {
- $order = $this->getOrder();
-
- $resultValue = '';
- if (is_array($value)) {
- if (isset($value['qty'])) {
- $resultValue .= sprintf('%d', $value['qty']) . ' x ';
- }
-
- $resultValue .= $value['title'];
-
- if (isset($value['price'])) {
- $resultValue .= ' ' . $order->formatPrice($value['price']);
- }
- return $resultValue;
- } else {
- return $value;
- }
- }
-
- /**
- * @deprecated To be Removed on next release
- *
- * @return array
- */
- protected function _parseDescription()
- {
- $description = $this->getItem()->getDescription();
- if (preg_match_all('/(.*?)<\/li>/i', $description, $matches)) {
- return $matches[1];
- }
-
- return [$description];
- }
-
/**
* Get array of arrays with item prices information for display in PDF
* array(
@@ -294,6 +252,63 @@ public function getItemOptions()
return $result;
}
+ /**
+ * Return item Sku
+ *
+ * @param Mage_Sales_Model_Order_Invoice_Item|Mage_Sales_Model_Order_Creditmemo_Item $item
+ * @return string
+ */
+ public function getSku($item)
+ {
+ if ($item->getOrderItem()->getProductOptionByCode('simple_sku')) {
+ return $item->getOrderItem()->getProductOptionByCode('simple_sku');
+ } else {
+ return $item->getSku();
+ }
+ }
+
+ /**
+ * Format option value process
+ *
+ * @param array|string $value
+ * @return string
+ */
+ protected function _formatOptionValue($value)
+ {
+ $order = $this->getOrder();
+
+ $resultValue = '';
+ if (is_array($value)) {
+ if (isset($value['qty'])) {
+ $resultValue .= sprintf('%d', $value['qty']) . ' x ';
+ }
+
+ $resultValue .= $value['title'];
+
+ if (isset($value['price'])) {
+ $resultValue .= ' ' . $order->formatPrice($value['price']);
+ }
+ return $resultValue;
+ } else {
+ return $value;
+ }
+ }
+
+ /**
+ * @deprecated To be Removed on next release
+ *
+ * @return array
+ */
+ protected function _parseDescription()
+ {
+ $description = $this->getItem()->getDescription();
+ if (preg_match_all('/(.*?)<\/li>/i', $description, $matches)) {
+ return $matches[1];
+ }
+
+ return [$description];
+ }
+
/**
* Set font as regular
*
@@ -332,19 +347,4 @@ protected function _setFontItalic($size = 7)
$this->getPage()->setFont($font, $size);
return $font;
}
-
- /**
- * Return item Sku
- *
- * @param Mage_Sales_Model_Order_Invoice_Item|Mage_Sales_Model_Order_Creditmemo_Item $item
- * @return string
- */
- public function getSku($item)
- {
- if ($item->getOrderItem()->getProductOptionByCode('simple_sku')) {
- return $item->getOrderItem()->getProductOptionByCode('simple_sku');
- } else {
- return $item->getSku();
- }
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php
index 7f18eb8b4ca..a1180173d11 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php
@@ -22,47 +22,6 @@
*/
class Mage_Sales_Model_Order_Pdf_Shipment extends Mage_Sales_Model_Order_Pdf_Abstract
{
- /**
- * Draw table header for product items
- */
- protected function _drawHeader(Zend_Pdf_Page $page)
- {
- /* Add table head */
- $this->_setFontRegular($page, 10);
- $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
- $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
- $page->setLineWidth(0.5);
- $page->drawRectangle(25, $this->y, 570, $this->y - 15);
- $this->y -= 10;
- $page->setFillColor(new Zend_Pdf_Color_Rgb(0, 0, 0));
-
- //columns headers
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('Products'),
- 'feed' => 100,
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('Qty'),
- 'feed' => 35,
- ];
-
- $lines[0][] = [
- 'text' => Mage::helper('sales')->__('SKU'),
- 'feed' => 565,
- 'align' => 'right',
- ];
-
- $lineBlock = [
- 'lines' => $lines,
- 'height' => 10,
- ];
-
- $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
- $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
- $this->y -= 20;
- }
-
/**
* Return PDF document
*
@@ -135,4 +94,44 @@ public function newPage(array $settings = [])
}
return $page;
}
+ /**
+ * Draw table header for product items
+ */
+ protected function _drawHeader(Zend_Pdf_Page $page)
+ {
+ /* Add table head */
+ $this->_setFontRegular($page, 10);
+ $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
+ $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
+ $page->setLineWidth(0.5);
+ $page->drawRectangle(25, $this->y, 570, $this->y - 15);
+ $this->y -= 10;
+ $page->setFillColor(new Zend_Pdf_Color_Rgb(0, 0, 0));
+
+ //columns headers
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('Products'),
+ 'feed' => 100,
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('Qty'),
+ 'feed' => 35,
+ ];
+
+ $lines[0][] = [
+ 'text' => Mage::helper('sales')->__('SKU'),
+ 'feed' => 565,
+ 'align' => 'right',
+ ];
+
+ $lineBlock = [
+ 'lines' => $lines,
+ 'height' => 10,
+ ];
+
+ $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
+ $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
+ $this->y -= 20;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Total/Default.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Total/Default.php
index a5a92543d1b..247319066d7 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Total/Default.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Total/Default.php
@@ -64,14 +64,6 @@ public function getTotalsForDisplay()
return [$total];
}
- /**
- * @return Mage_Sales_Helper_Data
- */
- protected function _getSalesHelper()
- {
- return Mage::helper('sales');
- }
-
/**
* Get array of arrays with tax information for display in PDF
* array(
@@ -127,72 +119,80 @@ public function getFullTaxInfo()
}
/**
- * Get full rate info
+ * Check if we can display total information in PDF
*
- * @return array
+ * @return bool
*/
- protected function _getFullRateInfo()
+ public function canDisplay()
{
- $rates = Mage::getModel('tax/sales_order_tax')->getCollection()->loadByOrder($this->getOrder())->toArray();
- return Mage::getSingleton('tax/calculation')->reproduceProcess($rates['items']);
+ $amount = $this->getAmount();
+ return $this->getDisplayZero() || ($amount != 0);
}
/**
- * @return Mage_Tax_Helper_Data
+ * Get Total amount from source
+ *
+ * @return float
*/
- protected function _getTaxHelper()
+ public function getAmount()
{
- return Mage::helper('tax');
+ return $this->getSource()->getDataUsingMethod($this->getSourceField());
}
/**
- * Get shipping tax
+ * Get title description from source
*
- * @return array
+ * @return mixed
*/
- protected function _getShippingTax()
+ public function getTitleDescription()
{
- return $this->_getTaxHelper()->getShippingTax($this->getOrder());
+ return $this->getSource()->getDataUsingMethod($this->getTitleSourceField());
}
/**
- * Get calculated taxes
+ * @return Mage_Sales_Helper_Data
+ */
+ protected function _getSalesHelper()
+ {
+ return Mage::helper('sales');
+ }
+
+ /**
+ * Get full rate info
*
* @return array
*/
- protected function _getCalculatedTaxes()
+ protected function _getFullRateInfo()
{
- return $this->_getTaxHelper()->getCalculatedTaxes($this->getOrder());
+ $rates = Mage::getModel('tax/sales_order_tax')->getCollection()->loadByOrder($this->getOrder())->toArray();
+ return Mage::getSingleton('tax/calculation')->reproduceProcess($rates['items']);
}
/**
- * Check if we can display total information in PDF
- *
- * @return bool
+ * @return Mage_Tax_Helper_Data
*/
- public function canDisplay()
+ protected function _getTaxHelper()
{
- $amount = $this->getAmount();
- return $this->getDisplayZero() || ($amount != 0);
+ return Mage::helper('tax');
}
/**
- * Get Total amount from source
+ * Get shipping tax
*
- * @return float
+ * @return array
*/
- public function getAmount()
+ protected function _getShippingTax()
{
- return $this->getSource()->getDataUsingMethod($this->getSourceField());
+ return $this->_getTaxHelper()->getShippingTax($this->getOrder());
}
/**
- * Get title description from source
+ * Get calculated taxes
*
- * @return mixed
+ * @return array
*/
- public function getTitleDescription()
+ protected function _getCalculatedTaxes()
{
- return $this->getSource()->getDataUsingMethod($this->getTitleSourceField());
+ return $this->_getTaxHelper()->getCalculatedTaxes($this->getOrder());
}
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Shipment.php b/app/code/core/Mage/Sales/Model/Order/Shipment.php
index 63e98572ccb..385afdbc745 100644
--- a/app/code/core/Mage/Sales/Model/Order/Shipment.php
+++ b/app/code/core/Mage/Sales/Model/Order/Shipment.php
@@ -101,24 +101,6 @@ class Mage_Sales_Model_Order_Shipment extends Mage_Sales_Model_Abstract
protected $_eventPrefix = 'sales_order_shipment';
protected $_eventObject = 'shipment';
- /**
- * Initialize shipment resource model
- */
- protected function _construct()
- {
- $this->_init('sales/order_shipment');
- }
-
- /**
- * Init mapping array of short fields to its full names
- *
- * @return $this
- */
- protected function _initOldFieldsMap()
- {
- return $this;
- }
-
/**
* Load shipment by increment id
*
@@ -575,6 +557,60 @@ public function sendUpdateEmail($notifyCustomer = true, $comment = '')
return $this;
}
+ /**
+ * Retrieve store model instance
+ *
+ * @return Mage_Core_Model_Store
+ */
+ public function getStore()
+ {
+ return $this->getOrder()->getStore();
+ }
+
+ /**
+ * Set shipping label
+ *
+ * @param string $label label representation (image or pdf file)
+ * @return $this
+ */
+ public function setShippingLabel($label)
+ {
+ $this->setData('shipping_label', $label);
+ return $this;
+ }
+
+ /**
+ * Get shipping label and decode by db adapter
+ *
+ * @return string
+ */
+ public function getShippingLabel()
+ {
+ $label = $this->getData('shipping_label');
+ if ($label) {
+ return $this->getResource()->getReadConnection()->decodeVarbinary($label);
+ }
+ return $label;
+ }
+
+ /**
+ * Initialize shipment resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/order_shipment');
+ }
+
+ /**
+ * Init mapping array of short fields to its full names
+ *
+ * @return $this
+ */
+ protected function _initOldFieldsMap()
+ {
+ return $this;
+ }
+
/**
* @param string $configPath
* @return array|false
@@ -650,40 +686,4 @@ protected function _afterSave()
return parent::_afterSave();
}
-
- /**
- * Retrieve store model instance
- *
- * @return Mage_Core_Model_Store
- */
- public function getStore()
- {
- return $this->getOrder()->getStore();
- }
-
- /**
- * Set shipping label
- *
- * @param string $label label representation (image or pdf file)
- * @return $this
- */
- public function setShippingLabel($label)
- {
- $this->setData('shipping_label', $label);
- return $this;
- }
-
- /**
- * Get shipping label and decode by db adapter
- *
- * @return string
- */
- public function getShippingLabel()
- {
- $label = $this->getData('shipping_label');
- if ($label) {
- return $this->getResource()->getReadConnection()->decodeVarbinary($label);
- }
- return $label;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Shipment/Api/V2.php b/app/code/core/Mage/Sales/Model/Order/Shipment/Api/V2.php
index 5ba48008546..6e238f22a33 100644
--- a/app/code/core/Mage/Sales/Model/Order/Shipment/Api/V2.php
+++ b/app/code/core/Mage/Sales/Model/Order/Shipment/Api/V2.php
@@ -22,21 +22,6 @@
*/
class Mage_Sales_Model_Order_Shipment_Api_V2 extends Mage_Sales_Model_Order_Shipment_Api
{
- /**
- * @param array $data
- * @return array
- */
- protected function _prepareItemQtyData($data)
- {
- $_data = [];
- foreach ($data as $item) {
- if (isset($item->order_item_id) && isset($item->qty)) {
- $_data[$item->order_item_id] = $item->qty;
- }
- }
- return $_data;
- }
-
/**
* Create new shipment for order
*
@@ -116,4 +101,18 @@ public function getCarriers($orderIncrementId)
return $carriers;
}
+ /**
+ * @param array $data
+ * @return array
+ */
+ protected function _prepareItemQtyData($data)
+ {
+ $_data = [];
+ foreach ($data as $item) {
+ if (isset($item->order_item_id) && isset($item->qty)) {
+ $_data[$item->order_item_id] = $item->qty;
+ }
+ }
+ return $_data;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Shipment/Comment.php b/app/code/core/Mage/Sales/Model/Order/Shipment/Comment.php
index 4436b179c20..e61bb3372fd 100644
--- a/app/code/core/Mage/Sales/Model/Order/Shipment/Comment.php
+++ b/app/code/core/Mage/Sales/Model/Order/Shipment/Comment.php
@@ -44,11 +44,6 @@ class Mage_Sales_Model_Order_Shipment_Comment extends Mage_Sales_Model_Abstract
*/
protected $_shipment;
- protected function _construct()
- {
- $this->_init('sales/order_shipment_comment');
- }
-
/**
* Declare Shipment instance
*
@@ -83,6 +78,11 @@ public function getStore()
return Mage::app()->getStore();
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_shipment_comment');
+ }
+
/**
* Before object save
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Shipment/Track.php b/app/code/core/Mage/Sales/Model/Order/Shipment/Track.php
index 846ab6906d2..d35232182e7 100644
--- a/app/code/core/Mage/Sales/Model/Order/Shipment/Track.php
+++ b/app/code/core/Mage/Sales/Model/Order/Shipment/Track.php
@@ -61,19 +61,6 @@ public function _construct()
$this->_init('sales/order_shipment_track');
}
- /**
- * Init mapping array of short fields to
- * its full names
- *
- * @return void
- */
- protected function _initOldFieldsMap()
- {
- $this->_oldFieldsMap = [
- 'number' => 'track_number',
- ];
- }
-
/**
* Back compatibility with old versions.
*
@@ -174,6 +161,19 @@ public function getStoreId()
return $this->getStore()->getId();
}
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return void
+ */
+ protected function _initOldFieldsMap()
+ {
+ $this->_oldFieldsMap = [
+ 'number' => 'track_number',
+ ];
+ }
+
/**
* Before object save
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Status.php b/app/code/core/Mage/Sales/Model/Order/Status.php
index 9e0a9145d3f..667e6178574 100644
--- a/app/code/core/Mage/Sales/Model/Order/Status.php
+++ b/app/code/core/Mage/Sales/Model/Order/Status.php
@@ -30,11 +30,6 @@
*/
class Mage_Sales_Model_Order_Status extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_status');
- }
-
/**
* Assign order status to particular state
*
@@ -119,4 +114,8 @@ public function loadDefaultByState($state)
$this->load($state, 'default_state');
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_status');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Order/Status/History.php b/app/code/core/Mage/Sales/Model/Order/Status/History.php
index f1cffa95046..f22f47f3efb 100644
--- a/app/code/core/Mage/Sales/Model/Order/Status/History.php
+++ b/app/code/core/Mage/Sales/Model/Order/Status/History.php
@@ -49,11 +49,6 @@ class Mage_Sales_Model_Order_Status_History extends Mage_Sales_Model_Abstract
protected $_eventPrefix = 'sales_order_status_history';
protected $_eventObject = 'status_history';
- protected function _construct()
- {
- $this->_init('sales/order_status_history');
- }
-
/**
* Set order object
*
@@ -137,6 +132,11 @@ public function getStore()
return Mage::app()->getStore();
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_status_history');
+ }
+
/**
* Set order again if required
*
diff --git a/app/code/core/Mage/Sales/Model/Order/Total/Config/Base.php b/app/code/core/Mage/Sales/Model/Order/Total/Config/Base.php
index e5c8551e4ab..50d11e491fe 100644
--- a/app/code/core/Mage/Sales/Model/Order/Total/Config/Base.php
+++ b/app/code/core/Mage/Sales/Model/Order/Total/Config/Base.php
@@ -43,6 +43,21 @@ class Mage_Sales_Model_Order_Total_Config_Base extends Mage_Sales_Model_Config_O
*/
protected $_totalsConfigNode = 'totals';
+ /**
+ * Retrieve total calculation models
+ *
+ * @return array
+ */
+ public function getTotalModels()
+ {
+ if (empty($this->_totalModels)) {
+ $this->_initModels();
+ $this->_initCollectors();
+ $this->_totalModels = $this->_collectors;
+ }
+ return $this->_totalModels;
+ }
+
/**
* Init model class by configuration
*
@@ -65,19 +80,4 @@ protected function _initModelInstance($class, $totalCode, $totalConfig)
$this->_modelsConfig[$totalCode] = $model->processConfigArray($this->_modelsConfig[$totalCode]);
return $model;
}
-
- /**
- * Retrieve total calculation models
- *
- * @return array
- */
- public function getTotalModels()
- {
- if (empty($this->_totalModels)) {
- $this->_initModels();
- $this->_initCollectors();
- $this->_totalModels = $this->_collectors;
- }
- return $this->_totalModels;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote.php b/app/code/core/Mage/Sales/Model/Quote.php
index 6e31796a00c..f668dfea71b 100644
--- a/app/code/core/Mage/Sales/Model/Quote.php
+++ b/app/code/core/Mage/Sales/Model/Quote.php
@@ -179,6 +179,12 @@
*/
class Mage_Sales_Model_Quote extends Mage_Core_Model_Abstract
{
+ /**
+ * @deprecated after 1.4 beta1 - one page checkout responsibility
+ */
+ public const CHECKOUT_METHOD_REGISTER = 'register';
+ public const CHECKOUT_METHOD_GUEST = 'guest';
+ public const CHECKOUT_METHOD_LOGIN_IN = 'login_in';
protected $_eventPrefix = 'sales_quote';
protected $_eventObject = 'quote';
@@ -233,25 +239,6 @@ class Mage_Sales_Model_Quote extends Mage_Core_Model_Abstract
*/
protected $_preventSaving = false;
- /**
- * Init resource model
- */
- protected function _construct()
- {
- $this->_init('sales/quote');
- }
-
- /**
- * Init mapping array of short fields to
- * its full names
- *
- * @return Varien_Object
- */
- protected function _initOldFieldsMap()
- {
- return $this;
- }
-
/**
* Get quote store identifier
*
@@ -305,87 +292,6 @@ public function getSharedStoreIds()
return $ids;
}
- /**
- * @inheritDoc
- * @throws Mage_Core_Exception
- */
- protected function _beforeSave()
- {
- /**
- * Currency logic
- *
- * global - currency which is set for default in backend
- * base - currency which is set for current website. all attributes that
- * have 'base_' prefix saved in this currency
- * store - all the time it was currency of website and all attributes
- * with 'base_' were saved in this currency. From now on it is
- * deprecated and will be duplication of base currency code.
- * quote/order - currency which was selected by customer or configured by
- * admin for current store. currency in which customer sees
- * price thought all checkout.
- *
- * Rates:
- * store_to_base & store_to_quote/store_to_order - are deprecated
- * base_to_global & base_to_quote/base_to_order - must be used instead
- */
-
- $globalCurrencyCode = Mage::app()->getBaseCurrencyCode();
- $baseCurrency = $this->getStore()->getBaseCurrency();
-
- if ($this->hasForcedCurrency()) {
- $quoteCurrency = $this->getForcedCurrency();
- } else {
- $quoteCurrency = $this->getStore()->getCurrentCurrency();
- }
-
- $this->setGlobalCurrencyCode($globalCurrencyCode);
- $this->setBaseCurrencyCode($baseCurrency->getCode());
- $this->setStoreCurrencyCode($baseCurrency->getCode());
- $this->setQuoteCurrencyCode($quoteCurrency->getCode());
-
- //deprecated, read above
- $this->setStoreToBaseRate($baseCurrency->getRate($globalCurrencyCode));
- $this->setStoreToQuoteRate($baseCurrency->getRate($quoteCurrency));
-
- $this->setBaseToGlobalRate($baseCurrency->getRate($globalCurrencyCode));
- $this->setBaseToQuoteRate($baseCurrency->getRate($quoteCurrency));
-
- if (!$this->hasChangedFlag() || $this->getChangedFlag() == true) {
- $this->setIsChanged(1);
- } else {
- $this->setIsChanged(0);
- }
-
- if ($this->_customer) {
- $this->setCustomerId($this->_customer->getId());
- }
-
- return parent::_beforeSave();
- }
-
- /**
- * Save related items
- *
- * @return $this
- */
- protected function _afterSave()
- {
- parent::_afterSave();
-
- if ($this->_addresses !== null) {
- $this->getAddressesCollection()->save();
- }
-
- if ($this->_items !== null) {
- $this->getItemsCollection()->save();
- }
-
- if ($this->_payments !== null) {
- $this->getPaymentsCollection()->save();
- }
- return $this;
- }
-
/**
* Loading quote data by customer
*
@@ -571,25 +477,6 @@ public function getAddressesCollection()
return $this->_addresses;
}
- /**
- * Retrieve quote address by type
- *
- * @param string $type
- * @return Mage_Sales_Model_Quote_Address
- */
- protected function _getAddressByType($type)
- {
- foreach ($this->getAddressesCollection() as $address) {
- if ($address->getAddressType() == $type && !$address->isDeleted()) {
- return $address;
- }
- }
-
- $address = Mage::getModel('sales/quote_address')->setAddressType($type);
- $this->addAddress($address);
- return $address;
- }
-
/**
* Retrieve quote billing address
*
@@ -1116,46 +1003,6 @@ public function addProduct(Mage_Catalog_Model_Product $product, $request = null)
);
}
- /**
- * Adding catalog product object data to quote
- *
- * @param int $qty
- * @return Mage_Sales_Model_Quote_Item
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _addCatalogProduct(Mage_Catalog_Model_Product $product, $qty = 1)
- {
- $newItem = false;
- $item = $this->getItemByProduct($product);
- if (!$item) {
- $item = Mage::getModel('sales/quote_item');
- $item->setQuote($this);
- if (Mage::app()->getStore()->isAdmin()) {
- $item->setStoreId($this->getStore()->getId());
- } else {
- $item->setStoreId(Mage::app()->getStore()->getId());
- }
- $newItem = true;
- }
-
- /**
- * We can't modify existing child items
- */
- if ($item->getId() && $product->getParentProductId()) {
- return $item;
- }
-
- $item->setOptions($product->getCustomOptions())
- ->setProduct($product);
-
- // Add only item that is not in quote already (there can be other new or already saved item
- if ($newItem) {
- $this->addItem($item);
- }
-
- return $item;
- }
-
/**
* Updates quote item with new configuration
*
@@ -1573,17 +1420,6 @@ public function getErrors()
return $errors;
}
- /**
- * Sets flag, whether this quote has some error associated with it.
- *
- * @param bool $flag
- * @return $this
- */
- protected function _setHasError($flag)
- {
- return $this->setData('has_error', $flag);
- }
-
/**
* Sets flag, whether this quote has some error associated with it.
* When TRUE - also adds 'unknown' error information to list of quote errors.
@@ -1604,19 +1440,6 @@ public function setHasError($flag)
return $this;
}
- /**
- * Clears list of errors, associated with this quote.
- * Also automatically removes error-flag from oneself.
- *
- * @return $this
- */
- protected function _clearErrorInfo()
- {
- $this->_errorInfoGroups = [];
- $this->_setHasError(false);
- return $this;
- }
-
/**
* Adds error information to the quote.
* Automatically sets error flag.
@@ -1974,51 +1797,6 @@ public function prepareRecurringPaymentProfiles()
return $result;
}
- /**
- * @return $this
- */
- protected function _validateCouponCode()
- {
- $code = $this->getCouponCode();
- if (strlen($code)) {
- $addressHasCoupon = false;
- $addresses = $this->getAllAddresses();
- if (count($addresses) > 0) {
- foreach ($addresses as $address) {
- if ($address->hasCouponCode()) {
- $addressHasCoupon = true;
- }
- }
- if (!$addressHasCoupon) {
- $this->setCouponCode('');
- }
- }
- }
- return $this;
- }
-
- /**
- * Trigger collect totals after loading, if required
- *
- * @inheritDoc
- */
- protected function _afterLoad()
- {
- // collect totals and save me, if required
- if ($this->getData('trigger_recollect') == 1) {
- $this->setTriggerRecollect(0)->getResource()->save($this);
- $this->collectTotals()->save();
- }
- return parent::_afterLoad();
- }
-
- /**
- * @deprecated after 1.4 beta1 - one page checkout responsibility
- */
- public const CHECKOUT_METHOD_REGISTER = 'register';
- public const CHECKOUT_METHOD_GUEST = 'guest';
- public const CHECKOUT_METHOD_LOGIN_IN = 'login_in';
-
/**
* Return quote checkout method code
*
@@ -2081,4 +1859,225 @@ public function setCouponCode(?string $couponCode)
{
return $this->setData('coupon_code', $couponCode);
}
+
+ /**
+ * Init resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/quote');
+ }
+
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return Varien_Object
+ */
+ protected function _initOldFieldsMap()
+ {
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ * @throws Mage_Core_Exception
+ */
+ protected function _beforeSave()
+ {
+ /**
+ * Currency logic
+ *
+ * global - currency which is set for default in backend
+ * base - currency which is set for current website. all attributes that
+ * have 'base_' prefix saved in this currency
+ * store - all the time it was currency of website and all attributes
+ * with 'base_' were saved in this currency. From now on it is
+ * deprecated and will be duplication of base currency code.
+ * quote/order - currency which was selected by customer or configured by
+ * admin for current store. currency in which customer sees
+ * price thought all checkout.
+ *
+ * Rates:
+ * store_to_base & store_to_quote/store_to_order - are deprecated
+ * base_to_global & base_to_quote/base_to_order - must be used instead
+ */
+
+ $globalCurrencyCode = Mage::app()->getBaseCurrencyCode();
+ $baseCurrency = $this->getStore()->getBaseCurrency();
+
+ if ($this->hasForcedCurrency()) {
+ $quoteCurrency = $this->getForcedCurrency();
+ } else {
+ $quoteCurrency = $this->getStore()->getCurrentCurrency();
+ }
+
+ $this->setGlobalCurrencyCode($globalCurrencyCode);
+ $this->setBaseCurrencyCode($baseCurrency->getCode());
+ $this->setStoreCurrencyCode($baseCurrency->getCode());
+ $this->setQuoteCurrencyCode($quoteCurrency->getCode());
+
+ //deprecated, read above
+ $this->setStoreToBaseRate($baseCurrency->getRate($globalCurrencyCode));
+ $this->setStoreToQuoteRate($baseCurrency->getRate($quoteCurrency));
+
+ $this->setBaseToGlobalRate($baseCurrency->getRate($globalCurrencyCode));
+ $this->setBaseToQuoteRate($baseCurrency->getRate($quoteCurrency));
+
+ if (!$this->hasChangedFlag() || $this->getChangedFlag() == true) {
+ $this->setIsChanged(1);
+ } else {
+ $this->setIsChanged(0);
+ }
+
+ if ($this->_customer) {
+ $this->setCustomerId($this->_customer->getId());
+ }
+
+ return parent::_beforeSave();
+ }
+
+ /**
+ * Save related items
+ *
+ * @return $this
+ */
+ protected function _afterSave()
+ {
+ parent::_afterSave();
+
+ if ($this->_addresses !== null) {
+ $this->getAddressesCollection()->save();
+ }
+
+ if ($this->_items !== null) {
+ $this->getItemsCollection()->save();
+ }
+
+ if ($this->_payments !== null) {
+ $this->getPaymentsCollection()->save();
+ }
+ return $this;
+ }
+
+ /**
+ * Retrieve quote address by type
+ *
+ * @param string $type
+ * @return Mage_Sales_Model_Quote_Address
+ */
+ protected function _getAddressByType($type)
+ {
+ foreach ($this->getAddressesCollection() as $address) {
+ if ($address->getAddressType() == $type && !$address->isDeleted()) {
+ return $address;
+ }
+ }
+
+ $address = Mage::getModel('sales/quote_address')->setAddressType($type);
+ $this->addAddress($address);
+ return $address;
+ }
+
+ /**
+ * Adding catalog product object data to quote
+ *
+ * @param int $qty
+ * @return Mage_Sales_Model_Quote_Item
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _addCatalogProduct(Mage_Catalog_Model_Product $product, $qty = 1)
+ {
+ $newItem = false;
+ $item = $this->getItemByProduct($product);
+ if (!$item) {
+ $item = Mage::getModel('sales/quote_item');
+ $item->setQuote($this);
+ if (Mage::app()->getStore()->isAdmin()) {
+ $item->setStoreId($this->getStore()->getId());
+ } else {
+ $item->setStoreId(Mage::app()->getStore()->getId());
+ }
+ $newItem = true;
+ }
+
+ /**
+ * We can't modify existing child items
+ */
+ if ($item->getId() && $product->getParentProductId()) {
+ return $item;
+ }
+
+ $item->setOptions($product->getCustomOptions())
+ ->setProduct($product);
+
+ // Add only item that is not in quote already (there can be other new or already saved item
+ if ($newItem) {
+ $this->addItem($item);
+ }
+
+ return $item;
+ }
+
+ /**
+ * Sets flag, whether this quote has some error associated with it.
+ *
+ * @param bool $flag
+ * @return $this
+ */
+ protected function _setHasError($flag)
+ {
+ return $this->setData('has_error', $flag);
+ }
+
+ /**
+ * Clears list of errors, associated with this quote.
+ * Also automatically removes error-flag from oneself.
+ *
+ * @return $this
+ */
+ protected function _clearErrorInfo()
+ {
+ $this->_errorInfoGroups = [];
+ $this->_setHasError(false);
+ return $this;
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _validateCouponCode()
+ {
+ $code = $this->getCouponCode();
+ if (strlen($code)) {
+ $addressHasCoupon = false;
+ $addresses = $this->getAllAddresses();
+ if (count($addresses) > 0) {
+ foreach ($addresses as $address) {
+ if ($address->hasCouponCode()) {
+ $addressHasCoupon = true;
+ }
+ }
+ if (!$addressHasCoupon) {
+ $this->setCouponCode('');
+ }
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Trigger collect totals after loading, if required
+ *
+ * @inheritDoc
+ */
+ protected function _afterLoad()
+ {
+ // collect totals and save me, if required
+ if ($this->getData('trigger_recollect') == 1) {
+ $this->setTriggerRecollect(0)->getResource()->save($this);
+ $this->collectTotals()->save();
+ }
+ return parent::_afterLoad();
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote/Address.php b/app/code/core/Mage/Sales/Model/Quote/Address.php
index 08363d23c9d..c1084f5682a 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Address.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Address.php
@@ -296,114 +296,11 @@ class Mage_Sales_Model_Quote_Address extends Mage_Customer_Model_Address_Abstrac
protected $_nominalOnly = null;
/**
- * Initialize resource
- */
- protected function _construct()
- {
- $this->_init('sales/quote_address');
- }
-
- /**
- * Init mapping array of short fields to its full names
- *
- * @return $this
- */
- protected function _initOldFieldsMap()
- {
- return $this;
- }
-
- /**
- * Initialize Quote identifier before save
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
- $this->_populateBeforeSaveData();
- return $this;
- }
-
- /**
- * Set the required fields
- */
- protected function _populateBeforeSaveData()
- {
- if ($this->getQuote()) {
- $this->_dataSaveAllowed = (bool) $this->getQuote()->getId();
-
- if ($this->getQuote()->getId()) {
- $this->setQuoteId($this->getQuote()->getId());
- }
- $this->setCustomerId($this->getQuote()->getCustomerId());
-
- /**
- * Init customer address id if customer address is assigned
- */
- if ($this->getCustomerAddress()) {
- $this->setCustomerAddressId($this->getCustomerAddress()->getId());
- }
-
- /**
- * Set same_as_billing to "1" when default shipping address is set as default
- * and it is not equal billing address
- */
- if (!$this->getId()) {
- $this->setSameAsBilling((int) $this->_isSameAsBilling());
- }
- }
- }
-
- /**
- * Returns true if the billing address is same as the shipping
- *
- * @return bool
- */
- protected function _isSameAsBilling()
- {
- return ($this->getAddressType() === self::TYPE_SHIPPING
- && ($this->_isNotRegisteredCustomer() || $this->_isDefaultShippingNullOrSameAsBillingAddress()));
- }
-
- /**
- * Checks if the user is a registered customer
- *
- * @return bool
- */
- protected function _isNotRegisteredCustomer()
- {
- return !$this->getQuote()->getCustomerId() || $this->getCustomerAddressId() === null;
- }
-
- /**
- * Returns true if the def billing address is same as customer address
- *
- * @return bool
- */
- protected function _isDefaultShippingNullOrSameAsBillingAddress()
- {
- $customer = $this->getQuote()->getCustomer();
- return !$customer->getDefaultShippingAddress()
- || $customer->getDefaultBillingAddress() && $customer->getDefaultShippingAddress()
- && $customer->getDefaultBillingAddress()->getId() == $customer->getDefaultShippingAddress()->getId();
- }
-
- /**
- * Save child collections
- *
- * @return $this
+ * Rewrite clone method
*/
- protected function _afterSave()
+ public function __clone()
{
- parent::_afterSave();
- if ($this->_items !== null) {
- $this->getItemsCollection()->save();
- }
- if ($this->_rates !== null) {
- $this->getShippingRatesCollection()->save();
- }
- return $this;
+ $this->setId(null);
}
/**
@@ -620,24 +517,6 @@ public function getAllNominalItems()
return $result;
}
- /**
- * Segregate by nominal criteria
- *
- * true: get nominals only
- * false: get non-nominals only
- * null: get all
- *
- * @param Mage_Sales_Model_Quote_Item_Abstract $item
- * @return Mage_Sales_Model_Quote_Item_Abstract|false
- */
- protected function _filterNominal($item)
- {
- return ($this->_nominalOnly === null)
- || (($this->_nominalOnly === false) && !$item->isNominal())
- || (($this->_nominalOnly === true) && $item->isNominal())
- ? $item : false;
- }
-
/**
* Retrieve all visible items
*
@@ -853,24 +732,6 @@ public function getGroupedAllShippingRates()
return $rates;
}
- /**
- * Sort rates recursive callback
- *
- * @param array $a
- * @param array $b
- * @return int
- */
- protected function _sortRates($a, $b)
- {
- if ((int) $a[0]->carrier_sort_order < (int) $b[0]->carrier_sort_order) {
- return -1;
- } elseif ((int) $a[0]->carrier_sort_order > (int) $b[0]->carrier_sort_order) {
- return 1;
- } else {
- return 0;
- }
- }
-
/**
* Retrieve shipping rate by identifier
*
@@ -1122,14 +983,6 @@ public function addTotal($total)
return $this;
}
- /**
- * Rewrite clone method
- */
- public function __clone()
- {
- $this->setId(null);
- }
-
/**
* Validate minimum amount
*
@@ -1337,4 +1190,151 @@ public function getCouponCode(): string
{
return (string) $this->_getData('coupon_code');
}
+
+ /**
+ * Initialize resource
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/quote_address');
+ }
+
+ /**
+ * Init mapping array of short fields to its full names
+ *
+ * @return $this
+ */
+ protected function _initOldFieldsMap()
+ {
+ return $this;
+ }
+
+ /**
+ * Initialize Quote identifier before save
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ $this->_populateBeforeSaveData();
+ return $this;
+ }
+
+ /**
+ * Set the required fields
+ */
+ protected function _populateBeforeSaveData()
+ {
+ if ($this->getQuote()) {
+ $this->_dataSaveAllowed = (bool) $this->getQuote()->getId();
+
+ if ($this->getQuote()->getId()) {
+ $this->setQuoteId($this->getQuote()->getId());
+ }
+ $this->setCustomerId($this->getQuote()->getCustomerId());
+
+ /**
+ * Init customer address id if customer address is assigned
+ */
+ if ($this->getCustomerAddress()) {
+ $this->setCustomerAddressId($this->getCustomerAddress()->getId());
+ }
+
+ /**
+ * Set same_as_billing to "1" when default shipping address is set as default
+ * and it is not equal billing address
+ */
+ if (!$this->getId()) {
+ $this->setSameAsBilling((int) $this->_isSameAsBilling());
+ }
+ }
+ }
+
+ /**
+ * Returns true if the billing address is same as the shipping
+ *
+ * @return bool
+ */
+ protected function _isSameAsBilling()
+ {
+ return ($this->getAddressType() === self::TYPE_SHIPPING
+ && ($this->_isNotRegisteredCustomer() || $this->_isDefaultShippingNullOrSameAsBillingAddress()));
+ }
+
+ /**
+ * Checks if the user is a registered customer
+ *
+ * @return bool
+ */
+ protected function _isNotRegisteredCustomer()
+ {
+ return !$this->getQuote()->getCustomerId() || $this->getCustomerAddressId() === null;
+ }
+
+ /**
+ * Returns true if the def billing address is same as customer address
+ *
+ * @return bool
+ */
+ protected function _isDefaultShippingNullOrSameAsBillingAddress()
+ {
+ $customer = $this->getQuote()->getCustomer();
+ return !$customer->getDefaultShippingAddress()
+ || $customer->getDefaultBillingAddress() && $customer->getDefaultShippingAddress()
+ && $customer->getDefaultBillingAddress()->getId() == $customer->getDefaultShippingAddress()->getId();
+ }
+
+ /**
+ * Save child collections
+ *
+ * @return $this
+ */
+ protected function _afterSave()
+ {
+ parent::_afterSave();
+ if ($this->_items !== null) {
+ $this->getItemsCollection()->save();
+ }
+ if ($this->_rates !== null) {
+ $this->getShippingRatesCollection()->save();
+ }
+ return $this;
+ }
+
+ /**
+ * Segregate by nominal criteria
+ *
+ * true: get nominals only
+ * false: get non-nominals only
+ * null: get all
+ *
+ * @param Mage_Sales_Model_Quote_Item_Abstract $item
+ * @return Mage_Sales_Model_Quote_Item_Abstract|false
+ */
+ protected function _filterNominal($item)
+ {
+ return ($this->_nominalOnly === null)
+ || (($this->_nominalOnly === false) && !$item->isNominal())
+ || (($this->_nominalOnly === true) && $item->isNominal())
+ ? $item : false;
+ }
+
+ /**
+ * Sort rates recursive callback
+ *
+ * @param array $a
+ * @param array $b
+ * @return int
+ */
+ protected function _sortRates($a, $b)
+ {
+ if ((int) $a[0]->carrier_sort_order < (int) $b[0]->carrier_sort_order) {
+ return -1;
+ } elseif ((int) $a[0]->carrier_sort_order > (int) $b[0]->carrier_sort_order) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote/Address/Item.php b/app/code/core/Mage/Sales/Model/Quote/Address/Item.php
index 5810bf523c7..e1fa525e629 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Address/Item.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Address/Item.php
@@ -118,23 +118,6 @@ class Mage_Sales_Model_Quote_Address_Item extends Mage_Sales_Model_Quote_Item_Ab
protected $_address;
protected $_quote;
- protected function _construct()
- {
- $this->_init('sales/quote_address_item');
- }
-
- /**
- * @return $this
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
- if ($this->getAddress()) {
- $this->setQuoteAddressId($this->getAddress()->getId());
- }
- return $this;
- }
-
/**
* Declare address model
*
@@ -205,4 +188,21 @@ public function getOptionBycode($code)
}
return null;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/quote_address_item');
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ if ($this->getAddress()) {
+ $this->setQuoteAddressId($this->getAddress()->getId());
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote/Address/Rate.php b/app/code/core/Mage/Sales/Model/Quote/Address/Rate.php
index 290b15329b4..dfd26b55ffd 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Address/Rate.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Address/Rate.php
@@ -50,23 +50,6 @@ class Mage_Sales_Model_Quote_Address_Rate extends Mage_Shipping_Model_Rate_Abstr
{
protected $_address;
- protected function _construct()
- {
- $this->_init('sales/quote_address_rate');
- }
-
- /**
- * @return $this
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
- if ($this->getAddress()) {
- $this->setAddressId($this->getAddress()->getId());
- }
- return $this;
- }
-
/**
* @return $this
*/
@@ -109,4 +92,21 @@ public function importShippingRate(Mage_Shipping_Model_Rate_Result_Abstract $rat
}
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/quote_address_rate');
+ }
+
+ /**
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ if ($this->getAddress()) {
+ $this->setAddressId($this->getAddress()->getId());
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Abstract.php b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Abstract.php
index c5e10a50b54..2d0faab8a0b 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Abstract.php
@@ -107,6 +107,58 @@ public function fetch(Mage_Sales_Model_Quote_Address $address)
return [];
}
+ /**
+ * Getter for row default total
+ *
+ * @return float
+ */
+ public function getItemRowTotal(Mage_Sales_Model_Quote_Item_Abstract $item)
+ {
+ if (!$this->_itemRowTotalKey) {
+ return 0;
+ }
+ return $item->getDataUsingMethod($this->_itemRowTotalKey);
+ }
+
+ /**
+ * Getter for row default base total
+ *
+ * @return float
+ */
+ public function getItemBaseRowTotal(Mage_Sales_Model_Quote_Item_Abstract $item)
+ {
+ if (!$this->_itemRowTotalKey) {
+ return 0;
+ }
+ return $item->getDataUsingMethod('base_' . $this->_itemRowTotalKey);
+ }
+
+ /**
+ * Whether the item row total may be compounded with others
+ *
+ * @return bool
+ */
+ public function getIsItemRowTotalCompoundable(Mage_Sales_Model_Quote_Item_Abstract $item)
+ {
+ if ($item->getData("skip_compound_{$this->_itemRowTotalKey}")) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Process model configuration array.
+ * This method can be used for changing models apply sort order
+ *
+ * @param array $config
+ * @param Mage_Core_Model_Store $store
+ * @return array
+ */
+ public function processConfigArray($config, $store)
+ {
+ return $config;
+ }
+
/**
* Set address which can be used inside totals calculation
*
@@ -199,56 +251,4 @@ protected function _getAddressItems(Mage_Sales_Model_Quote_Address $address)
{
return $address->getAllNonNominalItems();
}
-
- /**
- * Getter for row default total
- *
- * @return float
- */
- public function getItemRowTotal(Mage_Sales_Model_Quote_Item_Abstract $item)
- {
- if (!$this->_itemRowTotalKey) {
- return 0;
- }
- return $item->getDataUsingMethod($this->_itemRowTotalKey);
- }
-
- /**
- * Getter for row default base total
- *
- * @return float
- */
- public function getItemBaseRowTotal(Mage_Sales_Model_Quote_Item_Abstract $item)
- {
- if (!$this->_itemRowTotalKey) {
- return 0;
- }
- return $item->getDataUsingMethod('base_' . $this->_itemRowTotalKey);
- }
-
- /**
- * Whether the item row total may be compounded with others
- *
- * @return bool
- */
- public function getIsItemRowTotalCompoundable(Mage_Sales_Model_Quote_Item_Abstract $item)
- {
- if ($item->getData("skip_compound_{$this->_itemRowTotalKey}")) {
- return false;
- }
- return true;
- }
-
- /**
- * Process model configuration array.
- * This method can be used for changing models apply sort order
- *
- * @param array $config
- * @param Mage_Core_Model_Store $store
- * @return array
- */
- public function processConfigArray($config, $store)
- {
- return $config;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Subtotal.php b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Subtotal.php
index 12062bf919d..46f5ae1d55a 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Subtotal.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Subtotal.php
@@ -63,6 +63,31 @@ public function collect(Mage_Sales_Model_Quote_Address $address)
return $this;
}
+ /**
+ * Assign subtotal amount and label to address object
+ *
+ * @return Mage_Sales_Model_Quote_Address_Total_Subtotal
+ */
+ public function fetch(Mage_Sales_Model_Quote_Address $address)
+ {
+ $address->addTotal([
+ 'code' => $this->getCode(),
+ 'title' => Mage::helper('sales')->__('Subtotal'),
+ 'value' => $address->getSubtotal(),
+ ]);
+ return $this;
+ }
+
+ /**
+ * Get Subtotal label
+ *
+ * @return string
+ */
+ public function getLabel()
+ {
+ return Mage::helper('sales')->__('Subtotal');
+ }
+
/**
* Address item initialization
*
@@ -139,29 +164,4 @@ protected function _removeItem($address, $item)
return $this;
}
-
- /**
- * Assign subtotal amount and label to address object
- *
- * @return Mage_Sales_Model_Quote_Address_Total_Subtotal
- */
- public function fetch(Mage_Sales_Model_Quote_Address $address)
- {
- $address->addTotal([
- 'code' => $this->getCode(),
- 'title' => Mage::helper('sales')->__('Subtotal'),
- 'value' => $address->getSubtotal(),
- ]);
- return $this;
- }
-
- /**
- * Get Subtotal label
- *
- * @return string
- */
- public function getLabel()
- {
- return Mage::helper('sales')->__('Subtotal');
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Tax.php b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Tax.php
index 244c610d678..80f8a05a88f 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Tax.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Tax.php
@@ -190,6 +190,26 @@ public function collect(Mage_Sales_Model_Quote_Address $address)
return $this;
}
+ /**
+ * @return $this
+ */
+ public function fetch(Mage_Sales_Model_Quote_Address $address)
+ {
+ $applied = $address->getAppliedTaxes();
+ $store = $address->getQuote()->getStore();
+ $amount = $address->getTaxAmount();
+
+ if (($amount != 0) || (Mage::helper('tax')->displayZeroTax($store))) {
+ $address->addTotal([
+ 'code' => $this->getCode(),
+ 'title' => Mage::helper('sales')->__('Tax'),
+ 'full_info' => $applied ? $applied : [],
+ 'value' => $amount,
+ ]);
+ }
+ return $this;
+ }
+
/**
* @param array $applied
* @param float $amount
@@ -233,24 +253,4 @@ protected function _saveAppliedTaxes(Mage_Sales_Model_Quote_Address $address, $a
}
$address->setAppliedTaxes($previouslyAppliedTaxes);
}
-
- /**
- * @return $this
- */
- public function fetch(Mage_Sales_Model_Quote_Address $address)
- {
- $applied = $address->getAppliedTaxes();
- $store = $address->getQuote()->getStore();
- $amount = $address->getTaxAmount();
-
- if (($amount != 0) || (Mage::helper('tax')->displayZeroTax($store))) {
- $address->addTotal([
- 'code' => $this->getCode(),
- 'title' => Mage::helper('sales')->__('Tax'),
- 'full_info' => $applied ? $applied : [],
- 'value' => $amount,
- ]);
- }
- return $this;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote/Item.php b/app/code/core/Mage/Sales/Model/Quote/Item.php
index d914981ce22..b6356d6084a 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Item.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Item.php
@@ -219,36 +219,19 @@ class Mage_Sales_Model_Quote_Item extends Mage_Sales_Model_Quote_Item_Abstract
*/
protected $_errorInfos = null;
- protected function _construct()
- {
- $this->_init('sales/quote_item');
- $this->_errorInfos = Mage::getModel('sales/status_list');
- }
-
- /**
- * Init mapping array of short fields to
- * its full names
- *
- * @return $this
- */
- protected function _initOldFieldsMap()
- {
- return $this;
- }
-
/**
- * Quote Item Before Save prepare data process
- *
- * @return $this
+ * Clone quote item
*/
- protected function _beforeSave()
+ public function __clone()
{
- parent::_beforeSave();
- $this->setIsVirtual($this->getProduct()->getIsVirtual());
- if ($this->getQuote()) {
- $this->setQuoteId($this->getQuote()->getId());
+ parent::__clone();
+ $options = $this->getOptions();
+ $this->_quote = null;
+ $this->_options = [];
+ $this->_optionsByCode = [];
+ foreach ($options as $option) {
+ $this->addOption(clone $option);
}
- return $this;
}
/**
@@ -278,28 +261,6 @@ public function getQuote()
return $this->_quote;
}
- /**
- * Prepare quantity
- *
- * @param float|int $qty
- * @return int|float
- */
- protected function _prepareQty($qty)
- {
- $qty = Mage::app()->getLocale()->getNumber($qty);
- return ($qty > 0) ? $qty : 1;
- }
-
- /**
- * Get Magento App instance
- *
- * @return Mage_Core_Model_App
- */
- protected function _getApp()
- {
- return Mage::app();
- }
-
/**
* Adding quantity to quote item
*
@@ -693,22 +654,6 @@ public function removeOption($code)
return $this;
}
- /**
- * Register option code
- *
- * @param Mage_Sales_Model_Quote_Item_Option $option
- * @return $this
- */
- protected function _addOptionCode($option)
- {
- if (!isset($this->_optionsByCode[$option->getCode()])) {
- $this->_optionsByCode[$option->getCode()] = $option;
- } else {
- Mage::throwException(Mage::helper('sales')->__('An item option with code %s already exists.', $option->getCode()));
- }
- return $this;
- }
-
/**
* Get item option by code
*
@@ -723,45 +668,6 @@ public function getOptionByCode($code)
return null;
}
- /**
- * Checks that item model has data changes.
- * Call save item options if model isn't need to save in DB
- *
- * @return bool
- */
- protected function _hasModelChanged()
- {
- if (!$this->hasDataChanges()) {
- return false;
- }
-
- return $this->_getResource()->hasDataChanged($this);
- }
-
- /**
- * Save item options
- *
- * @return $this
- */
- protected function _saveItemOptions()
- {
- foreach ($this->_options as $index => $option) {
- if ($option->isDeleted()) {
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $option->delete();
- unset($this->_options[$index]);
- unset($this->_optionsByCode[$option->getCode()]);
- } else {
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $option->save();
- }
- }
-
- $this->_flagOptionsSaved = true; // Report to watchers that options were saved
-
- return $this;
- }
-
/**
* Save model plus its options
* Ensures saving options in case when resource model was not changed
@@ -780,32 +686,6 @@ public function save()
return $this;
}
- /**
- * Save item options after item saved
- *
- * @inheritDoc
- */
- protected function _afterSave()
- {
- $this->_saveItemOptions();
- return parent::_afterSave();
- }
-
- /**
- * Clone quote item
- */
- public function __clone()
- {
- parent::__clone();
- $options = $this->getOptions();
- $this->_quote = null;
- $this->_options = [];
- $this->_optionsByCode = [];
- foreach ($options as $option) {
- $this->addOption(clone $option);
- }
- }
-
/**
* Returns formatted buy request - object, holding request received from
* product view page with keys and options for configured product
@@ -824,17 +704,6 @@ public function getBuyRequest()
return $buyRequest;
}
- /**
- * Sets flag, whether this quote item has some error associated with it.
- *
- * @param bool $flag
- * @return $this
- */
- protected function _setHasError($flag)
- {
- return $this->setData('has_error', $flag);
- }
-
/**
* Sets flag, whether this quote item has some error associated with it.
* When TRUE - also adds 'unknown' error information to list of quote item errors.
@@ -855,19 +724,6 @@ public function setHasError($flag)
return $this;
}
- /**
- * Clears list of errors, associated with this quote item.
- * Also automatically removes error-flag from oneself.
- *
- * @return $this
- */
- protected function _clearErrorInfo()
- {
- $this->_errorInfos->clear();
- $this->_setHasError(false);
- return $this;
- }
-
/**
* Adds error information to the quote item.
* Automatically sets error flag.
@@ -922,4 +778,148 @@ public function removeErrorInfosByParams($params)
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/quote_item');
+ $this->_errorInfos = Mage::getModel('sales/status_list');
+ }
+
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return $this
+ */
+ protected function _initOldFieldsMap()
+ {
+ return $this;
+ }
+
+ /**
+ * Quote Item Before Save prepare data process
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ $this->setIsVirtual($this->getProduct()->getIsVirtual());
+ if ($this->getQuote()) {
+ $this->setQuoteId($this->getQuote()->getId());
+ }
+ return $this;
+ }
+
+ /**
+ * Prepare quantity
+ *
+ * @param float|int $qty
+ * @return int|float
+ */
+ protected function _prepareQty($qty)
+ {
+ $qty = Mage::app()->getLocale()->getNumber($qty);
+ return ($qty > 0) ? $qty : 1;
+ }
+
+ /**
+ * Get Magento App instance
+ *
+ * @return Mage_Core_Model_App
+ */
+ protected function _getApp()
+ {
+ return Mage::app();
+ }
+
+ /**
+ * Register option code
+ *
+ * @param Mage_Sales_Model_Quote_Item_Option $option
+ * @return $this
+ */
+ protected function _addOptionCode($option)
+ {
+ if (!isset($this->_optionsByCode[$option->getCode()])) {
+ $this->_optionsByCode[$option->getCode()] = $option;
+ } else {
+ Mage::throwException(Mage::helper('sales')->__('An item option with code %s already exists.', $option->getCode()));
+ }
+ return $this;
+ }
+
+ /**
+ * Checks that item model has data changes.
+ * Call save item options if model isn't need to save in DB
+ *
+ * @return bool
+ */
+ protected function _hasModelChanged()
+ {
+ if (!$this->hasDataChanges()) {
+ return false;
+ }
+
+ return $this->_getResource()->hasDataChanged($this);
+ }
+
+ /**
+ * Save item options
+ *
+ * @return $this
+ */
+ protected function _saveItemOptions()
+ {
+ foreach ($this->_options as $index => $option) {
+ if ($option->isDeleted()) {
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $option->delete();
+ unset($this->_options[$index]);
+ unset($this->_optionsByCode[$option->getCode()]);
+ } else {
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $option->save();
+ }
+ }
+
+ $this->_flagOptionsSaved = true; // Report to watchers that options were saved
+
+ return $this;
+ }
+
+ /**
+ * Save item options after item saved
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave()
+ {
+ $this->_saveItemOptions();
+ return parent::_afterSave();
+ }
+
+ /**
+ * Sets flag, whether this quote item has some error associated with it.
+ *
+ * @param bool $flag
+ * @return $this
+ */
+ protected function _setHasError($flag)
+ {
+ return $this->setData('has_error', $flag);
+ }
+
+ /**
+ * Clears list of errors, associated with this quote item.
+ * Also automatically removes error-flag from oneself.
+ *
+ * @return $this
+ */
+ protected function _clearErrorInfo()
+ {
+ $this->_errorInfos->clear();
+ $this->_setHasError(false);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php b/app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php
index 6b54dfc1bf1..bc34727aa16 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php
@@ -192,6 +192,17 @@ abstract class Mage_Sales_Model_Quote_Item_Abstract extends Mage_Core_Model_Abst
*/
protected $_optionsByCode;
+ /**
+ * Clone quote item
+ */
+ public function __clone()
+ {
+ $this->setId(null);
+ $this->_parentItem = null;
+ $this->_children = [];
+ $this->_messages = [];
+ }
+
/**
* Retrieve Quote instance
*
@@ -236,20 +247,6 @@ public function getFileDownloadParams()
return null;
}
- /**
- * Specify parent item id before saving data
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
- if ($this->getParentItem()) {
- $this->setParentItemId($this->getParentItem()->getId());
- }
- return $this;
- }
-
/**
* Set parent item
*
@@ -687,17 +684,6 @@ public function setConvertedPrice($value)
return $this;
}
- /**
- * Clone quote item
- */
- public function __clone()
- {
- $this->setId(null);
- $this->_parentItem = null;
- $this->_children = [];
- $this->_messages = [];
- }
-
/**
* Checking if there children calculated or parent item
* when we have parent quote item and its children
@@ -821,6 +807,20 @@ public function getBaseTaxAmount()
return $this->_getData('base_tax_amount');
}
+ /**
+ * Specify parent item id before saving data
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ if ($this->getParentItem()) {
+ $this->setParentItemId($this->getParentItem()->getId());
+ }
+ return $this;
+ }
+
/**
* Get item price (item price always exclude price)
*
diff --git a/app/code/core/Mage/Sales/Model/Quote/Item/Option.php b/app/code/core/Mage/Sales/Model/Quote/Item/Option.php
index 7d1785e1cfc..888478a90db 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Item/Option.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Item/Option.php
@@ -42,23 +42,13 @@ class Mage_Sales_Model_Quote_Item_Option extends Mage_Core_Model_Abstract implem
protected $_item;
protected $_product;
- protected function _construct()
- {
- $this->_init('sales/quote_item_option');
- }
-
/**
- * Checks that item option model has data changes
- *
- * @return bool
+ * Clone option object
*/
- protected function _hasModelChanged()
+ public function __clone()
{
- if (!$this->hasDataChanges()) {
- return false;
- }
-
- return $this->_getResource()->hasDataChanged($this);
+ $this->setId(null);
+ $this->_item = null;
}
/**
@@ -121,6 +111,25 @@ public function getValue()
return $this->_getData('value');
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote_item_option');
+ }
+
+ /**
+ * Checks that item option model has data changes
+ *
+ * @return bool
+ */
+ protected function _hasModelChanged()
+ {
+ if (!$this->hasDataChanges()) {
+ return false;
+ }
+
+ return $this->_getResource()->hasDataChanged($this);
+ }
+
/**
* Initialize item identifier before save data
*
@@ -133,13 +142,4 @@ protected function _beforeSave()
}
return parent::_beforeSave();
}
-
- /**
- * Clone option object
- */
- public function __clone()
- {
- $this->setId(null);
- $this->_item = null;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Quote/Payment.php b/app/code/core/Mage/Sales/Model/Quote/Payment.php
index 3907bf1a027..667e57323ae 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Payment.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Payment.php
@@ -91,11 +91,6 @@ class Mage_Sales_Model_Quote_Payment extends Mage_Payment_Model_Info
protected $_quote;
- protected function _construct()
- {
- $this->_init('sales/quote_payment');
- }
-
/**
* Declare quote model instance
*
@@ -162,25 +157,6 @@ public function importData(array $data)
return $this;
}
- /**
- * Prepare object for save
- *
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- if ($this->getQuote()) {
- $this->setQuoteId($this->getQuote()->getId());
- }
- try {
- $method = $this->getMethodInstance();
- } catch (Mage_Core_Exception $e) {
- return parent::_beforeSave();
- }
- $method->prepareSave();
- return parent::_beforeSave();
- }
-
/**
* Checkout redirect URL getter
*
@@ -219,4 +195,28 @@ public function getMethodInstance()
$method = parent::getMethodInstance();
return $method->setStore($this->getQuote()->getStore());
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/quote_payment');
+ }
+
+ /**
+ * Prepare object for save
+ *
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ if ($this->getQuote()) {
+ $this->setQuoteId($this->getQuote()->getId());
+ }
+ try {
+ $method = $this->getMethodInstance();
+ } catch (Mage_Core_Exception $e) {
+ return parent::_beforeSave();
+ }
+ $method->prepareSave();
+ return parent::_beforeSave();
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Recurring/Profile.php b/app/code/core/Mage/Sales/Model/Recurring/Profile.php
index 77e14940f43..6c13d966a95 100644
--- a/app/code/core/Mage/Sales/Model/Recurring/Profile.php
+++ b/app/code/core/Mage/Sales/Model/Recurring/Profile.php
@@ -543,6 +543,32 @@ public function getInfoValue($infoKey, $infoValueKey)
}
}
+ /**
+ * Return recurring profile child orders Ids
+ *
+ * @return array
+ */
+ public function getChildOrderIds()
+ {
+ $ids = $this->_getResource()->getChildOrderIds($this);
+ if (empty($ids)) {
+ $ids[] = '-1';
+ }
+ return $ids;
+ }
+
+ /**
+ * Add order relation to recurring profile
+ *
+ * @param int $orderId
+ * @return $this
+ */
+ public function addOrderRelation($orderId)
+ {
+ $this->getResource()->addOrderRelation($this->getId(), $orderId);
+ return $this;
+ }
+
protected function _construct()
{
$this->_init('sales/recurring_profile');
@@ -602,32 +628,6 @@ protected function _checkWorkflow($againstState, $soft = true)
return $result;
}
- /**
- * Return recurring profile child orders Ids
- *
- * @return array
- */
- public function getChildOrderIds()
- {
- $ids = $this->_getResource()->getChildOrderIds($this);
- if (empty($ids)) {
- $ids[] = '-1';
- }
- return $ids;
- }
-
- /**
- * Add order relation to recurring profile
- *
- * @param int $orderId
- * @return $this
- */
- public function addOrderRelation($orderId)
- {
- $this->getResource()->addOrderRelation($this->getId(), $orderId);
- return $this;
- }
-
/**
* Create and return new order item based on profile item data and $itemInfo
*
diff --git a/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement.php b/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement.php
index f97ba127870..7437def5766 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Resource_Billing_Agreement extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/billing_agreement', 'agreement_id');
- }
-
/**
* Add order relation to billing agreement
*
@@ -45,4 +40,8 @@ public function addOrderRelation($agreementId, $orderId)
);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/billing_agreement', 'agreement_id');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement/Collection.php
index d76c2d03d23..3dd8e09d83a 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement/Collection.php
@@ -36,15 +36,6 @@ class Mage_Sales_Model_Resource_Billing_Agreement_Collection extends Mage_Core_M
'agreement_updated_at' => 'main_table.updated_at',
]];
- /**
- * Collection initialization
- *
- */
- protected function _construct()
- {
- $this->_init('sales/billing_agreement');
- }
-
/**
* Add cutomer details(email, firstname, lastname) to select
*
@@ -94,4 +85,13 @@ public function addCustomerDetails()
);
return $this;
}
+
+ /**
+ * Collection initialization
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/billing_agreement');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Collection/Abstract.php b/app/code/core/Mage/Sales/Model/Resource/Collection/Abstract.php
index 8b0b171184b..fbdccd67c69 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Collection/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Collection/Abstract.php
@@ -22,26 +22,6 @@
*/
abstract class Mage_Sales_Model_Resource_Collection_Abstract extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Check if $attribute is Mage_Eav_Model_Entity_Attribute and convert to string field name
- *
- * @param string|Mage_Eav_Model_Entity_Attribute $attribute
- * @return string
- */
- protected function _attributeToField($attribute)
- {
- $field = false;
- if (is_string($attribute)) {
- $field = $attribute;
- } elseif ($attribute instanceof Mage_Eav_Model_Entity_Attribute) {
- $field = $attribute->getAttributeCode();
- }
- if (!$field) {
- Mage::throwException(Mage::helper('sales')->__('Cannot determine the field name.'));
- }
- return $field;
- }
-
/**
* Add attribute to select result set.
* Backward compatibility with EAV collection
@@ -98,26 +78,6 @@ public function setPage($pageNum, $pageSize)
return $this;
}
- /**
- * Create all ids retrieving select with limitation
- * Backward compatibility with EAV collection
- *
- * @param int $limit
- * @param int $offset
- * @return Varien_Db_Select
- */
- protected function _getAllIdsSelect($limit = null, $offset = null)
- {
- $idsSelect = clone $this->getSelect();
- $idsSelect->reset(Zend_Db_Select::ORDER);
- $idsSelect->reset(Zend_Db_Select::LIMIT_COUNT);
- $idsSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
- $idsSelect->reset(Zend_Db_Select::COLUMNS);
- $idsSelect->columns($this->getResource()->getIdFieldName(), 'main_table');
- $idsSelect->limit($limit, $offset);
- return $idsSelect;
- }
-
/**
* Retrieve all ids for collection
* Backward compatibility with EAV collection
@@ -151,4 +111,43 @@ public function joinAttribute($alias, $attribute, $bind, $filter = null, $joinTy
{
return $this;
}
+ /**
+ * Check if $attribute is Mage_Eav_Model_Entity_Attribute and convert to string field name
+ *
+ * @param string|Mage_Eav_Model_Entity_Attribute $attribute
+ * @return string
+ */
+ protected function _attributeToField($attribute)
+ {
+ $field = false;
+ if (is_string($attribute)) {
+ $field = $attribute;
+ } elseif ($attribute instanceof Mage_Eav_Model_Entity_Attribute) {
+ $field = $attribute->getAttributeCode();
+ }
+ if (!$field) {
+ Mage::throwException(Mage::helper('sales')->__('Cannot determine the field name.'));
+ }
+ return $field;
+ }
+
+ /**
+ * Create all ids retrieving select with limitation
+ * Backward compatibility with EAV collection
+ *
+ * @param int $limit
+ * @param int $offset
+ * @return Varien_Db_Select
+ */
+ protected function _getAllIdsSelect($limit = null, $offset = null)
+ {
+ $idsSelect = clone $this->getSelect();
+ $idsSelect->reset(Zend_Db_Select::ORDER);
+ $idsSelect->reset(Zend_Db_Select::LIMIT_COUNT);
+ $idsSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
+ $idsSelect->reset(Zend_Db_Select::COLUMNS);
+ $idsSelect->columns($this->getResource()->getIdFieldName(), 'main_table');
+ $idsSelect->limit($limit, $offset);
+ return $idsSelect;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order.php b/app/code/core/Mage/Sales/Model/Resource/Order.php
index ee116af5738..33934ce0337 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order.php
@@ -51,48 +51,6 @@ class Mage_Sales_Model_Resource_Order extends Mage_Sales_Model_Resource_Order_Ab
*/
protected $_entityCodeForIncrementId = 'order';
- protected function _construct()
- {
- $this->_init('sales/order', 'entity_id');
- }
-
- /**
- * Init virtual grid records for entity
- *
- * @return $this
- */
- protected function _initVirtualGridColumns()
- {
- parent::_initVirtualGridColumns();
- $adapter = $this->getReadConnection();
- $ifnullFirst = $adapter->getIfNullSql('{{table}}.firstname', $adapter->quote(''));
- $ifnullMiddle = $adapter->getIfNullSql('{{table}}.middlename', $adapter->quote(''));
- $ifnullLast = $adapter->getIfNullSql('{{table}}.lastname', $adapter->quote(''));
- $concatAddress = $adapter->getConcatSql([
- $ifnullFirst,
- $adapter->quote(' '),
- $ifnullMiddle,
- $adapter->quote(' '),
- $ifnullLast,
- ]);
- $concatAddress = new Zend_Db_Expr("TRIM(REPLACE($concatAddress,' ', ' '))");
-
- $this->addVirtualGridColumn(
- 'billing_name',
- 'sales/order_address',
- ['billing_address_id' => 'entity_id'],
- $concatAddress,
- )
- ->addVirtualGridColumn(
- 'shipping_name',
- 'sales/order_address',
- ['shipping_address_id' => 'entity_id'],
- $concatAddress,
- );
-
- return $this;
- }
-
/**
* Count existent products of order items by specified product types
*
@@ -141,4 +99,46 @@ public function getIncrementId($orderId)
->where('entity_id = :entity_id');
return $adapter->fetchOne($select, $bind);
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order', 'entity_id');
+ }
+
+ /**
+ * Init virtual grid records for entity
+ *
+ * @return $this
+ */
+ protected function _initVirtualGridColumns()
+ {
+ parent::_initVirtualGridColumns();
+ $adapter = $this->getReadConnection();
+ $ifnullFirst = $adapter->getIfNullSql('{{table}}.firstname', $adapter->quote(''));
+ $ifnullMiddle = $adapter->getIfNullSql('{{table}}.middlename', $adapter->quote(''));
+ $ifnullLast = $adapter->getIfNullSql('{{table}}.lastname', $adapter->quote(''));
+ $concatAddress = $adapter->getConcatSql([
+ $ifnullFirst,
+ $adapter->quote(' '),
+ $ifnullMiddle,
+ $adapter->quote(' '),
+ $ifnullLast,
+ ]);
+ $concatAddress = new Zend_Db_Expr("TRIM(REPLACE($concatAddress,' ', ' '))");
+
+ $this->addVirtualGridColumn(
+ 'billing_name',
+ 'sales/order_address',
+ ['billing_address_id' => 'entity_id'],
+ $concatAddress,
+ )
+ ->addVirtualGridColumn(
+ 'shipping_name',
+ 'sales/order_address',
+ ['shipping_address_id' => 'entity_id'],
+ $concatAddress,
+ );
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Abstract.php b/app/code/core/Mage/Sales/Model/Resource/Order/Abstract.php
index f493933134a..5b0ee599fb1 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Abstract.php
@@ -114,22 +114,6 @@ public function getVirtualGridColumns()
return $this->_virtualGridColumns;
}
- /**
- * Init virtual grid records for entity
- *
- * @return $this
- */
- protected function _initVirtualGridColumns()
- {
- $this->_virtualGridColumns = [];
- if ($this->_eventPrefix && $this->_eventObject) {
- Mage::dispatchEvent($this->_eventPrefix . '_init_virtual_grid_columns', [
- $this->_eventObject => $this,
- ]);
- }
- return $this;
- }
-
/**
* Update records in grid table
*
@@ -264,42 +248,6 @@ public function getGridTable()
return false;
}
- /**
- * Before save object attribute
- *
- * @param string $attribute
- * @return $this
- */
- protected function _beforeSaveAttribute(Mage_Core_Model_Abstract $object, $attribute)
- {
- if ($this->_eventObject && $this->_eventPrefix) {
- Mage::dispatchEvent($this->_eventPrefix . '_save_attribute_before', [
- $this->_eventObject => $this,
- 'object' => $object,
- 'attribute' => $attribute,
- ]);
- }
- return $this;
- }
-
- /**
- * After save object attribute
- *
- * @param string $attribute
- * @return $this
- */
- protected function _afterSaveAttribute(Mage_Core_Model_Abstract $object, $attribute)
- {
- if ($this->_eventObject && $this->_eventPrefix) {
- Mage::dispatchEvent($this->_eventPrefix . '_save_attribute_after', [
- $this->_eventObject => $this,
- 'object' => $object,
- 'attribute' => $attribute,
- ]);
- }
- return $this;
- }
-
/**
* Perform actions after object save
*
@@ -343,44 +291,6 @@ public function saveAttribute(Mage_Core_Model_Abstract $object, $attribute)
return $this;
}
- /**
- * Perform actions before object save
- *
- * @return $this
- */
- protected function _beforeSave(Mage_Core_Model_Abstract $object)
- {
- if ($this->_useIncrementId && !$object->getIncrementId()) {
- /** @var Mage_Eav_Model_Entity_Type $entityType */
- $entityType = Mage::getSingleton('eav/config')->getEntityType($this->_entityTypeForIncrementId);
- $object->setIncrementId($entityType->fetchNewIncrementId($object->getStoreId()));
- }
- parent::_beforeSave($object);
- return $this;
- }
-
- /**
- * Update field in table if model have been already saved
- *
- * @param Mage_Core_Model_Abstract $object
- * @param array $data
- * @return $this
- */
- protected function _postSaveFieldsUpdate($object, $data)
- {
- if ($object->getId() && !empty($data)) {
- $table = $this->getMainTable();
- $this->_getWriteAdapter()->update(
- $table,
- $data,
- [$this->getIdFieldName() . '=?' => (int) $object->getId()],
- );
- $object->addData($data);
- }
-
- return $this;
- }
-
/**
* Set main resource table
*
@@ -432,4 +342,94 @@ public function updateOnRelatedRecordChanged($field, $entityId)
}
return $this;
}
+
+ /**
+ * Init virtual grid records for entity
+ *
+ * @return $this
+ */
+ protected function _initVirtualGridColumns()
+ {
+ $this->_virtualGridColumns = [];
+ if ($this->_eventPrefix && $this->_eventObject) {
+ Mage::dispatchEvent($this->_eventPrefix . '_init_virtual_grid_columns', [
+ $this->_eventObject => $this,
+ ]);
+ }
+ return $this;
+ }
+
+ /**
+ * Before save object attribute
+ *
+ * @param string $attribute
+ * @return $this
+ */
+ protected function _beforeSaveAttribute(Mage_Core_Model_Abstract $object, $attribute)
+ {
+ if ($this->_eventObject && $this->_eventPrefix) {
+ Mage::dispatchEvent($this->_eventPrefix . '_save_attribute_before', [
+ $this->_eventObject => $this,
+ 'object' => $object,
+ 'attribute' => $attribute,
+ ]);
+ }
+ return $this;
+ }
+
+ /**
+ * After save object attribute
+ *
+ * @param string $attribute
+ * @return $this
+ */
+ protected function _afterSaveAttribute(Mage_Core_Model_Abstract $object, $attribute)
+ {
+ if ($this->_eventObject && $this->_eventPrefix) {
+ Mage::dispatchEvent($this->_eventPrefix . '_save_attribute_after', [
+ $this->_eventObject => $this,
+ 'object' => $object,
+ 'attribute' => $attribute,
+ ]);
+ }
+ return $this;
+ }
+
+ /**
+ * Perform actions before object save
+ *
+ * @return $this
+ */
+ protected function _beforeSave(Mage_Core_Model_Abstract $object)
+ {
+ if ($this->_useIncrementId && !$object->getIncrementId()) {
+ /** @var Mage_Eav_Model_Entity_Type $entityType */
+ $entityType = Mage::getSingleton('eav/config')->getEntityType($this->_entityTypeForIncrementId);
+ $object->setIncrementId($entityType->fetchNewIncrementId($object->getStoreId()));
+ }
+ parent::_beforeSave($object);
+ return $this;
+ }
+
+ /**
+ * Update field in table if model have been already saved
+ *
+ * @param Mage_Core_Model_Abstract $object
+ * @param array $data
+ * @return $this
+ */
+ protected function _postSaveFieldsUpdate($object, $data)
+ {
+ if ($object->getId() && !empty($data)) {
+ $table = $this->getMainTable();
+ $this->_getWriteAdapter()->update(
+ $table,
+ $data,
+ [$this->getIdFieldName() . '=?' => (int) $object->getId()],
+ );
+ $object->addData($data);
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Address.php b/app/code/core/Mage/Sales/Model/Resource/Order/Address.php
index 54bca339f15..23c69af7b66 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Address.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Address.php
@@ -27,11 +27,6 @@ class Mage_Sales_Model_Resource_Order_Address extends Mage_Sales_Model_Resource_
*/
protected $_eventPrefix = 'sales_order_address_resource';
- protected function _construct()
- {
- $this->_init('sales/order_address', 'entity_id');
- }
-
/**
* Return configuration for all attributes
*
@@ -56,6 +51,11 @@ public function getAllAttributes()
return $attributes;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_address', 'entity_id');
+ }
+
/**
* Update related grid table after object save
*
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Collection.php
index a85801fd113..12527b03c3f 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Collection.php
@@ -32,15 +32,6 @@ class Mage_Sales_Model_Resource_Order_Collection extends Mage_Sales_Model_Resour
*/
protected $_eventObject = 'order_collection';
- protected function _construct()
- {
- $this->_init('sales/order');
- $this
- ->addFilterToMap('entity_id', 'main_table.entity_id')
- ->addFilterToMap('customer_id', 'main_table.customer_id')
- ->addFilterToMap('quote_address_id', 'main_table.quote_address_id');
- }
-
/**
* Add items count expr to collection select, backward capability with eav structure
*
@@ -70,78 +61,6 @@ public function getSelectCountSql()
return $countSelect;
}
- /**
- * Reset left join
- *
- * @param int $limit
- * @param int $offset
- * @return Varien_Db_Select
- */
- protected function _getAllIdsSelect($limit = null, $offset = null)
- {
- $idsSelect = parent::_getAllIdsSelect($limit, $offset);
- $idsSelect->resetJoinLeft();
- return $idsSelect;
- }
-
- /**
- * Join table sales_flat_order_address to select for billing and shipping order addresses.
- * Create corillation map
- *
- * @return $this
- */
- protected function _addAddressFields()
- {
- $billingAliasName = 'billing_o_a';
- $shippingAliasName = 'shipping_o_a';
- $joinTable = $this->getTable('sales/order_address');
-
- $this
- ->addFilterToMap('billing_firstname', $billingAliasName . '.firstname')
- ->addFilterToMap('billing_middlename', $billingAliasName . '.middlename')
- ->addFilterToMap('billing_lastname', $billingAliasName . '.lastname')
- ->addFilterToMap('billing_telephone', $billingAliasName . '.telephone')
- ->addFilterToMap('billing_postcode', $billingAliasName . '.postcode')
-
- ->addFilterToMap('shipping_firstname', $shippingAliasName . '.firstname')
- ->addFilterToMap('shipping_middlename', $shippingAliasName . '.middlename')
- ->addFilterToMap('shipping_lastname', $shippingAliasName . '.lastname')
- ->addFilterToMap('shipping_telephone', $shippingAliasName . '.telephone')
- ->addFilterToMap('shipping_postcode', $shippingAliasName . '.postcode');
-
- $this
- ->getSelect()
- ->joinLeft(
- [$billingAliasName => $joinTable],
- "(main_table.entity_id = {$billingAliasName}.parent_id"
- . " AND {$billingAliasName}.address_type = 'billing')",
- [
- $billingAliasName . '.firstname',
- $billingAliasName . '.middlename',
- $billingAliasName . '.lastname',
- $billingAliasName . '.telephone',
- $billingAliasName . '.postcode',
- ],
- )
- ->joinLeft(
- [$shippingAliasName => $joinTable],
- "(main_table.entity_id = {$shippingAliasName}.parent_id"
- . " AND {$shippingAliasName}.address_type = 'shipping')",
- [
- $shippingAliasName . '.firstname',
- $shippingAliasName . '.middlename',
- $shippingAliasName . '.lastname',
- $shippingAliasName . '.telephone',
- $shippingAliasName . '.postcode',
- ],
- );
-
- /** @var Mage_Core_Model_Resource_Helper_Mysql4 $helper */
- $helper = Mage::getResourceHelper('core');
- $helper->prepareColumnsList($this->getSelect());
- return $this;
- }
-
/**
* Add addresses information to select
*
@@ -228,4 +147,85 @@ public function addRecurringProfilesFilter($ids)
->where('srpo.profile_id IN(?)', $ids);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order');
+ $this
+ ->addFilterToMap('entity_id', 'main_table.entity_id')
+ ->addFilterToMap('customer_id', 'main_table.customer_id')
+ ->addFilterToMap('quote_address_id', 'main_table.quote_address_id');
+ }
+
+ /**
+ * Reset left join
+ *
+ * @param int $limit
+ * @param int $offset
+ * @return Varien_Db_Select
+ */
+ protected function _getAllIdsSelect($limit = null, $offset = null)
+ {
+ $idsSelect = parent::_getAllIdsSelect($limit, $offset);
+ $idsSelect->resetJoinLeft();
+ return $idsSelect;
+ }
+
+ /**
+ * Join table sales_flat_order_address to select for billing and shipping order addresses.
+ * Create corillation map
+ *
+ * @return $this
+ */
+ protected function _addAddressFields()
+ {
+ $billingAliasName = 'billing_o_a';
+ $shippingAliasName = 'shipping_o_a';
+ $joinTable = $this->getTable('sales/order_address');
+
+ $this
+ ->addFilterToMap('billing_firstname', $billingAliasName . '.firstname')
+ ->addFilterToMap('billing_middlename', $billingAliasName . '.middlename')
+ ->addFilterToMap('billing_lastname', $billingAliasName . '.lastname')
+ ->addFilterToMap('billing_telephone', $billingAliasName . '.telephone')
+ ->addFilterToMap('billing_postcode', $billingAliasName . '.postcode')
+
+ ->addFilterToMap('shipping_firstname', $shippingAliasName . '.firstname')
+ ->addFilterToMap('shipping_middlename', $shippingAliasName . '.middlename')
+ ->addFilterToMap('shipping_lastname', $shippingAliasName . '.lastname')
+ ->addFilterToMap('shipping_telephone', $shippingAliasName . '.telephone')
+ ->addFilterToMap('shipping_postcode', $shippingAliasName . '.postcode');
+
+ $this
+ ->getSelect()
+ ->joinLeft(
+ [$billingAliasName => $joinTable],
+ "(main_table.entity_id = {$billingAliasName}.parent_id"
+ . " AND {$billingAliasName}.address_type = 'billing')",
+ [
+ $billingAliasName . '.firstname',
+ $billingAliasName . '.middlename',
+ $billingAliasName . '.lastname',
+ $billingAliasName . '.telephone',
+ $billingAliasName . '.postcode',
+ ],
+ )
+ ->joinLeft(
+ [$shippingAliasName => $joinTable],
+ "(main_table.entity_id = {$shippingAliasName}.parent_id"
+ . " AND {$shippingAliasName}.address_type = 'shipping')",
+ [
+ $shippingAliasName . '.firstname',
+ $shippingAliasName . '.middlename',
+ $shippingAliasName . '.lastname',
+ $shippingAliasName . '.telephone',
+ $shippingAliasName . '.postcode',
+ ],
+ );
+
+ /** @var Mage_Core_Model_Resource_Helper_Mysql4 $helper */
+ $helper = Mage::getResourceHelper('core');
+ $helper->prepareColumnsList($this->getSelect());
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Collection.php
index e7814709c4f..9026217a42f 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Collection.php
@@ -39,22 +39,6 @@ class Mage_Sales_Model_Resource_Order_Creditmemo_Collection extends Mage_Sales_M
*/
protected $_orderField = 'order_id';
- protected function _construct()
- {
- $this->_init('sales/order_creditmemo');
- }
-
- /**
- * Used to emulate after load functionality for each item without loading them
- *
- * @return $this
- */
- protected function _afterLoad()
- {
- $this->walk('afterLoad');
- return $this;
- }
-
/**
* Add filtration conditions
*
@@ -70,4 +54,20 @@ public function getFiltered($filter = null)
}
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_creditmemo');
+ }
+
+ /**
+ * Used to emulate after load functionality for each item without loading them
+ *
+ * @return $this
+ */
+ protected function _afterLoad()
+ {
+ $this->walk('afterLoad');
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Comment/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Comment/Collection.php
index 79bf4578df5..e74b3bd190c 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Comment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Comment/Collection.php
@@ -32,12 +32,6 @@ class Mage_Sales_Model_Resource_Order_Creditmemo_Comment_Collection extends Mage
*/
protected $_eventObject = 'order_creditmemo_comment_collection';
- protected function _construct()
- {
- parent::_construct();
- $this->_init('sales/order_creditmemo_comment');
- }
-
/**
* Set creditmemo filter
*
@@ -48,4 +42,10 @@ public function setCreditmemoFilter($creditmemoId)
{
return $this->setParentFilter($creditmemoId);
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('sales/order_creditmemo_comment');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Item/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Item/Collection.php
index 9484ba011c8..4f3d36b8879 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Item/Collection.php
@@ -32,11 +32,6 @@ class Mage_Sales_Model_Resource_Order_Creditmemo_Item_Collection extends Mage_Sa
*/
protected $_eventObject = 'order_creditmemo_item_collection';
- protected function _construct()
- {
- $this->_init('sales/order_creditmemo_item');
- }
-
/**
* Set creditmemo filter
*
@@ -48,4 +43,9 @@ public function setCreditmemoFilter($creditmemoId)
$this->addFieldToFilter('parent_id', $creditmemoId);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_creditmemo_item');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Grid/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Grid/Collection.php
index 5e8273467b0..18bf107098d 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Grid/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Grid/Collection.php
@@ -37,12 +37,6 @@ class Mage_Sales_Model_Resource_Order_Grid_Collection extends Mage_Sales_Model_R
*/
protected $_customerModeFlag = false;
- protected function _construct()
- {
- parent::_construct();
- $this->setMainTable('sales/order_grid');
- }
-
/**
* Get SQL for get record count
*
@@ -90,4 +84,10 @@ public function getIsCustomerMode()
{
return $this->_customerModeFlag;
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setMainTable('sales/order_grid');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Invoice/Comment/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Invoice/Comment/Collection.php
index 17475a65158..638f30c486f 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Invoice/Comment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Invoice/Comment/Collection.php
@@ -32,12 +32,6 @@ class Mage_Sales_Model_Resource_Order_Invoice_Comment_Collection extends Mage_Sa
*/
protected $_eventObject = 'order_invoice_comment_collection';
- protected function _construct()
- {
- parent::_construct();
- $this->_init('sales/order_invoice_comment');
- }
-
/**
* Set invoice filter
*
@@ -48,4 +42,10 @@ public function setInvoiceFilter($invoiceId)
{
return $this->setParentFilter($invoiceId);
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('sales/order_invoice_comment');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Invoice/Item/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Invoice/Item/Collection.php
index 309e4eb8327..f9a056e6a62 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Invoice/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Invoice/Item/Collection.php
@@ -32,11 +32,6 @@ class Mage_Sales_Model_Resource_Order_Invoice_Item_Collection extends Mage_Sales
*/
protected $_eventObject = 'order_invoice_item_collection';
- protected function _construct()
- {
- $this->_init('sales/order_invoice_item');
- }
-
/**
* Set invoice filter
*
@@ -48,4 +43,9 @@ public function setInvoiceFilter($invoiceId)
$this->addFieldToFilter('parent_id', $invoiceId);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_invoice_item');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Item/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Item/Collection.php
index 9debea02be8..e752a5d8930 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Item/Collection.php
@@ -41,30 +41,6 @@ class Mage_Sales_Model_Resource_Order_Item_Collection extends Mage_Sales_Model_R
*/
protected $_orderField = 'order_id';
- protected function _construct()
- {
- $this->_init('sales/order_item');
- }
-
- /**
- * Assign parent items on after collection load
- *
- * @return $this
- */
- protected function _afterLoad()
- {
- parent::_afterLoad();
- /**
- * Assign parent items
- */
- foreach ($this as $item) {
- if ($item->getParentItemId()) {
- $item->setParentItem($this->getItemById($item->getParentItemId()));
- }
- }
- return $this;
- }
-
/**
* Set random items order
*
@@ -152,4 +128,28 @@ public function addFilterByCustomerId($customerId)
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_item');
+ }
+
+ /**
+ * Assign parent items on after collection load
+ *
+ * @return $this
+ */
+ protected function _afterLoad()
+ {
+ parent::_afterLoad();
+ /**
+ * Assign parent items
+ */
+ foreach ($this as $item) {
+ if ($item->getParentItemId()) {
+ $item->setParentItem($this->getItemById($item->getParentItemId()));
+ }
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction.php b/app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction.php
index a7169044736..1596aedb31e 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction.php
@@ -31,38 +31,6 @@ class Mage_Sales_Model_Resource_Order_Payment_Transaction extends Mage_Sales_Mod
'additional_information' => [null, []],
];
- /**
- * Initialize main table and the primary key field name
- *
- */
- protected function _construct()
- {
- $this->_init('sales/payment_transaction', 'transaction_id');
- }
-
- /**
- * Unserialize Varien_Object field in an object
- *
- * @param string $field
- * @param mixed $defaultValue
- */
- protected function _unserializeField(Varien_Object $object, $field, $defaultValue = null)
- {
- $value = $object->getData($field);
- if (empty($value)) {
- $object->setData($field, $defaultValue);
- } elseif (!is_array($value) && !is_object($value)) {
- $unserializedValue = false;
- try {
- $unserializedValue = Mage::helper('core/unserializeArray')
- ->unserialize($value);
- } catch (Exception $e) {
- Mage::logException($e);
- }
- $object->setData($field, $unserializedValue);
- }
- }
-
/**
* Update transactions in database using provided transaction as parent for them
* have to repeat the business logic to avoid accidental injection of wrong transactions
@@ -138,6 +106,38 @@ public function getOrderWebsiteId($orderId)
return $adapter->fetchOne($select, $bind);
}
+ /**
+ * Initialize main table and the primary key field name
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/payment_transaction', 'transaction_id');
+ }
+
+ /**
+ * Unserialize Varien_Object field in an object
+ *
+ * @param string $field
+ * @param mixed $defaultValue
+ */
+ protected function _unserializeField(Varien_Object $object, $field, $defaultValue = null)
+ {
+ $value = $object->getData($field);
+ if (empty($value)) {
+ $object->setData($field, $defaultValue);
+ } elseif (!is_array($value) && !is_object($value)) {
+ $unserializedValue = false;
+ try {
+ $unserializedValue = Mage::helper('core/unserializeArray')
+ ->unserialize($value);
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+ $object->setData($field, $unserializedValue);
+ }
+ }
+
/**
* Lookup for parent_id in already saved transactions of this payment by the order_id
* Also serialize additional information, if any
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction/Collection.php
index f611c1d9ec6..4f5a6b77238 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction/Collection.php
@@ -78,15 +78,6 @@ class Mage_Sales_Model_Resource_Order_Payment_Transaction_Collection extends Mag
*/
protected $_orderField = 'order_id';
- /**
- * Initialize collection items factory class
- */
- protected function _construct()
- {
- $this->_init('sales/order_payment_transaction');
- parent::_construct();
- }
-
/**
* Join order information
*
@@ -179,6 +170,15 @@ public function addStoreFilter($storeIds)
return $this;
}
+ /**
+ * Initialize collection items factory class
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/order_payment_transaction');
+ parent::_construct();
+ }
+
/**
* Prepare filters
*
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Comment/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Comment/Collection.php
index 05d1c9524f4..d80149a05ed 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Comment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Comment/Collection.php
@@ -35,11 +35,6 @@ class Mage_Sales_Model_Resource_Order_Shipment_Comment_Collection extends Mage_S
*/
protected $_eventObject = 'order_shipment_comment_collection';
- protected function _construct()
- {
- $this->_init('sales/order_shipment_comment');
- }
-
/**
* Set shipment filter
*
@@ -50,4 +45,9 @@ public function setShipmentFilter($shipmentId)
{
return $this->setParentFilter($shipmentId);
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_shipment_comment');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Item/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Item/Collection.php
index 07a37ddd252..b0c224a8edd 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Item/Collection.php
@@ -35,11 +35,6 @@ class Mage_Sales_Model_Resource_Order_Shipment_Item_Collection extends Mage_Sale
*/
protected $_eventObject = 'order_shipment_item_collection';
- protected function _construct()
- {
- $this->_init('sales/order_shipment_item');
- }
-
/**
* Set shipment filter
*
@@ -51,4 +46,9 @@ public function setShipmentFilter($shipmentId)
$this->addFieldToFilter('parent_id', $shipmentId);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_shipment_item');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Track/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Track/Collection.php
index 81d3a878c54..b1e799d5603 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Track/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Shipment/Track/Collection.php
@@ -42,11 +42,6 @@ class Mage_Sales_Model_Resource_Order_Shipment_Track_Collection extends Mage_Sal
*/
protected $_orderField = 'order_id';
- protected function _construct()
- {
- $this->_init('sales/order_shipment_track');
- }
-
/**
* Set shipment filter
*
@@ -58,4 +53,9 @@ public function setShipmentFilter($shipmentId)
$this->addFieldToFilter('parent_id', $shipmentId);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_shipment_track');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Status.php b/app/code/core/Mage/Sales/Model/Resource/Order/Status.php
index 9d4745a6e2c..2268e1c04da 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Status.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Status.php
@@ -36,44 +36,6 @@ class Mage_Sales_Model_Resource_Order_Status extends Mage_Core_Model_Resource_Db
*/
protected $_stateTable;
- /**
- * Internal constructor
- */
- protected function _construct()
- {
- $this->_init('sales/order_status', 'status');
- $this->_isPkAutoIncrement = false;
- $this->_labelsTable = $this->getTable('sales/order_status_label');
- $this->_stateTable = $this->getTable('sales/order_status_state');
- }
-
- /**
- * Retrieve select object for load object data
- *
- * @param string $field
- * @param mixed $value
- * @param Varien_Object $object
- * @return Zend_Db_Select
- */
- protected function _getLoadSelect($field, $value, $object)
- {
- if ($field == 'default_state') {
- $select = $this->_getReadAdapter()->select()
- ->from($this->getMainTable(), ['label'])
- ->join(
- ['state_table' => $this->_stateTable],
- $this->getMainTable() . '.status = state_table.status',
- 'status',
- )
- ->where('state_table.state = ?', $value)
- ->order('state_table.is_default DESC')
- ->limit(1);
- } else {
- $select = parent::_getLoadSelect($field, $value, $object);
- }
- return $select;
- }
-
/**
* Store labels getter
*
@@ -87,38 +49,6 @@ public function getStoreLabels(Mage_Core_Model_Abstract $status)
return $this->_getReadAdapter()->fetchPairs($select);
}
- /**
- * Save status labels per store
- *
- * @param Mage_Sales_Model_Order|Mage_Sales_Model_Order_Status $object
- * @inheritDoc
- */
- protected function _afterSave(Mage_Core_Model_Abstract $object)
- {
- if ($object->hasStoreLabels()) {
- $labels = $object->getStoreLabels();
- $this->_getWriteAdapter()->delete(
- $this->_labelsTable,
- ['status = ?' => $object->getStatus()],
- );
- $data = [];
- foreach ($labels as $storeId => $label) {
- if (empty($label)) {
- continue;
- }
- $data[] = [
- 'status' => $object->getStatus(),
- 'store_id' => $storeId,
- 'label' => $label,
- ];
- }
- if (!empty($data)) {
- $this->_getWriteAdapter()->insertMultiple($this->_labelsTable, $data);
- }
- }
- return parent::_afterSave($object);
- }
-
/**
* Assign order status to order state
*
@@ -198,4 +128,74 @@ public function unassignState($status, $state)
}
return $this;
}
+
+ /**
+ * Internal constructor
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/order_status', 'status');
+ $this->_isPkAutoIncrement = false;
+ $this->_labelsTable = $this->getTable('sales/order_status_label');
+ $this->_stateTable = $this->getTable('sales/order_status_state');
+ }
+
+ /**
+ * Retrieve select object for load object data
+ *
+ * @param string $field
+ * @param mixed $value
+ * @param Varien_Object $object
+ * @return Zend_Db_Select
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ if ($field == 'default_state') {
+ $select = $this->_getReadAdapter()->select()
+ ->from($this->getMainTable(), ['label'])
+ ->join(
+ ['state_table' => $this->_stateTable],
+ $this->getMainTable() . '.status = state_table.status',
+ 'status',
+ )
+ ->where('state_table.state = ?', $value)
+ ->order('state_table.is_default DESC')
+ ->limit(1);
+ } else {
+ $select = parent::_getLoadSelect($field, $value, $object);
+ }
+ return $select;
+ }
+
+ /**
+ * Save status labels per store
+ *
+ * @param Mage_Sales_Model_Order|Mage_Sales_Model_Order_Status $object
+ * @inheritDoc
+ */
+ protected function _afterSave(Mage_Core_Model_Abstract $object)
+ {
+ if ($object->hasStoreLabels()) {
+ $labels = $object->getStoreLabels();
+ $this->_getWriteAdapter()->delete(
+ $this->_labelsTable,
+ ['status = ?' => $object->getStatus()],
+ );
+ $data = [];
+ foreach ($labels as $storeId => $label) {
+ if (empty($label)) {
+ continue;
+ }
+ $data[] = [
+ 'status' => $object->getStatus(),
+ 'store_id' => $storeId,
+ 'label' => $label,
+ ];
+ }
+ if (!empty($data)) {
+ $this->_getWriteAdapter()->insertMultiple($this->_labelsTable, $data);
+ }
+ }
+ return parent::_afterSave($object);
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Status/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Status/Collection.php
index a0cdf64dcf2..0ee507bdf94 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Status/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Status/Collection.php
@@ -25,14 +25,6 @@
*/
class Mage_Sales_Model_Resource_Order_Status_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Internal constructor
- */
- protected function _construct()
- {
- $this->_init('sales/order_status');
- }
-
/**
* Get collection data as options array
*
@@ -107,4 +99,11 @@ public function orderByLabel($dir = 'ASC')
$this->getSelect()->order('main_table.label ' . $dir);
return $this;
}
+ /**
+ * Internal constructor
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/order_status');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Status/History/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Status/History/Collection.php
index e89cad0ce78..4c4a44fda2e 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Status/History/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Status/History/Collection.php
@@ -32,11 +32,6 @@ class Mage_Sales_Model_Resource_Order_Status_History_Collection extends Mage_Sal
*/
protected $_eventObject = 'order_status_history_collection';
- protected function _construct()
- {
- $this->_init('sales/order_status_history');
- }
-
/**
* Get history object collection for specified instance (order, shipment, invoice or credit memo)
* Parameter instance may be one of the following types: Mage_Sales_Model_Order,
@@ -60,4 +55,9 @@ public function getUnnotifiedForInstance($instance, $historyEntityName = Mage_Sa
}
return null;
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/order_status_history');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Tax/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Tax/Collection.php
index bd3c84568b0..3ea3a4fa558 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Tax/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Tax/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Resource_Order_Tax_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_tax', 'sales/order_tax');
- }
-
/**
* Load by order
*
@@ -41,4 +36,8 @@ public function loadByOrder($order)
->order('process');
return $this->load();
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_tax', 'sales/order_tax');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Quote.php b/app/code/core/Mage/Sales/Model/Resource/Quote.php
index e62b49e9400..99e0d7158ff 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Quote.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Quote.php
@@ -22,39 +22,6 @@
*/
class Mage_Sales_Model_Resource_Quote extends Mage_Sales_Model_Resource_Abstract
{
- /**
- * Initialize table nad PK name
- *
- */
- protected function _construct()
- {
- $this->_init('sales/quote', 'entity_id');
- }
-
- /**
- * Retrieve select object for load object data
- *
- * @param string $field
- * @param mixed $value
- * @param Mage_Core_Model_Abstract|Mage_Sales_Model_Quote $object
- * @return Varien_Db_Select
- */
- protected function _getLoadSelect($field, $value, $object)
- {
- $select = parent::_getLoadSelect($field, $value, $object);
- $storeIds = $object->getSharedStoreIds();
- if ($storeIds) {
- $select->where('store_id IN (?)', $storeIds);
- } else {
- /**
- * For empty result
- */
- $select->where('store_id < ?', 0);
- }
-
- return $select;
- }
-
/**
* Load quote data by customer identifier
*
@@ -279,4 +246,36 @@ public function markQuotesRecollect($productIds)
return $this;
}
+ /**
+ * Initialize table nad PK name
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/quote', 'entity_id');
+ }
+
+ /**
+ * Retrieve select object for load object data
+ *
+ * @param string $field
+ * @param mixed $value
+ * @param Mage_Core_Model_Abstract|Mage_Sales_Model_Quote $object
+ * @return Varien_Db_Select
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ $select = parent::_getLoadSelect($field, $value, $object);
+ $storeIds = $object->getSharedStoreIds();
+ if ($storeIds) {
+ $select->where('store_id IN (?)', $storeIds);
+ } else {
+ /**
+ * For empty result
+ */
+ $select->where('store_id < ?', 0);
+ }
+
+ return $select;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Collection.php
index 28b80468356..050bc33f4fa 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Collection.php
@@ -32,11 +32,6 @@ class Mage_Sales_Model_Resource_Quote_Address_Collection extends Mage_Core_Model
*/
protected $_eventObject = 'quote_address_collection';
- protected function _construct()
- {
- $this->_init('sales/quote_address');
- }
-
/**
* Setting filter on quote_id field but if quote_id is 0
* we should exclude loading junk data from DB
@@ -50,6 +45,11 @@ public function setQuoteFilter($quoteId)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote_address');
+ }
+
/**
* Redeclare after load method for dispatch event
*
diff --git a/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Item/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Item/Collection.php
index a982f854604..31a5801a0ed 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Item/Collection.php
@@ -22,6 +22,23 @@
*/
class Mage_Sales_Model_Resource_Quote_Address_Item_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
+ /**
+ * Set address filter
+ *
+ * @param int $addressId
+ * @return $this
+ */
+ public function setAddressFilter($addressId)
+ {
+ if ($addressId) {
+ $this->addFieldToFilter('quote_address_id', $addressId);
+ } else {
+ $this->_totalRecords = 0;
+ $this->_setIsLoaded(true);
+ }
+
+ return $this;
+ }
protected function _construct()
{
$this->_init('sales/quote_address_item');
@@ -46,22 +63,4 @@ protected function _afterLoad()
return $this;
}
-
- /**
- * Set address filter
- *
- * @param int $addressId
- * @return $this
- */
- public function setAddressFilter($addressId)
- {
- if ($addressId) {
- $this->addFieldToFilter('quote_address_id', $addressId);
- } else {
- $this->_totalRecords = 0;
- $this->_setIsLoaded(true);
- }
-
- return $this;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Rate/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Rate/Collection.php
index 6acfd0b0b98..06c7b29b64b 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Rate/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Quote/Address/Rate/Collection.php
@@ -29,11 +29,6 @@ class Mage_Sales_Model_Resource_Quote_Address_Rate_Collection extends Mage_Core_
*/
protected $_allowFixedOnly = false;
- protected function _construct()
- {
- $this->_init('sales/quote_address_rate');
- }
-
/**
* Set filter by address id
*
@@ -76,4 +71,9 @@ public function addItem(Varien_Object $rate)
}
return parent::addItem($rate);
}
+
+ protected function _construct()
+ {
+ $this->_init('sales/quote_address_rate');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Quote/Item/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Quote/Item/Collection.php
index 10bc6e1243a..50c8e0fa655 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Quote/Item/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Quote/Item/Collection.php
@@ -39,11 +39,6 @@ class Mage_Sales_Model_Resource_Quote_Item_Collection extends Mage_Core_Model_Re
*/
protected $_productIds = [];
- protected function _construct()
- {
- $this->_init('sales/quote_item');
- }
-
/**
* Retrieve store Id (From Quote)
*
@@ -99,6 +94,11 @@ public function resetJoinQuotes($quotesTableName, $productId = null)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote_item');
+ }
+
/**
* After load processing
*
diff --git a/app/code/core/Mage/Sales/Model/Resource/Quote/Item/Option/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Quote/Item/Option/Collection.php
index e8657233254..dc79a77226d 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Quote/Item/Option/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Quote/Item/Option/Collection.php
@@ -36,43 +36,6 @@ class Mage_Sales_Model_Resource_Quote_Item_Option_Collection extends Mage_Core_M
*/
protected $_optionsByProduct = [];
- /**
- * Define resource model for collection
- *
- */
- protected function _construct()
- {
- $this->_init('sales/quote_item_option');
- }
-
- /**
- * Fill array of options by item and product
- *
- * @return $this
- */
- protected function _afterLoad()
- {
- parent::_afterLoad();
-
- foreach ($this as $option) {
- $optionId = $option->getId();
- $itemId = $option->getItemId();
- $productId = $option->getProductId();
- if (isset($this->_optionsByItem[$itemId])) {
- $this->_optionsByItem[$itemId][] = $optionId;
- } else {
- $this->_optionsByItem[$itemId] = [$optionId];
- }
- if (isset($this->_optionsByProduct[$productId])) {
- $this->_optionsByProduct[$productId][] = $optionId;
- } else {
- $this->_optionsByProduct[$productId] = [$optionId];
- }
- }
-
- return $this;
- }
-
/**
* Apply quote item(s) filter to collection
*
@@ -158,4 +121,41 @@ public function getOptionsByProduct($product)
return $options;
}
+
+ /**
+ * Define resource model for collection
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/quote_item_option');
+ }
+
+ /**
+ * Fill array of options by item and product
+ *
+ * @return $this
+ */
+ protected function _afterLoad()
+ {
+ parent::_afterLoad();
+
+ foreach ($this as $option) {
+ $optionId = $option->getId();
+ $itemId = $option->getItemId();
+ $productId = $option->getProductId();
+ if (isset($this->_optionsByItem[$itemId])) {
+ $this->_optionsByItem[$itemId][] = $optionId;
+ } else {
+ $this->_optionsByItem[$itemId] = [$optionId];
+ }
+ if (isset($this->_optionsByProduct[$productId])) {
+ $this->_optionsByProduct[$productId][] = $optionId;
+ } else {
+ $this->_optionsByProduct[$productId] = [$optionId];
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Quote/Payment/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Quote/Payment/Collection.php
index e1304599302..0003d677bcf 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Quote/Payment/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Quote/Payment/Collection.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Resource_Quote_Payment_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/quote_payment');
- }
-
/**
* Setquote filter to result
*
@@ -37,6 +32,10 @@ public function setQuoteFilter($quoteId)
{
return $this->addFieldToFilter('quote_id', $quoteId);
}
+ protected function _construct()
+ {
+ $this->_init('sales/quote_payment');
+ }
/**
* Unserialize additional_information in each item
diff --git a/app/code/core/Mage/Sales/Model/Resource/Recurring/Profile.php b/app/code/core/Mage/Sales/Model/Resource/Recurring/Profile.php
index f300f0c2eec..c0a3dc0a002 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Recurring/Profile.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Recurring/Profile.php
@@ -22,6 +22,45 @@
*/
class Mage_Sales_Model_Resource_Recurring_Profile extends Mage_Sales_Model_Resource_Abstract
{
+ /**
+ * Return recurring profile child Orders Ids
+ *
+ *
+ * @param Varien_Object $object
+ * @return array
+ */
+ public function getChildOrderIds($object)
+ {
+ $adapter = $this->_getReadAdapter();
+ $bind = [':profile_id' => $object->getId()];
+ $select = $adapter->select()
+ ->from(
+ ['main_table' => $this->getTable('sales/recurring_profile_order')],
+ ['order_id'],
+ )
+ ->where('profile_id=:profile_id');
+
+ return $adapter->fetchCol($select, $bind);
+ }
+
+ /**
+ * Add order relation to recurring profile
+ *
+ * @param int $recurringProfileId
+ * @param int $orderId
+ * @return $this
+ */
+ public function addOrderRelation($recurringProfileId, $orderId)
+ {
+ $this->_getWriteAdapter()->insert(
+ $this->getTable('sales/recurring_profile_order'),
+ [
+ 'profile_id' => $recurringProfileId,
+ 'order_id' => $orderId,
+ ],
+ );
+ return $this;
+ }
/**
* Initialize main table and column
*
@@ -66,44 +105,4 @@ protected function _unserializeField(Varien_Object $object, $field, $defaultValu
$object->setData($field, $unserializedValue);
}
}
-
- /**
- * Return recurring profile child Orders Ids
- *
- *
- * @param Varien_Object $object
- * @return array
- */
- public function getChildOrderIds($object)
- {
- $adapter = $this->_getReadAdapter();
- $bind = [':profile_id' => $object->getId()];
- $select = $adapter->select()
- ->from(
- ['main_table' => $this->getTable('sales/recurring_profile_order')],
- ['order_id'],
- )
- ->where('profile_id=:profile_id');
-
- return $adapter->fetchCol($select, $bind);
- }
-
- /**
- * Add order relation to recurring profile
- *
- * @param int $recurringProfileId
- * @param int $orderId
- * @return $this
- */
- public function addOrderRelation($recurringProfileId, $orderId)
- {
- $this->_getWriteAdapter()->insert(
- $this->getTable('sales/recurring_profile_order'),
- [
- 'profile_id' => $recurringProfileId,
- 'order_id' => $orderId,
- ],
- );
- return $this;
- }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report.php b/app/code/core/Mage/Sales/Model/Resource/Report.php
index 825fff7f721..69d1e3fbfc2 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report.php
@@ -22,8 +22,6 @@
*/
class Mage_Sales_Model_Resource_Report extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct() {}
-
/**
* Set main table and idField
*
@@ -36,4 +34,5 @@ public function init($table, $field = 'id')
$this->_init($table, $field);
return $this;
}
+ protected function _construct() {}
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers.php b/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers.php
index 30fe2cfd8cd..a9a0b402eb7 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers.php
@@ -26,14 +26,6 @@ class Mage_Sales_Model_Resource_Report_Bestsellers extends Mage_Sales_Model_Reso
public const AGGREGATION_MONTHLY = 'monthly';
public const AGGREGATION_YEARLY = 'yearly';
- /**
- * Model initialization
- */
- protected function _construct()
- {
- $this->_init('sales/bestsellers_aggregated_' . self::AGGREGATION_DAILY, 'id');
- }
-
/**
* Aggregate Orders data by order created at
*
@@ -228,6 +220,14 @@ public function aggregate($from = null, $to = null)
return $this;
}
+ /**
+ * Model initialization
+ */
+ protected function _construct()
+ {
+ $this->_init('sales/bestsellers_aggregated_' . self::AGGREGATION_DAILY, 'id');
+ }
+
/**
* Aggregate Orders data for default store
*
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers/Collection.php
index f2bd3a13db3..f199719ac31 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers/Collection.php
@@ -50,6 +50,45 @@ public function __construct()
$this->_applyFilters = false;
}
+ /**
+ * Get SQL for get record count
+ *
+ * @return Varien_Db_Select
+ */
+ public function getSelectCountSql()
+ {
+ $this->_renderFilters();
+ $select = clone $this->getSelect();
+ $select->reset(Zend_Db_Select::ORDER);
+ return $this->getConnection()->select()->from($select, 'COUNT(*)');
+ }
+
+ /**
+ * Set ids for store restrictions
+ *
+ * @param array $storeIds
+ * @return $this
+ */
+ public function addStoreRestrictions($storeIds)
+ {
+ if (!is_array($storeIds)) {
+ $storeIds = [$storeIds];
+ }
+ $currentStoreIds = $this->_storesIds;
+ if (isset($currentStoreIds) && $currentStoreIds != Mage_Core_Model_App::ADMIN_STORE_ID
+ && $currentStoreIds != [Mage_Core_Model_App::ADMIN_STORE_ID]
+ ) {
+ if (!is_array($currentStoreIds)) {
+ $currentStoreIds = [$currentStoreIds];
+ }
+ $this->_storesIds = array_intersect($currentStoreIds, $storeIds);
+ } else {
+ $this->_storesIds = $storeIds;
+ }
+
+ return $this;
+ }
+
/**
* Retrieve columns for select
*
@@ -158,45 +197,6 @@ protected function _initSelect()
return $this;
}
- /**
- * Get SQL for get record count
- *
- * @return Varien_Db_Select
- */
- public function getSelectCountSql()
- {
- $this->_renderFilters();
- $select = clone $this->getSelect();
- $select->reset(Zend_Db_Select::ORDER);
- return $this->getConnection()->select()->from($select, 'COUNT(*)');
- }
-
- /**
- * Set ids for store restrictions
- *
- * @param array $storeIds
- * @return $this
- */
- public function addStoreRestrictions($storeIds)
- {
- if (!is_array($storeIds)) {
- $storeIds = [$storeIds];
- }
- $currentStoreIds = $this->_storesIds;
- if (isset($currentStoreIds) && $currentStoreIds != Mage_Core_Model_App::ADMIN_STORE_ID
- && $currentStoreIds != [Mage_Core_Model_App::ADMIN_STORE_ID]
- ) {
- if (!is_array($currentStoreIds)) {
- $currentStoreIds = [$currentStoreIds];
- }
- $this->_storesIds = array_intersect($currentStoreIds, $storeIds);
- } else {
- $this->_storesIds = $storeIds;
- }
-
- return $this;
- }
-
/**
* Redeclare parent method for applying filters after parent method
* but before adding unions and calculating totals
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Invoiced.php b/app/code/core/Mage/Sales/Model/Resource/Report/Invoiced.php
index 3e2e548c75b..ede7cf0f456 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Invoiced.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Invoiced.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Resource_Report_Invoiced extends Mage_Sales_Model_Resource_Report_Abstract
{
- protected function _construct()
- {
- $this->_setResource('sales');
- }
-
/**
* Aggregate Invoiced data
*
@@ -47,6 +42,10 @@ public function aggregate($from = null, $to = null)
$this->_setFlagData(Mage_Reports_Model_Flag::REPORT_INVOICE_FLAG_CODE);
return $this;
}
+ protected function _construct()
+ {
+ $this->_setResource('sales');
+ }
/**
* Aggregate Invoiced data by invoice created_at as period
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Order.php b/app/code/core/Mage/Sales/Model/Resource/Report/Order.php
index 91d17aa3b3f..2e0f26c0480 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Order.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Order.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Resource_Report_Order extends Mage_Sales_Model_Resource_Report_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_aggregated_created', 'id');
- }
-
/**
* Aggregate Orders data
*
@@ -42,4 +37,8 @@ public function aggregate($from = null, $to = null)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_aggregated_created', 'id');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Createdat.php b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Createdat.php
index 420c6f75699..040cf2f82ac 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Createdat.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Createdat.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Resource_Report_Order_Createdat extends Mage_Sales_Model_Resource_Report_Abstract
{
- protected function _construct()
- {
- $this->_init('sales/order_aggregated_created', 'id');
- }
-
/**
* Aggregate Orders data by order created at
*
@@ -38,6 +33,10 @@ public function aggregate($from = null, $to = null)
{
return $this->_aggregateByField('created_at', $from, $to);
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_aggregated_created', 'id');
+ }
/**
* Aggregate Orders data by custom field
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Updatedat.php b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Updatedat.php
index 3549a799454..12eb64834bd 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Updatedat.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Updatedat.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Resource_Report_Order_Updatedat extends Mage_Sales_Model_Resource_Report_Order_Createdat
{
- protected function _construct()
- {
- $this->_init('sales/order_aggregated_updated', 'id');
- }
-
/**
* Aggregate Orders data by order updated at
*
@@ -38,4 +33,8 @@ public function aggregate($from = null, $to = null)
{
return $this->_aggregateByField('updated_at', $from, $to);
}
+ protected function _construct()
+ {
+ $this->_init('sales/order_aggregated_updated', 'id');
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Refunded.php b/app/code/core/Mage/Sales/Model/Resource/Report/Refunded.php
index 17dcac7a204..d901c72f5a0 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Refunded.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Refunded.php
@@ -22,14 +22,6 @@
*/
class Mage_Sales_Model_Resource_Report_Refunded extends Mage_Sales_Model_Resource_Report_Abstract
{
- /**
- * Model initialization
- */
- protected function _construct()
- {
- $this->_setResource('sales');
- }
-
/**
* Aggregate Refunded data
*
@@ -50,6 +42,13 @@ public function aggregate($from = null, $to = null)
$this->_setFlagData(Mage_Reports_Model_Flag::REPORT_REFUNDED_FLAG_CODE);
return $this;
}
+ /**
+ * Model initialization
+ */
+ protected function _construct()
+ {
+ $this->_setResource('sales');
+ }
/**
* Aggregate refunded data by order created at as period
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Shipping.php b/app/code/core/Mage/Sales/Model/Resource/Report/Shipping.php
index 2c420e1c166..74cde50d110 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Shipping.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Shipping.php
@@ -22,11 +22,6 @@
*/
class Mage_Sales_Model_Resource_Report_Shipping extends Mage_Sales_Model_Resource_Report_Abstract
{
- protected function _construct()
- {
- $this->_setResource('sales');
- }
-
/**
* Aggregate Shipping data
*
@@ -46,6 +41,10 @@ public function aggregate($from = null, $to = null)
$this->_setFlagData(Mage_Reports_Model_Flag::REPORT_SHIPPING_FLAG_CODE);
return $this;
}
+ protected function _construct()
+ {
+ $this->_setResource('sales');
+ }
/**
* Aggregate shipping report by order create_at as period
diff --git a/app/code/core/Mage/Sales/Model/Resource/Sale/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Sale/Collection.php
index 1af7f5b521d..4969f30f45f 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Sale/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Sale/Collection.php
@@ -102,48 +102,6 @@ public function setOrderStateFilter($state, $exclude = false)
return $this;
}
- /**
- * Before load action
- *
- * @return Varien_Data_Collection_Db
- */
- protected function _beforeLoad()
- {
- $this->getSelect()
- ->from(
- ['sales' => Mage::getResourceSingleton('sales/order')->getMainTable()],
- [
- 'store_id',
- 'lifetime' => new Zend_Db_Expr('SUM(sales.base_grand_total)'),
- 'base_lifetime' => new Zend_Db_Expr('SUM(sales.base_grand_total * sales.base_to_global_rate)'),
- 'avgsale' => new Zend_Db_Expr('AVG(sales.base_grand_total)'),
- 'base_avgsale' => new Zend_Db_Expr('AVG(sales.base_grand_total * sales.base_to_global_rate)'),
- 'num_orders' => new Zend_Db_Expr('COUNT(sales.base_grand_total)'),
- ],
- )
- ->group('sales.store_id');
-
- if ($this->_customer instanceof Mage_Customer_Model_Customer) {
- $this->addFieldToFilter('sales.customer_id', $this->_customer->getId());
- }
-
- if (!is_null($this->_orderStateValue)) {
- $condition = '';
- switch ($this->_orderStateCondition) {
- case 'IN':
- $condition = 'in';
- break;
- case 'NOT IN':
- $condition = 'nin';
- break;
- }
- $this->addFieldToFilter('state', [$condition => $this->_orderStateValue]);
- }
-
- Mage::dispatchEvent('sales_sale_collection_query_before', ['collection' => $this]);
- return $this;
- }
-
/**
* Load data
*
@@ -205,4 +163,46 @@ public function getTotals()
{
return new Varien_Object($this->_totals);
}
+
+ /**
+ * Before load action
+ *
+ * @return Varien_Data_Collection_Db
+ */
+ protected function _beforeLoad()
+ {
+ $this->getSelect()
+ ->from(
+ ['sales' => Mage::getResourceSingleton('sales/order')->getMainTable()],
+ [
+ 'store_id',
+ 'lifetime' => new Zend_Db_Expr('SUM(sales.base_grand_total)'),
+ 'base_lifetime' => new Zend_Db_Expr('SUM(sales.base_grand_total * sales.base_to_global_rate)'),
+ 'avgsale' => new Zend_Db_Expr('AVG(sales.base_grand_total)'),
+ 'base_avgsale' => new Zend_Db_Expr('AVG(sales.base_grand_total * sales.base_to_global_rate)'),
+ 'num_orders' => new Zend_Db_Expr('COUNT(sales.base_grand_total)'),
+ ],
+ )
+ ->group('sales.store_id');
+
+ if ($this->_customer instanceof Mage_Customer_Model_Customer) {
+ $this->addFieldToFilter('sales.customer_id', $this->_customer->getId());
+ }
+
+ if (!is_null($this->_orderStateValue)) {
+ $condition = '';
+ switch ($this->_orderStateCondition) {
+ case 'IN':
+ $condition = 'in';
+ break;
+ case 'NOT IN':
+ $condition = 'nin';
+ break;
+ }
+ $this->addFieldToFilter('state', [$condition => $this->_orderStateValue]);
+ }
+
+ Mage::dispatchEvent('sales_sale_collection_query_before', ['collection' => $this]);
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Resource/Setup.php b/app/code/core/Mage/Sales/Model/Resource/Setup.php
index 76e59975f43..5a765f6a5aa 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Setup.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Setup.php
@@ -63,18 +63,6 @@ class Mage_Sales_Model_Resource_Setup extends Mage_Eav_Model_Entity_Setup
'creditmemo',
];
- /**
- * Check if table exist for flat entity
- *
- * @param string $table
- * @return bool
- */
- protected function _flatTableExist($table)
- {
- $tablesList = $this->getConnection()->listTables();
- return in_array(strtoupper($this->getTable($table)), array_map('strtoupper', $tablesList));
- }
-
/**
* Add entity attribute. Overwrited for flat entities support
*
@@ -95,90 +83,6 @@ public function addAttribute($entityTypeId, $code, array $attr)
return $this;
}
- /**
- * Add attribute as separate column in the table
- *
- * @param string $table
- * @param string $attribute
- * @param array $attr
- * @return $this
- */
- protected function _addFlatAttribute($table, $attribute, $attr)
- {
- $tableInfo = $this->getConnection()->describeTable($this->getTable($table));
- if (isset($tableInfo[$attribute])) {
- return $this;
- }
- $columnDefinition = $this->_getAttributeColumnDefinition($attribute, $attr);
- $this->getConnection()->addColumn($this->getTable($table), $attribute, $columnDefinition);
- return $this;
- }
-
- /**
- * Add attribute to grid table if necessary
- *
- * @param string $table
- * @param string $attribute
- * @param array $attr
- * @param string $entityTypeId
- * @return $this
- */
- protected function _addGridAttribute($table, $attribute, $attr, $entityTypeId)
- {
- if (in_array($entityTypeId, $this->_flatEntitiesGrid) && !empty($attr['grid'])) {
- $columnDefinition = $this->_getAttributeColumnDefinition($attribute, $attr);
- $this->getConnection()->addColumn($this->getTable($table . '_grid'), $attribute, $columnDefinition);
- }
- return $this;
- }
-
- /**
- * Retrieve definition of column for create in flat table
- *
- * @param string $code
- * @param array $data
- * @return array
- */
- protected function _getAttributeColumnDefinition($code, $data)
- {
- // Convert attribute type to column info
- $data['type'] = $data['type'] ?? 'varchar';
- $type = null;
- $length = null;
- switch ($data['type']) {
- case 'timestamp':
- $type = Varien_Db_Ddl_Table::TYPE_TIMESTAMP;
- break;
- case 'datetime':
- $type = Varien_Db_Ddl_Table::TYPE_DATETIME;
- break;
- case 'decimal':
- $type = Varien_Db_Ddl_Table::TYPE_DECIMAL;
- $length = '12,4';
- break;
- case 'int':
- $type = Varien_Db_Ddl_Table::TYPE_INTEGER;
- break;
- case 'text':
- $type = Varien_Db_Ddl_Table::TYPE_TEXT;
- $length = 65536;
- break;
- case 'char':
- case 'varchar':
- $type = Varien_Db_Ddl_Table::TYPE_TEXT;
- $length = 255;
- break;
- }
- if ($type !== null) {
- $data['type'] = $type;
- $data['length'] = $length;
- }
-
- $data['nullable'] = isset($data['required']) ? !$data['required'] : true;
- $data['comment'] = $data['comment'] ?? ucwords(str_replace('_', ' ', $code));
- return $data;
- }
-
/**
* Retrieve default entities
*
@@ -972,4 +876,100 @@ public function getDefaultEntities()
];
}
+
+ /**
+ * Check if table exist for flat entity
+ *
+ * @param string $table
+ * @return bool
+ */
+ protected function _flatTableExist($table)
+ {
+ $tablesList = $this->getConnection()->listTables();
+ return in_array(strtoupper($this->getTable($table)), array_map('strtoupper', $tablesList));
+ }
+
+ /**
+ * Add attribute as separate column in the table
+ *
+ * @param string $table
+ * @param string $attribute
+ * @param array $attr
+ * @return $this
+ */
+ protected function _addFlatAttribute($table, $attribute, $attr)
+ {
+ $tableInfo = $this->getConnection()->describeTable($this->getTable($table));
+ if (isset($tableInfo[$attribute])) {
+ return $this;
+ }
+ $columnDefinition = $this->_getAttributeColumnDefinition($attribute, $attr);
+ $this->getConnection()->addColumn($this->getTable($table), $attribute, $columnDefinition);
+ return $this;
+ }
+
+ /**
+ * Add attribute to grid table if necessary
+ *
+ * @param string $table
+ * @param string $attribute
+ * @param array $attr
+ * @param string $entityTypeId
+ * @return $this
+ */
+ protected function _addGridAttribute($table, $attribute, $attr, $entityTypeId)
+ {
+ if (in_array($entityTypeId, $this->_flatEntitiesGrid) && !empty($attr['grid'])) {
+ $columnDefinition = $this->_getAttributeColumnDefinition($attribute, $attr);
+ $this->getConnection()->addColumn($this->getTable($table . '_grid'), $attribute, $columnDefinition);
+ }
+ return $this;
+ }
+
+ /**
+ * Retrieve definition of column for create in flat table
+ *
+ * @param string $code
+ * @param array $data
+ * @return array
+ */
+ protected function _getAttributeColumnDefinition($code, $data)
+ {
+ // Convert attribute type to column info
+ $data['type'] = $data['type'] ?? 'varchar';
+ $type = null;
+ $length = null;
+ switch ($data['type']) {
+ case 'timestamp':
+ $type = Varien_Db_Ddl_Table::TYPE_TIMESTAMP;
+ break;
+ case 'datetime':
+ $type = Varien_Db_Ddl_Table::TYPE_DATETIME;
+ break;
+ case 'decimal':
+ $type = Varien_Db_Ddl_Table::TYPE_DECIMAL;
+ $length = '12,4';
+ break;
+ case 'int':
+ $type = Varien_Db_Ddl_Table::TYPE_INTEGER;
+ break;
+ case 'text':
+ $type = Varien_Db_Ddl_Table::TYPE_TEXT;
+ $length = 65536;
+ break;
+ case 'char':
+ case 'varchar':
+ $type = Varien_Db_Ddl_Table::TYPE_TEXT;
+ $length = 255;
+ break;
+ }
+ if ($type !== null) {
+ $data['type'] = $type;
+ $data['length'] = $length;
+ }
+
+ $data['nullable'] = isset($data['required']) ? !$data['required'] : true;
+ $data['comment'] = $data['comment'] ?? ucwords(str_replace('_', ' ', $code));
+ return $data;
+ }
}
diff --git a/app/code/core/Mage/Sales/Model/Service/Order.php b/app/code/core/Mage/Sales/Model/Service/Order.php
index 46f2eea74bf..da0cd70cc82 100644
--- a/app/code/core/Mage/Sales/Model/Service/Order.php
+++ b/app/code/core/Mage/Sales/Model/Service/Order.php
@@ -86,17 +86,6 @@ public function updateLocaleNumbers(&$data)
return $this;
}
- /**
- * Perform numbers conversion according to locale
- *
- * @param mixed $value
- * @return float
- */
- protected function _getLocaleNumber($value)
- {
- return Mage::app()->getLocale()->getNumber($value);
- }
-
/**
* Prepare order invoice based on order data and requested items qtys. If $qtys is not empty - the function will
* prepare only specified items, otherwise all containing in the order.
@@ -328,6 +317,17 @@ public function prepareInvoiceCreditmemo($invoice, $data = [])
return $creditmemo;
}
+ /**
+ * Perform numbers conversion according to locale
+ *
+ * @param mixed $value
+ * @return float
+ */
+ protected function _getLocaleNumber($value)
+ {
+ return Mage::app()->getLocale()->getNumber($value);
+ }
+
/**
* Initialize creditmemo state based on requested parameters
*
diff --git a/app/code/core/Mage/Sales/controllers/DownloadController.php b/app/code/core/Mage/Sales/controllers/DownloadController.php
index 01b457865fa..950ae6150be 100644
--- a/app/code/core/Mage/Sales/controllers/DownloadController.php
+++ b/app/code/core/Mage/Sales/controllers/DownloadController.php
@@ -22,87 +22,6 @@
*/
class Mage_Sales_DownloadController extends Mage_Core_Controller_Front_Action
{
- /**
- * Custom options downloader
- *
- * @param mixed $info
- */
- protected function _downloadFileAction($info)
- {
- $secretKey = $this->getRequest()->getParam('key');
- try {
- if ($secretKey != $info['secret_key']) {
- throw new Exception();
- }
-
- $this->_validateFilePath($info);
-
- $filePath = Mage::getBaseDir() . $info['order_path'];
- if ((!is_file($filePath) || !is_readable($filePath)) && !$this->_processDatabaseFile($filePath)) {
- //try get file from quote
- $filePath = Mage::getBaseDir() . $info['quote_path'];
- if ((!is_file($filePath) || !is_readable($filePath)) && !$this->_processDatabaseFile($filePath)) {
- throw new Exception();
- }
- }
- $this->_prepareDownloadResponse($info['title'], [
- 'value' => $filePath,
- 'type' => 'filename',
- ]);
- } catch (Exception $e) {
- $this->_forward('noRoute');
- }
- }
-
- /**
- * @param array $info
- * @throws Exception
- */
- protected function _validateFilePath($info)
- {
- $optionFile = Mage::getModel('catalog/product_option_type_file');
- $optionStoragePath = $optionFile->getOrderTargetDir(true);
- if (strpos($info['order_path'], $optionStoragePath) !== 0) {
- throw new Exception('Unexpected file path');
- }
- }
-
- /**
- * Check file in database storage if needed and place it on file system
- *
- * @param string $filePath
- * @return bool
- *
- * @SuppressWarnings("PHPMD.ErrorControlOperator")
- */
- protected function _processDatabaseFile($filePath)
- {
- if (!Mage::helper('core/file_storage_database')->checkDbUsage()) {
- return false;
- }
-
- $relativePath = Mage::helper('core/file_storage_database')->getMediaRelativePath($filePath);
- $file = Mage::getModel('core/file_storage_database')->loadByFilename($relativePath);
-
- if (!$file->getId()) {
- return false;
- }
-
- $directory = dirname($filePath);
- @mkdir($directory, 0777, true);
-
- $io = new Varien_Io_File();
- $io->cd($directory);
-
- $io->streamOpen($filePath);
- $io->streamLock(true);
- $io->streamWrite($file->getContent());
- $io->streamUnlock();
- $io->streamClose();
-
- return true;
- }
-
/**
* Profile custom options download action
*/
@@ -189,4 +108,84 @@ public function downloadCustomOptionAction()
}
exit(0);
}
+ /**
+ * Custom options downloader
+ *
+ * @param mixed $info
+ */
+ protected function _downloadFileAction($info)
+ {
+ $secretKey = $this->getRequest()->getParam('key');
+ try {
+ if ($secretKey != $info['secret_key']) {
+ throw new Exception();
+ }
+
+ $this->_validateFilePath($info);
+
+ $filePath = Mage::getBaseDir() . $info['order_path'];
+ if ((!is_file($filePath) || !is_readable($filePath)) && !$this->_processDatabaseFile($filePath)) {
+ //try get file from quote
+ $filePath = Mage::getBaseDir() . $info['quote_path'];
+ if ((!is_file($filePath) || !is_readable($filePath)) && !$this->_processDatabaseFile($filePath)) {
+ throw new Exception();
+ }
+ }
+ $this->_prepareDownloadResponse($info['title'], [
+ 'value' => $filePath,
+ 'type' => 'filename',
+ ]);
+ } catch (Exception $e) {
+ $this->_forward('noRoute');
+ }
+ }
+
+ /**
+ * @param array $info
+ * @throws Exception
+ */
+ protected function _validateFilePath($info)
+ {
+ $optionFile = Mage::getModel('catalog/product_option_type_file');
+ $optionStoragePath = $optionFile->getOrderTargetDir(true);
+ if (strpos($info['order_path'], $optionStoragePath) !== 0) {
+ throw new Exception('Unexpected file path');
+ }
+ }
+
+ /**
+ * Check file in database storage if needed and place it on file system
+ *
+ * @param string $filePath
+ * @return bool
+ *
+ * @SuppressWarnings("PHPMD.ErrorControlOperator")
+ */
+ protected function _processDatabaseFile($filePath)
+ {
+ if (!Mage::helper('core/file_storage_database')->checkDbUsage()) {
+ return false;
+ }
+
+ $relativePath = Mage::helper('core/file_storage_database')->getMediaRelativePath($filePath);
+ $file = Mage::getModel('core/file_storage_database')->loadByFilename($relativePath);
+
+ if (!$file->getId()) {
+ return false;
+ }
+
+ $directory = dirname($filePath);
+ @mkdir($directory, 0777, true);
+
+ $io = new Varien_Io_File();
+ $io->cd($directory);
+
+ $io->streamOpen($filePath);
+ $io->streamLock(true);
+ $io->streamWrite($file->getContent());
+ $io->streamUnlock();
+ $io->streamClose();
+
+ return true;
+ }
}
diff --git a/app/code/core/Mage/Sales/controllers/GuestController.php b/app/code/core/Mage/Sales/controllers/GuestController.php
index cde3cbe5ef0..43695c43c02 100644
--- a/app/code/core/Mage/Sales/controllers/GuestController.php
+++ b/app/code/core/Mage/Sales/controllers/GuestController.php
@@ -22,43 +22,6 @@
*/
class Mage_Sales_GuestController extends Mage_Sales_Controller_Abstract
{
- /**
- * Try to load valid order and register it
- *
- * @param int $orderId
- * @return bool
- */
- protected function _loadValidOrder($orderId = null)
- {
- return Mage::helper('sales/guest')->loadValidOrder();
- }
-
- /**
- * Check order view availability
- *
- * @param Mage_Sales_Model_Order $order
- * @return bool
- */
- protected function _canViewOrder($order)
- {
- $currentOrder = Mage::registry('current_order');
- if ($order->getId() && ($order->getId() === $currentOrder->getId())) {
- return true;
- }
- return false;
- }
-
- protected function _viewAction()
- {
- if (!$this->_loadValidOrder()) {
- return;
- }
-
- $this->loadLayout();
- Mage::helper('sales/guest')->getBreadcrumbs($this);
- $this->renderLayout();
- }
-
/**
* Order view form page
*/
@@ -146,4 +109,40 @@ public function printCreditmemoAction()
$this->_redirect('sales/guest/form');
}
}
+ /**
+ * Try to load valid order and register it
+ *
+ * @param int $orderId
+ * @return bool
+ */
+ protected function _loadValidOrder($orderId = null)
+ {
+ return Mage::helper('sales/guest')->loadValidOrder();
+ }
+
+ /**
+ * Check order view availability
+ *
+ * @param Mage_Sales_Model_Order $order
+ * @return bool
+ */
+ protected function _canViewOrder($order)
+ {
+ $currentOrder = Mage::registry('current_order');
+ if ($order->getId() && ($order->getId() === $currentOrder->getId())) {
+ return true;
+ }
+ return false;
+ }
+
+ protected function _viewAction()
+ {
+ if (!$this->_loadValidOrder()) {
+ return;
+ }
+
+ $this->loadLayout();
+ Mage::helper('sales/guest')->getBreadcrumbs($this);
+ $this->renderLayout();
+ }
}
diff --git a/app/code/core/Mage/Sales/controllers/OrderController.php b/app/code/core/Mage/Sales/controllers/OrderController.php
index c9df472a307..f104e8ee8de 100644
--- a/app/code/core/Mage/Sales/controllers/OrderController.php
+++ b/app/code/core/Mage/Sales/controllers/OrderController.php
@@ -56,25 +56,25 @@ public function historyAction()
}
/**
- * Check osCommerce order view availability
+ * osCommerce Order view page
*
* @deprecated after 1.6.0.0
- * @param array $order
- * @return bool
+ *
*/
- protected function _canViewOscommerceOrder($order)
+ public function viewOldAction()
{
- return false;
+ $this->_forward('noRoute');
}
/**
- * osCommerce Order view page
+ * Check osCommerce order view availability
*
* @deprecated after 1.6.0.0
- *
+ * @param array $order
+ * @return bool
*/
- public function viewOldAction()
+ protected function _canViewOscommerceOrder($order)
{
- $this->_forward('noRoute');
+ return false;
}
}
diff --git a/app/code/core/Mage/SalesRule/Model/Coupon.php b/app/code/core/Mage/SalesRule/Model/Coupon.php
index 92495f415be..64bbb536e21 100644
--- a/app/code/core/Mage/SalesRule/Model/Coupon.php
+++ b/app/code/core/Mage/SalesRule/Model/Coupon.php
@@ -50,25 +50,6 @@ class Mage_SalesRule_Model_Coupon extends Mage_Core_Model_Abstract
*/
protected $_rule;
- protected function _construct()
- {
- parent::_construct();
- $this->_init('salesrule/coupon');
- }
-
- /**
- * Processing object before save data
- *
- * @return Mage_Core_Model_Abstract
- */
- protected function _beforeSave()
- {
- if (!$this->getRuleId() && $this->_rule instanceof Mage_SalesRule_Model_Rule) {
- $this->setRuleId($this->_rule->getId());
- }
- return parent::_beforeSave();
- }
-
/**
* Set rule instance
*
@@ -103,4 +84,23 @@ public function loadByCode($couponCode)
$this->load($couponCode, 'code');
return $this;
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('salesrule/coupon');
+ }
+
+ /**
+ * Processing object before save data
+ *
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _beforeSave()
+ {
+ if (!$this->getRuleId() && $this->_rule instanceof Mage_SalesRule_Model_Rule) {
+ $this->setRuleId($this->_rule->getId());
+ }
+ return parent::_beforeSave();
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Coupon/Massgenerator.php b/app/code/core/Mage/SalesRule/Model/Coupon/Massgenerator.php
index 432381186cc..71ae1476380 100644
--- a/app/code/core/Mage/SalesRule/Model/Coupon/Massgenerator.php
+++ b/app/code/core/Mage/SalesRule/Model/Coupon/Massgenerator.php
@@ -50,14 +50,6 @@ class Mage_SalesRule_Model_Coupon_Massgenerator extends Mage_Core_Model_Abstract
*/
protected $_generatedCount = 0;
- /**
- * Initialize resource
- */
- protected function _construct()
- {
- $this->_init('salesrule/coupon');
- }
-
/**
* Generate coupon code
*
@@ -190,4 +182,12 @@ public function getGeneratedCount()
{
return $this->_generatedCount;
}
+
+ /**
+ * Initialize resource
+ */
+ protected function _construct()
+ {
+ $this->_init('salesrule/coupon');
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Observer.php b/app/code/core/Mage/SalesRule/Model/Observer.php
index c97c4f2336c..ba265447a25 100644
--- a/app/code/core/Mage/SalesRule/Model/Observer.php
+++ b/app/code/core/Mage/SalesRule/Model/Observer.php
@@ -190,63 +190,6 @@ public function aggregateSalesReportCouponsData($schedule)
return $this;
}
- /**
- * Check rules that contains affected attribute
- * If rules were found they will be set to inactive and notice will be add to admin session
- *
- * @param string $attributeCode
- * @return $this
- */
- protected function _checkSalesRulesAvailability($attributeCode)
- {
- /** @var Mage_SalesRule_Model_Resource_Rule_Collection $collection */
- $collection = Mage::getResourceModel('salesrule/rule_collection')
- ->addAttributeInConditionFilter($attributeCode);
-
- $disabledRulesCount = 0;
- foreach ($collection as $rule) {
- /** @var Mage_SalesRule_Model_Rule $rule */
- $rule->setIsActive(0);
- /** @var $rule->getConditions() Mage_SalesRule_Model_Rule_Condition_Combine */
- $this->_removeAttributeFromConditions($rule->getConditions(), $attributeCode);
- $this->_removeAttributeFromConditions($rule->getActions(), $attributeCode);
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $rule->save();
-
- $disabledRulesCount++;
- }
-
- if ($disabledRulesCount) {
- Mage::getSingleton('adminhtml/session')->addWarning(
- Mage::helper('salesrule')->__('%d Shopping Cart Price Rules based on "%s" attribute have been disabled.', $disabledRulesCount, $attributeCode),
- );
- }
-
- return $this;
- }
-
- /**
- * Remove catalog attribute condition by attribute code from rule conditions
- *
- * @param Mage_Rule_Model_Condition_Combine $combine
- * @param string $attributeCode
- */
- protected function _removeAttributeFromConditions($combine, $attributeCode)
- {
- $conditions = $combine->getConditions();
- foreach ($conditions as $conditionId => $condition) {
- if ($condition instanceof Mage_Rule_Model_Condition_Combine) {
- $this->_removeAttributeFromConditions($condition, $attributeCode);
- }
- if ($condition instanceof Mage_SalesRule_Model_Rule_Condition_Product) {
- if ($condition->getAttribute() == $attributeCode) {
- unset($conditions[$conditionId]);
- }
- }
- }
- $combine->setConditions($conditions);
- }
-
/**
* After save attribute if it is not used for promo rules already check rules for containing this attribute
*
@@ -341,4 +284,61 @@ public function addSalesRuleNameToOrder($observer)
return $this;
}
+
+ /**
+ * Check rules that contains affected attribute
+ * If rules were found they will be set to inactive and notice will be add to admin session
+ *
+ * @param string $attributeCode
+ * @return $this
+ */
+ protected function _checkSalesRulesAvailability($attributeCode)
+ {
+ /** @var Mage_SalesRule_Model_Resource_Rule_Collection $collection */
+ $collection = Mage::getResourceModel('salesrule/rule_collection')
+ ->addAttributeInConditionFilter($attributeCode);
+
+ $disabledRulesCount = 0;
+ foreach ($collection as $rule) {
+ /** @var Mage_SalesRule_Model_Rule $rule */
+ $rule->setIsActive(0);
+ /** @var $rule->getConditions() Mage_SalesRule_Model_Rule_Condition_Combine */
+ $this->_removeAttributeFromConditions($rule->getConditions(), $attributeCode);
+ $this->_removeAttributeFromConditions($rule->getActions(), $attributeCode);
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $rule->save();
+
+ $disabledRulesCount++;
+ }
+
+ if ($disabledRulesCount) {
+ Mage::getSingleton('adminhtml/session')->addWarning(
+ Mage::helper('salesrule')->__('%d Shopping Cart Price Rules based on "%s" attribute have been disabled.', $disabledRulesCount, $attributeCode),
+ );
+ }
+
+ return $this;
+ }
+
+ /**
+ * Remove catalog attribute condition by attribute code from rule conditions
+ *
+ * @param Mage_Rule_Model_Condition_Combine $combine
+ * @param string $attributeCode
+ */
+ protected function _removeAttributeFromConditions($combine, $attributeCode)
+ {
+ $conditions = $combine->getConditions();
+ foreach ($conditions as $conditionId => $condition) {
+ if ($condition instanceof Mage_Rule_Model_Condition_Combine) {
+ $this->_removeAttributeFromConditions($condition, $attributeCode);
+ }
+ if ($condition instanceof Mage_SalesRule_Model_Rule_Condition_Product) {
+ if ($condition->getAttribute() == $attributeCode) {
+ unset($conditions[$conditionId]);
+ }
+ }
+ }
+ $combine->setConditions($conditions);
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Quote/Discount.php b/app/code/core/Mage/SalesRule/Model/Quote/Discount.php
index c2e25dc5f10..db87d655162 100644
--- a/app/code/core/Mage/SalesRule/Model/Quote/Discount.php
+++ b/app/code/core/Mage/SalesRule/Model/Quote/Discount.php
@@ -118,19 +118,6 @@ public function collect(Mage_Sales_Model_Quote_Address $address)
return $this;
}
- /**
- * Aggregate item discount information to address data and related properties
- *
- * @param Mage_Sales_Model_Quote_Item_Abstract $item
- * @return $this
- */
- protected function _aggregateItemDiscount($item)
- {
- $this->_addAmount(-$item->getDiscountAmount());
- $this->_addBaseAmount(-$item->getBaseDiscountAmount());
- return $this;
- }
-
/**
* Add discount total information to address
*
@@ -155,4 +142,17 @@ public function fetch(Mage_Sales_Model_Quote_Address $address)
}
return $this;
}
+
+ /**
+ * Aggregate item discount information to address data and related properties
+ *
+ * @param Mage_Sales_Model_Quote_Item_Abstract $item
+ * @return $this
+ */
+ protected function _aggregateItemDiscount($item)
+ {
+ $this->_addAmount(-$item->getDiscountAmount());
+ $this->_addBaseAmount(-$item->getBaseDiscountAmount());
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Coupon.php b/app/code/core/Mage/SalesRule/Model/Resource/Coupon.php
index 1c8f8b1636e..52ccd3281ea 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Coupon.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Coupon.php
@@ -22,15 +22,6 @@
*/
class Mage_SalesRule_Model_Resource_Coupon extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('salesrule/coupon', 'coupon_id');
- $this->addUniqueField([
- 'field' => 'code',
- 'title' => Mage::helper('salesrule')->__('Coupon with the same code'),
- ]);
- }
-
/**
* Perform actions before object save
*
@@ -139,4 +130,12 @@ public function updateSpecificCoupons(Mage_SalesRule_Model_Rule $rule)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('salesrule/coupon', 'coupon_id');
+ $this->addUniqueField([
+ 'field' => 'code',
+ 'title' => Mage::helper('salesrule')->__('Coupon with the same code'),
+ ]);
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Coupon/Collection.php b/app/code/core/Mage/SalesRule/Model/Resource/Coupon/Collection.php
index b255e5ce8df..3d7769f8db5 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Coupon/Collection.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Coupon/Collection.php
@@ -22,12 +22,6 @@
*/
class Mage_SalesRule_Model_Resource_Coupon_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- parent::_construct();
- $this->_init('salesrule/coupon');
- }
-
/**
* Add rule to filter
*
@@ -85,4 +79,9 @@ public function addIsUsedFilterCallback($collection, $column)
$resultCondition = $this->_getConditionSql($fieldExpression, ['eq' => $filterValue]);
$collection->getSelect()->where($resultCondition);
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('salesrule/coupon');
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Coupon/Usage.php b/app/code/core/Mage/SalesRule/Model/Resource/Coupon/Usage.php
index db5f35df0ff..d89b5f05b6b 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Coupon/Usage.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Coupon/Usage.php
@@ -22,11 +22,6 @@
*/
class Mage_SalesRule_Model_Resource_Coupon_Usage extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('salesrule/coupon_usage', '');
- }
-
/**
* Increment times_used counter
*
@@ -97,4 +92,8 @@ public function loadByCustomerCoupon(Varien_Object $object, $customerId, $coupon
}
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('salesrule/coupon_usage', '');
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Report/Collection.php b/app/code/core/Mage/SalesRule/Model/Resource/Report/Collection.php
index 4b4d1c385c5..df5f32f0389 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Report/Collection.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Report/Collection.php
@@ -62,6 +62,18 @@ public function __construct()
$this->setConnection($this->getResource()->getReadConnection());
}
+ /**
+ * Add filtering by rules ids
+ *
+ * @param array $rulesList
+ * @return $this
+ */
+ public function addRuleFilter($rulesList)
+ {
+ $this->_rulesIdsFilter = $rulesList;
+ return $this;
+ }
+
/**
* collect columns for collection
*
@@ -127,18 +139,6 @@ protected function _initSelect()
return $this;
}
- /**
- * Add filtering by rules ids
- *
- * @param array $rulesList
- * @return $this
- */
- public function addRuleFilter($rulesList)
- {
- $this->_rulesIdsFilter = $rulesList;
- return $this;
- }
-
/**
* Apply filtering by rules ids
*
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule.php b/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule.php
index 4980e773b1c..9b639cc988d 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule.php
@@ -22,11 +22,6 @@
*/
class Mage_SalesRule_Model_Resource_Report_Rule extends Mage_Reports_Model_Resource_Report_Abstract
{
- protected function _construct()
- {
- $this->_setResource('salesrule');
- }
-
/**
* Aggregate Coupons data
*
@@ -71,6 +66,10 @@ public function getUniqRulesNamesList()
return $result;
}
+ protected function _construct()
+ {
+ $this->_setResource('salesrule');
+ }
/**
* Aggregate coupons reports by order created at as range
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Createdat.php b/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Createdat.php
index db1f71dc08c..577d70dd17e 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Createdat.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Createdat.php
@@ -22,15 +22,6 @@
*/
class Mage_SalesRule_Model_Resource_Report_Rule_Createdat extends Mage_Reports_Model_Resource_Report_Abstract
{
- /**
- * Resource Report Rule constructor
- *
- */
- protected function _construct()
- {
- $this->_init('salesrule/coupon_aggregated', 'id');
- }
-
/**
* Aggregate Coupons data by order created at
*
@@ -42,6 +33,14 @@ public function aggregate($from = null, $to = null)
{
return $this->_aggregateByOrder('created_at', $from, $to);
}
+ /**
+ * Resource Report Rule constructor
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('salesrule/coupon_aggregated', 'id');
+ }
/**
* Aggregate coupons reports by orders
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Updatedat.php b/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Updatedat.php
index cabe3496ab4..c63c753d657 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Updatedat.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Updatedat.php
@@ -22,11 +22,6 @@
*/
class Mage_SalesRule_Model_Resource_Report_Rule_Updatedat extends Mage_SalesRule_Model_Resource_Report_Rule_Createdat
{
- protected function _construct()
- {
- $this->_init('salesrule/coupon_aggregated_updated', 'id');
- }
-
/**
* Aggregate Coupons data by order updated at
*
@@ -38,4 +33,8 @@ public function aggregate($from = null, $to = null)
{
return $this->_aggregateByOrder('updated_at', $from, $to);
}
+ protected function _construct()
+ {
+ $this->_init('salesrule/coupon_aggregated_updated', 'id');
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Rule.php b/app/code/core/Mage/SalesRule/Model/Resource/Rule.php
index 908e9d3a380..3008b1d425c 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Rule.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Rule.php
@@ -40,29 +40,6 @@ class Mage_SalesRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abstra
],
];
- /**
- * Initialize main table and table id field
- */
- protected function _construct()
- {
- $this->_init('salesrule/rule', 'rule_id');
- }
-
- /**
- * Add customer group ids and website ids to rule data after load
- *
- *
- * @return $this
- */
- protected function _afterLoad(Mage_Core_Model_Abstract $object)
- {
- $object->setData('customer_group_ids', (array) $this->getCustomerGroupIds($object->getId()));
- $object->setData('website_ids', (array) $this->getWebsiteIds($object->getId()));
-
- parent::_afterLoad($object);
- return $this;
- }
-
/**
* Prepare sales rule's discount quantity
*
@@ -79,52 +56,6 @@ public function _beforeSave(Mage_Core_Model_Abstract $object)
return $this;
}
- /**
- * Bind sales rule to customer group(s) and website(s).
- * Save rule's associated store labels.
- * Save product attributes used in rule.
- *
- * @param Mage_SalesRule_Model_Rule $object
- * @inheritDoc
- */
- protected function _afterSave(Mage_Core_Model_Abstract $object)
- {
- if ($object->hasStoreLabels()) {
- $this->saveStoreLabels($object->getId(), $object->getStoreLabels());
- }
-
- if ($object->hasWebsiteIds()) {
- $websiteIds = $object->getWebsiteIds();
- if (!is_array($websiteIds)) {
- $websiteIds = explode(',', (string) $websiteIds);
- }
- $this->bindRuleToEntity($object->getId(), $websiteIds, 'website');
- }
-
- if ($object->hasCustomerGroupIds()) {
- $customerGroupIds = $object->getCustomerGroupIds();
- if (!is_array($customerGroupIds)) {
- $customerGroupIds = explode(',', (string) $customerGroupIds);
- }
- $this->bindRuleToEntity($object->getId(), $customerGroupIds, 'customer_group');
- }
-
- // Save product attributes used in rule
- $ruleProductAttributes = array_merge(
- $this->getProductAttributes(serialize($object->getConditions()->asArray())),
- $this->getProductAttributes(serialize($object->getActions()->asArray())),
- );
- if (count($ruleProductAttributes)) {
- $this->setActualProductAttributes($object, $ruleProductAttributes);
- }
-
- // Update auto geterated specific coupons if exists
- if ($object->getUseAutoGeneration() && $object->hasDataChanges()) {
- Mage::getResourceModel('salesrule/coupon')->updateSpecificCoupons($object);
- }
- return parent::_afterSave($object);
- }
-
/**
* Retrieve coupon/rule uses for specified customer
*
@@ -300,4 +231,73 @@ public function getProductAttributes($serializedString)
return $result;
}
+
+ /**
+ * Initialize main table and table id field
+ */
+ protected function _construct()
+ {
+ $this->_init('salesrule/rule', 'rule_id');
+ }
+
+ /**
+ * Add customer group ids and website ids to rule data after load
+ *
+ *
+ * @return $this
+ */
+ protected function _afterLoad(Mage_Core_Model_Abstract $object)
+ {
+ $object->setData('customer_group_ids', (array) $this->getCustomerGroupIds($object->getId()));
+ $object->setData('website_ids', (array) $this->getWebsiteIds($object->getId()));
+
+ parent::_afterLoad($object);
+ return $this;
+ }
+
+ /**
+ * Bind sales rule to customer group(s) and website(s).
+ * Save rule's associated store labels.
+ * Save product attributes used in rule.
+ *
+ * @param Mage_SalesRule_Model_Rule $object
+ * @inheritDoc
+ */
+ protected function _afterSave(Mage_Core_Model_Abstract $object)
+ {
+ if ($object->hasStoreLabels()) {
+ $this->saveStoreLabels($object->getId(), $object->getStoreLabels());
+ }
+
+ if ($object->hasWebsiteIds()) {
+ $websiteIds = $object->getWebsiteIds();
+ if (!is_array($websiteIds)) {
+ $websiteIds = explode(',', (string) $websiteIds);
+ }
+ $this->bindRuleToEntity($object->getId(), $websiteIds, 'website');
+ }
+
+ if ($object->hasCustomerGroupIds()) {
+ $customerGroupIds = $object->getCustomerGroupIds();
+ if (!is_array($customerGroupIds)) {
+ $customerGroupIds = explode(',', (string) $customerGroupIds);
+ }
+ $this->bindRuleToEntity($object->getId(), $customerGroupIds, 'customer_group');
+ }
+
+ // Save product attributes used in rule
+ $ruleProductAttributes = array_merge(
+ $this->getProductAttributes(serialize($object->getConditions()->asArray())),
+ $this->getProductAttributes(serialize($object->getActions()->asArray())),
+ );
+ if (count($ruleProductAttributes)) {
+ $this->setActualProductAttributes($object, $ruleProductAttributes);
+ }
+
+ // Update auto geterated specific coupons if exists
+ if ($object->getUseAutoGeneration() && $object->hasDataChanges()) {
+ Mage::getResourceModel('salesrule/coupon')->updateSpecificCoupons($object);
+ }
+ return parent::_afterSave($object);
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php b/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php
index bb9b8187f2e..4992e64f872 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php
@@ -40,15 +40,6 @@ class Mage_SalesRule_Model_Resource_Rule_Collection extends Mage_Rule_Model_Reso
],
];
- /**
- * Set resource model and determine field mapping
- */
- protected function _construct()
- {
- $this->_init('salesrule/rule');
- $this->_map['fields']['rule_id'] = 'main_table.rule_id';
- }
-
/**
* Filter collection by specified website, customer group, coupon code, date.
* Filter collection to use only active rules.
@@ -213,4 +204,13 @@ public function addAllowedSalesRulesFilter()
return $this;
}
+
+ /**
+ * Set resource model and determine field mapping
+ */
+ protected function _construct()
+ {
+ $this->_init('salesrule/rule');
+ $this->_map['fields']['rule_id'] = 'main_table.rule_id';
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Rule/Customer.php b/app/code/core/Mage/SalesRule/Model/Resource/Rule/Customer.php
index 495226915c9..5c8b997beaa 100644
--- a/app/code/core/Mage/SalesRule/Model/Resource/Rule/Customer.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Rule/Customer.php
@@ -22,11 +22,6 @@
*/
class Mage_SalesRule_Model_Resource_Rule_Customer extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('salesrule/rule_customer', 'rule_customer_id');
- }
-
/**
* Get rule usage record for a customer
*
@@ -49,4 +44,8 @@ public function loadByCustomerRule($rule, $customerId, $ruleId)
$rule->setData($data);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('salesrule/rule_customer', 'rule_customer_id');
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Rule.php b/app/code/core/Mage/SalesRule/Model/Rule.php
index 2acb66e1d08..4b070621ca5 100644
--- a/app/code/core/Mage/SalesRule/Model/Rule.php
+++ b/app/code/core/Mage/SalesRule/Model/Rule.php
@@ -160,16 +160,6 @@ class Mage_SalesRule_Model_Rule extends Mage_Rule_Model_Abstract
*/
protected $_validatedAddresses = [];
- /**
- * Set resource model and Id field name
- */
- protected function _construct()
- {
- parent::_construct();
- $this->_init('salesrule/rule');
- $this->setIdFieldName('rule_id');
- }
-
/**
* Returns code mass generator instance for auto generated specific coupons
*
@@ -180,46 +170,6 @@ public static function getCouponMassGenerator()
return Mage::getSingleton('salesrule/coupon_massgenerator');
}
- /**
- * Set coupon code and uses per coupon
- *
- * @inheritDoc
- */
- protected function _afterLoad()
- {
- $this->setCouponCode($this->getPrimaryCoupon()->getCode());
- if ($this->getUsesPerCoupon() !== null && !$this->getUseAutoGeneration()) {
- $this->setUsesPerCoupon($this->getPrimaryCoupon()->getUsageLimit());
- }
- return parent::_afterLoad();
- }
-
- /**
- * Save/delete coupon
- *
- * @return $this
- */
- protected function _afterSave()
- {
- $couponCode = trim((string) $this->getCouponCode());
- if (strlen($couponCode)
- && $this->getCouponType() == self::COUPON_TYPE_SPECIFIC
- && !$this->getUseAutoGeneration()
- ) {
- $this->getPrimaryCoupon()
- ->setCode($couponCode)
- ->setUsageLimit($this->getUsesPerCoupon() ? $this->getUsesPerCoupon() : null)
- ->setUsagePerCustomer($this->getUsesPerCustomer() ? $this->getUsesPerCustomer() : null)
- ->setExpirationDate($this->getToDate())
- ->save();
- } else {
- $this->getPrimaryCoupon()->delete();
- }
-
- parent::_afterSave();
- return $this;
- }
-
/**
* Initialize rule model data from array.
* Set store labels if applicable.
@@ -477,34 +427,6 @@ public function getIsValidForAddress($address)
return $this->_validatedAddresses[$addressId] ?? false;
}
- /**
- * Return id for address
- *
- * @param Mage_Sales_Model_Quote_Address $address
- * @return string
- */
- private function _getAddressId($address)
- {
- if ($address instanceof Mage_Sales_Model_Quote_Address) {
- return $address->getId();
- }
- return $address;
- }
-
- /**
- * Collect all product attributes used in serialized rule's action or condition
- *
- * @deprecated after 1.6.2.0 use Mage_SalesRule_Model_Resource_Rule::getProductAttributes() instead
- *
- * @param string $serializedString
- *
- * @return array
- */
- protected function _getUsedAttributes($serializedString)
- {
- return $this->_getResource()->getProductAttributes($serializedString);
- }
-
/**
* @deprecated after 1.6.2.0
*
@@ -537,4 +459,82 @@ public function toArray(array $arrAttributes = [])
{
return parent::toArray($arrAttributes);
}
+
+ /**
+ * Set resource model and Id field name
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('salesrule/rule');
+ $this->setIdFieldName('rule_id');
+ }
+
+ /**
+ * Set coupon code and uses per coupon
+ *
+ * @inheritDoc
+ */
+ protected function _afterLoad()
+ {
+ $this->setCouponCode($this->getPrimaryCoupon()->getCode());
+ if ($this->getUsesPerCoupon() !== null && !$this->getUseAutoGeneration()) {
+ $this->setUsesPerCoupon($this->getPrimaryCoupon()->getUsageLimit());
+ }
+ return parent::_afterLoad();
+ }
+
+ /**
+ * Save/delete coupon
+ *
+ * @return $this
+ */
+ protected function _afterSave()
+ {
+ $couponCode = trim((string) $this->getCouponCode());
+ if (strlen($couponCode)
+ && $this->getCouponType() == self::COUPON_TYPE_SPECIFIC
+ && !$this->getUseAutoGeneration()
+ ) {
+ $this->getPrimaryCoupon()
+ ->setCode($couponCode)
+ ->setUsageLimit($this->getUsesPerCoupon() ? $this->getUsesPerCoupon() : null)
+ ->setUsagePerCustomer($this->getUsesPerCustomer() ? $this->getUsesPerCustomer() : null)
+ ->setExpirationDate($this->getToDate())
+ ->save();
+ } else {
+ $this->getPrimaryCoupon()->delete();
+ }
+
+ parent::_afterSave();
+ return $this;
+ }
+
+ /**
+ * Collect all product attributes used in serialized rule's action or condition
+ *
+ * @deprecated after 1.6.2.0 use Mage_SalesRule_Model_Resource_Rule::getProductAttributes() instead
+ *
+ * @param string $serializedString
+ *
+ * @return array
+ */
+ protected function _getUsedAttributes($serializedString)
+ {
+ return $this->_getResource()->getProductAttributes($serializedString);
+ }
+
+ /**
+ * Return id for address
+ *
+ * @param Mage_Sales_Model_Quote_Address $address
+ * @return string
+ */
+ private function _getAddressId($address)
+ {
+ if ($address instanceof Mage_Sales_Model_Quote_Address) {
+ return $address->getId();
+ }
+ return $address;
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product.php b/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product.php
index 1bdee85fe4a..5e6380b1733 100644
--- a/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product.php
+++ b/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product.php
@@ -22,17 +22,6 @@
*/
class Mage_SalesRule_Model_Rule_Condition_Product extends Mage_Rule_Model_Condition_Product_Abstract
{
- /**
- * Add special attributes
- */
- protected function _addSpecialAttributes(array &$attributes)
- {
- parent::_addSpecialAttributes($attributes);
- $attributes['quote_item_qty'] = Mage::helper('salesrule')->__('Quantity in cart');
- $attributes['quote_item_price'] = Mage::helper('salesrule')->__('Price in cart');
- $attributes['quote_item_row_total'] = Mage::helper('salesrule')->__('Row total in cart');
- }
-
/**
* Validate Product Rule Condition
*
@@ -54,4 +43,14 @@ public function validate(Varien_Object $object)
return parent::validate($product);
}
+ /**
+ * Add special attributes
+ */
+ protected function _addSpecialAttributes(array &$attributes)
+ {
+ parent::_addSpecialAttributes($attributes);
+ $attributes['quote_item_qty'] = Mage::helper('salesrule')->__('Quantity in cart');
+ $attributes['quote_item_price'] = Mage::helper('salesrule')->__('Price in cart');
+ $attributes['quote_item_row_total'] = Mage::helper('salesrule')->__('Row total in cart');
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product/Attribute/Assigned.php b/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product/Attribute/Assigned.php
index aa0d7113bb7..abbf9830a26 100644
--- a/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product/Attribute/Assigned.php
+++ b/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product/Attribute/Assigned.php
@@ -49,27 +49,6 @@ class Mage_SalesRule_Model_Rule_Condition_Product_Attribute_Assigned extends Mag
*/
protected $_cachedOperatorSelectOptionsCache = null;
- /**
- * Initialize and retrieve a helper instance
- * @return Mage_SalesRule_Helper_Data
- */
- protected function _getHelper()
- {
- return Mage::helper('salesrule');
- }
-
- /**
- * Retrieve a product instance and initialize if needed
- *
- * @return Mage_Catalog_Model_Product
- */
- protected function _getProduct(Varien_Object $object)
- {
- return $object->getProduct() instanceof Mage_Catalog_Model_Product
- ? $object->getProduct()
- : Mage::getModel('catalog/product')->load($object->getProductId());
- }
-
/**
* Initialize options hash
*/
@@ -143,4 +122,25 @@ public function asHtml()
$this->getTypeElementHtml(),
);
}
+
+ /**
+ * Initialize and retrieve a helper instance
+ * @return Mage_SalesRule_Helper_Data
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('salesrule');
+ }
+
+ /**
+ * Retrieve a product instance and initialize if needed
+ *
+ * @return Mage_Catalog_Model_Product
+ */
+ protected function _getProduct(Varien_Object $object)
+ {
+ return $object->getProduct() instanceof Mage_Catalog_Model_Product
+ ? $object->getProduct()
+ : Mage::getModel('catalog/product')->load($object->getProductId());
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product/Combine.php b/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product/Combine.php
index 0869ca05181..08d9bc855d6 100644
--- a/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product/Combine.php
+++ b/app/code/core/Mage/SalesRule/Model/Rule/Condition/Product/Combine.php
@@ -41,6 +41,95 @@ class Mage_SalesRule_Model_Rule_Condition_Product_Combine extends Mage_Rule_Mode
*/
protected $_productAttributesInfo = null;
+ /**
+ * Initialize a rule condition
+ */
+ public function __construct()
+ {
+ parent::__construct();
+ $this->setType('salesrule/rule_condition_product_combine');
+ }
+
+ /**
+ * Generate a conditions data
+ * @return array
+ */
+ public function getNewChildSelectOptions()
+ {
+ $conditions = parent::getNewChildSelectOptions();
+ return array_merge_recursive(
+ $conditions,
+ [
+ [
+ 'label' => Mage::helper('catalog')->__('Conditions Combination'),
+ 'value' => 'salesrule/rule_condition_product_combine',
+ ],
+ [
+ 'label' => Mage::helper('catalog')->__('Cart Item Attribute'),
+ 'value' => $this->_getAttributeConditions(self::PRODUCT_ATTRIBUTES_TYPE_QUOTE_ITEM),
+ ],
+ [
+ 'label' => Mage::helper('catalog')->__('Product Attribute'),
+ 'value' => $this->_getAttributeConditions(self::PRODUCT_ATTRIBUTES_TYPE_PRODUCT),
+ ],
+ [
+ 'label' => $this->_getHelper()->__('Product Attribute Assigned'),
+ 'value' => $this->_getAttributeConditions(self::PRODUCT_ATTRIBUTES_TYPE_ISSET),
+ ],
+ ],
+ );
+ }
+
+ /**
+ * Collect all validated attributes
+ * @param Mage_Catalog_Model_Resource_Product_Collection $productCollection
+ * @return $this
+ */
+ public function collectValidatedAttributes($productCollection)
+ {
+ foreach ($this->getConditions() as $condition) {
+ $condition->collectValidatedAttributes($productCollection);
+ }
+ return $this;
+ }
+
+ /**
+ * Validate a condition with the checking of the child value
+ *
+ * @return bool
+ */
+ public function validate(Varien_Object $object)
+ {
+ /** @var Mage_Catalog_Model_Product $product */
+ $product = $object->getProduct();
+ if (!($product instanceof Mage_Catalog_Model_Product)) {
+ $product = Mage::getModel('catalog/product')->load($object->getProductId());
+ }
+
+ $valid = parent::validate($object);
+ if (!$valid && $product->getTypeId() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) {
+ $children = $object->getChildren();
+ if (is_array($children) && isset($children[0])) {
+ $child = $children[0];
+
+ /** @var Mage_Catalog_Model_Product $childProduct */
+ $childProduct = Mage::getModel('catalog/product')->load($child->getProductId());
+ $childProduct
+ ->setQuoteItemQty($object->getQty())
+ ->setQuoteItemPrice($object->getPrice())
+ ->setQuoteItemRowTotal($object->getBaseRowTotal());
+
+ if (!$childProduct->isVisibleInSiteVisibility()) {
+ $childProduct->setCategoryIds($product->getCategoryIds());
+ }
+
+ $valid = parent::validate($childProduct);
+ }
+ }
+
+ return $valid;
+ }
+
/**
* Initialize and retrieve a helper instance
* @return Mage_Catalog_Helper_Data
@@ -136,93 +225,4 @@ protected function _initializeProductAttributesInfo()
return $this;
}
-
- /**
- * Initialize a rule condition
- */
- public function __construct()
- {
- parent::__construct();
- $this->setType('salesrule/rule_condition_product_combine');
- }
-
- /**
- * Generate a conditions data
- * @return array
- */
- public function getNewChildSelectOptions()
- {
- $conditions = parent::getNewChildSelectOptions();
- return array_merge_recursive(
- $conditions,
- [
- [
- 'label' => Mage::helper('catalog')->__('Conditions Combination'),
- 'value' => 'salesrule/rule_condition_product_combine',
- ],
- [
- 'label' => Mage::helper('catalog')->__('Cart Item Attribute'),
- 'value' => $this->_getAttributeConditions(self::PRODUCT_ATTRIBUTES_TYPE_QUOTE_ITEM),
- ],
- [
- 'label' => Mage::helper('catalog')->__('Product Attribute'),
- 'value' => $this->_getAttributeConditions(self::PRODUCT_ATTRIBUTES_TYPE_PRODUCT),
- ],
- [
- 'label' => $this->_getHelper()->__('Product Attribute Assigned'),
- 'value' => $this->_getAttributeConditions(self::PRODUCT_ATTRIBUTES_TYPE_ISSET),
- ],
- ],
- );
- }
-
- /**
- * Collect all validated attributes
- * @param Mage_Catalog_Model_Resource_Product_Collection $productCollection
- * @return $this
- */
- public function collectValidatedAttributes($productCollection)
- {
- foreach ($this->getConditions() as $condition) {
- $condition->collectValidatedAttributes($productCollection);
- }
- return $this;
- }
-
- /**
- * Validate a condition with the checking of the child value
- *
- * @return bool
- */
- public function validate(Varien_Object $object)
- {
- /** @var Mage_Catalog_Model_Product $product */
- $product = $object->getProduct();
- if (!($product instanceof Mage_Catalog_Model_Product)) {
- $product = Mage::getModel('catalog/product')->load($object->getProductId());
- }
-
- $valid = parent::validate($object);
- if (!$valid && $product->getTypeId() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) {
- $children = $object->getChildren();
- if (is_array($children) && isset($children[0])) {
- $child = $children[0];
-
- /** @var Mage_Catalog_Model_Product $childProduct */
- $childProduct = Mage::getModel('catalog/product')->load($child->getProductId());
- $childProduct
- ->setQuoteItemQty($object->getQty())
- ->setQuoteItemPrice($object->getPrice())
- ->setQuoteItemRowTotal($object->getBaseRowTotal());
-
- if (!$childProduct->isVisibleInSiteVisibility()) {
- $childProduct->setCategoryIds($product->getCategoryIds());
- }
-
- $valid = parent::validate($childProduct);
- }
- }
-
- return $valid;
- }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Rule/Customer.php b/app/code/core/Mage/SalesRule/Model/Rule/Customer.php
index de42642a99c..de6f5eabcf0 100644
--- a/app/code/core/Mage/SalesRule/Model/Rule/Customer.php
+++ b/app/code/core/Mage/SalesRule/Model/Rule/Customer.php
@@ -31,12 +31,6 @@
*/
class Mage_SalesRule_Model_Rule_Customer extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- parent::_construct();
- $this->_init('salesrule/rule_customer');
- }
-
/**
* @param int $customerId
* @param int $ruleId
@@ -47,4 +41,9 @@ public function loadByCustomerRule($customerId, $ruleId)
$this->_getResource()->loadByCustomerRule($this, $customerId, $ruleId);
return $this;
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('salesrule/rule_customer');
+ }
}
diff --git a/app/code/core/Mage/SalesRule/Model/Validator.php b/app/code/core/Mage/SalesRule/Model/Validator.php
index 033beb4dc48..4b22fcfaed4 100644
--- a/app/code/core/Mage/SalesRule/Model/Validator.php
+++ b/app/code/core/Mage/SalesRule/Model/Validator.php
@@ -121,118 +121,6 @@ public function init($websiteId, $customerGroupId, $couponCode)
return $this;
}
- /**
- * Get rules collection for current object state
- *
- * @return Mage_SalesRule_Model_Resource_Rule_Collection
- */
- protected function _getRules()
- {
- $key = $this->getWebsiteId() . '_' . $this->getCustomerGroupId() . '_' . $this->getCouponCode();
- return $this->_rules[$key] ?? null;
- }
-
- /**
- * Get address object which can be used for discount calculation
- *
- * @return Mage_Sales_Model_Quote_Address
- */
- protected function _getAddress(Mage_Sales_Model_Quote_Item_Abstract $item)
- {
- if ($item instanceof Mage_Sales_Model_Quote_Address_Item) {
- $address = $item->getAddress();
- } elseif ($this->_address) {
- $address = $this->_address;
- } elseif ($item->getQuote()->getItemVirtualQty() > 0) {
- $address = $item->getQuote()->getBillingAddress();
- } else {
- $address = $item->getQuote()->getShippingAddress();
- }
- return $address;
- }
-
- /**
- * Check if rule can be applied for specific address/quote/customer
- *
- * @param Mage_SalesRule_Model_Rule $rule
- * @param Mage_Sales_Model_Quote_Address $address
- * @return bool
- */
- protected function _canProcessRule($rule, $address)
- {
- if ($rule->hasIsValidForAddress($address) && !$address->isObjectNew()) {
- return $rule->getIsValidForAddress($address);
- }
-
- /**
- * check per coupon usage limit
- */
- if ($rule->getCouponType() != Mage_SalesRule_Model_Rule::COUPON_TYPE_NO_COUPON) {
- $couponCode = $address->getQuote()->getCouponCode();
- if (strlen($couponCode)) {
- $coupon = Mage::getModel('salesrule/coupon');
- $coupon->load($couponCode, 'code');
- if ($coupon->getId()) {
- // check entire usage limit
- if ($coupon->getUsageLimit() && $coupon->getTimesUsed() >= $coupon->getUsageLimit()) {
- $rule->setIsValidForAddress($address, false);
- return false;
- }
- // check coupon expiration
- if ($coupon->hasExpirationDate() && ($coupon->getExpirationDate() < Mage::getModel('core/date')->date())) {
- $rule->setIsValidForAddress($address, false);
- return false;
- }
- // check per customer usage limit
- $customerId = $address->getQuote()->getCustomerId();
- if ($customerId && $coupon->getUsagePerCustomer()) {
- $couponUsage = new Varien_Object();
- Mage::getResourceModel('salesrule/coupon_usage')->loadByCustomerCoupon(
- $couponUsage,
- $customerId,
- $coupon->getId(),
- );
- if ($couponUsage->getCouponId() &&
- $couponUsage->getTimesUsed() >= $coupon->getUsagePerCustomer()
- ) {
- $rule->setIsValidForAddress($address, false);
- return false;
- }
- }
- }
- }
- }
-
- /**
- * check per rule usage limit
- */
- $ruleId = $rule->getId();
- if ($ruleId && $rule->getUsesPerCustomer()) {
- $customerId = $address->getQuote()->getCustomerId();
- $ruleCustomer = Mage::getModel('salesrule/rule_customer');
- $ruleCustomer->loadByCustomerRule($customerId, $ruleId);
- if ($ruleCustomer->getId()) {
- if ($ruleCustomer->getTimesUsed() >= $rule->getUsesPerCustomer()) {
- $rule->setIsValidForAddress($address, false);
- return false;
- }
- }
- }
- $rule->afterLoad();
- /**
- * quote does not meet rule's conditions
- */
- if (!$rule->validate($address)) {
- $rule->setIsValidForAddress($address, false);
- return false;
- }
- /**
- * passed all validations, remember to be valid
- */
- $rule->setIsValidForAddress($address, true);
- return true;
- }
-
/**
* Quote item free shipping ability check
* This process not affect information about applied rules, coupon code etc.
@@ -703,39 +591,6 @@ public function processWeeeAmount(Mage_Sales_Model_Quote_Address $address, $item
return $this;
}
- /**
- * Round the amount with deltas collected
- *
- * @param string $key
- * @param float $amount
- * @param Mage_Core_Model_Store $store
- * @return float
- */
- protected function _roundWithDeltas($key, $amount, $store)
- {
- $delta = $this->_roundingDeltas[$key] ?? 0;
- $this->_roundingDeltas[$key] = $store->roundPrice($amount + $delta)
- - $amount;
- return $store->roundPrice($amount + $delta);
- }
-
- /**
- * Round the amount with deltas collected
- *
- * @param string $key
- * @param float $amount
- * @param Mage_Core_Model_Store $store
- * @return float
- */
- protected function _roundWithDeltasForBase($key, $amount, $store)
- {
- $delta = isset($this->_baseRoundingDeltas[$key]) ?
- $this->_roundingDeltas[$key] : 0;
- $this->_baseRoundingDeltas[$key] = $store->roundPrice($amount + $delta)
- - $amount;
- return $store->roundPrice($amount + $delta);
- }
-
/**
* Apply discounts to shipping amount
*
@@ -919,6 +774,197 @@ public function initTotals($items, Mage_Sales_Model_Quote_Address $address)
return $this;
}
+ /**
+ * Convert address discount description array to string
+ *
+ * @param Mage_Sales_Model_Quote_Address $address
+ * @param string $separator
+ * @return $this
+ */
+ public function prepareDescription($address, $separator = ', ')
+ {
+ $descriptionArray = $address->getDiscountDescriptionArray();
+ /** @see Mage_SalesRule_Model_Validator::_getAddress */
+ if (!$descriptionArray && $address->getQuote()->getItemVirtualQty() > 0) {
+ $descriptionArray = $address->getQuote()->getBillingAddress()->getDiscountDescriptionArray();
+ }
+
+ $description = $descriptionArray && is_array($descriptionArray)
+ ? implode($separator, array_unique($descriptionArray))
+ : '';
+
+ $address->setDiscountDescription($description);
+ return $this;
+ }
+
+ /**
+ * Return items list sorted by possibility to apply prioritized rules
+ *
+ * @param array $items
+ * @return array $items
+ */
+ public function sortItemsByPriority($items)
+ {
+ $itemsSorted = [];
+ foreach ($this->_getRules() as $rule) {
+ foreach ($items as $itemKey => $itemValue) {
+ if ($rule->getActions()->validate($itemValue)) {
+ unset($items[$itemKey]);
+ $itemsSorted[] = $itemValue;
+ }
+ }
+ }
+ if (!empty($itemsSorted)) {
+ $items = array_merge($itemsSorted, $items);
+ }
+ return $items;
+ }
+
+ /**
+ * Get rules collection for current object state
+ *
+ * @return Mage_SalesRule_Model_Resource_Rule_Collection
+ */
+ protected function _getRules()
+ {
+ $key = $this->getWebsiteId() . '_' . $this->getCustomerGroupId() . '_' . $this->getCouponCode();
+ return $this->_rules[$key] ?? null;
+ }
+
+ /**
+ * Get address object which can be used for discount calculation
+ *
+ * @return Mage_Sales_Model_Quote_Address
+ */
+ protected function _getAddress(Mage_Sales_Model_Quote_Item_Abstract $item)
+ {
+ if ($item instanceof Mage_Sales_Model_Quote_Address_Item) {
+ $address = $item->getAddress();
+ } elseif ($this->_address) {
+ $address = $this->_address;
+ } elseif ($item->getQuote()->getItemVirtualQty() > 0) {
+ $address = $item->getQuote()->getBillingAddress();
+ } else {
+ $address = $item->getQuote()->getShippingAddress();
+ }
+ return $address;
+ }
+
+ /**
+ * Check if rule can be applied for specific address/quote/customer
+ *
+ * @param Mage_SalesRule_Model_Rule $rule
+ * @param Mage_Sales_Model_Quote_Address $address
+ * @return bool
+ */
+ protected function _canProcessRule($rule, $address)
+ {
+ if ($rule->hasIsValidForAddress($address) && !$address->isObjectNew()) {
+ return $rule->getIsValidForAddress($address);
+ }
+
+ /**
+ * check per coupon usage limit
+ */
+ if ($rule->getCouponType() != Mage_SalesRule_Model_Rule::COUPON_TYPE_NO_COUPON) {
+ $couponCode = $address->getQuote()->getCouponCode();
+ if (strlen($couponCode)) {
+ $coupon = Mage::getModel('salesrule/coupon');
+ $coupon->load($couponCode, 'code');
+ if ($coupon->getId()) {
+ // check entire usage limit
+ if ($coupon->getUsageLimit() && $coupon->getTimesUsed() >= $coupon->getUsageLimit()) {
+ $rule->setIsValidForAddress($address, false);
+ return false;
+ }
+ // check coupon expiration
+ if ($coupon->hasExpirationDate() && ($coupon->getExpirationDate() < Mage::getModel('core/date')->date())) {
+ $rule->setIsValidForAddress($address, false);
+ return false;
+ }
+ // check per customer usage limit
+ $customerId = $address->getQuote()->getCustomerId();
+ if ($customerId && $coupon->getUsagePerCustomer()) {
+ $couponUsage = new Varien_Object();
+ Mage::getResourceModel('salesrule/coupon_usage')->loadByCustomerCoupon(
+ $couponUsage,
+ $customerId,
+ $coupon->getId(),
+ );
+ if ($couponUsage->getCouponId() &&
+ $couponUsage->getTimesUsed() >= $coupon->getUsagePerCustomer()
+ ) {
+ $rule->setIsValidForAddress($address, false);
+ return false;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * check per rule usage limit
+ */
+ $ruleId = $rule->getId();
+ if ($ruleId && $rule->getUsesPerCustomer()) {
+ $customerId = $address->getQuote()->getCustomerId();
+ $ruleCustomer = Mage::getModel('salesrule/rule_customer');
+ $ruleCustomer->loadByCustomerRule($customerId, $ruleId);
+ if ($ruleCustomer->getId()) {
+ if ($ruleCustomer->getTimesUsed() >= $rule->getUsesPerCustomer()) {
+ $rule->setIsValidForAddress($address, false);
+ return false;
+ }
+ }
+ }
+ $rule->afterLoad();
+ /**
+ * quote does not meet rule's conditions
+ */
+ if (!$rule->validate($address)) {
+ $rule->setIsValidForAddress($address, false);
+ return false;
+ }
+ /**
+ * passed all validations, remember to be valid
+ */
+ $rule->setIsValidForAddress($address, true);
+ return true;
+ }
+
+ /**
+ * Round the amount with deltas collected
+ *
+ * @param string $key
+ * @param float $amount
+ * @param Mage_Core_Model_Store $store
+ * @return float
+ */
+ protected function _roundWithDeltas($key, $amount, $store)
+ {
+ $delta = $this->_roundingDeltas[$key] ?? 0;
+ $this->_roundingDeltas[$key] = $store->roundPrice($amount + $delta)
+ - $amount;
+ return $store->roundPrice($amount + $delta);
+ }
+
+ /**
+ * Round the amount with deltas collected
+ *
+ * @param string $key
+ * @param float $amount
+ * @param Mage_Core_Model_Store $store
+ * @return float
+ */
+ protected function _roundWithDeltasForBase($key, $amount, $store)
+ {
+ $delta = isset($this->_baseRoundingDeltas[$key]) ?
+ $this->_roundingDeltas[$key] : 0;
+ $this->_baseRoundingDeltas[$key] = $store->roundPrice($amount + $delta)
+ - $amount;
+ return $store->roundPrice($amount + $delta);
+ }
+
/**
* Set coupon code to address if $rule contains validated coupon
*
@@ -1030,29 +1076,6 @@ protected function _getItemQty($item, $rule)
return $rule->getDiscountQty() ? min($qty, $rule->getDiscountQty()) : $qty;
}
- /**
- * Convert address discount description array to string
- *
- * @param Mage_Sales_Model_Quote_Address $address
- * @param string $separator
- * @return $this
- */
- public function prepareDescription($address, $separator = ', ')
- {
- $descriptionArray = $address->getDiscountDescriptionArray();
- /** @see Mage_SalesRule_Model_Validator::_getAddress */
- if (!$descriptionArray && $address->getQuote()->getItemVirtualQty() > 0) {
- $descriptionArray = $address->getQuote()->getBillingAddress()->getDiscountDescriptionArray();
- }
-
- $description = $descriptionArray && is_array($descriptionArray)
- ? implode($separator, array_unique($descriptionArray))
- : '';
-
- $address->setDiscountDescription($description);
- return $this;
- }
-
/**
* wrap Mage::getSingleton
*
@@ -1074,27 +1097,4 @@ protected function _getHelper($name)
{
return Mage::helper($name);
}
-
- /**
- * Return items list sorted by possibility to apply prioritized rules
- *
- * @param array $items
- * @return array $items
- */
- public function sortItemsByPriority($items)
- {
- $itemsSorted = [];
- foreach ($this->_getRules() as $rule) {
- foreach ($items as $itemKey => $itemValue) {
- if ($rule->getActions()->validate($itemValue)) {
- unset($items[$itemKey]);
- $itemsSorted[] = $itemValue;
- }
- }
- }
- if (!empty($itemsSorted)) {
- $items = array_merge($itemsSorted, $items);
- }
- return $items;
- }
}
diff --git a/app/code/core/Mage/Shipping/Block/Tracking/Popup.php b/app/code/core/Mage/Shipping/Block/Tracking/Popup.php
index 4106c4e7f72..0a526f6886d 100644
--- a/app/code/core/Mage/Shipping/Block/Tracking/Popup.php
+++ b/app/code/core/Mage/Shipping/Block/Tracking/Popup.php
@@ -93,40 +93,6 @@ public function getTrackId()
return $this->_getData('track_id');
}
- /**
- * @deprecated after 1.4.0.0-alpha3
- * Initialize order model instance
- *
- * @return Mage_Sales_Model_Order|false
- */
- protected function _initOrder()
- {
- $order = Mage::getModel('sales/order')->load($this->getOrderId());
-
- if (!$order->getId() || $this->getProtectCode() != $order->getProtectCode()) {
- return false;
- }
-
- return $order;
- }
-
- /**
- * @deprecated after 1.4.0.0-alpha3
- * Initialize ship model instance
- *
- * @return Mage_Sales_Model_Order_Shipment|false
- */
- protected function _initShipment()
- {
- $ship = Mage::getModel('sales/order_shipment')->load($this->getShipId());
-
- if (!$ship->getEntityId() || $this->getProtectCode() != $ship->getProtectCode()) {
- return false;
- }
-
- return $ship;
- }
-
/**
* Retrieve array of tracking info
*
@@ -274,4 +240,38 @@ public function getContactUs()
{
return $this->getUrl('contacts');
}
+
+ /**
+ * @deprecated after 1.4.0.0-alpha3
+ * Initialize order model instance
+ *
+ * @return Mage_Sales_Model_Order|false
+ */
+ protected function _initOrder()
+ {
+ $order = Mage::getModel('sales/order')->load($this->getOrderId());
+
+ if (!$order->getId() || $this->getProtectCode() != $order->getProtectCode()) {
+ return false;
+ }
+
+ return $order;
+ }
+
+ /**
+ * @deprecated after 1.4.0.0-alpha3
+ * Initialize ship model instance
+ *
+ * @return Mage_Sales_Model_Order_Shipment|false
+ */
+ protected function _initShipment()
+ {
+ $ship = Mage::getModel('sales/order_shipment')->load($this->getShipId());
+
+ if (!$ship->getEntityId() || $this->getProtectCode() != $ship->getProtectCode()) {
+ return false;
+ }
+
+ return $ship;
+ }
}
diff --git a/app/code/core/Mage/Shipping/Helper/Data.php b/app/code/core/Mage/Shipping/Helper/Data.php
index 0b8f1ffa58f..d231b184319 100644
--- a/app/code/core/Mage/Shipping/Helper/Data.php
+++ b/app/code/core/Mage/Shipping/Helper/Data.php
@@ -44,32 +44,6 @@ public function decodeTrackingHash($hash)
return [];
}
- /**
- * Retrieve tracking url with params
- *
- * @deprecated the non-model usage
- *
- * @param string $key
- * @param int|Mage_Sales_Model_Order|Mage_Sales_Model_Order_Shipment|Mage_Sales_Model_Order_Shipment_Track $model
- * @param string $method - option
- * @return string
- */
- protected function _getTrackingUrl($key, $model, $method = 'getId')
- {
- if (empty($model)) {
- $param = [$key => '']; // @deprecated after 1.4.0.0-alpha3
- } elseif (!is_object($model)) {
- $param = [$key => $model]; // @deprecated after 1.4.0.0-alpha3
- } else {
- $param = [
- 'hash' => Mage::helper('core')->urlEncode("{$key}:{$model->$method()}:{$model->getProtectCode()}"),
- ];
- }
- $storeId = is_object($model) ? $model->getStoreId() : null;
- $storeModel = Mage::app()->getStore($storeId);
- return $storeModel->getUrl('shipping/tracking/popup', $param);
- }
-
/**
* @param string $order
* @return string
@@ -157,4 +131,30 @@ public function isFreeMethod($method, $storeId = null)
$freeMethod = Mage::getStoreConfig('carriers/' . $arr[0] . '/free_method', $storeId);
return $freeMethod == $arr[1];
}
+
+ /**
+ * Retrieve tracking url with params
+ *
+ * @deprecated the non-model usage
+ *
+ * @param string $key
+ * @param int|Mage_Sales_Model_Order|Mage_Sales_Model_Order_Shipment|Mage_Sales_Model_Order_Shipment_Track $model
+ * @param string $method - option
+ * @return string
+ */
+ protected function _getTrackingUrl($key, $model, $method = 'getId')
+ {
+ if (empty($model)) {
+ $param = [$key => '']; // @deprecated after 1.4.0.0-alpha3
+ } elseif (!is_object($model)) {
+ $param = [$key => $model]; // @deprecated after 1.4.0.0-alpha3
+ } else {
+ $param = [
+ 'hash' => Mage::helper('core')->urlEncode("{$key}:{$model->$method()}:{$model->getProtectCode()}"),
+ ];
+ }
+ $storeId = is_object($model) ? $model->getStoreId() : null;
+ $storeModel = Mage::app()->getStore($storeId);
+ return $storeModel->getUrl('shipping/tracking/popup', $param);
+ }
}
diff --git a/app/code/core/Mage/Shipping/Model/Carrier/Abstract.php b/app/code/core/Mage/Shipping/Model/Carrier/Abstract.php
index 8e14ecdf741..411efd77109 100644
--- a/app/code/core/Mage/Shipping/Model/Carrier/Abstract.php
+++ b/app/code/core/Mage/Shipping/Model/Carrier/Abstract.php
@@ -29,6 +29,15 @@
*/
abstract class Mage_Shipping_Model_Carrier_Abstract extends Varien_Object
{
+ public const USA_COUNTRY_ID = 'US';
+ public const CANADA_COUNTRY_ID = 'CA';
+ public const MEXICO_COUNTRY_ID = 'MX';
+
+ public const HANDLING_TYPE_PERCENT = 'P';
+ public const HANDLING_TYPE_FIXED = 'F';
+
+ public const HANDLING_ACTION_PERPACKAGE = 'P';
+ public const HANDLING_ACTION_PERORDER = 'O';
/**
* Carrier's code
*
@@ -71,16 +80,6 @@ abstract class Mage_Shipping_Model_Carrier_Abstract extends Varien_Object
*/
protected $_customizableContainerTypes = [];
- public const USA_COUNTRY_ID = 'US';
- public const CANADA_COUNTRY_ID = 'CA';
- public const MEXICO_COUNTRY_ID = 'MX';
-
- public const HANDLING_TYPE_PERCENT = 'P';
- public const HANDLING_TYPE_FIXED = 'F';
-
- public const HANDLING_ACTION_PERPACKAGE = 'P';
- public const HANDLING_ACTION_PERORDER = 'O';
-
/**
* Fields that should be replaced in debug with '***'
*
@@ -173,58 +172,6 @@ public function getContainerTypes(?Varien_Object $params = null)
return [];
}
- /**
- * Get allowed containers of carrier
- *
- * @return array|bool
- */
- protected function _getAllowedContainers(?Varien_Object $params = null)
- {
- $containersAll = $this->getContainerTypesAll();
- if (empty($containersAll)) {
- return [];
- }
- if (empty($params)) {
- return $containersAll;
- }
- $containersFilter = $this->getContainerTypesFilter();
- $containersFiltered = [];
- $method = $params->getMethod();
- $countryShipper = $params->getCountryShipper();
- $countryRecipient = $params->getCountryRecipient();
-
- if (empty($containersFilter)) {
- return $containersAll;
- }
- if (!$params || !$method || !$countryShipper || !$countryRecipient) {
- return $containersAll;
- }
-
- if ($countryShipper == self::USA_COUNTRY_ID && $countryRecipient == self::USA_COUNTRY_ID) {
- $direction = 'within_us';
- } elseif ($countryShipper == self::USA_COUNTRY_ID && $countryRecipient != self::USA_COUNTRY_ID) {
- $direction = 'from_us';
- } else {
- return $containersAll;
- }
-
- foreach ($containersFilter as $dataItem) {
- $containers = $dataItem['containers'];
- $filters = $dataItem['filters'];
- if (!empty($filters[$direction]['method'])
- && in_array($method, $filters[$direction]['method'])
- ) {
- foreach ($containers as $container) {
- if (!empty($containersAll[$container])) {
- $containersFiltered[$container] = $containersAll[$container];
- }
- }
- }
- }
-
- return !empty($containersFiltered) ? $containersFiltered : $containersAll;
- }
-
/**
* Get Container Types, that could be customized
*
@@ -342,68 +289,6 @@ public function getSortOrder()
return $this->getConfigData('sort_order');
}
- /**
- * @param Mage_Shipping_Model_Rate_Request $request
- */
- protected function _updateFreeMethodQuote($request)
- {
- if ($request->getFreeMethodWeight() == $request->getPackageWeight() || !$request->hasFreeMethodWeight()) {
- return;
- }
-
- $freeMethod = $this->getConfigData($this->_freeMethod);
- if (!$freeMethod) {
- return;
- }
- $freeRateId = false;
-
- if (is_object($this->_result)) {
- foreach ($this->_result->getAllRates() as $i => $item) {
- if ($item->getMethod() == $freeMethod) {
- $freeRateId = $i;
- break;
- }
- }
- }
-
- if ($freeRateId === false) {
- return;
- }
- $price = null;
- if ($request->getFreeMethodWeight() > 0) {
- $this->_setFreeMethodRequest($freeMethod);
-
- $result = $this->_getQuotes();
- if ($result && ($rates = $result->getAllRates()) && count($rates) > 0) {
- if ((count($rates) == 1) && ($rates[0] instanceof Mage_Shipping_Model_Rate_Result_Method)) {
- $price = $rates[0]->getPrice();
- }
- if (count($rates) > 1) {
- foreach ($rates as $rate) {
- if ($rate instanceof Mage_Shipping_Model_Rate_Result_Method
- && $rate->getMethod() == $freeMethod
- ) {
- $price = $rate->getPrice();
- }
- }
- }
- }
- } else {
- /**
- * if we can apply free shipping for all order we should force price
- * to $0.00 for shipping with out sending second request to carrier
- */
- $price = 0;
- }
-
- /**
- * if we did not get our free shipping method in response we must use its old price
- */
- if (!is_null($price)) {
- $this->_result->getRateById($freeRateId)->setPrice($price);
- }
- }
-
/**
* Calculate price considering free shipping and handling fee
*
@@ -443,40 +328,6 @@ public function getFinalPriceWithHandlingFee($cost)
: $this->_getPerorderPrice($cost, $handlingType, $handlingFee);
}
- /**
- * Get final price for shipping method with handling fee per package
- *
- * @param float $cost
- * @param string $handlingType
- * @param float $handlingFee
- * @return float
- */
- protected function _getPerpackagePrice($cost, $handlingType, $handlingFee)
- {
- if ($handlingType == self::HANDLING_TYPE_PERCENT) {
- return ($cost + ($cost * $handlingFee / 100)) * $this->_numBoxes;
- }
-
- return ($cost + $handlingFee) * $this->_numBoxes;
- }
-
- /**
- * Get final price for shipping method with handling fee per order
- *
- * @param float $cost
- * @param string $handlingType
- * @param float $handlingFee
- * @return float
- */
- protected function _getPerorderPrice($cost, $handlingType, $handlingFee)
- {
- if ($handlingType == self::HANDLING_TYPE_PERCENT) {
- return ($cost * $this->_numBoxes) + ($cost * $this->_numBoxes * $handlingFee / 100);
- }
-
- return ($cost * $this->_numBoxes) + $handlingFee;
- }
-
/**
* Return weight in pounds
*
@@ -540,20 +391,6 @@ public function isZipCodeRequired($countryId = null)
return false;
}
- /**
- * Log debug data to file
- *
- * @param mixed $debugData
- */
- protected function _debug($debugData)
- {
- if ($this->getDebugFlag()) {
- Mage::getModel('core/log_adapter', 'shipping_' . $this->getCarrierCode() . '.log')
- ->setFilterDataKeys($this->_debugReplacePrivateDataKeys)
- ->log($debugData);
- }
- }
-
/**
* Define if debugging is enabled
*
@@ -593,4 +430,166 @@ public function getContentTypes(Varien_Object $params)
{
return [];
}
+
+ /**
+ * Get allowed containers of carrier
+ *
+ * @return array|bool
+ */
+ protected function _getAllowedContainers(?Varien_Object $params = null)
+ {
+ $containersAll = $this->getContainerTypesAll();
+ if (empty($containersAll)) {
+ return [];
+ }
+ if (empty($params)) {
+ return $containersAll;
+ }
+ $containersFilter = $this->getContainerTypesFilter();
+ $containersFiltered = [];
+ $method = $params->getMethod();
+ $countryShipper = $params->getCountryShipper();
+ $countryRecipient = $params->getCountryRecipient();
+
+ if (empty($containersFilter)) {
+ return $containersAll;
+ }
+ if (!$params || !$method || !$countryShipper || !$countryRecipient) {
+ return $containersAll;
+ }
+
+ if ($countryShipper == self::USA_COUNTRY_ID && $countryRecipient == self::USA_COUNTRY_ID) {
+ $direction = 'within_us';
+ } elseif ($countryShipper == self::USA_COUNTRY_ID && $countryRecipient != self::USA_COUNTRY_ID) {
+ $direction = 'from_us';
+ } else {
+ return $containersAll;
+ }
+
+ foreach ($containersFilter as $dataItem) {
+ $containers = $dataItem['containers'];
+ $filters = $dataItem['filters'];
+ if (!empty($filters[$direction]['method'])
+ && in_array($method, $filters[$direction]['method'])
+ ) {
+ foreach ($containers as $container) {
+ if (!empty($containersAll[$container])) {
+ $containersFiltered[$container] = $containersAll[$container];
+ }
+ }
+ }
+ }
+
+ return !empty($containersFiltered) ? $containersFiltered : $containersAll;
+ }
+
+ /**
+ * @param Mage_Shipping_Model_Rate_Request $request
+ */
+ protected function _updateFreeMethodQuote($request)
+ {
+ if ($request->getFreeMethodWeight() == $request->getPackageWeight() || !$request->hasFreeMethodWeight()) {
+ return;
+ }
+
+ $freeMethod = $this->getConfigData($this->_freeMethod);
+ if (!$freeMethod) {
+ return;
+ }
+ $freeRateId = false;
+
+ if (is_object($this->_result)) {
+ foreach ($this->_result->getAllRates() as $i => $item) {
+ if ($item->getMethod() == $freeMethod) {
+ $freeRateId = $i;
+ break;
+ }
+ }
+ }
+
+ if ($freeRateId === false) {
+ return;
+ }
+ $price = null;
+ if ($request->getFreeMethodWeight() > 0) {
+ $this->_setFreeMethodRequest($freeMethod);
+
+ $result = $this->_getQuotes();
+ if ($result && ($rates = $result->getAllRates()) && count($rates) > 0) {
+ if ((count($rates) == 1) && ($rates[0] instanceof Mage_Shipping_Model_Rate_Result_Method)) {
+ $price = $rates[0]->getPrice();
+ }
+ if (count($rates) > 1) {
+ foreach ($rates as $rate) {
+ if ($rate instanceof Mage_Shipping_Model_Rate_Result_Method
+ && $rate->getMethod() == $freeMethod
+ ) {
+ $price = $rate->getPrice();
+ }
+ }
+ }
+ }
+ } else {
+ /**
+ * if we can apply free shipping for all order we should force price
+ * to $0.00 for shipping with out sending second request to carrier
+ */
+ $price = 0;
+ }
+
+ /**
+ * if we did not get our free shipping method in response we must use its old price
+ */
+ if (!is_null($price)) {
+ $this->_result->getRateById($freeRateId)->setPrice($price);
+ }
+ }
+
+ /**
+ * Get final price for shipping method with handling fee per package
+ *
+ * @param float $cost
+ * @param string $handlingType
+ * @param float $handlingFee
+ * @return float
+ */
+ protected function _getPerpackagePrice($cost, $handlingType, $handlingFee)
+ {
+ if ($handlingType == self::HANDLING_TYPE_PERCENT) {
+ return ($cost + ($cost * $handlingFee / 100)) * $this->_numBoxes;
+ }
+
+ return ($cost + $handlingFee) * $this->_numBoxes;
+ }
+
+ /**
+ * Get final price for shipping method with handling fee per order
+ *
+ * @param float $cost
+ * @param string $handlingType
+ * @param float $handlingFee
+ * @return float
+ */
+ protected function _getPerorderPrice($cost, $handlingType, $handlingFee)
+ {
+ if ($handlingType == self::HANDLING_TYPE_PERCENT) {
+ return ($cost * $this->_numBoxes) + ($cost * $this->_numBoxes * $handlingFee / 100);
+ }
+
+ return ($cost * $this->_numBoxes) + $handlingFee;
+ }
+
+ /**
+ * Log debug data to file
+ *
+ * @param mixed $debugData
+ */
+ protected function _debug($debugData)
+ {
+ if ($this->getDebugFlag()) {
+ Mage::getModel('core/log_adapter', 'shipping_' . $this->getCarrierCode() . '.log')
+ ->setFilterDataKeys($this->_debugReplacePrivateDataKeys)
+ ->log($debugData);
+ }
+ }
}
diff --git a/app/code/core/Mage/Shipping/Model/Carrier/Freeshipping.php b/app/code/core/Mage/Shipping/Model/Carrier/Freeshipping.php
index 088faca0d4f..699d736faf4 100644
--- a/app/code/core/Mage/Shipping/Model/Carrier/Freeshipping.php
+++ b/app/code/core/Mage/Shipping/Model/Carrier/Freeshipping.php
@@ -72,6 +72,16 @@ public function collectRates(Mage_Shipping_Model_Rate_Request $request)
return $result;
}
+ /**
+ * Get allowed shipping methods
+ *
+ * @return array
+ */
+ public function getAllowedMethods()
+ {
+ return ['freeshipping' => $this->getConfigData('name')];
+ }
+
/**
* Allows free shipping when all product items have free shipping (promotions etc.)
*
@@ -95,14 +105,4 @@ protected function _updateFreeMethodQuote($request)
$request->setFreeShipping(true);
}
}
-
- /**
- * Get allowed shipping methods
- *
- * @return array
- */
- public function getAllowedMethods()
- {
- return ['freeshipping' => $this->getConfigData('name')];
- }
}
diff --git a/app/code/core/Mage/Shipping/Model/Carrier/Tablerate.php b/app/code/core/Mage/Shipping/Model/Carrier/Tablerate.php
index f4fd7c6ce4b..abd04a5a3ef 100644
--- a/app/code/core/Mage/Shipping/Model/Carrier/Tablerate.php
+++ b/app/code/core/Mage/Shipping/Model/Carrier/Tablerate.php
@@ -191,17 +191,6 @@ public function collectRates(Mage_Shipping_Model_Rate_Request $request)
return $result;
}
- /**
- * Get Model
- *
- * @param string $modelName
- * @return Mage_Core_Model_Abstract
- */
- protected function _getModel($modelName)
- {
- return Mage::getModel($modelName);
- }
-
/**
* Get Rate
*
@@ -261,4 +250,15 @@ public function getAllowedMethods()
{
return ['bestway' => $this->getConfigData('name')];
}
+
+ /**
+ * Get Model
+ *
+ * @param string $modelName
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _getModel($modelName)
+ {
+ return Mage::getModel($modelName);
+ }
}
diff --git a/app/code/core/Mage/Shipping/Model/Info.php b/app/code/core/Mage/Shipping/Model/Info.php
index a9162c11ae8..120eb43a359 100644
--- a/app/code/core/Mage/Shipping/Model/Info.php
+++ b/app/code/core/Mage/Shipping/Model/Info.php
@@ -71,39 +71,6 @@ public function getTrackingInfo()
return $this->_trackingInfo;
}
- /**
- * Instantiate order model
- *
- * @return Mage_Sales_Model_Order|bool
- */
- protected function _initOrder()
- {
- $order = Mage::getModel('sales/order')->load($this->getOrderId());
-
- if (!$order->getId() || $this->getProtectCode() !== $order->getProtectCode()) {
- return false;
- }
-
- return $order;
- }
-
- /**
- * Instantiate ship model
- *
- * @return Mage_Sales_Model_Order_Shipment|bool
- */
- protected function _initShipment()
- {
- /** @var Mage_Sales_Model_Order_Shipment $model */
- $model = Mage::getModel('sales/order_shipment');
- $ship = $model->load($this->getShipId());
- if (!$ship->getEntityId() || $this->getProtectCode() !== $ship->getProtectCode()) {
- return false;
- }
-
- return $ship;
- }
-
/**
* Retrieve all tracking by order id
*
@@ -167,4 +134,37 @@ public function getTrackingInfoByTrackId()
}
return $this->_trackingInfo;
}
+
+ /**
+ * Instantiate order model
+ *
+ * @return Mage_Sales_Model_Order|bool
+ */
+ protected function _initOrder()
+ {
+ $order = Mage::getModel('sales/order')->load($this->getOrderId());
+
+ if (!$order->getId() || $this->getProtectCode() !== $order->getProtectCode()) {
+ return false;
+ }
+
+ return $order;
+ }
+
+ /**
+ * Instantiate ship model
+ *
+ * @return Mage_Sales_Model_Order_Shipment|bool
+ */
+ protected function _initShipment()
+ {
+ /** @var Mage_Sales_Model_Order_Shipment $model */
+ $model = Mage::getModel('sales/order_shipment');
+ $ship = $model->load($this->getShipId());
+ if (!$ship->getEntityId() || $this->getProtectCode() !== $ship->getProtectCode()) {
+ return false;
+ }
+
+ return $ship;
+ }
}
diff --git a/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php b/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php
index e714e28a4da..719c3e3a267 100644
--- a/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php
+++ b/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php
@@ -86,11 +86,6 @@ class Mage_Shipping_Model_Resource_Carrier_Tablerate extends Mage_Core_Model_Res
*/
protected $_conditionFullNames = [];
- protected function _construct()
- {
- $this->_init('shipping/tablerate', 'pk');
- }
-
/**
* Return table rate array or false by rate request
*
@@ -270,6 +265,11 @@ public function uploadAndImport(Varien_Object $object)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('shipping/tablerate', 'pk');
+ }
+
/**
* Load directory countries
*
diff --git a/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate/Collection.php b/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate/Collection.php
index 56473206d24..ed3e3384677 100644
--- a/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate/Collection.php
+++ b/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate/Collection.php
@@ -44,18 +44,6 @@ class Mage_Shipping_Model_Resource_Carrier_Tablerate_Collection extends Mage_Cor
*/
protected $_regionTable;
- /**
- * Define resource model and item
- *
- */
- protected function _construct()
- {
- $this->_init('shipping/carrier_tablerate');
- $this->_shipTable = $this->getMainTable();
- $this->_countryTable = $this->getTable('directory/country');
- $this->_regionTable = $this->getTable('directory/country_region');
- }
-
/**
* Initialize select, add country iso3 code and region name
*
@@ -117,4 +105,16 @@ public function setCountryFilter($countryId)
{
return $this->addFieldToFilter('dest_country_id', $countryId);
}
+
+ /**
+ * Define resource model and item
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('shipping/carrier_tablerate');
+ $this->_shipTable = $this->getMainTable();
+ $this->_countryTable = $this->getTable('directory/country');
+ $this->_regionTable = $this->getTable('directory/country_region');
+ }
}
diff --git a/app/code/core/Mage/Shipping/Model/Shipping.php b/app/code/core/Mage/Shipping/Model/Shipping.php
index a789a593244..d2b785add49 100644
--- a/app/code/core/Mage/Shipping/Model/Shipping.php
+++ b/app/code/core/Mage/Shipping/Model/Shipping.php
@@ -304,53 +304,6 @@ public function composePackagesForCarrier($carrier, $request)
return $this->_makePieces($fullItems, $maxWeight);
}
- /**
- * Make pieces
- * Compose packeges list based on given items, so that each package is as heavy as possible
- *
- * @param array $items
- * @param float $maxWeight
- * @return array
- */
- protected function _makePieces($items, $maxWeight)
- {
- $pieces = [];
- if (!empty($items)) {
- $sumWeight = 0;
-
- $reverseOrderItems = $items;
- arsort($reverseOrderItems);
-
- foreach ($reverseOrderItems as $key => $weight) {
- if (!isset($items[$key])) {
- continue;
- }
- unset($items[$key]);
- $sumWeight = $weight;
- foreach ($items as $keyItem => $weightItem) {
- if (($sumWeight + $weightItem) < $maxWeight) {
- unset($items[$keyItem]);
- $sumWeight += $weightItem;
- } elseif (($sumWeight + $weightItem) > $maxWeight) {
- $pieces[] = (string) (float) $sumWeight;
- break;
- } else {
- unset($items[$keyItem]);
- $pieces[] = (string) (float) ($sumWeight + $weightItem);
- $sumWeight = 0;
- break;
- }
- }
- }
- if ($sumWeight > 0) {
- $pieces[] = (string) (float) $sumWeight;
- }
- $pieces = array_count_values($pieces);
- }
-
- return $pieces;
- }
-
/**
* Collect rates by address
*
@@ -493,4 +446,51 @@ public function requestToShipment(Mage_Sales_Model_Order_Shipment $orderShipment
return $shipmentCarrier->requestToShipment($request);
}
+
+ /**
+ * Make pieces
+ * Compose packeges list based on given items, so that each package is as heavy as possible
+ *
+ * @param array $items
+ * @param float $maxWeight
+ * @return array
+ */
+ protected function _makePieces($items, $maxWeight)
+ {
+ $pieces = [];
+ if (!empty($items)) {
+ $sumWeight = 0;
+
+ $reverseOrderItems = $items;
+ arsort($reverseOrderItems);
+
+ foreach ($reverseOrderItems as $key => $weight) {
+ if (!isset($items[$key])) {
+ continue;
+ }
+ unset($items[$key]);
+ $sumWeight = $weight;
+ foreach ($items as $keyItem => $weightItem) {
+ if (($sumWeight + $weightItem) < $maxWeight) {
+ unset($items[$keyItem]);
+ $sumWeight += $weightItem;
+ } elseif (($sumWeight + $weightItem) > $maxWeight) {
+ $pieces[] = (string) (float) $sumWeight;
+ break;
+ } else {
+ unset($items[$keyItem]);
+ $pieces[] = (string) (float) ($sumWeight + $weightItem);
+ $sumWeight = 0;
+ break;
+ }
+ }
+ }
+ if ($sumWeight > 0) {
+ $pieces[] = (string) (float) $sumWeight;
+ }
+ $pieces = array_count_values($pieces);
+ }
+
+ return $pieces;
+ }
}
diff --git a/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Category.php b/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Category.php
index 8808a39261a..8131bbfec29 100644
--- a/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Category.php
+++ b/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Category.php
@@ -22,14 +22,6 @@
*/
class Mage_Sitemap_Model_Resource_Catalog_Category extends Mage_Sitemap_Model_Resource_Catalog_Abstract
{
- /**
- * Init resource model (catalog/category)
- */
- protected function _construct()
- {
- $this->_init('catalog/category', 'entity_id');
- }
-
/**
* Get category collection array
*
@@ -65,6 +57,13 @@ public function getCollection($storeId)
return $this->_loadEntities();
}
+ /**
+ * Init resource model (catalog/category)
+ */
+ protected function _construct()
+ {
+ $this->_init('catalog/category', 'entity_id');
+ }
/**
* Prepare category
diff --git a/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Product.php b/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Product.php
index 3823315b0b5..a8a723eff4e 100644
--- a/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Product.php
+++ b/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Product.php
@@ -22,11 +22,6 @@
*/
class Mage_Sitemap_Model_Resource_Catalog_Product extends Mage_Sitemap_Model_Resource_Catalog_Abstract
{
- protected function _construct()
- {
- $this->_init('catalog/product', 'entity_id');
- }
-
/**
* Get product collection array
*
@@ -69,6 +64,10 @@ public function getCollection($storeId)
return $this->_loadEntities();
}
+ protected function _construct()
+ {
+ $this->_init('catalog/product', 'entity_id');
+ }
/**
* Prepare product
diff --git a/app/code/core/Mage/Sitemap/Model/Resource/Cms/Page.php b/app/code/core/Mage/Sitemap/Model/Resource/Cms/Page.php
index fc551477f23..73c5830cb16 100644
--- a/app/code/core/Mage/Sitemap/Model/Resource/Cms/Page.php
+++ b/app/code/core/Mage/Sitemap/Model/Resource/Cms/Page.php
@@ -22,11 +22,6 @@
*/
class Mage_Sitemap_Model_Resource_Cms_Page extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('cms/page', 'page_id');
- }
-
/**
* Retrieve cms page collection array
*
@@ -57,6 +52,10 @@ public function getCollection($storeId)
return $pages;
}
+ protected function _construct()
+ {
+ $this->_init('cms/page', 'page_id');
+ }
/**
* Prepare page object
diff --git a/app/code/core/Mage/Sitemap/Model/Sitemap.php b/app/code/core/Mage/Sitemap/Model/Sitemap.php
index a0cc4ca3225..b87a00f4f54 100644
--- a/app/code/core/Mage/Sitemap/Model/Sitemap.php
+++ b/app/code/core/Mage/Sitemap/Model/Sitemap.php
@@ -45,68 +45,6 @@ class Mage_Sitemap_Model_Sitemap extends Mage_Core_Model_Abstract
*/
protected $_filePath;
- /**
- * Init model
- */
- protected function _construct()
- {
- $this->_init('sitemap/sitemap');
- }
-
- /**
- * @inheritDoc
- * @throws Mage_Core_Exception
- */
- protected function _beforeSave()
- {
- $io = new Varien_Io_File();
- $realPath = $io->getCleanPath(Mage::getBaseDir() . '/' . $this->getSitemapPath());
-
- /**
- * Check path is allow
- */
- if (!$io->allowedPath($realPath, Mage::getBaseDir())) {
- Mage::throwException(Mage::helper('sitemap')->__('Please define correct path'));
- }
- /**
- * Check exists and writeable path
- */
- if (!$io->fileExists($realPath, false)) {
- Mage::throwException(Mage::helper('sitemap')->__('Please create the specified folder "%s" before saving the sitemap.', Mage::helper('core')->escapeHtml($this->getSitemapPath())));
- }
-
- if (!$io->isWriteable($realPath)) {
- Mage::throwException(Mage::helper('sitemap')->__('Please make sure that "%s" is writable by web-server.', $this->getSitemapPath()));
- }
- /**
- * Check allow filename
- */
- if (!preg_match('#^[a-zA-Z0-9_\.]+$#', $this->getSitemapFilename())) {
- Mage::throwException(Mage::helper('sitemap')->__('Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in the filename. No spaces or other characters are allowed.'));
- }
- if (!preg_match('#\.xml$#', $this->getSitemapFilename())) {
- $this->setSitemapFilename($this->getSitemapFilename() . '.xml');
- }
-
- $this->setSitemapPath(rtrim(str_replace(str_replace('\\', '/', Mage::getBaseDir()), '', $realPath), '/') . '/');
-
- return parent::_beforeSave();
- }
-
- /**
- * Return real file path
- *
- * @return string
- */
- protected function getPath()
- {
- if (is_null($this->_filePath)) {
- $this->_filePath = str_replace('//', '/', Mage::getBaseDir() .
- $this->getSitemapPath());
- }
- return $this->_filePath;
- }
-
/**
* Return full file name with path
*
@@ -223,6 +161,68 @@ public function generateXml()
return $this;
}
+ /**
+ * Init model
+ */
+ protected function _construct()
+ {
+ $this->_init('sitemap/sitemap');
+ }
+
+ /**
+ * @inheritDoc
+ * @throws Mage_Core_Exception
+ */
+ protected function _beforeSave()
+ {
+ $io = new Varien_Io_File();
+ $realPath = $io->getCleanPath(Mage::getBaseDir() . '/' . $this->getSitemapPath());
+
+ /**
+ * Check path is allow
+ */
+ if (!$io->allowedPath($realPath, Mage::getBaseDir())) {
+ Mage::throwException(Mage::helper('sitemap')->__('Please define correct path'));
+ }
+ /**
+ * Check exists and writeable path
+ */
+ if (!$io->fileExists($realPath, false)) {
+ Mage::throwException(Mage::helper('sitemap')->__('Please create the specified folder "%s" before saving the sitemap.', Mage::helper('core')->escapeHtml($this->getSitemapPath())));
+ }
+
+ if (!$io->isWriteable($realPath)) {
+ Mage::throwException(Mage::helper('sitemap')->__('Please make sure that "%s" is writable by web-server.', $this->getSitemapPath()));
+ }
+ /**
+ * Check allow filename
+ */
+ if (!preg_match('#^[a-zA-Z0-9_\.]+$#', $this->getSitemapFilename())) {
+ Mage::throwException(Mage::helper('sitemap')->__('Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in the filename. No spaces or other characters are allowed.'));
+ }
+ if (!preg_match('#\.xml$#', $this->getSitemapFilename())) {
+ $this->setSitemapFilename($this->getSitemapFilename() . '.xml');
+ }
+
+ $this->setSitemapPath(rtrim(str_replace(str_replace('\\', '/', Mage::getBaseDir()), '', $realPath), '/') . '/');
+
+ return parent::_beforeSave();
+ }
+
+ /**
+ * Return real file path
+ *
+ * @return string
+ */
+ protected function getPath()
+ {
+ if (is_null($this->_filePath)) {
+ $this->_filePath = str_replace('//', '/', Mage::getBaseDir() .
+ $this->getSitemapPath());
+ }
+ return $this->_filePath;
+ }
+
/**
* Get sitemap row
*
diff --git a/app/code/core/Mage/Tag/Block/All.php b/app/code/core/Mage/Tag/Block/All.php
index 900c683917e..f156639b89d 100644
--- a/app/code/core/Mage/Tag/Block/All.php
+++ b/app/code/core/Mage/Tag/Block/All.php
@@ -26,6 +26,32 @@ class Mage_Tag_Block_All extends Mage_Core_Block_Template
protected $_minPopularity;
protected $_maxPopularity;
+ /**
+ * @return Mage_Tag_Model_Tag[]
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ public function getTags()
+ {
+ $this->_loadTags();
+ return $this->_tags;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMaxPopularity()
+ {
+ return $this->_maxPopularity;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMinPopularity()
+ {
+ return $this->_minPopularity;
+ }
+
/**
* @return $this
* @throws Mage_Core_Model_Store_Exception
@@ -58,32 +84,6 @@ protected function _loadTags()
return $this;
}
- /**
- * @return Mage_Tag_Model_Tag[]
- * @throws Mage_Core_Model_Store_Exception
- */
- public function getTags()
- {
- $this->_loadTags();
- return $this->_tags;
- }
-
- /**
- * @return int
- */
- public function getMaxPopularity()
- {
- return $this->_maxPopularity;
- }
-
- /**
- * @return int
- */
- public function getMinPopularity()
- {
- return $this->_minPopularity;
- }
-
/**
* @return string
*/
diff --git a/app/code/core/Mage/Tag/Block/Customer/Recent.php b/app/code/core/Mage/Tag/Block/Customer/Recent.php
index 52648e9fae9..26aa5885dd4 100644
--- a/app/code/core/Mage/Tag/Block/Customer/Recent.php
+++ b/app/code/core/Mage/Tag/Block/Customer/Recent.php
@@ -27,24 +27,6 @@ class Mage_Tag_Block_Customer_Recent extends Mage_Core_Block_Template
*/
protected $_collection;
- protected function _construct()
- {
- parent::_construct();
-
- $this->_collection = Mage::getModel('tag/tag')->getEntityCollection()
- ->addStoreFilter(Mage::app()->getStore()->getId())
- ->addCustomerFilter(Mage::getSingleton('customer/session')->getCustomerId())
- ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
- ->setDescOrder()
- ->setPageSize(5)
- ->setActiveFilter()
- ->load()
- ->addProductTags();
-
- Mage::getSingleton('catalog/product_visibility')
- ->addVisibleInSiteFilterToCollection($this->_collection);
- }
-
/**
* @return int
*/
@@ -53,14 +35,6 @@ public function count()
return $this->_collection->getSize();
}
- /**
- * @return Mage_Tag_Model_Resource_Product_Collection
- */
- protected function _getCollection()
- {
- return $this->_collection;
- }
-
/**
* @return Mage_Tag_Model_Resource_Product_Collection
*/
@@ -86,6 +60,32 @@ public function getAllTagsUrl()
return Mage::getUrl('tag/customer');
}
+ protected function _construct()
+ {
+ parent::_construct();
+
+ $this->_collection = Mage::getModel('tag/tag')->getEntityCollection()
+ ->addStoreFilter(Mage::app()->getStore()->getId())
+ ->addCustomerFilter(Mage::getSingleton('customer/session')->getCustomerId())
+ ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
+ ->setDescOrder()
+ ->setPageSize(5)
+ ->setActiveFilter()
+ ->load()
+ ->addProductTags();
+
+ Mage::getSingleton('catalog/product_visibility')
+ ->addVisibleInSiteFilterToCollection($this->_collection);
+ }
+
+ /**
+ * @return Mage_Tag_Model_Resource_Product_Collection
+ */
+ protected function _getCollection()
+ {
+ return $this->_collection;
+ }
+
/**
* @return string
*/
diff --git a/app/code/core/Mage/Tag/Block/Customer/Tags.php b/app/code/core/Mage/Tag/Block/Customer/Tags.php
index 679a14c0d38..0730677dc5e 100644
--- a/app/code/core/Mage/Tag/Block/Customer/Tags.php
+++ b/app/code/core/Mage/Tag/Block/Customer/Tags.php
@@ -26,6 +26,31 @@ class Mage_Tag_Block_Customer_Tags extends Mage_Customer_Block_Account_Dashboard
protected $_minPopularity;
protected $_maxPopularity;
+ /**
+ * @return Mage_Tag_Model_Tag[]
+ */
+ public function getTags()
+ {
+ $this->_loadTags();
+ return $this->_tags;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMaxPopularity()
+ {
+ return $this->_maxPopularity;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMinPopularity()
+ {
+ return $this->_minPopularity;
+ }
+
protected function _loadTags()
{
if (empty($this->_tags)) {
@@ -58,29 +83,4 @@ protected function _loadTags()
}
ksort($this->_tags);
}
-
- /**
- * @return Mage_Tag_Model_Tag[]
- */
- public function getTags()
- {
- $this->_loadTags();
- return $this->_tags;
- }
-
- /**
- * @return int
- */
- public function getMaxPopularity()
- {
- return $this->_maxPopularity;
- }
-
- /**
- * @return int
- */
- public function getMinPopularity()
- {
- return $this->_minPopularity;
- }
}
diff --git a/app/code/core/Mage/Tag/Block/Customer/View.php b/app/code/core/Mage/Tag/Block/Customer/View.php
index d3246a5140e..550655eb401 100644
--- a/app/code/core/Mage/Tag/Block/Customer/View.php
+++ b/app/code/core/Mage/Tag/Block/Customer/View.php
@@ -39,16 +39,6 @@ class Mage_Tag_Block_Customer_View extends Mage_Catalog_Block_Product_Abstract
*/
protected $_tagInfo;
- /**
- * Initialize block
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTagId(Mage::registry('tagId'));
- }
-
/**
* Retrieve current Tag object
*
@@ -94,21 +84,6 @@ public function getReviewUrl($productId)
return Mage::getUrl('review/product/list', ['id' => $productId]);
}
- /**
- * Preparing block layout
- *
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $toolbar = $this->getLayout()
- ->createBlock('page/html_pager', 'customer_tag_list.toolbar')
- ->setCollection($this->_getCollection());
-
- $this->setChild('toolbar', $toolbar);
- return parent::_prepareLayout();
- }
-
/**
* Retrieve Toolbar block HTML
*
@@ -129,6 +104,31 @@ public function getMode()
return $this->getChild('toolbar')->getCurrentMode();
}
+ /**
+ * Initialize block
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTagId(Mage::registry('tagId'));
+ }
+
+ /**
+ * Preparing block layout
+ *
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $toolbar = $this->getLayout()
+ ->createBlock('page/html_pager', 'customer_tag_list.toolbar')
+ ->setCollection($this->_getCollection());
+
+ $this->setChild('toolbar', $toolbar);
+ return parent::_prepareLayout();
+ }
+
/**
* Retrieve Tagged product(s) collection
*
diff --git a/app/code/core/Mage/Tag/Block/Popular.php b/app/code/core/Mage/Tag/Block/Popular.php
index 94f9e5fb5c0..2652096122f 100644
--- a/app/code/core/Mage/Tag/Block/Popular.php
+++ b/app/code/core/Mage/Tag/Block/Popular.php
@@ -26,6 +26,32 @@ class Mage_Tag_Block_Popular extends Mage_Core_Block_Template
protected $_minPopularity;
protected $_maxPopularity;
+ /**
+ * @return Mage_Tag_Model_Tag[]
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ public function getTags()
+ {
+ $this->_loadTags();
+ return $this->_tags;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMaxPopularity()
+ {
+ return $this->_maxPopularity;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMinPopularity()
+ {
+ return $this->_minPopularity;
+ }
+
/**
* @return $this
* @throws Mage_Core_Model_Store_Exception
@@ -60,32 +86,6 @@ protected function _loadTags()
return $this;
}
- /**
- * @return Mage_Tag_Model_Tag[]
- * @throws Mage_Core_Model_Store_Exception
- */
- public function getTags()
- {
- $this->_loadTags();
- return $this->_tags;
- }
-
- /**
- * @return int
- */
- public function getMaxPopularity()
- {
- return $this->_maxPopularity;
- }
-
- /**
- * @return int
- */
- public function getMinPopularity()
- {
- return $this->_minPopularity;
- }
-
/**
* @return string
* @throws Mage_Core_Model_Store_Exception
diff --git a/app/code/core/Mage/Tag/Block/Product/List.php b/app/code/core/Mage/Tag/Block/Product/List.php
index a1ba15c838c..ad090d85990 100644
--- a/app/code/core/Mage/Tag/Block/Product/List.php
+++ b/app/code/core/Mage/Tag/Block/Product/List.php
@@ -58,38 +58,6 @@ public function getProductId()
return false;
}
- /**
- * @return mixed
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _getCollection()
- {
- if (!$this->_collection && $this->getProductId()) {
- $model = Mage::getModel('tag/tag');
- $this->_collection = $model->getResourceCollection()
- ->addPopularity()
- ->addStatusFilter($model->getApprovedStatus())
- ->addProductFilter($this->getProductId())
- ->setFlag('relation', true)
- ->addStoreFilter(Mage::app()->getStore()->getId())
- ->setActiveFilter()
- ->load();
- }
- return $this->_collection;
- }
-
- /**
- * @inheritDoc
- */
- protected function _beforeToHtml()
- {
- if (!$this->getProductId()) {
- return $this;
- }
-
- return parent::_beforeToHtml();
- }
-
/**
* @return string
*/
@@ -137,4 +105,36 @@ public function getUniqueHtmlId($prefix = '')
}
return $this->_uniqueHtmlId;
}
+
+ /**
+ * @return mixed
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _getCollection()
+ {
+ if (!$this->_collection && $this->getProductId()) {
+ $model = Mage::getModel('tag/tag');
+ $this->_collection = $model->getResourceCollection()
+ ->addPopularity()
+ ->addStatusFilter($model->getApprovedStatus())
+ ->addProductFilter($this->getProductId())
+ ->setFlag('relation', true)
+ ->addStoreFilter(Mage::app()->getStore()->getId())
+ ->setActiveFilter()
+ ->load();
+ }
+ return $this->_collection;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ protected function _beforeToHtml()
+ {
+ if (!$this->getProductId()) {
+ return $this;
+ }
+
+ return parent::_beforeToHtml();
+ }
}
diff --git a/app/code/core/Mage/Tag/Block/Product/Result.php b/app/code/core/Mage/Tag/Block/Product/Result.php
index dac21a98099..f14d417b145 100644
--- a/app/code/core/Mage/Tag/Block/Product/Result.php
+++ b/app/code/core/Mage/Tag/Block/Product/Result.php
@@ -37,17 +37,6 @@ public function getTag()
return Mage::registry('current_tag');
}
- /**
- * @inheritDoc
- */
- protected function _prepareLayout()
- {
- $title = $this->getHeaderText();
- $this->getLayout()->getBlock('head')->setTitle($title);
- $this->getLayout()->getBlock('root')->setHeaderTitle($title);
- return parent::_prepareLayout();
- }
-
public function setListOrders()
{
$this->getChild('search_result_list')
@@ -81,32 +70,6 @@ public function getProductListHtml()
return $this->getChildHtml('search_result_list');
}
- /**
- * @return Mage_Tag_Model_Resource_Product_Collection
- * @throws Mage_Core_Model_Store_Exception
- */
- protected function _getProductCollection()
- {
- if (is_null($this->_productCollection)) {
- $tagModel = Mage::getModel('tag/tag');
- $this->_productCollection = $tagModel->getEntityCollection()
- ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
- ->addTagFilter($this->getTag()->getId())
- ->addStoreFilter(Mage::app()->getStore()->getId())
- ->addAttributeToFilter('status', [
- 'in' => Mage::getSingleton('catalog/product_status')->getSaleableStatusIds(),
- ])
- ->addMinimalPrice()
- ->addUrlRewrite()
- ->setActiveFilter();
- Mage::getSingleton('catalog/product_visibility')->addVisibleInSiteFilterToCollection(
- $this->_productCollection,
- );
- }
-
- return $this->_productCollection;
- }
-
/**
* @return int
* @throws Mage_Core_Model_Store_Exception
@@ -146,4 +109,41 @@ public function getNoResultText()
{
return Mage::helper('tag')->__('No matches found.');
}
+
+ /**
+ * @inheritDoc
+ */
+ protected function _prepareLayout()
+ {
+ $title = $this->getHeaderText();
+ $this->getLayout()->getBlock('head')->setTitle($title);
+ $this->getLayout()->getBlock('root')->setHeaderTitle($title);
+ return parent::_prepareLayout();
+ }
+
+ /**
+ * @return Mage_Tag_Model_Resource_Product_Collection
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ protected function _getProductCollection()
+ {
+ if (is_null($this->_productCollection)) {
+ $tagModel = Mage::getModel('tag/tag');
+ $this->_productCollection = $tagModel->getEntityCollection()
+ ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
+ ->addTagFilter($this->getTag()->getId())
+ ->addStoreFilter(Mage::app()->getStore()->getId())
+ ->addAttributeToFilter('status', [
+ 'in' => Mage::getSingleton('catalog/product_status')->getSaleableStatusIds(),
+ ])
+ ->addMinimalPrice()
+ ->addUrlRewrite()
+ ->setActiveFilter();
+ Mage::getSingleton('catalog/product_visibility')->addVisibleInSiteFilterToCollection(
+ $this->_productCollection,
+ );
+ }
+
+ return $this->_productCollection;
+ }
}
diff --git a/app/code/core/Mage/Tag/Model/Indexer/Summary.php b/app/code/core/Mage/Tag/Model/Indexer/Summary.php
index 2c1fa75b6e4..5f212f519c9 100644
--- a/app/code/core/Mage/Tag/Model/Indexer/Summary.php
+++ b/app/code/core/Mage/Tag/Model/Indexer/Summary.php
@@ -58,11 +58,6 @@ class Mage_Tag_Model_Indexer_Summary extends Mage_Index_Model_Indexer_Abstract
],
];
- protected function _construct()
- {
- $this->_init('tag/indexer_summary');
- }
-
/**
* Retrieve Indexer name
*
@@ -83,6 +78,11 @@ public function getDescription()
return Mage::helper('tag')->__('Rebuild Tag aggregation data');
}
+ protected function _construct()
+ {
+ $this->_init('tag/indexer_summary');
+ }
+
/**
* Retrieve attribute list that has an effect on tags
*
diff --git a/app/code/core/Mage/Tag/Model/Resource/Customer/Collection.php b/app/code/core/Mage/Tag/Model/Resource/Customer/Collection.php
index c60f213573d..a579897d421 100644
--- a/app/code/core/Mage/Tag/Model/Resource/Customer/Collection.php
+++ b/app/code/core/Mage/Tag/Model/Resource/Customer/Collection.php
@@ -220,30 +220,6 @@ public function addCustomerFilter($customerId)
return $this;
}
- /**
- * Joins tables to select
- *
- */
- protected function _joinFields()
- {
- $tagRelationTable = $this->getTable('tag/relation');
- $tagTable = $this->getTable('tag/tag');
-
- //TODO: add full name logic
- $this->addAttributeToSelect('firstname')
- ->addAttributeToSelect('middlename')
- ->addAttributeToSelect('lastname')
- ->addAttributeToSelect('email');
-
- $this->getSelect()
- ->join(
- ['tr' => $tagRelationTable],
- 'tr.customer_id = e.entity_id',
- ['tag_relation_id', 'product_id', 'active', 'added_in' => 'store_id'],
- )
- ->join(['t' => $tagTable], 't.tag_id = tr.tag_id', ['*']);
- }
-
/**
* Gets number of rows
*
@@ -369,6 +345,30 @@ public function addFieldToFilter($attribute, $condition = null)
}
}
+ /**
+ * Joins tables to select
+ *
+ */
+ protected function _joinFields()
+ {
+ $tagRelationTable = $this->getTable('tag/relation');
+ $tagTable = $this->getTable('tag/tag');
+
+ //TODO: add full name logic
+ $this->addAttributeToSelect('firstname')
+ ->addAttributeToSelect('middlename')
+ ->addAttributeToSelect('lastname')
+ ->addAttributeToSelect('email');
+
+ $this->getSelect()
+ ->join(
+ ['tr' => $tagRelationTable],
+ 'tr.customer_id = e.entity_id',
+ ['tag_relation_id', 'product_id', 'active', 'added_in' => 'store_id'],
+ )
+ ->join(['t' => $tagTable], 't.tag_id = tr.tag_id', ['*']);
+ }
+
/**
* Treat "order by" items as attributes to sort
*
diff --git a/app/code/core/Mage/Tag/Model/Resource/Indexer/Summary.php b/app/code/core/Mage/Tag/Model/Resource/Indexer/Summary.php
index bb2004ff580..2683e239e7e 100644
--- a/app/code/core/Mage/Tag/Model/Resource/Indexer/Summary.php
+++ b/app/code/core/Mage/Tag/Model/Resource/Indexer/Summary.php
@@ -22,11 +22,6 @@
*/
class Mage_Tag_Model_Resource_Indexer_Summary extends Mage_Catalog_Model_Resource_Product_Indexer_Abstract
{
- protected function _construct()
- {
- $this->_init('tag/summary', 'tag_id');
- }
-
/**
* Process tag save
*
@@ -244,4 +239,8 @@ public function aggregate($tagIds = null)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('tag/summary', 'tag_id');
+ }
}
diff --git a/app/code/core/Mage/Tag/Model/Resource/Popular/Collection.php b/app/code/core/Mage/Tag/Model/Resource/Popular/Collection.php
index 983afa2662f..81a99677e97 100644
--- a/app/code/core/Mage/Tag/Model/Resource/Popular/Collection.php
+++ b/app/code/core/Mage/Tag/Model/Resource/Popular/Collection.php
@@ -22,15 +22,6 @@
*/
class Mage_Tag_Model_Resource_Popular_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Defines resource model and model
- *
- */
- protected function _construct()
- {
- $this->_init('tag/tag');
- }
-
/**
* Replacing popularity by sum of popularity and base_popularity
*
@@ -113,4 +104,12 @@ public function getSelectCountSql()
$countSelect->from(['a' => $select], 'COUNT(popularity)');
return $countSelect;
}
+ /**
+ * Defines resource model and model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('tag/tag');
+ }
}
diff --git a/app/code/core/Mage/Tag/Model/Resource/Product/Collection.php b/app/code/core/Mage/Tag/Model/Resource/Product/Collection.php
index f5f51afae22..d59ce9050cc 100644
--- a/app/code/core/Mage/Tag/Model/Resource/Product/Collection.php
+++ b/app/code/core/Mage/Tag/Model/Resource/Product/Collection.php
@@ -45,26 +45,6 @@ class Mage_Tag_Model_Resource_Product_Collection extends Mage_Catalog_Model_Reso
*/
protected $_joinFlags = [];
- /**
- * Initialize collection select
- *
- * @return $this
- */
- protected function _initSelect()
- {
- parent::_initSelect();
-
- $this->_joinFields();
- $this->getSelect()->group('e.entity_id');
-
- /*
- * Allow analytic function usage
- */
- $this->_useAnalyticFunction = true;
-
- return $this;
- }
-
/**
* Set flag about joined table.
* setFlag method must be used in future.
@@ -120,44 +100,6 @@ public function addStoresVisibility()
return $this;
}
- /**
- * Add tag visibility on stores process
- *
- * @return $this
- */
- protected function _addStoresVisibility()
- {
- $tagIds = [];
- foreach ($this as $item) {
- $tagIds[] = $item->getTagId();
- }
-
- $tagsStores = [];
- if (count($tagIds)) {
- $select = $this->getConnection()->select()
- ->from($this->getTable('tag/relation'), ['store_id', 'tag_id'])
- ->where('tag_id IN(?)', $tagIds);
- $tagsRaw = $this->getConnection()->fetchAll($select);
- foreach ($tagsRaw as $tag) {
- if (!isset($tagsStores[$tag['tag_id']])) {
- $tagsStores[$tag['tag_id']] = [];
- }
-
- $tagsStores[$tag['tag_id']][] = $tag['store_id'];
- }
- }
-
- foreach ($this as $item) {
- if (isset($tagsStores[$item->getTagId()])) {
- $item->setStores($tagsStores[$item->getTagId()]);
- } else {
- $item->setStores([]);
- }
- }
-
- return $this;
- }
-
/**
* Add group by tag
*
@@ -353,6 +295,104 @@ public function addProductTags($storeId = null)
return $this;
}
+ /**
+ * Render SQL for retrieve product count
+ *
+ * @return Varien_Db_Select
+ */
+ public function getSelectCountSql()
+ {
+ $countSelect = clone $this->getSelect();
+
+ $countSelect->reset(Zend_Db_Select::COLUMNS);
+ $countSelect->reset(Zend_Db_Select::ORDER);
+ $countSelect->reset(Zend_Db_Select::LIMIT_COUNT);
+ $countSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
+ $countSelect->reset(Zend_Db_Select::GROUP);
+
+ if ($this->getFlag('group_tag')) {
+ $field = 'relation.tag_id';
+ } else {
+ $field = 'e.entity_id';
+ }
+ $expr = new Zend_Db_Expr('COUNT('
+ . ($this->getFlag('distinct') ? 'DISTINCT ' : '')
+ . $field . ')');
+
+ $countSelect->columns($expr);
+
+ return $countSelect;
+ }
+
+ /**
+ * Set Id Fieldname as Tag Relation Id
+ *
+ * @return $this
+ */
+ public function setRelationId()
+ {
+ $this->_setIdFieldName('tag_relation_id');
+ return $this;
+ }
+
+ /**
+ * Initialize collection select
+ *
+ * @return $this
+ */
+ protected function _initSelect()
+ {
+ parent::_initSelect();
+
+ $this->_joinFields();
+ $this->getSelect()->group('e.entity_id');
+
+ /*
+ * Allow analytic function usage
+ */
+ $this->_useAnalyticFunction = true;
+
+ return $this;
+ }
+
+ /**
+ * Add tag visibility on stores process
+ *
+ * @return $this
+ */
+ protected function _addStoresVisibility()
+ {
+ $tagIds = [];
+ foreach ($this as $item) {
+ $tagIds[] = $item->getTagId();
+ }
+
+ $tagsStores = [];
+ if (count($tagIds)) {
+ $select = $this->getConnection()->select()
+ ->from($this->getTable('tag/relation'), ['store_id', 'tag_id'])
+ ->where('tag_id IN(?)', $tagIds);
+ $tagsRaw = $this->getConnection()->fetchAll($select);
+ foreach ($tagsRaw as $tag) {
+ if (!isset($tagsStores[$tag['tag_id']])) {
+ $tagsStores[$tag['tag_id']] = [];
+ }
+
+ $tagsStores[$tag['tag_id']][] = $tag['store_id'];
+ }
+ }
+
+ foreach ($this as $item) {
+ if (isset($tagsStores[$item->getTagId()])) {
+ $item->setStores($tagsStores[$item->getTagId()]);
+ } else {
+ $item->setStores([]);
+ }
+ }
+
+ return $this;
+ }
+
/**
* Join fields process
*
@@ -412,35 +452,6 @@ protected function _afterLoad()
return $this;
}
- /**
- * Render SQL for retrieve product count
- *
- * @return Varien_Db_Select
- */
- public function getSelectCountSql()
- {
- $countSelect = clone $this->getSelect();
-
- $countSelect->reset(Zend_Db_Select::COLUMNS);
- $countSelect->reset(Zend_Db_Select::ORDER);
- $countSelect->reset(Zend_Db_Select::LIMIT_COUNT);
- $countSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
- $countSelect->reset(Zend_Db_Select::GROUP);
-
- if ($this->getFlag('group_tag')) {
- $field = 'relation.tag_id';
- } else {
- $field = 'e.entity_id';
- }
- $expr = new Zend_Db_Expr('COUNT('
- . ($this->getFlag('distinct') ? 'DISTINCT ' : '')
- . $field . ')');
-
- $countSelect->columns($expr);
-
- return $countSelect;
- }
-
/**
* Treat "order by" items as attributes to sort
*
@@ -467,15 +478,4 @@ protected function _renderOrders()
}
return $this;
}
-
- /**
- * Set Id Fieldname as Tag Relation Id
- *
- * @return $this
- */
- public function setRelationId()
- {
- $this->_setIdFieldName('tag_relation_id');
- return $this;
- }
}
diff --git a/app/code/core/Mage/Tag/Model/Resource/Tag.php b/app/code/core/Mage/Tag/Model/Resource/Tag.php
index 773f9a2a16b..d0d3b1c3e0b 100644
--- a/app/code/core/Mage/Tag/Model/Resource/Tag.php
+++ b/app/code/core/Mage/Tag/Model/Resource/Tag.php
@@ -22,25 +22,6 @@
*/
class Mage_Tag_Model_Resource_Tag extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('tag/tag', 'tag_id');
- }
-
- /**
- * Initialize unique fields
- *
- * @return $this
- */
- protected function _initUniqueFields()
- {
- $this->_uniqueFields = [[
- 'field' => 'name',
- 'title' => Mage::helper('tag')->__('Tag'),
- ]];
- return $this;
- }
-
/**
* Loading tag by name
*
@@ -67,6 +48,137 @@ public function loadByName($model, $name)
}
}
+ /**
+ * Getting statistics data into buffer.
+ * Replacing our buffer array with new statistics and incoming data.
+ *
+ * @deprecated after 1.4.0.0
+ *
+ * @param Mage_Tag_Model_Tag $object
+ * @return Mage_Tag_Model_Tag
+ */
+ public function aggregate($object)
+ {
+ $tagId = (int) $object->getId();
+ $storeId = (int) $object->getStore();
+
+ // create final summary from existing data and add specified base popularity
+ $finalSummary = $this->_getExistingBasePopularity($tagId);
+ if ($object->hasBasePopularity() && $storeId) {
+ $finalSummary[$storeId]['store_id'] = $storeId;
+ $finalSummary[$storeId]['base_popularity'] = $object->getBasePopularity();
+ }
+
+ // calculate aggregation data
+ $summaries = $this->_getAggregationPerStoreView($tagId);
+ $summariesGlobal = $this->_getGlobalAggregation($tagId);
+ if ($summariesGlobal) {
+ $summaries[] = $summariesGlobal;
+ }
+
+ // override final summary with aggregated data
+ foreach ($summaries as $row) {
+ $storeId = (int) $row['store_id'];
+ foreach ($row as $key => $value) {
+ $finalSummary[$storeId][$key] = $value;
+ }
+ }
+
+ // prepare static parameters to final summary for insertion
+ foreach ($finalSummary as $key => $row) {
+ $finalSummary[$key]['tag_id'] = $tagId;
+ foreach (['base_popularity', 'popularity', 'historical_uses', 'uses', 'products', 'customers'] as $k) {
+ if (!isset($row[$k])) {
+ $finalSummary[$key][$k] = 0;
+ }
+ }
+ $finalSummary[$key]['popularity'] = $finalSummary[$key]['historical_uses'];
+ }
+
+ // remove old and insert new data
+ $write = $this->_getWriteAdapter();
+ $write->delete(
+ $this->getTable('tag/summary'),
+ ['tag_id = ?' => $tagId],
+ );
+ $write->insertMultiple($this->getTable('tag/summary'), $finalSummary);
+
+ return $object;
+ }
+
+ /**
+ * Decrementing tag products quantity as action for product delete
+ *
+ * @return int The number of affected rows
+ */
+ public function decrementProducts(array $tagsId)
+ {
+ $writeAdapter = $this->_getWriteAdapter();
+ if (empty($tagsId)) {
+ return 0;
+ }
+
+ return $writeAdapter->update(
+ $this->getTable('tag/summary'),
+ ['products' => new Zend_Db_Expr('products - 1')],
+ ['tag_id IN (?)' => $tagsId],
+ );
+ }
+
+ /**
+ * Add summary data to specified object
+ *
+ * @deprecated after 1.4.0.0
+ *
+ * @param Mage_Tag_Model_Tag $object
+ * @return Mage_Tag_Model_Tag
+ */
+ public function addSummary($object)
+ {
+ $read = $this->_getReadAdapter();
+ $select = $read->select()
+ ->from(['relation' => $this->getTable('tag/relation')], [])
+ ->joinLeft(
+ ['summary' => $this->getTable('tag/summary')],
+ 'relation.tag_id = summary.tag_id AND relation.store_id = summary.store_id',
+ [
+ 'customers',
+ 'products',
+ 'popularity',
+ ],
+ )
+ ->where('relation.tag_id = :tag_id')
+ ->where('relation.store_id = :store_id')
+ ->limit(1);
+ $bind = [
+ 'tag_id' => (int) $object->getId(),
+ 'store_id' => (int) $object->getStoreId(),
+ ];
+ $row = $read->fetchRow($select, $bind);
+ if ($row) {
+ $object->addData($row);
+ }
+ return $object;
+ }
+ protected function _construct()
+ {
+ $this->_init('tag/tag', 'tag_id');
+ }
+
+ /**
+ * Initialize unique fields
+ *
+ * @return $this
+ */
+ protected function _initUniqueFields()
+ {
+ $this->_uniqueFields = [[
+ 'field' => 'name',
+ 'title' => Mage::helper('tag')->__('Tag'),
+ ]];
+ return $this;
+ }
+
/**
* Before saving actions
*
@@ -271,119 +383,6 @@ protected function _getGlobalAggregation($tagId)
return $result;
}
- /**
- * Getting statistics data into buffer.
- * Replacing our buffer array with new statistics and incoming data.
- *
- * @deprecated after 1.4.0.0
- *
- * @param Mage_Tag_Model_Tag $object
- * @return Mage_Tag_Model_Tag
- */
- public function aggregate($object)
- {
- $tagId = (int) $object->getId();
- $storeId = (int) $object->getStore();
-
- // create final summary from existing data and add specified base popularity
- $finalSummary = $this->_getExistingBasePopularity($tagId);
- if ($object->hasBasePopularity() && $storeId) {
- $finalSummary[$storeId]['store_id'] = $storeId;
- $finalSummary[$storeId]['base_popularity'] = $object->getBasePopularity();
- }
-
- // calculate aggregation data
- $summaries = $this->_getAggregationPerStoreView($tagId);
- $summariesGlobal = $this->_getGlobalAggregation($tagId);
- if ($summariesGlobal) {
- $summaries[] = $summariesGlobal;
- }
-
- // override final summary with aggregated data
- foreach ($summaries as $row) {
- $storeId = (int) $row['store_id'];
- foreach ($row as $key => $value) {
- $finalSummary[$storeId][$key] = $value;
- }
- }
-
- // prepare static parameters to final summary for insertion
- foreach ($finalSummary as $key => $row) {
- $finalSummary[$key]['tag_id'] = $tagId;
- foreach (['base_popularity', 'popularity', 'historical_uses', 'uses', 'products', 'customers'] as $k) {
- if (!isset($row[$k])) {
- $finalSummary[$key][$k] = 0;
- }
- }
- $finalSummary[$key]['popularity'] = $finalSummary[$key]['historical_uses'];
- }
-
- // remove old and insert new data
- $write = $this->_getWriteAdapter();
- $write->delete(
- $this->getTable('tag/summary'),
- ['tag_id = ?' => $tagId],
- );
- $write->insertMultiple($this->getTable('tag/summary'), $finalSummary);
-
- return $object;
- }
-
- /**
- * Decrementing tag products quantity as action for product delete
- *
- * @return int The number of affected rows
- */
- public function decrementProducts(array $tagsId)
- {
- $writeAdapter = $this->_getWriteAdapter();
- if (empty($tagsId)) {
- return 0;
- }
-
- return $writeAdapter->update(
- $this->getTable('tag/summary'),
- ['products' => new Zend_Db_Expr('products - 1')],
- ['tag_id IN (?)' => $tagsId],
- );
- }
-
- /**
- * Add summary data to specified object
- *
- * @deprecated after 1.4.0.0
- *
- * @param Mage_Tag_Model_Tag $object
- * @return Mage_Tag_Model_Tag
- */
- public function addSummary($object)
- {
- $read = $this->_getReadAdapter();
- $select = $read->select()
- ->from(['relation' => $this->getTable('tag/relation')], [])
- ->joinLeft(
- ['summary' => $this->getTable('tag/summary')],
- 'relation.tag_id = summary.tag_id AND relation.store_id = summary.store_id',
- [
- 'customers',
- 'products',
- 'popularity',
- ],
- )
- ->where('relation.tag_id = :tag_id')
- ->where('relation.store_id = :store_id')
- ->limit(1);
- $bind = [
- 'tag_id' => (int) $object->getId(),
- 'store_id' => (int) $object->getStoreId(),
- ];
- $row = $read->fetchRow($select, $bind);
- if ($row) {
- $object->addData($row);
- }
- return $object;
- }
-
/**
* Retrieve select object for load object data
* Redeclare parent method just for adding tag's base popularity if flag exists
diff --git a/app/code/core/Mage/Tag/Model/Resource/Tag/Collection.php b/app/code/core/Mage/Tag/Model/Resource/Tag/Collection.php
index 5e5ed29706e..3ebc7730031 100644
--- a/app/code/core/Mage/Tag/Model/Resource/Tag/Collection.php
+++ b/app/code/core/Mage/Tag/Model/Resource/Tag/Collection.php
@@ -22,20 +22,6 @@
*/
class Mage_Tag_Model_Resource_Tag_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Use getFlag('store_filter') & setFlag('store_filter', true) instead.
- *
- * @var bool
- */
- protected $_isStoreFilter = false;
-
- /**
- * Joined tables
- *
- * @var array
- */
- protected $_joinFlags = [];
-
/**
* Mapping for fields
*
@@ -46,15 +32,19 @@ class Mage_Tag_Model_Resource_Tag_Collection extends Mage_Core_Model_Resource_Db
'tag_id' => 'main_table.tag_id',
],
];
+ /**
+ * Use getFlag('store_filter') & setFlag('store_filter', true) instead.
+ *
+ * @var bool
+ */
+ protected $_isStoreFilter = false;
/**
- * Define resource model and model
+ * Joined tables
*
+ * @var array
*/
- protected function _construct()
- {
- $this->_init('tag/tag');
- }
+ protected $_joinFlags = [];
/**
* Loads collection
@@ -209,42 +199,6 @@ public function addStoresVisibility()
return $this;
}
- /**
- * Adds store visibility
- *
- * @return $this
- */
- protected function _addStoresVisibility()
- {
- $tagIds = $this->getColumnValues('tag_id');
-
- $tagsStores = [];
- if (count($tagIds)) {
- $select = $this->getConnection()->select()
- ->from($this->getTable('tag/summary'), ['store_id', 'tag_id'])
- ->where('tag_id IN(?)', $tagIds);
- $tagsRaw = $this->getConnection()->fetchAll($select);
-
- foreach ($tagsRaw as $tag) {
- if (!isset($tagsStores[$tag['tag_id']])) {
- $tagsStores[$tag['tag_id']] = [];
- }
-
- $tagsStores[$tag['tag_id']][] = $tag['store_id'];
- }
- }
-
- foreach ($this as $item) {
- if (isset($tagsStores[$item->getId()])) {
- $item->setStores($tagsStores[$item->getId()]);
- } else {
- $item->setStores([]);
- }
- }
-
- return $this;
- }
-
/**
* Adds field to filter
*
@@ -408,4 +362,49 @@ public function joinRel()
);
return $this;
}
+
+ /**
+ * Define resource model and model
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('tag/tag');
+ }
+
+ /**
+ * Adds store visibility
+ *
+ * @return $this
+ */
+ protected function _addStoresVisibility()
+ {
+ $tagIds = $this->getColumnValues('tag_id');
+
+ $tagsStores = [];
+ if (count($tagIds)) {
+ $select = $this->getConnection()->select()
+ ->from($this->getTable('tag/summary'), ['store_id', 'tag_id'])
+ ->where('tag_id IN(?)', $tagIds);
+ $tagsRaw = $this->getConnection()->fetchAll($select);
+
+ foreach ($tagsRaw as $tag) {
+ if (!isset($tagsStores[$tag['tag_id']])) {
+ $tagsStores[$tag['tag_id']] = [];
+ }
+
+ $tagsStores[$tag['tag_id']][] = $tag['store_id'];
+ }
+ }
+
+ foreach ($this as $item) {
+ if (isset($tagsStores[$item->getId()])) {
+ $item->setStores($tagsStores[$item->getId()]);
+ } else {
+ $item->setStores([]);
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Tag/Model/Resource/Tag/Relation.php b/app/code/core/Mage/Tag/Model/Resource/Tag/Relation.php
index 841ce9d944d..8a2c93775a5 100644
--- a/app/code/core/Mage/Tag/Model/Resource/Tag/Relation.php
+++ b/app/code/core/Mage/Tag/Model/Resource/Tag/Relation.php
@@ -22,15 +22,6 @@
*/
class Mage_Tag_Model_Resource_Tag_Relation extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Initialize resource connection and define table resource
- *
- */
- protected function _construct()
- {
- $this->_init('tag/relation', 'tag_relation_id');
- }
-
/**
* Load by Tag and Customer
*
@@ -191,4 +182,12 @@ public function addRelations($model)
return $this;
}
+ /**
+ * Initialize resource connection and define table resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('tag/relation', 'tag_relation_id');
+ }
}
diff --git a/app/code/core/Mage/Tag/Model/Tag.php b/app/code/core/Mage/Tag/Model/Tag.php
index c7e4f7acc27..bdd27be9284 100644
--- a/app/code/core/Mage/Tag/Model/Tag.php
+++ b/app/code/core/Mage/Tag/Model/Tag.php
@@ -76,11 +76,6 @@ class Mage_Tag_Model_Tag extends Mage_Core_Model_Abstract
*/
protected $_addBasePopularity = false;
- protected function _construct()
- {
- $this->_init('tag/tag');
- }
-
/**
* Init indexing process after tag data commit
*
@@ -119,20 +114,6 @@ public function getAddBasePopularity()
return $this->_addBasePopularity;
}
- /**
- * Product event tags collection getter
- *
- * @return Mage_Tag_Model_Resource_Tag_Collection
- */
- protected function _getProductEventTagsCollection(Varien_Event_Observer $observer)
- {
- return $this->getResourceCollection()
- ->joinRel()
- ->addProductFilter($observer->getEvent()->getProduct()->getId())
- ->addTagGroup()
- ->load();
- }
-
/**
* @return int
*/
@@ -337,16 +318,6 @@ public function isAvailableInStore($storeId = null)
return in_array($storeId, $this->getVisibleInStoreIds());
}
- /**
- * @return Mage_Core_Model_Abstract
- * @throws Mage_Core_Exception
- */
- protected function _beforeDelete()
- {
- $this->_protectFromNonAdmin();
- return parent::_beforeDelete();
- }
-
/**
* Save tag relation with product, customer and store
*
@@ -416,6 +387,35 @@ public function saveRelation($productId, $customerId, $storeId)
return $result;
}
+ protected function _construct()
+ {
+ $this->_init('tag/tag');
+ }
+
+ /**
+ * Product event tags collection getter
+ *
+ * @return Mage_Tag_Model_Resource_Tag_Collection
+ */
+ protected function _getProductEventTagsCollection(Varien_Event_Observer $observer)
+ {
+ return $this->getResourceCollection()
+ ->joinRel()
+ ->addProductFilter($observer->getEvent()->getProduct()->getId())
+ ->addTagGroup()
+ ->load();
+ }
+
+ /**
+ * @return Mage_Core_Model_Abstract
+ * @throws Mage_Core_Exception
+ */
+ protected function _beforeDelete()
+ {
+ $this->_protectFromNonAdmin();
+ return parent::_beforeDelete();
+ }
+
/**
* Check whether product is already marked in store with tag
*
diff --git a/app/code/core/Mage/Tag/Model/Tag/Relation.php b/app/code/core/Mage/Tag/Model/Tag/Relation.php
index e7f89aabb23..632e6cc86f0 100644
--- a/app/code/core/Mage/Tag/Model/Tag/Relation.php
+++ b/app/code/core/Mage/Tag/Model/Tag/Relation.php
@@ -55,11 +55,6 @@ class Mage_Tag_Model_Tag_Relation extends Mage_Core_Model_Abstract
*/
public const ENTITY = 'tag_relation';
- protected function _construct()
- {
- $this->_init('tag/tag_relation');
- }
-
/**
* Init indexing process after tag data commit
*
@@ -151,4 +146,9 @@ public function addRelations(Mage_Tag_Model_Tag $model, $productIds = [])
$this->_getResource()->addRelations($this);
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_init('tag/tag_relation');
+ }
}
diff --git a/app/code/core/Mage/Tag/controllers/CustomerController.php b/app/code/core/Mage/Tag/controllers/CustomerController.php
index fa423fdc030..9266fa758ea 100644
--- a/app/code/core/Mage/Tag/controllers/CustomerController.php
+++ b/app/code/core/Mage/Tag/controllers/CustomerController.php
@@ -22,23 +22,6 @@
*/
class Mage_Tag_CustomerController extends Mage_Core_Controller_Front_Action
{
- /**
- * @return int|false
- * @throws Mage_Core_Exception
- */
- protected function _getTagId()
- {
- $tagId = (int) $this->getRequest()->getParam('tagId');
- if ($tagId) {
- $customerId = Mage::getSingleton('customer/session')->getCustomerId();
- $model = Mage::getModel('tag/tag_relation');
- $model->loadByTagCustomer(null, $tagId, $customerId);
- Mage::register('tagModel', $model);
- return $model->getTagId();
- }
- return false;
- }
-
public function indexAction()
{
if (!Mage::getSingleton('customer/session')->isLoggedIn()) {
@@ -135,4 +118,20 @@ public function saveAction()
{
$this->_forward('noRoute');
}
+ /**
+ * @return int|false
+ * @throws Mage_Core_Exception
+ */
+ protected function _getTagId()
+ {
+ $tagId = (int) $this->getRequest()->getParam('tagId');
+ if ($tagId) {
+ $customerId = Mage::getSingleton('customer/session')->getCustomerId();
+ $model = Mage::getModel('tag/tag_relation');
+ $model->loadByTagCustomer(null, $tagId, $customerId);
+ Mage::register('tagModel', $model);
+ return $model->getTagId();
+ }
+ return false;
+ }
}
diff --git a/app/code/core/Mage/Tax/Block/Sales/Order/Tax.php b/app/code/core/Mage/Tax/Block/Sales/Order/Tax.php
index bad6eb80167..46973871bcb 100644
--- a/app/code/core/Mage/Tax/Block/Sales/Order/Tax.php
+++ b/app/code/core/Mage/Tax/Block/Sales/Order/Tax.php
@@ -36,14 +36,6 @@ class Mage_Tax_Block_Sales_Order_Tax extends Mage_Core_Block_Template
*/
protected $_source;
- /**
- * Initialize configuration object
- */
- protected function _construct()
- {
- $this->_config = Mage::getSingleton('tax/config');
- }
-
/**
* Check if we need display full tax total info
*
@@ -90,6 +82,48 @@ public function initTotals()
return $this;
}
+ /**
+ * Get order store object
+ *
+ * @return Mage_Core_Model_Store
+ */
+ public function getStore()
+ {
+ return $this->_order->getStore();
+ }
+
+ /**
+ * @return Mage_Sales_Model_Order
+ */
+ public function getOrder()
+ {
+ return $this->_order;
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getLabelProperties()
+ {
+ return $this->getParentBlock()->getLabelProperties();
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getValueProperties()
+ {
+ return $this->getParentBlock()->getValueProperties();
+ }
+
+ /**
+ * Initialize configuration object
+ */
+ protected function _construct()
+ {
+ $this->_config = Mage::getSingleton('tax/config');
+ }
+
/**
* Add tax total string
*
@@ -106,16 +140,6 @@ protected function _addTax($after = 'discount')
return $this;
}
- /**
- * Get order store object
- *
- * @return Mage_Core_Model_Store
- */
- public function getStore()
- {
- return $this->_order->getStore();
- }
-
/**
* @return $this
*/
@@ -290,28 +314,4 @@ protected function _initGrandTotal()
}
return $this;
}
-
- /**
- * @return Mage_Sales_Model_Order
- */
- public function getOrder()
- {
- return $this->_order;
- }
-
- /**
- * @return mixed
- */
- public function getLabelProperties()
- {
- return $this->getParentBlock()->getLabelProperties();
- }
-
- /**
- * @return mixed
- */
- public function getValueProperties()
- {
- return $this->getParentBlock()->getValueProperties();
- }
}
diff --git a/app/code/core/Mage/Tax/Helper/Data.php b/app/code/core/Mage/Tax/Helper/Data.php
index 5cd4e158f37..a8fad5869f9 100644
--- a/app/code/core/Mage/Tax/Helper/Data.php
+++ b/app/code/core/Mage/Tax/Helper/Data.php
@@ -438,29 +438,6 @@ public function getAllRatesByProductClass($store = null)
return $this->_getAllRatesByProductClass($store);
}
- /**
- * Get all tax rates JSON for all product tax classes of specific store
- *
- * array(
- * value_{$productTaxClassId} => $rate
- * )
- *
- * @param null|string|bool|int|Mage_Core_Model_Store $store
- * @return string
- */
- protected function _getAllRatesByProductClass($store = null)
- {
- $result = [];
- $calc = Mage::getSingleton('tax/calculation');
- $rates = $calc->getRatesForAllProductTaxClasses($calc->getDefaultRateRequest($store));
-
- foreach ($rates as $class => $rate) {
- $result["value_{$class}"] = $rate;
- }
-
- return Mage::helper('core')->jsonEncode($result);
- }
-
/**
* Get product price with all tax settings processing
*
@@ -606,23 +583,6 @@ public function getPrice(
}
}
- /**
- * Given a store price that includes tax at the store rate, this function will back out the store's tax, and add in
- * the customer's tax. Returns this new price which is the customer's price including tax.
- *
- * @param float $storePriceInclTax
- * @param float $storePercent
- * @param float $customerPercent
- * @param Mage_Core_Model_Store $store
- * @return float
- */
- protected function _calculatePriceInclTax($storePriceInclTax, $storePercent, $customerPercent, $store)
- {
- $priceExclTax = $this->_calculatePrice($storePriceInclTax, $storePercent, false, false);
- $customerTax = $this->getCalculator()->calcTaxAmount($priceExclTax, $customerPercent, false, false);
- return $store->roundPrice($priceExclTax + $customerTax);
- }
-
/**
* Check if we have display in catalog prices including tax
*
@@ -654,46 +614,6 @@ public function displayBothPrices($store = null)
return $this->getPriceDisplayType($store) == Mage_Tax_Model_Config::DISPLAY_TYPE_BOTH;
}
- /**
- * Calculate price including/excluding tax base on tax rate percent
- *
- * @param float $price
- * @param float $percent
- * @param bool $type true - to calculate the price including tax and false if calculating price to exclude tax
- * @param bool $roundTaxFirst
- * @return float
- */
- protected function _calculatePrice($price, $percent, $type, $roundTaxFirst = false)
- {
- $calculator = $this->getCalculator();
- if ($type) {
- $taxAmount = $calculator->calcTaxAmount($price, $percent, false, $roundTaxFirst);
- return $price + $taxAmount;
- } else {
- $taxAmount = $calculator->calcTaxAmount($price, $percent, true, $roundTaxFirst);
- return $price - $taxAmount;
- }
- }
-
- /**
- * Calculate price including tax when multiple taxes is applied and rounded
- * independently.
- *
- * @param float $price
- * @param array $appliedRates
- * @return float
- */
- protected function _calculatePriceInclTaxWithMultipleRates($price, $appliedRates)
- {
- $calculator = $this->getCalculator();
- $tax = 0;
- foreach ($appliedRates as $appliedRate) {
- $taxRate = $appliedRate['percent'];
- $tax += $calculator->round($price * $taxRate / 100);
- }
- return $tax + $price;
- }
-
/**
* Returns the include / exclude tax label
*
@@ -1055,28 +975,6 @@ public function getCalculatedTaxes($source)
return $taxClassAmount;
}
- /**
- * Returns the array of tax rates for the order
- *
- * @param Mage_Sales_Model_Order $order
- * @return array
- */
- protected function _getTaxRateSubtotals($order)
- {
- return Mage::getModel('tax/sales_order_tax')->getCollection()->loadByOrder($order)->toArray();
- }
-
- /**
- * Retrieve a value from registry by a key
- *
- * @param string $key
- * @return mixed
- */
- protected function _getFromRegistry($key)
- {
- return Mage::registry($key);
- }
-
/**
* Get calculated Shipping & Handling Tax
*
@@ -1204,6 +1102,118 @@ public function isCrossBorderTradeEnabled($store = null)
return (bool) $this->_config->crossBorderTradeEnabled($store);
}
+ /**
+ * @return void
+ * @throws Throwable
+ */
+ public function setIsIgnored(string $key, bool $value)
+ {
+ $flag = Mage::getModel('core/flag', ['flag_code' => $key])->loadSelf();
+ $flag->setFlagData($value)->save();
+ }
+
+ /**
+ * Get all tax rates JSON for all product tax classes of specific store
+ *
+ * array(
+ * value_{$productTaxClassId} => $rate
+ * )
+ *
+ * @param null|string|bool|int|Mage_Core_Model_Store $store
+ * @return string
+ */
+ protected function _getAllRatesByProductClass($store = null)
+ {
+ $result = [];
+ $calc = Mage::getSingleton('tax/calculation');
+ $rates = $calc->getRatesForAllProductTaxClasses($calc->getDefaultRateRequest($store));
+
+ foreach ($rates as $class => $rate) {
+ $result["value_{$class}"] = $rate;
+ }
+
+ return Mage::helper('core')->jsonEncode($result);
+ }
+
+ /**
+ * Given a store price that includes tax at the store rate, this function will back out the store's tax, and add in
+ * the customer's tax. Returns this new price which is the customer's price including tax.
+ *
+ * @param float $storePriceInclTax
+ * @param float $storePercent
+ * @param float $customerPercent
+ * @param Mage_Core_Model_Store $store
+ * @return float
+ */
+ protected function _calculatePriceInclTax($storePriceInclTax, $storePercent, $customerPercent, $store)
+ {
+ $priceExclTax = $this->_calculatePrice($storePriceInclTax, $storePercent, false, false);
+ $customerTax = $this->getCalculator()->calcTaxAmount($priceExclTax, $customerPercent, false, false);
+ return $store->roundPrice($priceExclTax + $customerTax);
+ }
+
+ /**
+ * Calculate price including/excluding tax base on tax rate percent
+ *
+ * @param float $price
+ * @param float $percent
+ * @param bool $type true - to calculate the price including tax and false if calculating price to exclude tax
+ * @param bool $roundTaxFirst
+ * @return float
+ */
+ protected function _calculatePrice($price, $percent, $type, $roundTaxFirst = false)
+ {
+ $calculator = $this->getCalculator();
+ if ($type) {
+ $taxAmount = $calculator->calcTaxAmount($price, $percent, false, $roundTaxFirst);
+ return $price + $taxAmount;
+ } else {
+ $taxAmount = $calculator->calcTaxAmount($price, $percent, true, $roundTaxFirst);
+ return $price - $taxAmount;
+ }
+ }
+
+ /**
+ * Calculate price including tax when multiple taxes is applied and rounded
+ * independently.
+ *
+ * @param float $price
+ * @param array $appliedRates
+ * @return float
+ */
+ protected function _calculatePriceInclTaxWithMultipleRates($price, $appliedRates)
+ {
+ $calculator = $this->getCalculator();
+ $tax = 0;
+ foreach ($appliedRates as $appliedRate) {
+ $taxRate = $appliedRate['percent'];
+ $tax += $calculator->round($price * $taxRate / 100);
+ }
+ return $tax + $price;
+ }
+
+ /**
+ * Returns the array of tax rates for the order
+ *
+ * @param Mage_Sales_Model_Order $order
+ * @return array
+ */
+ protected function _getTaxRateSubtotals($order)
+ {
+ return Mage::getModel('tax/sales_order_tax')->getCollection()->loadByOrder($order)->toArray();
+ }
+
+ /**
+ * Retrieve a value from registry by a key
+ *
+ * @param string $key
+ * @return mixed
+ */
+ protected function _getFromRegistry($key)
+ {
+ return Mage::registry($key);
+ }
+
/**
* Use flag to store ignore setting rather than config to avoid config re-init/save
* Read config value for backwards compatibility.
@@ -1225,14 +1235,4 @@ protected function _isIgnored(string $key)
}
return false;
}
-
- /**
- * @return void
- * @throws Throwable
- */
- public function setIsIgnored(string $key, bool $value)
- {
- $flag = Mage::getModel('core/flag', ['flag_code' => $key])->loadSelf();
- $flag->setFlagData($value)->save();
- }
}
diff --git a/app/code/core/Mage/Tax/Model/Calculation.php b/app/code/core/Mage/Tax/Model/Calculation.php
index 31f4978736e..d05a31b5e83 100644
--- a/app/code/core/Mage/Tax/Model/Calculation.php
+++ b/app/code/core/Mage/Tax/Model/Calculation.php
@@ -58,19 +58,6 @@ class Mage_Tax_Model_Calculation extends Mage_Core_Model_Abstract
*/
public const CALC_TAX_AFTER_DISCOUNT_ON_INCL = '1_1';
- /**
- * Identifier constant for unit based calculation
- */
- protected $_rates = [];
- /**
- * Identifier constant for row based calculation
- */
- protected $_ctc = [];
- /**
- * Identifier constant for total based calculation
- */
- protected $_ptc = [];
-
/**
* CALC_UNIT_BASE
*/
@@ -86,6 +73,19 @@ class Mage_Tax_Model_Calculation extends Mage_Core_Model_Abstract
*/
public const CALC_TOTAL_BASE = 'TOTAL_BASE_CALCULATION';
+ /**
+ * Identifier constant for unit based calculation
+ */
+ protected $_rates = [];
+ /**
+ * Identifier constant for row based calculation
+ */
+ protected $_ctc = [];
+ /**
+ * Identifier constant for total based calculation
+ */
+ protected $_ptc = [];
+
/**
* Cache to hold the rates
*
@@ -121,11 +121,6 @@ class Mage_Tax_Model_Calculation extends Mage_Core_Model_Abstract
*/
protected $_taxHelper;
- protected function _construct()
- {
- $this->_init('tax/calculation');
- }
-
/**
* Initialize tax helper
*/
@@ -235,28 +230,6 @@ public function getProductTaxClasses($ruleId)
return $this->_ptc[$ruleId];
}
- /**
- * Aggregate tax calculation data to array
- *
- * @return array
- */
- protected function _formCalculationProcess()
- {
- $title = $this->getRateTitle();
- $value = $this->getRateValue();
- $id = $this->getRateId();
-
- $rate = [
- 'code' => $title, 'title' => $title, 'percent' => $value, 'position' => 1, 'priority' => 1];
-
- $process = [];
- $process['percent'] = $value;
- $process['id'] = "{$id}-{$value}";
- $process['rates'][] = $rate;
-
- return [$process];
- }
-
/**
* Get calculation tax rate by specific request
*
@@ -289,19 +262,6 @@ public function getRate($request)
return $this->_rateCache[$cacheKey];
}
- /**
- * Get cache key value for specific tax rate request
- *
- * @param Varien_Object $request
- * @return string
- */
- protected function _getRequestCacheKey($request)
- {
- $key = $request->getStore() ? $request->getStore()->getId() . '|' : '';
- return $key . ($request->getProductClassId() . '|' . $request->getCustomerClassId() . '|'
- . $request->getCountryId() . '|' . $request->getRegionId() . '|' . $request->getPostcode());
- }
-
/**
* Get tax rate based on store shipping origin address settings
* This rate can be used for conversion store price including tax to
@@ -525,29 +485,6 @@ public function compareRequests($first, $second)
return $identical;
}
- /**
- * Gets the tax rates by type
- *
- * @param Varien_Object $request
- * @param string $fieldName
- * @param string $type
- * @return array
- */
- protected function _getRates($request, $fieldName, $type)
- {
- $result = [];
- $classes = Mage::getModel('tax/class')->getCollection()
- ->addFieldToFilter('class_type', $type)
- ->load();
- /** @var Mage_Tax_Model_Class $class */
- foreach ($classes as $class) {
- $request->setData($fieldName, $class->getId());
- $result[$class->getId()] = $this->getRate($request);
- }
-
- return $result;
- }
-
/**
* Gets rates for all the product tax classes
*
@@ -706,4 +643,67 @@ public function roundDown($price)
{
return floor($price * 100) / 100;
}
+
+ protected function _construct()
+ {
+ $this->_init('tax/calculation');
+ }
+
+ /**
+ * Aggregate tax calculation data to array
+ *
+ * @return array
+ */
+ protected function _formCalculationProcess()
+ {
+ $title = $this->getRateTitle();
+ $value = $this->getRateValue();
+ $id = $this->getRateId();
+
+ $rate = [
+ 'code' => $title, 'title' => $title, 'percent' => $value, 'position' => 1, 'priority' => 1];
+
+ $process = [];
+ $process['percent'] = $value;
+ $process['id'] = "{$id}-{$value}";
+ $process['rates'][] = $rate;
+
+ return [$process];
+ }
+
+ /**
+ * Get cache key value for specific tax rate request
+ *
+ * @param Varien_Object $request
+ * @return string
+ */
+ protected function _getRequestCacheKey($request)
+ {
+ $key = $request->getStore() ? $request->getStore()->getId() . '|' : '';
+ return $key . ($request->getProductClassId() . '|' . $request->getCustomerClassId() . '|'
+ . $request->getCountryId() . '|' . $request->getRegionId() . '|' . $request->getPostcode());
+ }
+
+ /**
+ * Gets the tax rates by type
+ *
+ * @param Varien_Object $request
+ * @param string $fieldName
+ * @param string $type
+ * @return array
+ */
+ protected function _getRates($request, $fieldName, $type)
+ {
+ $result = [];
+ $classes = Mage::getModel('tax/class')->getCollection()
+ ->addFieldToFilter('class_type', $type)
+ ->load();
+ /** @var Mage_Tax_Model_Class $class */
+ foreach ($classes as $class) {
+ $request->setData($fieldName, $class->getId());
+ $result[$class->getId()] = $this->getRate($request);
+ }
+
+ return $result;
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Calculation/Rate.php b/app/code/core/Mage/Tax/Model/Calculation/Rate.php
index 1e49eb589d6..8c0af6ef7d5 100644
--- a/app/code/core/Mage/Tax/Model/Calculation/Rate.php
+++ b/app/code/core/Mage/Tax/Model/Calculation/Rate.php
@@ -62,6 +62,82 @@ class Mage_Tax_Model_Calculation_Rate extends Mage_Core_Model_Abstract
*/
protected $_titleModel = null;
+ /**
+ * Saves the tax titles
+ *
+ * @param array | null $titles
+ */
+ public function saveTitles($titles = null)
+ {
+ if (is_null($titles)) {
+ $titles = $this->getTitle();
+ }
+
+ $this->getTitleModel()->deleteByRateId($this->getId());
+ if (is_array($titles) && $titles) {
+ foreach ($titles as $store => $title) {
+ if ($title !== '') {
+ $this->getTitleModel()
+ ->setId(null)
+ ->setTaxCalculationRateId($this->getId())
+ ->setStoreId((int) $store)
+ ->setValue($title)
+ ->save();
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns the Mage_Tax_Model_Calculation_Rate_Title
+ *
+ * @return Mage_Tax_Model_Calculation_Rate_Title
+ */
+ public function getTitleModel()
+ {
+ if (is_null($this->_titleModel)) {
+ $this->_titleModel = Mage::getModel('tax/calculation_rate_title');
+ }
+ return $this->_titleModel;
+ }
+
+ /**
+ * Returns the list of tax titles
+ *
+ * @return array
+ */
+ public function getTitles()
+ {
+ if (is_null($this->_titles)) {
+ $this->_titles = $this->getTitleModel()->getCollection()->loadByRateId($this->getId());
+ }
+ return $this->_titles;
+ }
+
+ /**
+ * Deletes all tax rates
+ *
+ * @return $this
+ */
+ public function deleteAllRates()
+ {
+ $this->_getResource()->deleteAllRates();
+ Mage::dispatchEvent('tax_settings_change_after');
+ return $this;
+ }
+
+ /**
+ * Load rate model by code
+ *
+ * @param string $code
+ * @return $this
+ */
+ public function loadByCode($code)
+ {
+ $this->load($code, 'code');
+ return $this;
+ }
+
/**
* Varien model constructor
*/
@@ -166,82 +242,6 @@ protected function _afterDelete()
return parent::_afterDelete();
}
- /**
- * Saves the tax titles
- *
- * @param array | null $titles
- */
- public function saveTitles($titles = null)
- {
- if (is_null($titles)) {
- $titles = $this->getTitle();
- }
-
- $this->getTitleModel()->deleteByRateId($this->getId());
- if (is_array($titles) && $titles) {
- foreach ($titles as $store => $title) {
- if ($title !== '') {
- $this->getTitleModel()
- ->setId(null)
- ->setTaxCalculationRateId($this->getId())
- ->setStoreId((int) $store)
- ->setValue($title)
- ->save();
- }
- }
- }
- }
-
- /**
- * Returns the Mage_Tax_Model_Calculation_Rate_Title
- *
- * @return Mage_Tax_Model_Calculation_Rate_Title
- */
- public function getTitleModel()
- {
- if (is_null($this->_titleModel)) {
- $this->_titleModel = Mage::getModel('tax/calculation_rate_title');
- }
- return $this->_titleModel;
- }
-
- /**
- * Returns the list of tax titles
- *
- * @return array
- */
- public function getTitles()
- {
- if (is_null($this->_titles)) {
- $this->_titles = $this->getTitleModel()->getCollection()->loadByRateId($this->getId());
- }
- return $this->_titles;
- }
-
- /**
- * Deletes all tax rates
- *
- * @return $this
- */
- public function deleteAllRates()
- {
- $this->_getResource()->deleteAllRates();
- Mage::dispatchEvent('tax_settings_change_after');
- return $this;
- }
-
- /**
- * Load rate model by code
- *
- * @param string $code
- * @return $this
- */
- public function loadByCode($code)
- {
- $this->load($code, 'code');
- return $this;
- }
-
/**
* Check if rate exists in tax rule
*
diff --git a/app/code/core/Mage/Tax/Model/Calculation/Rate/Title.php b/app/code/core/Mage/Tax/Model/Calculation/Rate/Title.php
index c907cb92129..f74ebe53040 100644
--- a/app/code/core/Mage/Tax/Model/Calculation/Rate/Title.php
+++ b/app/code/core/Mage/Tax/Model/Calculation/Rate/Title.php
@@ -33,11 +33,6 @@
*/
class Mage_Tax_Model_Calculation_Rate_Title extends Mage_Core_Model_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/calculation_rate_title');
- }
-
/**
* @param int $rateId
* @return $this
@@ -47,4 +42,8 @@ public function deleteByRateId($rateId)
$this->getResource()->deleteByRateId($rateId);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('tax/calculation_rate_title');
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Calculation/Rule.php b/app/code/core/Mage/Tax/Model/Calculation/Rule.php
index e17dbad2fda..0a3816e02f3 100644
--- a/app/code/core/Mage/Tax/Model/Calculation/Rule.php
+++ b/app/code/core/Mage/Tax/Model/Calculation/Rule.php
@@ -86,40 +86,6 @@ class Mage_Tax_Model_Calculation_Rule extends Mage_Core_Model_Abstract
*/
protected $_calculationModel = null;
- /**
- * Varien model constructor
- */
- protected function _construct()
- {
- $this->_init('tax/calculation_rule');
- }
-
- /**
- * After save rule
- * Re - declared for populate rate calculations
- *
- * @return $this
- */
- protected function _afterSave()
- {
- parent::_afterSave();
- $this->saveCalculationData();
- Mage::dispatchEvent('tax_settings_change_after');
- return $this;
- }
-
- /**
- * After rule delete
- * redeclared for dispatch tax_settings_change_after event
- *
- * @inheritDoc
- */
- protected function _afterDelete()
- {
- Mage::dispatchEvent('tax_settings_change_after');
- return parent::_afterDelete();
- }
-
/**
* Saves the Calculation Data
*/
@@ -193,4 +159,38 @@ public function fetchRuleCodes($rateId, $customerTaxClassId, $productTaxClassId)
{
return $this->getResource()->fetchRuleCodes($rateId, $customerTaxClassId, $productTaxClassId);
}
+
+ /**
+ * Varien model constructor
+ */
+ protected function _construct()
+ {
+ $this->_init('tax/calculation_rule');
+ }
+
+ /**
+ * After save rule
+ * Re - declared for populate rate calculations
+ *
+ * @return $this
+ */
+ protected function _afterSave()
+ {
+ parent::_afterSave();
+ $this->saveCalculationData();
+ Mage::dispatchEvent('tax_settings_change_after');
+ return $this;
+ }
+
+ /**
+ * After rule delete
+ * redeclared for dispatch tax_settings_change_after event
+ *
+ * @inheritDoc
+ */
+ protected function _afterDelete()
+ {
+ Mage::dispatchEvent('tax_settings_change_after');
+ return parent::_afterDelete();
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Config.php b/app/code/core/Mage/Tax/Model/Config.php
index fbabd8cc268..400fa131204 100644
--- a/app/code/core/Mage/Tax/Model/Config.php
+++ b/app/code/core/Mage/Tax/Model/Config.php
@@ -145,18 +145,6 @@ class Mage_Tax_Model_Config
*/
protected $_shippingPriceIncludeTax = null;
- /**
- * Retrieve config value for store by path
- *
- * @param string $path
- * @param null|string|bool|int|Mage_Core_Model_Store $store
- * @return mixed
- */
- protected function _getStoreConfig($path, $store)
- {
- return Mage::getStoreConfig($path, $store);
- }
-
/**
* Check if product prices inputted include tax
*
@@ -759,4 +747,16 @@ public function crossBorderTradeEnabled($store = null)
{
return $this->_getStoreConfig(self::CONFIG_XML_PATH_CROSS_BORDER_TRADE_ENABLED, $store);
}
+
+ /**
+ * Retrieve config value for store by path
+ *
+ * @param string $path
+ * @param null|string|bool|int|Mage_Core_Model_Store $store
+ * @return mixed
+ */
+ protected function _getStoreConfig($path, $store)
+ {
+ return Mage::getStoreConfig($path, $store);
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Calculation.php b/app/code/core/Mage/Tax/Model/Resource/Calculation.php
index e386a0006fa..9da5daadf0d 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Calculation.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Calculation.php
@@ -36,11 +36,6 @@ class Mage_Tax_Model_Resource_Calculation extends Mage_Core_Model_Resource_Db_Ab
*/
protected $_isPkAutoIncrement = false;
- protected function _construct()
- {
- $this->_setMainTable('tax/tax_calculation');
- }
-
/**
* Delete calculation settings by rule id
*
@@ -185,6 +180,131 @@ public function getCalculationProcess($request, $rates = null)
return $result;
}
+ /**
+ * Get rate ids applicable for some address
+ *
+ * @param Varien_Object $request
+ * @return array
+ */
+ public function getApplicableRateIds($request)
+ {
+ $countryId = $request->getCountryId();
+ $regionId = $request->getRegionId();
+ $postcode = $request->getPostcode();
+
+ $select = $this->_getReadAdapter()->select()
+ ->from(['rate' => $this->getTable('tax/tax_calculation_rate')], ['tax_calculation_rate_id'])
+ ->where('rate.tax_country_id = ?', $countryId)
+ ->where('rate.tax_region_id IN(?)', [0, (int) $regionId]);
+
+ $expr = $this->_getWriteAdapter()->getCheckSql(
+ 'zip_is_range is NULL',
+ $this->_getWriteAdapter()->quoteInto(
+ "rate.tax_postcode IS NULL OR rate.tax_postcode IN('*', '', ?)",
+ $this->_createSearchPostCodeTemplates($postcode),
+ ),
+ $this->_getWriteAdapter()->quoteInto('? BETWEEN rate.zip_from AND rate.zip_to', $postcode),
+ );
+ $select->where($expr);
+ $select->order('tax_calculation_rate_id');
+ return $this->_getReadAdapter()->fetchCol($select);
+ }
+
+ /**
+ * Retrieve rate ids
+ *
+ * @param Varien_Object $request
+ * @return array
+ */
+ public function getRateIds($request)
+ {
+ $result = [];
+ $rates = $this->_getRates($request);
+ $countedRates = count($rates);
+ for ($i = 0; $i < $countedRates; $i++) {
+ $rate = $rates[$i];
+ $rule = $rate['tax_calculation_rule_id'];
+ $result[] = $rate['tax_calculation_rate_id'];
+ while (isset($rates[$i + 1]) && $rates[$i + 1]['tax_calculation_rule_id'] == $rule) {
+ $i++;
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Retrieve rates by customer tax class
+ *
+ * @param int $customerTaxClass
+ * @param int|null $productTaxClass
+ * @return array
+ */
+ public function getRatesByCustomerTaxClass($customerTaxClass, $productTaxClass = null)
+ {
+ $adapter = $this->_getReadAdapter();
+ $customerTaxClassId = (int) $customerTaxClass;
+ $calcJoinConditions = [
+ 'calc_table.tax_calculation_rate_id = main_table.tax_calculation_rate_id',
+ $adapter->quoteInto('calc_table.customer_tax_class_id = ?', $customerTaxClassId),
+
+ ];
+ if ($productTaxClass !== null) {
+ $productTaxClassId = (int) $productTaxClass;
+ $calcJoinConditions[] = $adapter->quoteInto('calc_table.product_tax_class_id = ?', $productTaxClassId);
+ }
+
+ $selectCSP = $adapter->select();
+ $selectCSP
+ ->from(
+ ['main_table' => $this->getTable('tax/tax_calculation_rate')],
+ ['country' => 'tax_country_id', 'region_id' => 'tax_region_id', 'postcode' => 'tax_postcode'],
+ )
+ ->joinInner(
+ ['calc_table' => $this->getTable('tax/tax_calculation')],
+ implode(' AND ', $calcJoinConditions),
+ ['product_class' => 'calc_table.product_tax_class_id'],
+ )
+ ->joinLeft(
+ ['state_table' => $this->getTable('directory/country_region')],
+ 'state_table.region_id = main_table.tax_region_id',
+ ['region_code' => 'state_table.code'],
+ )
+ ->distinct(true);
+
+ $csp = $adapter->fetchAll($selectCSP);
+
+ $result = [];
+ foreach ($csp as $one) {
+ $request = new Varien_Object();
+ $request->setCountryId($one['country'])
+ ->setRegionId($one['region_id'])
+ ->setPostcode($one['postcode'])
+ ->setCustomerClassId($customerTaxClassId)
+ ->setProductClassId($one['product_class']);
+
+ $rate = $this->getRate($request);
+ if ($rate) {
+ $row = [
+ 'value' => $rate / 100,
+ 'country' => $one['country'],
+ 'state' => $one['region_code'],
+ 'postcode' => $one['postcode'],
+ 'product_class' => $one['product_class'],
+ ];
+
+ $result[] = $row;
+ }
+ }
+
+ return $result;
+ }
+
+ protected function _construct()
+ {
+ $this->_setMainTable('tax/tax_calculation');
+ }
+
/**
* Return combined percent value
*
@@ -357,36 +477,6 @@ protected function _getRates($request)
return $this->_ratesCache[$cacheKey];
}
- /**
- * Get rate ids applicable for some address
- *
- * @param Varien_Object $request
- * @return array
- */
- public function getApplicableRateIds($request)
- {
- $countryId = $request->getCountryId();
- $regionId = $request->getRegionId();
- $postcode = $request->getPostcode();
-
- $select = $this->_getReadAdapter()->select()
- ->from(['rate' => $this->getTable('tax/tax_calculation_rate')], ['tax_calculation_rate_id'])
- ->where('rate.tax_country_id = ?', $countryId)
- ->where('rate.tax_region_id IN(?)', [0, (int) $regionId]);
-
- $expr = $this->_getWriteAdapter()->getCheckSql(
- 'zip_is_range is NULL',
- $this->_getWriteAdapter()->quoteInto(
- "rate.tax_postcode IS NULL OR rate.tax_postcode IN('*', '', ?)",
- $this->_createSearchPostCodeTemplates($postcode),
- ),
- $this->_getWriteAdapter()->quoteInto('? BETWEEN rate.zip_from AND rate.zip_to', $postcode),
- );
- $select->where($expr);
- $select->order('tax_calculation_rate_id');
- return $this->_getReadAdapter()->fetchCol($select);
- }
-
/**
* Calculate rate
*
@@ -422,94 +512,4 @@ protected function _calculateRate($rates)
return $result;
}
-
- /**
- * Retrieve rate ids
- *
- * @param Varien_Object $request
- * @return array
- */
- public function getRateIds($request)
- {
- $result = [];
- $rates = $this->_getRates($request);
- $countedRates = count($rates);
- for ($i = 0; $i < $countedRates; $i++) {
- $rate = $rates[$i];
- $rule = $rate['tax_calculation_rule_id'];
- $result[] = $rate['tax_calculation_rate_id'];
- while (isset($rates[$i + 1]) && $rates[$i + 1]['tax_calculation_rule_id'] == $rule) {
- $i++;
- }
- }
-
- return $result;
- }
-
- /**
- * Retrieve rates by customer tax class
- *
- * @param int $customerTaxClass
- * @param int|null $productTaxClass
- * @return array
- */
- public function getRatesByCustomerTaxClass($customerTaxClass, $productTaxClass = null)
- {
- $adapter = $this->_getReadAdapter();
- $customerTaxClassId = (int) $customerTaxClass;
- $calcJoinConditions = [
- 'calc_table.tax_calculation_rate_id = main_table.tax_calculation_rate_id',
- $adapter->quoteInto('calc_table.customer_tax_class_id = ?', $customerTaxClassId),
-
- ];
- if ($productTaxClass !== null) {
- $productTaxClassId = (int) $productTaxClass;
- $calcJoinConditions[] = $adapter->quoteInto('calc_table.product_tax_class_id = ?', $productTaxClassId);
- }
-
- $selectCSP = $adapter->select();
- $selectCSP
- ->from(
- ['main_table' => $this->getTable('tax/tax_calculation_rate')],
- ['country' => 'tax_country_id', 'region_id' => 'tax_region_id', 'postcode' => 'tax_postcode'],
- )
- ->joinInner(
- ['calc_table' => $this->getTable('tax/tax_calculation')],
- implode(' AND ', $calcJoinConditions),
- ['product_class' => 'calc_table.product_tax_class_id'],
- )
- ->joinLeft(
- ['state_table' => $this->getTable('directory/country_region')],
- 'state_table.region_id = main_table.tax_region_id',
- ['region_code' => 'state_table.code'],
- )
- ->distinct(true);
-
- $csp = $adapter->fetchAll($selectCSP);
-
- $result = [];
- foreach ($csp as $one) {
- $request = new Varien_Object();
- $request->setCountryId($one['country'])
- ->setRegionId($one['region_id'])
- ->setPostcode($one['postcode'])
- ->setCustomerClassId($customerTaxClassId)
- ->setProductClassId($one['product_class']);
-
- $rate = $this->getRate($request);
- if ($rate) {
- $row = [
- 'value' => $rate / 100,
- 'country' => $one['country'],
- 'state' => $one['region_code'],
- 'postcode' => $one['postcode'],
- 'product_class' => $one['product_class'],
- ];
-
- $result[] = $row;
- }
- }
-
- return $result;
- }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate.php b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate.php
index e7546bfdeaf..10db6827d80 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate.php
@@ -22,25 +22,6 @@
*/
class Mage_Tax_Model_Resource_Calculation_Rate extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/tax_calculation_rate', 'tax_calculation_rate_id');
- }
-
- /**
- * Initialize unique fields
- *
- * @return $this
- */
- protected function _initUniqueFields()
- {
- $this->_uniqueFields = [[
- 'field' => ['code'],
- 'title' => Mage::helper('tax')->__('Code'),
- ]];
- return $this;
- }
-
/**
* Delete all rates
*
@@ -66,4 +47,22 @@ public function isInRule($rateId)
->where('tax_calculation_rate_id = ?', $rateId);
return $adapter->fetchCol($select);
}
+ protected function _construct()
+ {
+ $this->_init('tax/tax_calculation_rate', 'tax_calculation_rate_id');
+ }
+
+ /**
+ * Initialize unique fields
+ *
+ * @return $this
+ */
+ protected function _initUniqueFields()
+ {
+ $this->_uniqueFields = [[
+ 'field' => ['code'],
+ 'title' => Mage::helper('tax')->__('Code'),
+ ]];
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Collection.php b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Collection.php
index 3477a306b4e..e961763624e 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Collection.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Collection.php
@@ -29,11 +29,6 @@ class Mage_Tax_Model_Resource_Calculation_Rate_Collection extends Mage_Core_Mode
*/
public const TAX_RULES_CHUNK_SIZE = 1000;
- protected function _construct()
- {
- $this->_init('tax/calculation_rate');
- }
-
/**
* Join country table to result
*
@@ -182,4 +177,9 @@ public function getOptionRates()
return $rates;
}
+
+ protected function _construct()
+ {
+ $this->_init('tax/calculation_rate');
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Title.php b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Title.php
index c53d146599c..d6a07d82e32 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Title.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Title.php
@@ -22,11 +22,6 @@
*/
class Mage_Tax_Model_Resource_Calculation_Rate_Title extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/tax_calculation_rate_title', 'tax_calculation_rate_title_id');
- }
-
/**
* Delete title by rate identifier
*
@@ -41,4 +36,8 @@ public function deleteByRateId($rateId)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('tax/tax_calculation_rate_title', 'tax_calculation_rate_title_id');
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Title/Collection.php b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Title/Collection.php
index b6a3db3fe4d..1c23b53588d 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Title/Collection.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rate/Title/Collection.php
@@ -24,11 +24,6 @@
*/
class Mage_Tax_Model_Resource_Calculation_Rate_Title_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/calculation_rate_title', 'tax/calculation_rate_title');
- }
-
/**
* Add rate id filter
*
@@ -40,4 +35,8 @@ public function loadByRateId($rateId)
$this->addFieldToFilter('main_table.tax_calculation_rate_id', $rateId);
return $this->load();
}
+ protected function _construct()
+ {
+ $this->_init('tax/calculation_rate_title', 'tax/calculation_rate_title');
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rule.php b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rule.php
index 791fc9e89eb..eb92f7a9ede 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rule.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rule.php
@@ -22,25 +22,6 @@
*/
class Mage_Tax_Model_Resource_Calculation_Rule extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/tax_calculation_rule', 'tax_calculation_rule_id');
- }
-
- /**
- * Initialize unique fields
- *
- * @return $this
- */
- protected function _initUniqueFields()
- {
- $this->_uniqueFields = [[
- 'field' => ['code'],
- 'title' => Mage::helper('tax')->__('Code'),
- ]];
- return $this;
- }
-
/**
* Fetches rules by rate, customer tax class and product tax class
* Returns array of rule codes
@@ -67,4 +48,22 @@ public function fetchRuleCodes($rateId, $customerTaxClassId, $productTaxClassId)
return $adapter->fetchCol($select);
}
+ protected function _construct()
+ {
+ $this->_init('tax/tax_calculation_rule', 'tax_calculation_rule_id');
+ }
+
+ /**
+ * Initialize unique fields
+ *
+ * @return $this
+ */
+ protected function _initUniqueFields()
+ {
+ $this->_uniqueFields = [[
+ 'field' => ['code'],
+ 'title' => Mage::helper('tax')->__('Code'),
+ ]];
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rule/Collection.php b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rule/Collection.php
index edd4f23c41c..eca9e7f3f9b 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Calculation/Rule/Collection.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Calculation/Rule/Collection.php
@@ -24,11 +24,6 @@
*/
class Mage_Tax_Model_Resource_Calculation_Rule_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/calculation_rule');
- }
-
/**
* Join calculation data to result
*
@@ -47,52 +42,6 @@ public function joinCalculationData($alias)
return $this;
}
- /**
- * Join tax data to collection
- *
- * @param string $itemTable
- * @param string $primaryJoinField
- * @param string $secondaryJoinField
- * @param string $titleField
- * @param string $dataField
- * @return $this
- */
- protected function _add($itemTable, $primaryJoinField, $secondaryJoinField, $titleField, $dataField)
- {
- $children = [];
- foreach ($this as $rule) {
- $children[$rule->getId()] = [];
- }
- if (!empty($children)) {
- $joinCondition = sprintf('item.%s = calculation.%s', $secondaryJoinField, $primaryJoinField);
- $select = $this->getConnection()->select()
- ->from(
- ['calculation' => $this->getTable('tax/tax_calculation')],
- ['calculation.tax_calculation_rule_id'],
- )
- ->join(
- ['item' => $this->getTable($itemTable)],
- $joinCondition,
- ["item.{$titleField}", "item.{$secondaryJoinField}"],
- )
- ->where('calculation.tax_calculation_rule_id IN (?)', array_keys($children))
- ->distinct(true);
-
- $data = $this->getConnection()->fetchAll($select);
- foreach ($data as $row) {
- $children[$row['tax_calculation_rule_id']][$row[$secondaryJoinField]] = $row[$titleField];
- }
- }
-
- foreach ($this as $rule) {
- if (isset($children[$rule->getId()])) {
- $rule->setData($dataField, array_keys($children[$rule->getId()]));
- }
- }
-
- return $this;
- }
-
/**
* Add product tax classes to result
*
@@ -148,4 +97,54 @@ public function setClassTypeFilter($type, $id)
$this->addFieldToFilter($field, $id);
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('tax/calculation_rule');
+ }
+
+ /**
+ * Join tax data to collection
+ *
+ * @param string $itemTable
+ * @param string $primaryJoinField
+ * @param string $secondaryJoinField
+ * @param string $titleField
+ * @param string $dataField
+ * @return $this
+ */
+ protected function _add($itemTable, $primaryJoinField, $secondaryJoinField, $titleField, $dataField)
+ {
+ $children = [];
+ foreach ($this as $rule) {
+ $children[$rule->getId()] = [];
+ }
+ if (!empty($children)) {
+ $joinCondition = sprintf('item.%s = calculation.%s', $secondaryJoinField, $primaryJoinField);
+ $select = $this->getConnection()->select()
+ ->from(
+ ['calculation' => $this->getTable('tax/tax_calculation')],
+ ['calculation.tax_calculation_rule_id'],
+ )
+ ->join(
+ ['item' => $this->getTable($itemTable)],
+ $joinCondition,
+ ["item.{$titleField}", "item.{$secondaryJoinField}"],
+ )
+ ->where('calculation.tax_calculation_rule_id IN (?)', array_keys($children))
+ ->distinct(true);
+
+ $data = $this->getConnection()->fetchAll($select);
+ foreach ($data as $row) {
+ $children[$row['tax_calculation_rule_id']][$row[$secondaryJoinField]] = $row[$titleField];
+ }
+ }
+
+ foreach ($this as $rule) {
+ if (isset($children[$rule->getId()])) {
+ $rule->setData($dataField, array_keys($children[$rule->getId()]));
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Report/Tax.php b/app/code/core/Mage/Tax/Model/Resource/Report/Tax.php
index 36456a458b9..24d4622a7f7 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Report/Tax.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Report/Tax.php
@@ -22,11 +22,6 @@
*/
class Mage_Tax_Model_Resource_Report_Tax extends Mage_Reports_Model_Resource_Report_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/tax_order_aggregated_created', 'id');
- }
-
/**
* Aggregate Tax data
*
@@ -42,4 +37,8 @@ public function aggregate($from = null, $to = null)
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('tax/tax_order_aggregated_created', 'id');
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Createdat.php b/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Createdat.php
index b2561e8a7eb..a3cd95dbc51 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Createdat.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Createdat.php
@@ -22,11 +22,6 @@
*/
class Mage_Tax_Model_Resource_Report_Tax_Createdat extends Mage_Reports_Model_Resource_Report_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/tax_order_aggregated_created', 'id');
- }
-
/**
* Aggregate Tax data by order created at
*
@@ -38,6 +33,10 @@ public function aggregate($from = null, $to = null)
{
return $this->_aggregateByOrder('created_at', $from, $to);
}
+ protected function _construct()
+ {
+ $this->_init('tax/tax_order_aggregated_created', 'id');
+ }
/**
* Aggregate Tax data by orders
diff --git a/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Updatedat.php b/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Updatedat.php
index 02a12339836..0f373aa8487 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Updatedat.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Updatedat.php
@@ -22,11 +22,6 @@
*/
class Mage_Tax_Model_Resource_Report_Tax_Updatedat extends Mage_Tax_Model_Resource_Report_Tax_Createdat
{
- protected function _construct()
- {
- $this->_init('tax/tax_order_aggregated_updated', 'id');
- }
-
/**
* Aggregate Tax data by order updated at
*
@@ -38,4 +33,8 @@ public function aggregate($from = null, $to = null)
{
return $this->_aggregateByOrder('updated_at', $from, $to);
}
+ protected function _construct()
+ {
+ $this->_init('tax/tax_order_aggregated_updated', 'id');
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Collection.php b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Collection.php
index 074ab0c09e0..dbc8aa3dfde 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Collection.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Collection.php
@@ -24,11 +24,6 @@
*/
class Mage_Tax_Model_Resource_Sales_Order_Tax_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/sales_order_tax');
- }
-
/**
* Retrieve order tax collection by order identifier
*
@@ -43,4 +38,8 @@ public function loadByOrder($order)
->order('process');
return $this->load();
}
+ protected function _construct()
+ {
+ $this->_init('tax/sales_order_tax');
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item.php b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item.php
index ceaa8fc5244..bfc6f98cf67 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item.php
@@ -22,11 +22,6 @@
*/
class Mage_Tax_Model_Resource_Sales_Order_Tax_Item extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('tax/sales_order_tax_item', 'tax_item_id');
- }
-
/**
* Get Tax Items with order tax information
*
@@ -48,4 +43,8 @@ public function getTaxItemsByItemId($itemId)
// phpcs:ignore Ecg.Performance.FetchAll.Found
return $adapter->fetchAll($select);
}
+ protected function _construct()
+ {
+ $this->_init('tax/sales_order_tax_item', 'tax_item_id');
+ }
}
diff --git a/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Tax.php b/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Tax.php
index 50a9ab2c3da..7f60f0533ea 100644
--- a/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Tax.php
+++ b/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Tax.php
@@ -96,49 +96,6 @@ public function __construct()
$this->_weeeHelper = Mage::helper('weee');
}
- /**
- * Round the total amounts in address
- *
- * @return $this
- */
- protected function _roundTotals(Mage_Sales_Model_Quote_Address $address)
- {
- // initialize the delta to a small number to avoid non-deterministic behavior with rounding of 0.5
- $totalDelta = 0.000001;
- $baseTotalDelta = 0.000001;
- /*
- * The order of rounding is import here.
- * Tax is rounded first, to be consistent with unit based calculation.
- * Hidden tax and shipping_hidden_tax are rounded next, which are really part of tax.
- * Shipping is rounded before subtotal to minimize the chance that subtotal is
- * rounded differently because of the delta.
- * Here is an example: 19.2% tax rate, subtotal = 49.95, shipping = 9.99, discount = 20%
- * subtotalExclTax = 41.90436, tax = 7.7238, hidden_tax = 1.609128, shippingPriceExclTax = 8.38087
- * shipping_hidden_tax = 0.321826, discount = -11.988
- * The grand total is 47.952 ~= 47.95
- * The rounded values are:
- * tax = 7.72, hidden_tax = 1.61, shipping_hidden_tax = 0.32,
- * shipping = 8.39 (instead of 8.38 from simple rounding), subtotal = 41.9, discount = -11.99
- * The grand total calculated from the rounded value is 47.95
- * If we simply round each value and add them up, the result is 47.94, which is one penny off
- */
- $totalCodes = ['tax', 'hidden_tax', 'shipping_hidden_tax', 'shipping', 'subtotal', 'weee', 'discount'];
- foreach ($totalCodes as $totalCode) {
- $exactAmount = $address->getTotalAmount($totalCode);
- $baseExactAmount = $address->getBaseTotalAmount($totalCode);
- if (!$exactAmount && !$baseExactAmount) {
- continue;
- }
- $roundedAmount = $this->_calculator->round($exactAmount + $totalDelta);
- $baseRoundedAmount = $this->_calculator->round($baseExactAmount + $baseTotalDelta);
- $address->setTotalAmount($totalCode, $roundedAmount);
- $address->setBaseTotalAmount($totalCode, $baseRoundedAmount);
- $totalDelta = $exactAmount + $totalDelta - $roundedAmount;
- $baseTotalDelta = $baseExactAmount + $baseTotalDelta - $baseRoundedAmount;
- }
- return $this;
- }
-
/**
* Collect tax totals for quote address
*
@@ -210,6 +167,145 @@ public function collect(Mage_Sales_Model_Quote_Address $address)
return $this;
}
+ /**
+ * Add tax totals information to address object
+ *
+ * @return $this
+ */
+ public function fetch(Mage_Sales_Model_Quote_Address $address)
+ {
+ $applied = $address->getAppliedTaxes();
+ $store = $address->getQuote()->getStore();
+ $amount = $address->getTaxAmount();
+
+ $items = $this->_getAddressItems($address);
+ $discountTaxCompensation = 0;
+ foreach ($items as $item) {
+ $discountTaxCompensation += $item->getDiscountTaxCompensation();
+ }
+ $taxAmount = $amount + $discountTaxCompensation;
+ /*
+ * when weee discount is not included in extraTaxAmount, we need to add it to the total tax
+ */
+ if ($this->_weeeHelper->isEnabled()) {
+ if (!$this->_weeeHelper->includeInSubtotal()) {
+ $taxAmount += $address->getWeeeDiscount();
+ }
+ }
+
+ $area = null;
+ if ($this->_config->displayCartTaxWithGrandTotal($store) && $address->getGrandTotal()) {
+ $area = 'taxes';
+ }
+
+ if (($amount != 0) || ($this->_config->displayCartZeroTax($store))) {
+ $address->addTotal([
+ 'code' => $this->getCode(),
+ 'title' => Mage::helper('tax')->__('Tax'),
+ 'full_info' => $applied ? $applied : [],
+ 'value' => $amount,
+ 'area' => $area,
+ ]);
+ }
+
+ $store = $address->getQuote()->getStore();
+ /**
+ * Modify subtotal
+ */
+ if ($this->_config->displayCartSubtotalBoth($store) || $this->_config->displayCartSubtotalInclTax($store)) {
+ if ($address->getSubtotalInclTax() > 0) {
+ $subtotalInclTax = $address->getSubtotalInclTax();
+ } else {
+ $subtotalInclTax = $address->getSubtotal() + $taxAmount - $address->getShippingTaxAmount();
+ }
+
+ $address->addTotal([
+ 'code' => 'subtotal',
+ 'title' => Mage::helper('sales')->__('Subtotal'),
+ 'value' => $subtotalInclTax,
+ 'value_incl_tax' => $subtotalInclTax,
+ 'value_excl_tax' => $address->getSubtotal(),
+ ]);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Process model configuration array.
+ * This method can be used for changing totals collect sort order
+ *
+ * @param array $config
+ * @param Mage_Core_Model_Store $store
+ * @return array
+ */
+ public function processConfigArray($config, $store)
+ {
+ $calculationSequence = $this->_helper->getCalculationSequence($store);
+ switch ($calculationSequence) {
+ case Mage_Tax_Model_Calculation::CALC_TAX_BEFORE_DISCOUNT_ON_INCL:
+ $config['before'][] = 'discount';
+ break;
+ default:
+ $config['after'][] = 'discount';
+ break;
+ }
+ return $config;
+ }
+
+ /**
+ * Get Tax label
+ *
+ * @return string
+ */
+ public function getLabel()
+ {
+ return Mage::helper('tax')->__('Tax');
+ }
+
+ /**
+ * Round the total amounts in address
+ *
+ * @return $this
+ */
+ protected function _roundTotals(Mage_Sales_Model_Quote_Address $address)
+ {
+ // initialize the delta to a small number to avoid non-deterministic behavior with rounding of 0.5
+ $totalDelta = 0.000001;
+ $baseTotalDelta = 0.000001;
+ /*
+ * The order of rounding is import here.
+ * Tax is rounded first, to be consistent with unit based calculation.
+ * Hidden tax and shipping_hidden_tax are rounded next, which are really part of tax.
+ * Shipping is rounded before subtotal to minimize the chance that subtotal is
+ * rounded differently because of the delta.
+ * Here is an example: 19.2% tax rate, subtotal = 49.95, shipping = 9.99, discount = 20%
+ * subtotalExclTax = 41.90436, tax = 7.7238, hidden_tax = 1.609128, shippingPriceExclTax = 8.38087
+ * shipping_hidden_tax = 0.321826, discount = -11.988
+ * The grand total is 47.952 ~= 47.95
+ * The rounded values are:
+ * tax = 7.72, hidden_tax = 1.61, shipping_hidden_tax = 0.32,
+ * shipping = 8.39 (instead of 8.38 from simple rounding), subtotal = 41.9, discount = -11.99
+ * The grand total calculated from the rounded value is 47.95
+ * If we simply round each value and add them up, the result is 47.94, which is one penny off
+ */
+ $totalCodes = ['tax', 'hidden_tax', 'shipping_hidden_tax', 'shipping', 'subtotal', 'weee', 'discount'];
+ foreach ($totalCodes as $totalCode) {
+ $exactAmount = $address->getTotalAmount($totalCode);
+ $baseExactAmount = $address->getBaseTotalAmount($totalCode);
+ if (!$exactAmount && !$baseExactAmount) {
+ continue;
+ }
+ $roundedAmount = $this->_calculator->round($exactAmount + $totalDelta);
+ $baseRoundedAmount = $this->_calculator->round($baseExactAmount + $baseTotalDelta);
+ $address->setTotalAmount($totalCode, $roundedAmount);
+ $address->setBaseTotalAmount($totalCode, $baseRoundedAmount);
+ $totalDelta = $exactAmount + $totalDelta - $roundedAmount;
+ $baseTotalDelta = $baseExactAmount + $baseTotalDelta - $baseRoundedAmount;
+ }
+ return $this;
+ }
+
/**
* Process hidden taxes for items and shipping (in accordance with hidden tax type)
*/
@@ -1433,37 +1529,6 @@ protected function _calculateRowWeeeTax($discountAmount, $item, $rate, $base = t
return $this->_getWeeeTax($rate, $item, $discountAmount, $totalWeeeAmountInclTax, $totalWeeeAmountExclTax);
}
- /**
- * Calculate the Weee tax based on the discount and rate
- *
- * @param float $rate
- * @param Mage_Sales_Model_Quote_Item_Abstract $item
- * @param float $discountAmount
- * @param float $weeeAmountIncludingTax
- * @param float $weeeAmountExclTax
- * @return mixed
- */
- // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
- private function _getWeeeTax($rate, $item, $discountAmount, $weeeAmountIncludingTax, $weeeAmountExclTax)
- {
- $isWeeeTaxAlreadyIncluded = $this->_weeeHelper->isTaxIncluded($this->_store);
-
- $sameRateAsStore = $this->_helper->isCrossBorderTradeEnabled($this->_store) ||
- ($rate == $this->_calculator->getStoreRateForItem($item));
- if ($sameRateAsStore && $isWeeeTaxAlreadyIncluded) {
- if (!$discountAmount || $discountAmount <= 0) {
- //We want to skip the re calculation and return the difference
- return max($weeeAmountIncludingTax - $weeeAmountExclTax, 0);
- } else {
- return $this->_calculator->calcTaxAmount($weeeAmountIncludingTax - $discountAmount, $rate, true, true);
- }
- }
- $discountAmount = !$discountAmount ? 0 : $discountAmount;
-
- ///Regular case where weee does not have the tax and we want to calculate the tax
- return $this->_calculator->calcTaxAmount($weeeAmountExclTax - $discountAmount, $rate, false, true);
- }
-
/**
* Round price based on previous rounding operation delta
*
@@ -1560,98 +1625,33 @@ protected function _saveAppliedTaxes(
}
/**
- * Add tax totals information to address object
+ * Calculate the Weee tax based on the discount and rate
*
- * @return $this
+ * @param float $rate
+ * @param Mage_Sales_Model_Quote_Item_Abstract $item
+ * @param float $discountAmount
+ * @param float $weeeAmountIncludingTax
+ * @param float $weeeAmountExclTax
+ * @return mixed
*/
- public function fetch(Mage_Sales_Model_Quote_Address $address)
+ // phpcs:ignore Ecg.PHP.PrivateClassMember.PrivateClassMemberError
+ private function _getWeeeTax($rate, $item, $discountAmount, $weeeAmountIncludingTax, $weeeAmountExclTax)
{
- $applied = $address->getAppliedTaxes();
- $store = $address->getQuote()->getStore();
- $amount = $address->getTaxAmount();
-
- $items = $this->_getAddressItems($address);
- $discountTaxCompensation = 0;
- foreach ($items as $item) {
- $discountTaxCompensation += $item->getDiscountTaxCompensation();
- }
- $taxAmount = $amount + $discountTaxCompensation;
- /*
- * when weee discount is not included in extraTaxAmount, we need to add it to the total tax
- */
- if ($this->_weeeHelper->isEnabled()) {
- if (!$this->_weeeHelper->includeInSubtotal()) {
- $taxAmount += $address->getWeeeDiscount();
- }
- }
-
- $area = null;
- if ($this->_config->displayCartTaxWithGrandTotal($store) && $address->getGrandTotal()) {
- $area = 'taxes';
- }
-
- if (($amount != 0) || ($this->_config->displayCartZeroTax($store))) {
- $address->addTotal([
- 'code' => $this->getCode(),
- 'title' => Mage::helper('tax')->__('Tax'),
- 'full_info' => $applied ? $applied : [],
- 'value' => $amount,
- 'area' => $area,
- ]);
- }
+ $isWeeeTaxAlreadyIncluded = $this->_weeeHelper->isTaxIncluded($this->_store);
- $store = $address->getQuote()->getStore();
- /**
- * Modify subtotal
- */
- if ($this->_config->displayCartSubtotalBoth($store) || $this->_config->displayCartSubtotalInclTax($store)) {
- if ($address->getSubtotalInclTax() > 0) {
- $subtotalInclTax = $address->getSubtotalInclTax();
+ $sameRateAsStore = $this->_helper->isCrossBorderTradeEnabled($this->_store) ||
+ ($rate == $this->_calculator->getStoreRateForItem($item));
+ if ($sameRateAsStore && $isWeeeTaxAlreadyIncluded) {
+ if (!$discountAmount || $discountAmount <= 0) {
+ //We want to skip the re calculation and return the difference
+ return max($weeeAmountIncludingTax - $weeeAmountExclTax, 0);
} else {
- $subtotalInclTax = $address->getSubtotal() + $taxAmount - $address->getShippingTaxAmount();
+ return $this->_calculator->calcTaxAmount($weeeAmountIncludingTax - $discountAmount, $rate, true, true);
}
-
- $address->addTotal([
- 'code' => 'subtotal',
- 'title' => Mage::helper('sales')->__('Subtotal'),
- 'value' => $subtotalInclTax,
- 'value_incl_tax' => $subtotalInclTax,
- 'value_excl_tax' => $address->getSubtotal(),
- ]);
}
+ $discountAmount = !$discountAmount ? 0 : $discountAmount;
- return $this;
- }
-
- /**
- * Process model configuration array.
- * This method can be used for changing totals collect sort order
- *
- * @param array $config
- * @param Mage_Core_Model_Store $store
- * @return array
- */
- public function processConfigArray($config, $store)
- {
- $calculationSequence = $this->_helper->getCalculationSequence($store);
- switch ($calculationSequence) {
- case Mage_Tax_Model_Calculation::CALC_TAX_BEFORE_DISCOUNT_ON_INCL:
- $config['before'][] = 'discount';
- break;
- default:
- $config['after'][] = 'discount';
- break;
- }
- return $config;
- }
-
- /**
- * Get Tax label
- *
- * @return string
- */
- public function getLabel()
- {
- return Mage::helper('tax')->__('Tax');
+ ///Regular case where weee does not have the tax and we want to calculate the tax
+ return $this->_calculator->calcTaxAmount($weeeAmountExclTax - $discountAmount, $rate, false, true);
}
}
diff --git a/app/code/core/Mage/Uploader/Block/Abstract.php b/app/code/core/Mage/Uploader/Block/Abstract.php
index 587a84e8280..707c1a38a47 100644
--- a/app/code/core/Mage/Uploader/Block/Abstract.php
+++ b/app/code/core/Mage/Uploader/Block/Abstract.php
@@ -22,6 +22,10 @@
*/
abstract class Mage_Uploader_Block_Abstract extends Mage_Adminhtml_Block_Widget
{
+ /**
+ * Default browse button ID suffix
+ */
+ public const DEFAULT_BROWSE_BUTTON_ID_SUFFIX = 'browse';
/**
* Template used for uploader
*
@@ -54,11 +58,6 @@ abstract class Mage_Uploader_Block_Abstract extends Mage_Adminhtml_Block_Widget
*/
protected $_idsMapping = [];
- /**
- * Default browse button ID suffix
- */
- public const DEFAULT_BROWSE_BUTTON_ID_SUFFIX = 'browse';
-
/**
* Constructor for uploader block
*
@@ -71,16 +70,6 @@ public function __construct()
$this->setId($this->getId() . '_Uploader');
}
- /**
- * Helper for file manipulation
- *
- * @return Mage_Uploader_Helper_File
- */
- protected function _getHelper()
- {
- return Mage::helper('uploader/file');
- }
-
/**
* @return string
*/
@@ -96,72 +85,6 @@ public function getJsonConfig()
]);
}
- /**
- * Get mapping of ids for front-end use
- *
- * @return array
- */
- protected function _getElementIdsMapping()
- {
- return $this->_idsMapping;
- }
-
- /**
- * Add mapping ids for front-end use
- *
- * @param array $additionalButtons
- * @return $this
- */
- protected function _addElementIdsMapping($additionalButtons = [])
- {
- $this->_idsMapping = array_merge($this->_idsMapping, $additionalButtons);
-
- return $this;
- }
-
- /**
- * Prepare layout, create buttons, set front-end elements ids
- *
- * @return Mage_Core_Block_Abstract
- */
- protected function _prepareLayout()
- {
- $this->setChild(
- 'browse_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->addData([
- // Workaround for IE9
- 'before_html' => sprintf(
- '',
- $this->getElementId(self::DEFAULT_BROWSE_BUTTON_ID_SUFFIX),
- ),
- 'after_html' => '
',
- 'id' => $this->getElementId(self::DEFAULT_BROWSE_BUTTON_ID_SUFFIX . '_button'),
- 'label' => Mage::helper('uploader')->__('Browse Files...'),
- 'type' => 'button',
- ]),
- );
-
- $this->setChild(
- 'delete_button',
- $this->getLayout()->createBlock('adminhtml/widget_button')
- ->addData([
- 'id' => '{{id}}',
- 'class' => 'delete',
- 'type' => 'button',
- 'label' => Mage::helper('uploader')->__('Remove'),
- ]),
- );
-
- $this->_addElementIdsMapping([
- 'container' => $this->getHtmlId(),
- 'templateFile' => $this->getElementId('template'),
- 'browse' => $this->_prepareElementsIds([self::DEFAULT_BROWSE_BUTTON_ID_SUFFIX]),
- ]);
-
- return parent::_prepareLayout();
- }
-
/**
* Get browse button html
*
@@ -232,6 +155,82 @@ public function getElementId($suffix)
return $this->getHtmlId() . '-' . $suffix;
}
+ /**
+ * Helper for file manipulation
+ *
+ * @return Mage_Uploader_Helper_File
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('uploader/file');
+ }
+
+ /**
+ * Get mapping of ids for front-end use
+ *
+ * @return array
+ */
+ protected function _getElementIdsMapping()
+ {
+ return $this->_idsMapping;
+ }
+
+ /**
+ * Add mapping ids for front-end use
+ *
+ * @param array $additionalButtons
+ * @return $this
+ */
+ protected function _addElementIdsMapping($additionalButtons = [])
+ {
+ $this->_idsMapping = array_merge($this->_idsMapping, $additionalButtons);
+
+ return $this;
+ }
+
+ /**
+ * Prepare layout, create buttons, set front-end elements ids
+ *
+ * @return Mage_Core_Block_Abstract
+ */
+ protected function _prepareLayout()
+ {
+ $this->setChild(
+ 'browse_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->addData([
+ // Workaround for IE9
+ 'before_html' => sprintf(
+ '',
+ $this->getElementId(self::DEFAULT_BROWSE_BUTTON_ID_SUFFIX),
+ ),
+ 'after_html' => '
',
+ 'id' => $this->getElementId(self::DEFAULT_BROWSE_BUTTON_ID_SUFFIX . '_button'),
+ 'label' => Mage::helper('uploader')->__('Browse Files...'),
+ 'type' => 'button',
+ ]),
+ );
+
+ $this->setChild(
+ 'delete_button',
+ $this->getLayout()->createBlock('adminhtml/widget_button')
+ ->addData([
+ 'id' => '{{id}}',
+ 'class' => 'delete',
+ 'type' => 'button',
+ 'label' => Mage::helper('uploader')->__('Remove'),
+ ]),
+ );
+
+ $this->_addElementIdsMapping([
+ 'container' => $this->getHtmlId(),
+ 'templateFile' => $this->getElementId('template'),
+ 'browse' => $this->_prepareElementsIds([self::DEFAULT_BROWSE_BUTTON_ID_SUFFIX]),
+ ]);
+
+ return parent::_prepareLayout();
+ }
+
/**
* Prepare actual elements ids from suffixes
*
diff --git a/app/code/core/Mage/Uploader/Block/Multiple.php b/app/code/core/Mage/Uploader/Block/Multiple.php
index 55fc7c006fe..19f6599353c 100644
--- a/app/code/core/Mage/Uploader/Block/Multiple.php
+++ b/app/code/core/Mage/Uploader/Block/Multiple.php
@@ -22,6 +22,16 @@ class Mage_Uploader_Block_Multiple extends Mage_Uploader_Block_Abstract
{
public const DEFAULT_UPLOAD_BUTTON_ID_SUFFIX = 'upload';
+ /**
+ * Get upload button html
+ *
+ * @return string
+ */
+ public function getUploadButtonHtml()
+ {
+ return $this->getChildHtml('upload_button');
+ }
+
/**
* @return $this
*/
@@ -45,14 +55,4 @@ protected function _prepareLayout()
return $this;
}
-
- /**
- * Get upload button html
- *
- * @return string
- */
- public function getUploadButtonHtml()
- {
- return $this->getChildHtml('upload_button');
- }
}
diff --git a/app/code/core/Mage/Uploader/Block/Single.php b/app/code/core/Mage/Uploader/Block/Single.php
index 2573fa2a185..3a9b3016923 100644
--- a/app/code/core/Mage/Uploader/Block/Single.php
+++ b/app/code/core/Mage/Uploader/Block/Single.php
@@ -20,6 +20,13 @@
*/
class Mage_Uploader_Block_Single extends Mage_Uploader_Block_Abstract
{
+ public function __construct()
+ {
+ parent::__construct();
+
+ $this->getUploaderConfig()->setSingleFile(true);
+ $this->getButtonConfig()->setSingleFile(true);
+ }
/**
* Prepare layout, change button and set front-end element ids mapping
*
@@ -32,12 +39,4 @@ protected function _prepareLayout()
return $this;
}
-
- public function __construct()
- {
- parent::__construct();
-
- $this->getUploaderConfig()->setSingleFile(true);
- $this->getButtonConfig()->setSingleFile(true);
- }
}
diff --git a/app/code/core/Mage/Uploader/Model/Config/Abstract.php b/app/code/core/Mage/Uploader/Model/Config/Abstract.php
index 0d0b2fa0dd2..063918ed611 100644
--- a/app/code/core/Mage/Uploader/Model/Config/Abstract.php
+++ b/app/code/core/Mage/Uploader/Model/Config/Abstract.php
@@ -22,16 +22,6 @@
*/
abstract class Mage_Uploader_Model_Config_Abstract extends Varien_Object
{
- /**
- * Get file helper
- *
- * @return Mage_Uploader_Helper_File
- */
- protected function _getHelper()
- {
- return Mage::helper('uploader/file');
- }
-
/**
* Set/Get attribute wrapper
* Also set data in cameCase for config values
@@ -60,4 +50,13 @@ public function __call($method, $args)
}
throw new Varien_Exception('Invalid method ' . get_class($this) . '::' . $method . '(' . print_r($args, true) . ')');
}
+ /**
+ * Get file helper
+ *
+ * @return Mage_Uploader_Helper_File
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('uploader/file');
+ }
}
diff --git a/app/code/core/Mage/Uploader/Model/Config/Browsebutton.php b/app/code/core/Mage/Uploader/Model/Config/Browsebutton.php
index f8ec98b2c75..6ff3239f96c 100644
--- a/app/code/core/Mage/Uploader/Model/Config/Browsebutton.php
+++ b/app/code/core/Mage/Uploader/Model/Config/Browsebutton.php
@@ -31,14 +31,6 @@
*/
class Mage_Uploader_Model_Config_Browsebutton extends Mage_Uploader_Model_Config_Abstract
{
- /**
- * Set params for browse button
- */
- protected function _construct()
- {
- $this->setIsDirectory(false);
- }
-
/**
* Get MIME types from files extensions
*
@@ -54,4 +46,11 @@ public function getMimeTypesByExtensions($exts)
return implode(',', $mimes);
}
+ /**
+ * Set params for browse button
+ */
+ protected function _construct()
+ {
+ $this->setIsDirectory(false);
+ }
}
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract.php
index 3c30902a207..a79d6b30379 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract.php
@@ -210,86 +210,6 @@ public function proccessAdditionalValidation(Mage_Shipping_Model_Rate_Request $r
return $this;
}
- /**
- * Returns cache key for some request to carrier quotes service
- *
- * @param string|array $requestParams
- * @return int
- */
- protected function _getQuotesCacheKey($requestParams)
- {
- if (is_array($requestParams)) {
- $requestParams = implode(
- ',',
- array_merge(
- [$this->getCarrierCode()],
- array_keys($requestParams),
- $requestParams,
- ),
- );
- }
- return crc32($requestParams);
- }
-
- /**
- * Checks whether some request to rates have already been done, so we have cache for it
- * Used to reduce number of same requests done to carrier service during one session
- *
- * Returns cached response or null
- *
- * @param string|array $requestParams
- * @return null|string
- */
- protected function _getCachedQuotes($requestParams)
- {
- $key = $this->_getQuotesCacheKey($requestParams);
- return self::$_quotesCache[$key] ?? null;
- }
-
- /**
- * Sets received carrier quotes to cache
- *
- * @param string|array $requestParams
- * @param string $response
- * @return Mage_Usa_Model_Shipping_Carrier_Abstract
- */
- protected function _setCachedQuotes($requestParams, $response)
- {
- $key = $this->_getQuotesCacheKey($requestParams);
- self::$_quotesCache[$key] = $response;
- return $this;
- }
-
- /**
- * Prepare service name. Strip tags and entities from name
- *
- * @param string|object $name service name or object with implemented __toString() method
- * @return string prepared service name
- */
- protected function _prepareServiceName($name)
- {
- $name = html_entity_decode((string) $name);
- $name = strip_tags(preg_replace('#&\w+;#', '', $name));
- return trim($name);
- }
-
- /**
- * Prepare shipment request.
- * Validate and correct request information
- *
- *
- */
- protected function _prepareShipmentRequest(Varien_Object $request)
- {
- $phonePattern = '/[\s\_\-\(\)]+/';
- $phoneNumber = $request->getShipperContactPhoneNumber();
- $phoneNumber = preg_replace($phonePattern, '', $phoneNumber);
- $request->setShipperContactPhoneNumber($phoneNumber);
- $phoneNumber = $request->getRecipientContactPhoneNumber();
- $phoneNumber = preg_replace($phonePattern, '', $phoneNumber);
- $request->setRecipientContactPhoneNumber($phoneNumber);
- }
-
/**
* Do request to shipment
*
@@ -399,6 +319,97 @@ public function rollBack($data)
return true;
}
+ /**
+ * Check whether girth is allowed for the carrier
+ *
+ * @param null|string $countyDest
+ * @return bool
+ */
+ public function isGirthAllowed($countyDest = null)
+ {
+ return false;
+ }
+
+ /**
+ * Returns cache key for some request to carrier quotes service
+ *
+ * @param string|array $requestParams
+ * @return int
+ */
+ protected function _getQuotesCacheKey($requestParams)
+ {
+ if (is_array($requestParams)) {
+ $requestParams = implode(
+ ',',
+ array_merge(
+ [$this->getCarrierCode()],
+ array_keys($requestParams),
+ $requestParams,
+ ),
+ );
+ }
+ return crc32($requestParams);
+ }
+
+ /**
+ * Checks whether some request to rates have already been done, so we have cache for it
+ * Used to reduce number of same requests done to carrier service during one session
+ *
+ * Returns cached response or null
+ *
+ * @param string|array $requestParams
+ * @return null|string
+ */
+ protected function _getCachedQuotes($requestParams)
+ {
+ $key = $this->_getQuotesCacheKey($requestParams);
+ return self::$_quotesCache[$key] ?? null;
+ }
+
+ /**
+ * Sets received carrier quotes to cache
+ *
+ * @param string|array $requestParams
+ * @param string $response
+ * @return Mage_Usa_Model_Shipping_Carrier_Abstract
+ */
+ protected function _setCachedQuotes($requestParams, $response)
+ {
+ $key = $this->_getQuotesCacheKey($requestParams);
+ self::$_quotesCache[$key] = $response;
+ return $this;
+ }
+
+ /**
+ * Prepare service name. Strip tags and entities from name
+ *
+ * @param string|object $name service name or object with implemented __toString() method
+ * @return string prepared service name
+ */
+ protected function _prepareServiceName($name)
+ {
+ $name = html_entity_decode((string) $name);
+ $name = strip_tags(preg_replace('#&\w+;#', '', $name));
+ return trim($name);
+ }
+
+ /**
+ * Prepare shipment request.
+ * Validate and correct request information
+ *
+ *
+ */
+ protected function _prepareShipmentRequest(Varien_Object $request)
+ {
+ $phonePattern = '/[\s\_\-\(\)]+/';
+ $phoneNumber = $request->getShipperContactPhoneNumber();
+ $phoneNumber = preg_replace($phonePattern, '', $phoneNumber);
+ $request->setShipperContactPhoneNumber($phoneNumber);
+ $phoneNumber = $request->getRecipientContactPhoneNumber();
+ $phoneNumber = preg_replace($phonePattern, '', $phoneNumber);
+ $request->setRecipientContactPhoneNumber($phoneNumber);
+ }
+
/**
* Do shipment request to carrier web service, obtain Print Shipping Labels and process errors in response
*
@@ -438,15 +449,4 @@ protected function _isCanada($countryId)
{
return $countryId == 'CA';
}
-
- /**
- * Check whether girth is allowed for the carrier
- *
- * @param null|string $countyDest
- * @return bool
- */
- public function isGirthAllowed($countyDest = null)
- {
- return false;
- }
}
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Backend/Abstract.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Backend/Abstract.php
index e8a9ffa0979..2b74a4bfe1d 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Backend/Abstract.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Backend/Abstract.php
@@ -37,16 +37,6 @@ abstract class Mage_Usa_Model_Shipping_Carrier_Abstract_Backend_Abstract extends
*/
protected $_nameErrorField;
- /**
- * Set source model to get allowed values
- */
- abstract protected function _setSourceModelData();
-
- /**
- * Set field name to display in error block
- */
- abstract protected function _setNameErrorField();
-
/**
* Mage_Usa_Model_Shipping_Carrier_Ups_Backend_Abstract constructor.
*/
@@ -57,6 +47,16 @@ public function __construct()
$this->_setNameErrorField();
}
+ /**
+ * Set source model to get allowed values
+ */
+ abstract protected function _setSourceModelData();
+
+ /**
+ * Set field name to display in error block
+ */
+ abstract protected function _setNameErrorField();
+
/**
* Check for presence in array with allow value.
*
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl.php
index 93ee932b9f1..ce271b4d73e 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl.php
@@ -29,6 +29,20 @@ class Mage_Usa_Model_Shipping_Carrier_Dhl extends Mage_Usa_Model_Shipping_Carrie
*/
public const CODE = 'dhl';
+ public const SUCCESS_CODE = 203;
+ public const SUCCESS_LABEL_CODE = 100;
+
+ public const ADDITIONAL_PROTECTION_ASSET = 'AP';
+ public const ADDITIONAL_PROTECTION_NOT_REQUIRED = 'NR';
+
+ public const ADDITIONAL_PROTECTION_VALUE_CONFIG = 0;
+ public const ADDITIONAL_PROTECTION_VALUE_SUBTOTAL = 1;
+ public const ADDITIONAL_PROTECTION_VALUE_SUBTOTAL_WITH_DISCOUNT = 2;
+
+ public const ADDITIONAL_PROTECTION_ROUNDING_FLOOR = 0;
+ public const ADDITIONAL_PROTECTION_ROUNDING_CEIL = 1;
+ public const ADDITIONAL_PROTECTION_ROUNDING_ROUND = 2;
+
/**
* Code of the carrier
*
@@ -85,20 +99,6 @@ class Mage_Usa_Model_Shipping_Carrier_Dhl extends Mage_Usa_Model_Shipping_Carrie
*/
protected $_customizableContainerTypes = ['P'];
- public const SUCCESS_CODE = 203;
- public const SUCCESS_LABEL_CODE = 100;
-
- public const ADDITIONAL_PROTECTION_ASSET = 'AP';
- public const ADDITIONAL_PROTECTION_NOT_REQUIRED = 'NR';
-
- public const ADDITIONAL_PROTECTION_VALUE_CONFIG = 0;
- public const ADDITIONAL_PROTECTION_VALUE_SUBTOTAL = 1;
- public const ADDITIONAL_PROTECTION_VALUE_SUBTOTAL_WITH_DISCOUNT = 2;
-
- public const ADDITIONAL_PROTECTION_ROUNDING_FLOOR = 0;
- public const ADDITIONAL_PROTECTION_ROUNDING_CEIL = 1;
- public const ADDITIONAL_PROTECTION_ROUNDING_ROUND = 2;
-
/**
* Collect and get rates
*
@@ -379,6 +379,166 @@ public function getResult()
return $this->_result;
}
+ /**
+ * Get configuration data of carrier
+ *
+ * @param string $type
+ * @param string $code
+ * @return array|bool
+ */
+ public function getCode($type, $code = '')
+ {
+ static $codes;
+ $codes = [
+ 'service' => [
+ 'IE' => Mage::helper('usa')->__('International Express'),
+ 'E SAT' => Mage::helper('usa')->__('Express Saturday'),
+ 'E 10:30AM' => Mage::helper('usa')->__('Express 10:30 AM'),
+ 'E' => Mage::helper('usa')->__('Express'),
+ 'N' => Mage::helper('usa')->__('Next Afternoon'),
+ 'S' => Mage::helper('usa')->__('Second Day Service'),
+ 'G' => Mage::helper('usa')->__('Ground'),
+ ],
+ 'shipment_type' => [
+ 'L' => Mage::helper('usa')->__('Letter'),
+ 'P' => Mage::helper('usa')->__('Package'),
+ ],
+ 'international_searvice' => 'IE',
+ 'dutypayment_type' => [
+ 'S' => Mage::helper('usa')->__('Sender'),
+ 'R' => Mage::helper('usa')->__('Receiver'),
+ '3' => Mage::helper('usa')->__('Third Party'),
+ ],
+
+ 'special_express' => [
+ 'E SAT' => 'SAT',
+ 'E 10:30AM' => '1030',
+ ],
+
+ 'descr_to_service' => [
+ 'E SAT' => 'Saturday',
+ 'E 10:30AM' => '10:30 A.M',
+ ],
+
+ ];
+
+ if (!isset($codes[$type])) {
+ return false;
+ } elseif ($code === '') {
+ return $codes[$type];
+ }
+
+ return $codes[$type][$code] ?? false;
+ }
+
+ /**
+ * Get tracking
+ *
+ * @param mixed $trackings
+ * @return Mage_Shipping_Model_Rate_Result|null
+ */
+ public function getTracking($trackings)
+ {
+ $this->setTrackingReqeust();
+
+ if (!is_array($trackings)) {
+ $trackings = [$trackings];
+ }
+ $this->_getXMLTracking($trackings);
+
+ return $this->_result;
+ }
+
+ /**
+ * Get tracking response
+ *
+ * @return string
+ */
+ public function getResponse()
+ {
+ $statuses = '';
+ if ($this->_result instanceof Mage_Shipping_Model_Tracking_Result) {
+ if ($trackings = $this->_result->getAllTrackings()) {
+ foreach ($trackings as $tracking) {
+ if ($data = $tracking->getAllData()) {
+ if (isset($data['status'])) {
+ $statuses .= Mage::helper('usa')->__($data['status']) . "\n
";
+ } else {
+ $statuses .= Mage::helper('usa')->__($data['error_message']) . "\n
";
+ }
+ }
+ }
+ }
+ }
+ if (empty($statuses)) {
+ $statuses = Mage::helper('usa')->__('Empty response');
+ }
+ return $statuses;
+ }
+
+ /**
+ * Get allowed shipping methods
+ *
+ * @return array
+ */
+ public function getAllowedMethods()
+ {
+ $allowed = explode(',', $this->getConfigData('allowed_methods'));
+ $arr = [];
+ foreach ($allowed as $k) {
+ $arr[$k] = $this->getCode('service', $k);
+ }
+ return $arr;
+ }
+
+ /**
+ * Is state province required
+ *
+ * @return bool
+ */
+ public function isStateProvinceRequired()
+ {
+ return true;
+ }
+
+ /**
+ * Get additional protection value types
+ *
+ * @return array
+ */
+ public function getAdditionalProtectionValueTypes()
+ {
+ return [
+ self::ADDITIONAL_PROTECTION_VALUE_CONFIG => Mage::helper('usa')->__('Configuration'),
+ self::ADDITIONAL_PROTECTION_VALUE_SUBTOTAL => Mage::helper('usa')->__('Subtotal'),
+ self::ADDITIONAL_PROTECTION_VALUE_SUBTOTAL_WITH_DISCOUNT => Mage::helper('usa')->__('Subtotal With Discount'),
+ ];
+ }
+
+ /**
+ * Get additional protection rounding types
+ *
+ * @return array
+ */
+ public function getAdditionalProtectionRoundingTypes()
+ {
+ return [
+ self::ADDITIONAL_PROTECTION_ROUNDING_FLOOR => Mage::helper('usa')->__('To Lower'),
+ self::ADDITIONAL_PROTECTION_ROUNDING_CEIL => Mage::helper('usa')->__('To Upper'),
+ self::ADDITIONAL_PROTECTION_ROUNDING_ROUND => Mage::helper('usa')->__('Round'),
+ ];
+ }
+
+ /**
+ * Return container types of carrier
+ *
+ * @return array|bool
+ */
+ public function getContainerTypes(?Varien_Object $params = null)
+ {
+ return $this->getCode('shipment_type');
+ }
+
/**
* Get quotes
*
@@ -844,58 +1004,6 @@ protected function _parseXmlObject($shipXml)
return $this;
}
- /**
- * Get configuration data of carrier
- *
- * @param string $type
- * @param string $code
- * @return array|bool
- */
- public function getCode($type, $code = '')
- {
- static $codes;
- $codes = [
- 'service' => [
- 'IE' => Mage::helper('usa')->__('International Express'),
- 'E SAT' => Mage::helper('usa')->__('Express Saturday'),
- 'E 10:30AM' => Mage::helper('usa')->__('Express 10:30 AM'),
- 'E' => Mage::helper('usa')->__('Express'),
- 'N' => Mage::helper('usa')->__('Next Afternoon'),
- 'S' => Mage::helper('usa')->__('Second Day Service'),
- 'G' => Mage::helper('usa')->__('Ground'),
- ],
- 'shipment_type' => [
- 'L' => Mage::helper('usa')->__('Letter'),
- 'P' => Mage::helper('usa')->__('Package'),
- ],
- 'international_searvice' => 'IE',
- 'dutypayment_type' => [
- 'S' => Mage::helper('usa')->__('Sender'),
- 'R' => Mage::helper('usa')->__('Receiver'),
- '3' => Mage::helper('usa')->__('Third Party'),
- ],
-
- 'special_express' => [
- 'E SAT' => 'SAT',
- 'E 10:30AM' => '1030',
- ],
-
- 'descr_to_service' => [
- 'E SAT' => 'Saturday',
- 'E 10:30AM' => '10:30 A.M',
- ],
-
- ];
-
- if (!isset($codes[$type])) {
- return false;
- } elseif ($code === '') {
- return $codes[$type];
- }
-
- return $codes[$type][$code] ?? false;
- }
-
/**
* Parse xml and add rates to instance property
*
@@ -932,24 +1040,6 @@ protected function _addRate($shipXml)
}
}
- /**
- * Get tracking
- *
- * @param mixed $trackings
- * @return Mage_Shipping_Model_Rate_Result|null
- */
- public function getTracking($trackings)
- {
- $this->setTrackingReqeust();
-
- if (!is_array($trackings)) {
- $trackings = [$trackings];
- }
- $this->_getXMLTracking($trackings);
-
- return $this->_result;
- }
-
/**
* Set tracking request
*/
@@ -1176,86 +1266,6 @@ protected function _parseXmlTrackingResponse($trackings, $response)
$this->_result = $result;
}
- /**
- * Get tracking response
- *
- * @return string
- */
- public function getResponse()
- {
- $statuses = '';
- if ($this->_result instanceof Mage_Shipping_Model_Tracking_Result) {
- if ($trackings = $this->_result->getAllTrackings()) {
- foreach ($trackings as $tracking) {
- if ($data = $tracking->getAllData()) {
- if (isset($data['status'])) {
- $statuses .= Mage::helper('usa')->__($data['status']) . "\n
";
- } else {
- $statuses .= Mage::helper('usa')->__($data['error_message']) . "\n
";
- }
- }
- }
- }
- }
- if (empty($statuses)) {
- $statuses = Mage::helper('usa')->__('Empty response');
- }
- return $statuses;
- }
-
- /**
- * Get allowed shipping methods
- *
- * @return array
- */
- public function getAllowedMethods()
- {
- $allowed = explode(',', $this->getConfigData('allowed_methods'));
- $arr = [];
- foreach ($allowed as $k) {
- $arr[$k] = $this->getCode('service', $k);
- }
- return $arr;
- }
-
- /**
- * Is state province required
- *
- * @return bool
- */
- public function isStateProvinceRequired()
- {
- return true;
- }
-
- /**
- * Get additional protection value types
- *
- * @return array
- */
- public function getAdditionalProtectionValueTypes()
- {
- return [
- self::ADDITIONAL_PROTECTION_VALUE_CONFIG => Mage::helper('usa')->__('Configuration'),
- self::ADDITIONAL_PROTECTION_VALUE_SUBTOTAL => Mage::helper('usa')->__('Subtotal'),
- self::ADDITIONAL_PROTECTION_VALUE_SUBTOTAL_WITH_DISCOUNT => Mage::helper('usa')->__('Subtotal With Discount'),
- ];
- }
-
- /**
- * Get additional protection rounding types
- *
- * @return array
- */
- public function getAdditionalProtectionRoundingTypes()
- {
- return [
- self::ADDITIONAL_PROTECTION_ROUNDING_FLOOR => Mage::helper('usa')->__('To Lower'),
- self::ADDITIONAL_PROTECTION_ROUNDING_CEIL => Mage::helper('usa')->__('To Upper'),
- self::ADDITIONAL_PROTECTION_ROUNDING_ROUND => Mage::helper('usa')->__('Round'),
- ];
- }
-
/**
* Map request to shipment
*/
@@ -1306,14 +1316,4 @@ protected function _doShipmentRequest(Varien_Object $request)
return $this->_doRequest();
}
-
- /**
- * Return container types of carrier
- *
- * @return array|bool
- */
- public function getContainerTypes(?Varien_Object $params = null)
- {
- return $this->getCode('shipment_type');
- }
}
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php
index 447bef796f1..741c5cd5675 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php
@@ -34,6 +34,11 @@ class Mage_Usa_Model_Shipping_Carrier_Dhl_International extends Mage_Usa_Model_S
public const DIMENSION_MIN_CM = 3;
public const DIMENSION_MIN_IN = 1;
+ /**
+ * Code of the carrier
+ */
+ public const CODE = 'dhlint';
+
/**
* Container types that could be customized
*
@@ -41,11 +46,6 @@ class Mage_Usa_Model_Shipping_Carrier_Dhl_International extends Mage_Usa_Model_S
*/
protected $_customizableContainerTypes = [self::DHL_CONTENT_TYPE_NON_DOC];
- /**
- * Code of the carrier
- */
- public const CODE = 'dhlint';
-
/**
* Rate request data
*
@@ -140,37 +140,6 @@ class Mage_Usa_Model_Shipping_Carrier_Dhl_International extends Mage_Usa_Model_S
*/
protected $_isDomestic = false;
- /**
- * Dhl International Class constructor
- *
- * Sets necessary data
- */
- protected function _construct()
- {
- if ($this->getConfigData('content_type') == self::DHL_CONTENT_TYPE_DOC) {
- $this->_freeMethod = 'free_method_doc';
- }
- }
-
- /**
- * Returns value of given variable
- *
- * @param mixed $origValue
- * @param string $pathToValue
- * @return mixed
- */
- protected function _getDefaultValue($origValue, $pathToValue)
- {
- if (!$origValue) {
- $origValue = Mage::getStoreConfig(
- $pathToValue,
- $this->getStore(),
- );
- }
-
- return $origValue;
- }
-
/**
* Collect and get rates
*
@@ -220,21 +189,6 @@ public function collectRates(Mage_Shipping_Model_Rate_Request $request)
return $this->_result;
}
- /**
- * Set Free Method Request
- *
- * @param string $freeMethod
- */
- protected function _setFreeMethodRequest($freeMethod)
- {
- $rawRequest = $this->_rawRequest;
-
- $rawRequest->setFreeMethodRequest(true);
- $freeWeight = $this->getTotalNumOfBoxes($rawRequest->getFreeMethodWeight());
- $rawRequest->setWeight($freeWeight);
- $rawRequest->setService($freeMethod);
- }
-
/**
* Returns request result
*
@@ -245,20 +199,6 @@ public function getResult()
return $this->_result;
}
- protected function _addParams($requestObject)
- {
- $request = $this->_request;
- foreach ($this->_requestVariables as $code => $objectCode) {
- if ($request->getDhlId()) {
- $value = $request->getData($objectCode['code']);
- } else {
- $value = $this->getConfigData($code);
- }
- $requestObject->setData($objectCode['setCode'], $value);
- }
- return $requestObject;
- }
-
/**
* Prepare and set request in property of current instance
*
@@ -526,6 +466,146 @@ public function getDhlProductTitle($code)
return $dhlProducts[$code] ?? false;
}
+ /**
+ * Processing additional validation to check is carrier applicable.
+ *
+ * @return Mage_Shipping_Model_Carrier_Abstract|Mage_Shipping_Model_Rate_Result_Error|bool
+ */
+ public function proccessAdditionalValidation(Mage_Shipping_Model_Rate_Request $request)
+ {
+ //Skip by item validation if there is no items in request
+ if (!count($this->getAllItems($request))) {
+ $this->_errors[] = Mage::helper('usa')->__('There is no items in this order');
+ }
+
+ $countryParams = $this->getCountryParams(
+ Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_COUNTRY_ID, $request->getStoreId()),
+ );
+ if (!$countryParams->getData()) {
+ $this->_errors[] = Mage::helper('usa')->__('Please, specify origin country');
+ }
+
+ if (!empty($this->_errors)) {
+ return $this->_showError();
+ }
+
+ return $this;
+ }
+
+ /**
+ * Return container types of carrier
+ *
+ * @return array
+ */
+ public function getContainerTypes(?Varien_Object $params = null)
+ {
+ return [
+ self::DHL_CONTENT_TYPE_DOC => Mage::helper('usa')->__('Documents'),
+ self::DHL_CONTENT_TYPE_NON_DOC => Mage::helper('usa')->__('Non Documents'),
+ ];
+ }
+
+ /**
+ * Get tracking
+ *
+ * @param mixed $trackings
+ * @return Mage_Shipping_Model_Rate_Result|null
+ */
+ public function getTracking($trackings)
+ {
+ if (!is_array($trackings)) {
+ $trackings = [$trackings];
+ }
+ $this->_getXMLTracking($trackings);
+
+ return $this->_result;
+ }
+
+ /**
+ * Do request to shipment
+ *
+ * @return Varien_Object
+ */
+ public function requestToShipment(Mage_Shipping_Model_Shipment_Request $request)
+ {
+ $packages = $request->getPackages();
+ if (!is_array($packages) || !$packages) {
+ Mage::throwException(Mage::helper('usa')->__('No packages for request'));
+ }
+ $result = $this->_doShipmentRequest($request);
+
+ $response = new Varien_Object([
+ 'info' => [[
+ 'tracking_number' => $result->getTrackingNumber(),
+ 'label_content' => $result->getShippingLabelContent(),
+ ]],
+ ]);
+
+ $request->setMasterTrackingId($result->getTrackingNumber());
+
+ return $response;
+ }
+
+ /**
+ * Dhl International Class constructor
+ *
+ * Sets necessary data
+ */
+ protected function _construct()
+ {
+ if ($this->getConfigData('content_type') == self::DHL_CONTENT_TYPE_DOC) {
+ $this->_freeMethod = 'free_method_doc';
+ }
+ }
+
+ /**
+ * Returns value of given variable
+ *
+ * @param mixed $origValue
+ * @param string $pathToValue
+ * @return mixed
+ */
+ protected function _getDefaultValue($origValue, $pathToValue)
+ {
+ if (!$origValue) {
+ $origValue = Mage::getStoreConfig(
+ $pathToValue,
+ $this->getStore(),
+ );
+ }
+
+ return $origValue;
+ }
+
+ /**
+ * Set Free Method Request
+ *
+ * @param string $freeMethod
+ */
+ protected function _setFreeMethodRequest($freeMethod)
+ {
+ $rawRequest = $this->_rawRequest;
+
+ $rawRequest->setFreeMethodRequest(true);
+ $freeWeight = $this->getTotalNumOfBoxes($rawRequest->getFreeMethodWeight());
+ $rawRequest->setWeight($freeWeight);
+ $rawRequest->setService($freeMethod);
+ }
+
+ protected function _addParams($requestObject)
+ {
+ $request = $this->_request;
+ foreach ($this->_requestVariables as $code => $objectCode) {
+ if ($request->getDhlId()) {
+ $value = $request->getData($objectCode['code']);
+ } else {
+ $value = $this->getConfigData($code);
+ }
+ $requestObject->setData($objectCode['setCode'], $value);
+ }
+ return $requestObject;
+ }
+
/**
* Convert item weight to needed weight based on config weight unit dimensions
*
@@ -1115,32 +1195,6 @@ protected function _doShipmentRequest(Varien_Object $request)
return $this->_doRequest();
}
- /**
- * Processing additional validation to check is carrier applicable.
- *
- * @return Mage_Shipping_Model_Carrier_Abstract|Mage_Shipping_Model_Rate_Result_Error|bool
- */
- public function proccessAdditionalValidation(Mage_Shipping_Model_Rate_Request $request)
- {
- //Skip by item validation if there is no items in request
- if (!count($this->getAllItems($request))) {
- $this->_errors[] = Mage::helper('usa')->__('There is no items in this order');
- }
-
- $countryParams = $this->getCountryParams(
- Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_COUNTRY_ID, $request->getStoreId()),
- );
- if (!$countryParams->getData()) {
- $this->_errors[] = Mage::helper('usa')->__('Please, specify origin country');
- }
-
- if (!empty($this->_errors)) {
- return $this->_showError();
- }
-
- return $this;
- }
-
/**
* Show default error
*
@@ -1163,19 +1217,6 @@ protected function _showError()
}
}
- /**
- * Return container types of carrier
- *
- * @return array
- */
- public function getContainerTypes(?Varien_Object $params = null)
- {
- return [
- self::DHL_CONTENT_TYPE_DOC => Mage::helper('usa')->__('Documents'),
- self::DHL_CONTENT_TYPE_NON_DOC => Mage::helper('usa')->__('Non Documents'),
- ];
- }
-
/**
* Map request to shipment
*/
@@ -1522,22 +1563,6 @@ protected function _shipmentDetails($xml, $rawRequest, $originRegion = '')
}
}
- /**
- * Get tracking
- *
- * @param mixed $trackings
- * @return Mage_Shipping_Model_Rate_Result|null
- */
- public function getTracking($trackings)
- {
- if (!is_array($trackings)) {
- $trackings = [$trackings];
- }
- $this->_getXMLTracking($trackings);
-
- return $this->_result;
- }
-
/**
* Send request for tracking
*
@@ -1717,31 +1742,6 @@ protected function _getPerpackagePrice($cost, $handlingType, $handlingFee)
return $cost + $this->_numBoxes * $handlingFee;
}
- /**
- * Do request to shipment
- *
- * @return Varien_Object
- */
- public function requestToShipment(Mage_Shipping_Model_Shipment_Request $request)
- {
- $packages = $request->getPackages();
- if (!is_array($packages) || !$packages) {
- Mage::throwException(Mage::helper('usa')->__('No packages for request'));
- }
- $result = $this->_doShipmentRequest($request);
-
- $response = new Varien_Object([
- 'info' => [[
- 'tracking_number' => $result->getTrackingNumber(),
- 'label_content' => $result->getShippingLabelContent(),
- ]],
- ]);
-
- $request->setMasterTrackingId($result->getTrackingNumber());
-
- return $response;
- }
-
/**
* Check if shipping is domestic
*
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/Label/Pdf/PageBuilder.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/Label/Pdf/PageBuilder.php
index 79634a09e8f..a2b5dd7f836 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/Label/Pdf/PageBuilder.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/Label/Pdf/PageBuilder.php
@@ -73,30 +73,6 @@ public function setPage(Zend_Pdf_Page $page)
return $this;
}
- /**
- * Calculate x coordinate with indentation
- *
- * @param int $pt
- * @return int
- * @SuppressWarnings("PHPMD.ShortMethodName")
- */
- protected function _x($pt)
- {
- return $pt + self::X_INDENT;
- }
-
- /**
- * Calculate y coordinate with indentation
- *
- * @param int $pt
- * @return int
- * @SuppressWarnings("PHPMD.ShortMethodName")
- */
- protected function _y($pt)
- {
- return 595 - self::Y_INDENT - $pt;
- }
-
/**
* Add Border
*
@@ -280,37 +256,6 @@ public function addSenderInfo(SimpleXMLElement $sender)
return $this;
}
- /**
- * Draw Sender Address
- *
- * @param string $phoneNumber
- * @return float
- */
- protected function _drawSenderAddress(SimpleXMLElement $addressLines, $phoneNumber)
- {
- $lines = [];
- foreach ($addressLines as $line) {
- $lines [] = $line;
- }
-
- $pageY = 0;
- if (strlen($lines[0]) > 28) {
- $firstLine = array_shift($lines);
- $pageY = $this->_page->drawLines([$firstLine], $this->_x(25), $this->_y(42), 28);
- $this->_page->drawText($phoneNumber, $this->_x(103), $this->_y(42));
- } else {
- $pageY = $this->_y(42);
- $lineLength = $this->_page->getTextWidth(
- $lines[0] . ' ',
- $this->_page->getFont(),
- $this->_page->getFontSize(),
- );
- $this->_page->drawText($phoneNumber, $this->_x(25 + $lineLength), $this->_y(42));
- }
-
- return $this->_page->drawLines($lines, $this->_x(25), $pageY, 49);
- }
-
/**
* Add Origin Info
*
@@ -656,4 +601,59 @@ public function addPieceNumber($pieceNumber, $piecesTotal)
$this->_page->restoreGS();
return $this;
}
+
+ /**
+ * Calculate x coordinate with indentation
+ *
+ * @param int $pt
+ * @return int
+ * @SuppressWarnings("PHPMD.ShortMethodName")
+ */
+ protected function _x($pt)
+ {
+ return $pt + self::X_INDENT;
+ }
+
+ /**
+ * Calculate y coordinate with indentation
+ *
+ * @param int $pt
+ * @return int
+ * @SuppressWarnings("PHPMD.ShortMethodName")
+ */
+ protected function _y($pt)
+ {
+ return 595 - self::Y_INDENT - $pt;
+ }
+
+ /**
+ * Draw Sender Address
+ *
+ * @param string $phoneNumber
+ * @return float
+ */
+ protected function _drawSenderAddress(SimpleXMLElement $addressLines, $phoneNumber)
+ {
+ $lines = [];
+ foreach ($addressLines as $line) {
+ $lines [] = $line;
+ }
+
+ $pageY = 0;
+ if (strlen($lines[0]) > 28) {
+ $firstLine = array_shift($lines);
+ $pageY = $this->_page->drawLines([$firstLine], $this->_x(25), $this->_y(42), 28);
+ $this->_page->drawText($phoneNumber, $this->_x(103), $this->_y(42));
+ } else {
+ $pageY = $this->_y(42);
+ $lineLength = $this->_page->getTextWidth(
+ $lines[0] . ' ',
+ $this->_page->getFont(),
+ $this->_page->getFontSize(),
+ );
+ $this->_page->drawText($phoneNumber, $this->_x(25 + $lineLength), $this->_y(42));
+ }
+
+ return $this->_page->drawLines($lines, $this->_x(25), $pageY, 49);
+ }
}
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php
index 1912f9f3307..26d245d955c 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php
@@ -108,55 +108,6 @@ public function __construct()
$this->_trackServiceWsdl = $wsdlBasePath . 'TrackService_v5.wsdl';
}
- /**
- * Create soap client with selected wsdl
- *
- * @param string $wsdl
- * @param bool|int $trace
- * @return SoapClient
- */
- protected function _createSoapClient($wsdl, $trace = false)
- {
- $client = new SoapClient($wsdl, ['trace' => $trace]);
- $client->__setLocation(
- $this->getConfigFlag('sandbox_mode')
- ? 'https://wsbeta.fedex.com:443/web-services'
- : 'https://ws.fedex.com:443/web-services',
- );
-
- return $client;
- }
-
- /**
- * Create rate soap client
- *
- * @return SoapClient
- */
- protected function _createRateSoapClient()
- {
- return $this->_createSoapClient($this->_rateServiceWsdl);
- }
-
- /**
- * Create ship soap client
- *
- * @return SoapClient
- */
- protected function _createShipSoapClient()
- {
- return $this->_createSoapClient($this->_shipServiceWsdl, 1);
- }
-
- /**
- * Create track soap client
- *
- * @return SoapClient
- */
- protected function _createTrackSoapClient()
- {
- return $this->_createSoapClient($this->_trackServiceWsdl, 1);
- }
-
/**
* Collect and get rates
*
@@ -290,677 +241,853 @@ public function getVersionInfo()
}
/**
- * Forming request for rate estimation depending to the purpose
+ * Get configuration data of carrier
*
- * @param string $purpose
- * @return array
+ * @param string $type
+ * @param string $code
+ * @return array|bool
*/
- protected function _formRateRequest($purpose)
+ public function getCode($type, $code = '')
{
- $r = $this->_rawRequest;
- $ratesRequest = [
- 'WebAuthenticationDetail' => [
- 'UserCredential' => [
- 'Key' => $r->getKey(),
- 'Password' => $r->getPassword(),
- ],
+ $codes = [
+ 'method' => [
+ 'EUROPE_FIRST_INTERNATIONAL_PRIORITY' => Mage::helper('usa')->__('Europe First Priority'),
+ 'FEDEX_1_DAY_FREIGHT' => Mage::helper('usa')->__('1 Day Freight'),
+ 'FEDEX_2_DAY_FREIGHT' => Mage::helper('usa')->__('2 Day Freight'),
+ 'FEDEX_2_DAY' => Mage::helper('usa')->__('2 Day'),
+ 'FEDEX_2_DAY_AM' => Mage::helper('usa')->__('2 Day AM'),
+ 'FEDEX_3_DAY_FREIGHT' => Mage::helper('usa')->__('3 Day Freight'),
+ 'FEDEX_EXPRESS_SAVER' => Mage::helper('usa')->__('Express Saver'),
+ 'FEDEX_GROUND' => Mage::helper('usa')->__('Ground'),
+ 'FIRST_OVERNIGHT' => Mage::helper('usa')->__('First Overnight'),
+ 'GROUND_HOME_DELIVERY' => Mage::helper('usa')->__('Home Delivery'),
+ 'INTERNATIONAL_ECONOMY' => Mage::helper('usa')->__('International Economy'),
+ 'INTERNATIONAL_ECONOMY_FREIGHT' => Mage::helper('usa')->__('Intl Economy Freight'),
+ 'INTERNATIONAL_FIRST' => Mage::helper('usa')->__('International First'),
+ 'INTERNATIONAL_GROUND' => Mage::helper('usa')->__('International Ground'),
+ 'INTERNATIONAL_PRIORITY' => Mage::helper('usa')->__('International Priority'),
+ 'INTERNATIONAL_PRIORITY_FREIGHT' => Mage::helper('usa')->__('Intl Priority Freight'),
+ 'PRIORITY_OVERNIGHT' => Mage::helper('usa')->__('Priority Overnight'),
+ 'SMART_POST' => Mage::helper('usa')->__('Smart Post'),
+ 'STANDARD_OVERNIGHT' => Mage::helper('usa')->__('Standard Overnight'),
+ 'FEDEX_FREIGHT' => Mage::helper('usa')->__('Freight'),
+ 'FEDEX_NATIONAL_FREIGHT' => Mage::helper('usa')->__('National Freight'),
],
- 'ClientDetail' => [
- 'AccountNumber' => $r->getAccount(),
- 'MeterNumber' => $r->getMeterNumber(),
+ 'dropoff' => [
+ 'REGULAR_PICKUP' => Mage::helper('usa')->__('Regular Pickup'),
+ 'REQUEST_COURIER' => Mage::helper('usa')->__('Request Courier'),
+ 'DROP_BOX' => Mage::helper('usa')->__('Drop Box'),
+ 'BUSINESS_SERVICE_CENTER' => Mage::helper('usa')->__('Business Service Center'),
+ 'STATION' => Mage::helper('usa')->__('Station'),
],
- 'Version' => $this->getVersionInfo(),
- 'RequestedShipment' => [
- 'DropoffType' => $r->getDropoffType(),
- 'ShipTimestamp' => date('c'),
- 'PackagingType' => $r->getPackaging(),
- 'TotalInsuredValue' => [
- 'Amount' => $r->getValue(),
- 'Currency' => $this->getCurrencyCode(),
- ],
- 'Shipper' => [
- 'Address' => [
- 'PostalCode' => $r->getOrigPostal(),
- 'CountryCode' => $r->getOrigCountry(),
- ],
- ],
- 'Recipient' => [
- 'Address' => [
- 'PostalCode' => $r->getDestPostal(),
- 'CountryCode' => $r->getDestCountry(),
- 'Residential' => (bool) $this->getConfigData('residence_delivery'),
+ 'packaging' => [
+ 'FEDEX_ENVELOPE' => Mage::helper('usa')->__('FedEx Envelope'),
+ 'FEDEX_PAK' => Mage::helper('usa')->__('FedEx Pak'),
+ 'FEDEX_BOX' => Mage::helper('usa')->__('FedEx Box'),
+ 'FEDEX_TUBE' => Mage::helper('usa')->__('FedEx Tube'),
+ 'FEDEX_10KG_BOX' => Mage::helper('usa')->__('FedEx 10kg Box'),
+ 'FEDEX_25KG_BOX' => Mage::helper('usa')->__('FedEx 25kg Box'),
+ 'YOUR_PACKAGING' => Mage::helper('usa')->__('Your Packaging'),
+ ],
+ 'containers_filter' => [
+ [
+ 'containers' => ['FEDEX_ENVELOPE', 'FEDEX_PAK'],
+ 'filters' => [
+ 'within_us' => [
+ 'method' => [
+ 'FEDEX_EXPRESS_SAVER',
+ 'FEDEX_2_DAY',
+ 'FEDEX_2_DAY_AM',
+ 'STANDARD_OVERNIGHT',
+ 'PRIORITY_OVERNIGHT',
+ 'FIRST_OVERNIGHT',
+ ],
+ ],
+ 'from_us' => [
+ 'method' => [
+ 'INTERNATIONAL_FIRST',
+ 'INTERNATIONAL_ECONOMY',
+ 'INTERNATIONAL_PRIORITY',
+ ],
+ ],
],
],
- 'ShippingChargesPayment' => [
- 'PaymentType' => 'SENDER',
- 'Payor' => [
- 'AccountNumber' => $r->getAccount(),
- 'CountryCode' => $r->getOrigCountry(),
+ [
+ 'containers' => ['FEDEX_BOX', 'FEDEX_TUBE'],
+ 'filters' => [
+ 'within_us' => [
+ 'method' => [
+ 'FEDEX_2_DAY',
+ 'FEDEX_2_DAY_AM',
+ 'STANDARD_OVERNIGHT',
+ 'PRIORITY_OVERNIGHT',
+ 'FIRST_OVERNIGHT',
+ 'FEDEX_FREIGHT',
+ 'FEDEX_1_DAY_FREIGHT',
+ 'FEDEX_2_DAY_FREIGHT',
+ 'FEDEX_3_DAY_FREIGHT',
+ 'FEDEX_NATIONAL_FREIGHT',
+ ],
+ ],
+ 'from_us' => [
+ 'method' => [
+ 'INTERNATIONAL_FIRST',
+ 'INTERNATIONAL_ECONOMY',
+ 'INTERNATIONAL_PRIORITY',
+ ],
+ ],
],
],
- 'CustomsClearanceDetail' => [
- 'CustomsValue' => [
- 'Amount' => $r->getValue(),
- 'Currency' => $this->getCurrencyCode(),
+ [
+ 'containers' => ['FEDEX_10KG_BOX', 'FEDEX_25KG_BOX'],
+ 'filters' => [
+ 'within_us' => [],
+ 'from_us' => ['method' => ['INTERNATIONAL_PRIORITY']],
],
],
- 'RateRequestTypes' => 'LIST',
- 'PackageCount' => '1',
- 'PackageDetail' => 'INDIVIDUAL_PACKAGES',
- 'RequestedPackageLineItems' => [
- '0' => [
- 'Weight' => [
- 'Value' => (float) $r->getWeight(),
- 'Units' => $this->getConfigData('unit_of_measure'),
+ [
+ 'containers' => ['YOUR_PACKAGING'],
+ 'filters' => [
+ 'within_us' => [
+ 'method' => [
+ 'FEDEX_GROUND',
+ 'GROUND_HOME_DELIVERY',
+ 'SMART_POST',
+ 'FEDEX_EXPRESS_SAVER',
+ 'FEDEX_2_DAY',
+ 'FEDEX_2_DAY_AM',
+ 'STANDARD_OVERNIGHT',
+ 'PRIORITY_OVERNIGHT',
+ 'FIRST_OVERNIGHT',
+ 'FEDEX_FREIGHT',
+ 'FEDEX_1_DAY_FREIGHT',
+ 'FEDEX_2_DAY_FREIGHT',
+ 'FEDEX_3_DAY_FREIGHT',
+ 'FEDEX_NATIONAL_FREIGHT',
+ ],
+ ],
+ 'from_us' => [
+ 'method' => [
+ 'INTERNATIONAL_FIRST',
+ 'INTERNATIONAL_ECONOMY',
+ 'INTERNATIONAL_PRIORITY',
+ 'INTERNATIONAL_GROUND',
+ 'FEDEX_FREIGHT',
+ 'FEDEX_1_DAY_FREIGHT',
+ 'FEDEX_2_DAY_FREIGHT',
+ 'FEDEX_3_DAY_FREIGHT',
+ 'FEDEX_NATIONAL_FREIGHT',
+ 'INTERNATIONAL_ECONOMY_FREIGHT',
+ 'INTERNATIONAL_PRIORITY_FREIGHT',
+ ],
],
- 'GroupPackageCount' => 1,
],
],
],
+
+ 'delivery_confirmation_types' => [
+ 'NO_SIGNATURE_REQUIRED' => Mage::helper('usa')->__('Not Required'),
+ 'ADULT' => Mage::helper('usa')->__('Adult'),
+ 'DIRECT' => Mage::helper('usa')->__('Direct'),
+ 'INDIRECT' => Mage::helper('usa')->__('Indirect'),
+ ],
+
+ 'unit_of_measure' => [
+ 'LB' => Mage::helper('usa')->__('Pounds'),
+ 'KG' => Mage::helper('usa')->__('Kilograms'),
+ ],
];
- if ($purpose == self::RATE_REQUEST_GENERAL) {
- $ratesRequest['RequestedShipment']['RequestedPackageLineItems'][0]['InsuredValue'] = [
- 'Amount' => $r->getValue(),
- 'Currency' => $this->getCurrencyCode(),
- ];
- } elseif ($purpose == self::RATE_REQUEST_SMARTPOST) {
- $ratesRequest['RequestedShipment']['ServiceType'] = self::RATE_REQUEST_SMARTPOST;
- $ratesRequest['RequestedShipment']['SmartPostDetail'] = [
- 'Indicia' => ((float) $r->getWeight() >= 1) ? 'PARCEL_SELECT' : 'PRESORTED_STANDARD',
- 'HubId' => $this->getConfigData('smartpost_hubid'),
- ];
+ if (!isset($codes[$type])) {
+ return false;
+ } elseif ($code === '') {
+ return $codes[$type];
}
- return $ratesRequest;
+ return $codes[$type][$code] ?? false;
}
/**
- * Makes remote request to the carrier and returns a response
+ * Return FeDex currency ISO code by Magento Base Currency Code
*
- * @param string $purpose
- * @return mixed
+ * @return string 3-digit currency code
*/
- protected function _doRatesRequest($purpose)
+ public function getCurrencyCode()
{
- $ratesRequest = $this->_formRateRequest($purpose);
- $requestString = serialize($ratesRequest);
- $response = $this->_getCachedQuotes($requestString);
- $debugData = ['request' => $ratesRequest];
- if ($response === null) {
- try {
- $client = $this->_createRateSoapClient();
- $response = $client->getRates($ratesRequest);
- $this->_setCachedQuotes($requestString, serialize($response));
- $debugData['result'] = $response;
- } catch (Exception $e) {
- $debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
- Mage::logException($e);
- }
- } else {
- $response = unserialize($response);
- $debugData['result'] = $response;
- }
- $this->_debug($debugData);
- return $response;
+ $codes = [
+ 'DOP' => 'RDD', // Dominican Peso
+ 'XCD' => 'ECD', // Caribbean Dollars
+ 'ARS' => 'ARN', // Argentina Peso
+ 'SGD' => 'SID', // Singapore Dollars
+ 'KRW' => 'WON', // South Korea Won
+ 'JMD' => 'JAD', // Jamaican Dollars
+ 'CHF' => 'SFR', // Swiss Francs
+ 'JPY' => 'JYE', // Japanese Yen
+ 'KWD' => 'KUD', // Kuwaiti Dinars
+ 'GBP' => 'UKL', // British Pounds
+ 'AED' => 'DHS', // UAE Dirhams
+ 'MXN' => 'NMP', // Mexican Pesos
+ 'UYU' => 'UYP', // Uruguay New Pesos
+ 'CLP' => 'CHP', // Chilean Pesos
+ 'TWD' => 'NTD', // New Taiwan Dollars
+ ];
+ $currencyCode = Mage::app()->getStore()->getBaseCurrencyCode();
+ return $codes[$currencyCode] ?? $currencyCode;
}
/**
- * Do remote request for and handle errors
+ * Get tracking
*
- * @return Mage_Shipping_Model_Rate_Result
+ * @param mixed $trackings
+ * @return Mage_Shipping_Model_Rate_Result|null
*/
- protected function _getQuotes()
+ public function getTracking($trackings)
{
- $this->_result = Mage::getModel('shipping/rate_result');
- $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
- if (in_array(self::RATE_REQUEST_SMARTPOST, $allowedMethods)) {
- $response = $this->_doRatesRequest(self::RATE_REQUEST_SMARTPOST);
- $preparedSmartpost = $this->_prepareRateResponse($response);
- $this->_result->append($preparedSmartpost);
- }
- $response = $this->_doRatesRequest(self::RATE_REQUEST_GENERAL);
- $preparedGeneral = $this->_prepareRateResponse($response);
- if ($this->_result->getError() && $preparedGeneral->getError()) {
- return $this->_result->getError();
- }
- $this->_result->append($preparedGeneral);
- $this->_removeErrorsIfRateExist();
-
- return $this->_result;
- }
+ $this->setTrackingReqeust();
- /**
- * Remove Errors in Case When Rate Exist
- *
- * @return Mage_Shipping_Model_Rate_Result
- */
- protected function _removeErrorsIfRateExist()
- {
- $rateResultExist = false;
- $rates = [];
- foreach ($this->_result->getAllRates() as $rate) {
- if (!($rate instanceof Mage_Shipping_Model_Rate_Result_Error)) {
- $rateResultExist = true;
- $rates[] = $rate;
- }
+ if (!is_array($trackings)) {
+ $trackings = [$trackings];
}
- if ($rateResultExist) {
- $this->_result->reset();
- $this->_result->setError(false);
- foreach ($rates as $rate) {
- $this->_result->append($rate);
- }
+ foreach ($trackings as $tracking) {
+ $this->_getXMLTracking($tracking);
}
return $this->_result;
}
/**
- * Prepare shipping rate result based on response
+ * Get tracking response
*
- * @param mixed $response
- * @return Mage_Shipping_Model_Rate_Result
+ * @return string
*/
- protected function _prepareRateResponse($response)
+ public function getResponse()
{
- $costArr = [];
- $priceArr = [];
- $errorTitle = 'Unable to retrieve tracking';
-
- if (is_object($response)) {
- if ($response->HighestSeverity == 'FAILURE' || $response->HighestSeverity == 'ERROR') {
- if (is_array($response->Notifications)) {
- $notification = array_pop($response->Notifications);
- $errorTitle = (string) $notification->Message;
- } else {
- $errorTitle = (string) $response->Notifications->Message;
- }
- } elseif (isset($response->RateReplyDetails)) {
- $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
-
- if (is_array($response->RateReplyDetails)) {
- foreach ($response->RateReplyDetails as $rate) {
- $serviceName = (string) $rate->ServiceType;
- if (in_array($serviceName, $allowedMethods)) {
- $amount = $this->_getRateAmountOriginBased($rate);
- $costArr[$serviceName] = $amount;
- $priceArr[$serviceName] = $this->getMethodPrice($amount, $serviceName);
+ $statuses = '';
+ if ($this->_result instanceof Mage_Shipping_Model_Tracking_Result) {
+ if ($trackings = $this->_result->getAllTrackings()) {
+ foreach ($trackings as $tracking) {
+ if ($data = $tracking->getAllData()) {
+ if (!empty($data['status'])) {
+ $statuses .= Mage::helper('usa')->__($data['status']) . "\n
";
+ } else {
+ $statuses .= Mage::helper('usa')->__('Empty response') . "\n
";
}
}
- asort($priceArr);
- } else {
- $rate = $response->RateReplyDetails;
- $serviceName = (string) $rate->ServiceType;
- if (in_array($serviceName, $allowedMethods)) {
- $amount = $this->_getRateAmountOriginBased($rate);
- $costArr[$serviceName] = $amount;
- $priceArr[$serviceName] = $this->getMethodPrice($amount, $serviceName);
- }
}
}
}
-
- $result = Mage::getModel('shipping/rate_result');
- if (empty($priceArr)) {
- $error = Mage::getModel('shipping/rate_result_error');
- $error->setCarrier($this->_code);
- $error->setCarrierTitle($this->getConfigData('title'));
- $error->setErrorMessage($errorTitle);
- $error->setErrorMessage($this->getConfigData('specificerrmsg'));
- $result->append($error);
- } else {
- foreach ($priceArr as $method => $price) {
- $rate = Mage::getModel('shipping/rate_result_method');
- $rate->setCarrier($this->_code);
- $rate->setCarrierTitle($this->getConfigData('title'));
- $rate->setMethod($method);
- $rate->setMethodTitle($this->getCode('method', $method));
- $rate->setCost($costArr[$method]);
- $rate->setPrice($price);
- $result->append($rate);
- }
+ if (empty($statuses)) {
+ $statuses = Mage::helper('usa')->__('Empty response');
}
- return $result;
+ return $statuses;
}
/**
- * Get origin based amount form response of rate estimation
+ * Get allowed shipping methods
*
- * @param stdClass $rate
- * @return null|float
+ * @return array
*/
- protected function _getRateAmountOriginBased($rate)
+ public function getAllowedMethods()
{
- $amount = null;
- $rateTypeAmounts = [];
-
- if (is_object($rate)) {
- // The "RATED..." rates are expressed in the currency of the origin country
- foreach ($rate->RatedShipmentDetails as $ratedShipmentDetail) {
- $netAmount = (string) $ratedShipmentDetail->ShipmentRateDetail->TotalNetCharge->Amount;
- $rateType = (string) $ratedShipmentDetail->ShipmentRateDetail->RateType;
- $rateTypeAmounts[$rateType] = $netAmount;
- }
-
- // Order is important
- $ratesOrder = [
- 'RATED_ACCOUNT_PACKAGE',
- 'PAYOR_ACCOUNT_PACKAGE',
- 'RATED_ACCOUNT_SHIPMENT',
- 'PAYOR_ACCOUNT_SHIPMENT',
- 'RATED_LIST_PACKAGE',
- 'PAYOR_LIST_PACKAGE',
- 'RATED_LIST_SHIPMENT',
- 'PAYOR_LIST_SHIPMENT',
- ];
- foreach ($ratesOrder as $rateType) {
- if (!empty($rateTypeAmounts[$rateType])) {
- $amount = $rateTypeAmounts[$rateType];
- break;
- }
- }
-
- if (is_null($amount)) {
- $amount = (string) $rate->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;
- }
+ $allowed = explode(',', $this->getConfigData('allowed_methods'));
+ $arr = [];
+ foreach ($allowed as $k) {
+ $arr[$k] = $this->getCode('method', $k);
}
-
- return $amount;
+ return $arr;
}
/**
- * Set free method request
+ * For multi package shipments. Delete requested shipments if the current shipment
+ * request is failed
*
- * @param $freeMethod
+ * @param array $data
+ * @return bool
*/
- protected function _setFreeMethodRequest($freeMethod)
+ public function rollBack($data)
{
- $r = $this->_rawRequest;
- $weight = $this->getTotalNumOfBoxes($r->getFreeMethodWeight());
- $r->setWeight($weight);
- $r->setService($freeMethod);
+ $requestData = $this->_getAuthDetails();
+ $requestData['DeletionControl'] = 'DELETE_ONE_PACKAGE';
+ foreach ($data as &$item) {
+ $requestData['TrackingId'] = $item['tracking_number'];
+ $client = $this->_createShipSoapClient();
+ $client->deleteShipment($requestData);
+ }
+ return true;
}
/**
- * Get xml quotes
+ * Return container types of carrier
*
- * @deprecated
- * @return Mage_Shipping_Model_Rate_Result
+ * @return array|bool
*/
- protected function _getXmlQuotes()
+ public function getContainerTypes(?Varien_Object $params = null)
{
- $r = $this->_rawRequest;
- $xml = new SimpleXMLElement('');
-
- $xml->addAttribute('xmlns:api', 'http://www.fedex.com/fsmapi');
- $xml->addAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
- $xml->addAttribute('xsi:noNamespaceSchemaLocation', 'FDXRateAvailableServicesRequest.xsd');
+ if ($params == null) {
+ return $this->_getAllowedContainers($params);
+ }
+ $method = $params->getMethod();
+ $countryShipper = $params->getCountryShipper();
+ $countryRecipient = $params->getCountryRecipient();
- $requestHeader = $xml->addChild('RequestHeader');
- $requestHeader->addChild('AccountNumber', $r->getAccount());
- $requestHeader->addChild('MeterNumber', '0');
-
- $xml->addChild('ShipDate', date('Y-m-d'));
- $xml->addChild('DropoffType', $r->getDropoffType());
- if ($r->hasService()) {
- $xml->addChild('Service', $r->getService());
- }
- $xml->addChild('Packaging', $r->getPackaging());
- $xml->addChild('WeightUnits', 'LBS');
- $xml->addChild('Weight', $r->getWeight());
-
- $originAddress = $xml->addChild('OriginAddress');
- $originAddress->addChild('PostalCode', $r->getOrigPostal());
- $originAddress->addChild('CountryCode', $r->getOrigCountry());
-
- $destinationAddress = $xml->addChild('DestinationAddress');
- $destinationAddress->addChild('PostalCode', $r->getDestPostal());
- $destinationAddress->addChild('CountryCode', $r->getDestCountry());
-
- $payment = $xml->addChild('Payment');
- $payment->addChild('PayorType', 'SENDER');
-
- $declaredValue = $xml->addChild('DeclaredValue');
- $declaredValue->addChild('Value', $r->getValue());
- $declaredValue->addChild('CurrencyCode', $this->getCurrencyCode());
-
- if ($this->getConfigData('residence_delivery')) {
- $specialServices = $xml->addChild('SpecialServices');
- $specialServices->addChild('ResidentialDelivery', 'true');
+ if (($countryShipper == self::USA_COUNTRY_ID && $countryRecipient == self::CANADA_COUNTRY_ID
+ || $countryShipper == self::CANADA_COUNTRY_ID && $countryRecipient == self::USA_COUNTRY_ID)
+ && $method == 'FEDEX_GROUND'
+ ) {
+ return ['YOUR_PACKAGING' => Mage::helper('usa')->__('Your Packaging')];
+ } elseif ($method == 'INTERNATIONAL_ECONOMY' || $method == 'INTERNATIONAL_FIRST') {
+ $allTypes = $this->getContainerTypesAll();
+ $exclude = ['FEDEX_10KG_BOX' => '', 'FEDEX_25KG_BOX' => ''];
+ return array_diff_key($allTypes, $exclude);
+ } elseif ($method == 'EUROPE_FIRST_INTERNATIONAL_PRIORITY') {
+ $allTypes = $this->getContainerTypesAll();
+ $exclude = ['FEDEX_BOX' => '', 'FEDEX_TUBE' => ''];
+ return array_diff_key($allTypes, $exclude);
+ } elseif ($countryShipper == self::CANADA_COUNTRY_ID && $countryRecipient == self::CANADA_COUNTRY_ID) {
+ // hack for Canada domestic. Apply the same filter rules as for US domestic
+ $params->setCountryShipper(self::USA_COUNTRY_ID);
+ $params->setCountryRecipient(self::USA_COUNTRY_ID);
}
- $xml->addChild('PackageCount', '1');
-
- $request = $xml->asXML();
-
- $responseBody = $this->_getCachedQuotes($request);
- if ($responseBody === null) {
- $debugData = ['request' => $request];
- try {
- $url = $this->getConfigData('gateway_url');
- if (!$url) {
- $url = $this->_defaultGatewayUrl;
- }
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
- $responseBody = curl_exec($ch);
- curl_close($ch);
+ return $this->_getAllowedContainers($params);
+ }
- $debugData['result'] = $responseBody;
- $this->_setCachedQuotes($request, $responseBody);
- } catch (Exception $e) {
- $debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
- $responseBody = '';
- }
- $this->_debug($debugData);
- }
- return $this->_parseXmlResponse($responseBody);
+ /**
+ * Return all container types of carrier
+ *
+ * @return array|bool
+ */
+ public function getContainerTypesAll()
+ {
+ return $this->getCode('packaging');
}
/**
- * Prepare shipping rate result based on response
+ * Return structured data of containers witch related with shipping methods
*
- * @param mixed $response
- * @return Mage_Shipping_Model_Rate_Result
+ * @return array|bool
*/
- protected function _parseXmlResponse($response)
+ public function getContainerTypesFilter()
{
- $costArr = [];
- $priceArr = [];
+ return $this->getCode('containers_filter');
+ }
- if (strlen(trim($response)) > 0) {
- if ($xml = $this->_parseXml($response)) {
- if (is_object($xml->Error) && is_object($xml->Error->Message)) {
- $errorTitle = (string) $xml->Error->Message;
- } elseif (is_object($xml->SoftError) && is_object($xml->SoftError->Message)) {
- $errorTitle = (string) $xml->SoftError->Message;
- } else {
- $errorTitle = 'Unknown error';
- }
+ /**
+ * Return delivery confirmation types of carrier
+ *
+ * @return array
+ */
+ public function getDeliveryConfirmationTypes(?Varien_Object $params = null)
+ {
+ return $this->getCode('delivery_confirmation_types');
+ }
- $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
+ /**
+ * Create soap client with selected wsdl
+ *
+ * @param string $wsdl
+ * @param bool|int $trace
+ * @return SoapClient
+ */
+ protected function _createSoapClient($wsdl, $trace = false)
+ {
+ $client = new SoapClient($wsdl, ['trace' => $trace]);
+ $client->__setLocation(
+ $this->getConfigFlag('sandbox_mode')
+ ? 'https://wsbeta.fedex.com:443/web-services'
+ : 'https://ws.fedex.com:443/web-services',
+ );
- foreach ($xml->Entry as $entry) {
- if (in_array((string) $entry->Service, $allowedMethods)) {
- $costArr[(string) $entry->Service] =
- (string) $entry->EstimatedCharges->DiscountedCharges->NetCharge;
- $priceArr[(string) $entry->Service] = $this->getMethodPrice(
- (float) $entry->EstimatedCharges->DiscountedCharges->NetCharge,
- (string) $entry->Service,
- );
- }
- }
+ return $client;
+ }
- asort($priceArr);
- } else {
- $errorTitle = 'Response is in the wrong format.';
- }
- } else {
- $errorTitle = 'Unable to retrieve tracking';
- }
+ /**
+ * Create rate soap client
+ *
+ * @return SoapClient
+ */
+ protected function _createRateSoapClient()
+ {
+ return $this->_createSoapClient($this->_rateServiceWsdl);
+ }
- $result = Mage::getModel('shipping/rate_result');
- if (empty($priceArr)) {
- $error = Mage::getModel('shipping/rate_result_error');
- $error->setCarrier('fedex');
- $error->setCarrierTitle($this->getConfigData('title'));
- $error->setErrorMessage($this->getConfigData('specificerrmsg'));
- $result->append($error);
- } else {
- foreach ($priceArr as $method => $price) {
- $rate = Mage::getModel('shipping/rate_result_method');
- $rate->setCarrier('fedex');
- $rate->setCarrierTitle($this->getConfigData('title'));
- $rate->setMethod($method);
- $rate->setMethodTitle($this->getCode('method', $method));
- $rate->setCost($costArr[$method]);
- $rate->setPrice($price);
- $result->append($rate);
- }
- }
- return $result;
+ /**
+ * Create ship soap client
+ *
+ * @return SoapClient
+ */
+ protected function _createShipSoapClient()
+ {
+ return $this->_createSoapClient($this->_shipServiceWsdl, 1);
}
/**
- * Parse XML string and return XML document object or false
+ * Create track soap client
*
- * @param string $xmlContent
- * @return SimpleXMLElement|bool
+ * @return SoapClient
*/
- protected function _parseXml($xmlContent)
+ protected function _createTrackSoapClient()
{
- try {
- try {
- return simplexml_load_string($xmlContent);
- } catch (Exception $e) {
- throw new Exception(Mage::helper('usa')->__('Failed to parse xml document: %s', $xmlContent));
- }
- } catch (Exception $e) {
- Mage::logException($e);
- return false;
- }
+ return $this->_createSoapClient($this->_trackServiceWsdl, 1);
}
/**
- * Get configuration data of carrier
+ * Forming request for rate estimation depending to the purpose
*
- * @param string $type
- * @param string $code
- * @return array|bool
+ * @param string $purpose
+ * @return array
*/
- public function getCode($type, $code = '')
+ protected function _formRateRequest($purpose)
{
- $codes = [
- 'method' => [
- 'EUROPE_FIRST_INTERNATIONAL_PRIORITY' => Mage::helper('usa')->__('Europe First Priority'),
- 'FEDEX_1_DAY_FREIGHT' => Mage::helper('usa')->__('1 Day Freight'),
- 'FEDEX_2_DAY_FREIGHT' => Mage::helper('usa')->__('2 Day Freight'),
- 'FEDEX_2_DAY' => Mage::helper('usa')->__('2 Day'),
- 'FEDEX_2_DAY_AM' => Mage::helper('usa')->__('2 Day AM'),
- 'FEDEX_3_DAY_FREIGHT' => Mage::helper('usa')->__('3 Day Freight'),
- 'FEDEX_EXPRESS_SAVER' => Mage::helper('usa')->__('Express Saver'),
- 'FEDEX_GROUND' => Mage::helper('usa')->__('Ground'),
- 'FIRST_OVERNIGHT' => Mage::helper('usa')->__('First Overnight'),
- 'GROUND_HOME_DELIVERY' => Mage::helper('usa')->__('Home Delivery'),
- 'INTERNATIONAL_ECONOMY' => Mage::helper('usa')->__('International Economy'),
- 'INTERNATIONAL_ECONOMY_FREIGHT' => Mage::helper('usa')->__('Intl Economy Freight'),
- 'INTERNATIONAL_FIRST' => Mage::helper('usa')->__('International First'),
- 'INTERNATIONAL_GROUND' => Mage::helper('usa')->__('International Ground'),
- 'INTERNATIONAL_PRIORITY' => Mage::helper('usa')->__('International Priority'),
- 'INTERNATIONAL_PRIORITY_FREIGHT' => Mage::helper('usa')->__('Intl Priority Freight'),
- 'PRIORITY_OVERNIGHT' => Mage::helper('usa')->__('Priority Overnight'),
- 'SMART_POST' => Mage::helper('usa')->__('Smart Post'),
- 'STANDARD_OVERNIGHT' => Mage::helper('usa')->__('Standard Overnight'),
- 'FEDEX_FREIGHT' => Mage::helper('usa')->__('Freight'),
- 'FEDEX_NATIONAL_FREIGHT' => Mage::helper('usa')->__('National Freight'),
+ $r = $this->_rawRequest;
+ $ratesRequest = [
+ 'WebAuthenticationDetail' => [
+ 'UserCredential' => [
+ 'Key' => $r->getKey(),
+ 'Password' => $r->getPassword(),
+ ],
],
- 'dropoff' => [
- 'REGULAR_PICKUP' => Mage::helper('usa')->__('Regular Pickup'),
- 'REQUEST_COURIER' => Mage::helper('usa')->__('Request Courier'),
- 'DROP_BOX' => Mage::helper('usa')->__('Drop Box'),
- 'BUSINESS_SERVICE_CENTER' => Mage::helper('usa')->__('Business Service Center'),
- 'STATION' => Mage::helper('usa')->__('Station'),
+ 'ClientDetail' => [
+ 'AccountNumber' => $r->getAccount(),
+ 'MeterNumber' => $r->getMeterNumber(),
],
- 'packaging' => [
- 'FEDEX_ENVELOPE' => Mage::helper('usa')->__('FedEx Envelope'),
- 'FEDEX_PAK' => Mage::helper('usa')->__('FedEx Pak'),
- 'FEDEX_BOX' => Mage::helper('usa')->__('FedEx Box'),
- 'FEDEX_TUBE' => Mage::helper('usa')->__('FedEx Tube'),
- 'FEDEX_10KG_BOX' => Mage::helper('usa')->__('FedEx 10kg Box'),
- 'FEDEX_25KG_BOX' => Mage::helper('usa')->__('FedEx 25kg Box'),
- 'YOUR_PACKAGING' => Mage::helper('usa')->__('Your Packaging'),
- ],
- 'containers_filter' => [
- [
- 'containers' => ['FEDEX_ENVELOPE', 'FEDEX_PAK'],
- 'filters' => [
- 'within_us' => [
- 'method' => [
- 'FEDEX_EXPRESS_SAVER',
- 'FEDEX_2_DAY',
- 'FEDEX_2_DAY_AM',
- 'STANDARD_OVERNIGHT',
- 'PRIORITY_OVERNIGHT',
- 'FIRST_OVERNIGHT',
- ],
- ],
- 'from_us' => [
- 'method' => [
- 'INTERNATIONAL_FIRST',
- 'INTERNATIONAL_ECONOMY',
- 'INTERNATIONAL_PRIORITY',
- ],
- ],
+ 'Version' => $this->getVersionInfo(),
+ 'RequestedShipment' => [
+ 'DropoffType' => $r->getDropoffType(),
+ 'ShipTimestamp' => date('c'),
+ 'PackagingType' => $r->getPackaging(),
+ 'TotalInsuredValue' => [
+ 'Amount' => $r->getValue(),
+ 'Currency' => $this->getCurrencyCode(),
+ ],
+ 'Shipper' => [
+ 'Address' => [
+ 'PostalCode' => $r->getOrigPostal(),
+ 'CountryCode' => $r->getOrigCountry(),
],
],
- [
- 'containers' => ['FEDEX_BOX', 'FEDEX_TUBE'],
- 'filters' => [
- 'within_us' => [
- 'method' => [
- 'FEDEX_2_DAY',
- 'FEDEX_2_DAY_AM',
- 'STANDARD_OVERNIGHT',
- 'PRIORITY_OVERNIGHT',
- 'FIRST_OVERNIGHT',
- 'FEDEX_FREIGHT',
- 'FEDEX_1_DAY_FREIGHT',
- 'FEDEX_2_DAY_FREIGHT',
- 'FEDEX_3_DAY_FREIGHT',
- 'FEDEX_NATIONAL_FREIGHT',
- ],
- ],
- 'from_us' => [
- 'method' => [
- 'INTERNATIONAL_FIRST',
- 'INTERNATIONAL_ECONOMY',
- 'INTERNATIONAL_PRIORITY',
- ],
- ],
+ 'Recipient' => [
+ 'Address' => [
+ 'PostalCode' => $r->getDestPostal(),
+ 'CountryCode' => $r->getDestCountry(),
+ 'Residential' => (bool) $this->getConfigData('residence_delivery'),
],
],
- [
- 'containers' => ['FEDEX_10KG_BOX', 'FEDEX_25KG_BOX'],
- 'filters' => [
- 'within_us' => [],
- 'from_us' => ['method' => ['INTERNATIONAL_PRIORITY']],
+ 'ShippingChargesPayment' => [
+ 'PaymentType' => 'SENDER',
+ 'Payor' => [
+ 'AccountNumber' => $r->getAccount(),
+ 'CountryCode' => $r->getOrigCountry(),
],
],
- [
- 'containers' => ['YOUR_PACKAGING'],
- 'filters' => [
- 'within_us' => [
- 'method' => [
- 'FEDEX_GROUND',
- 'GROUND_HOME_DELIVERY',
- 'SMART_POST',
- 'FEDEX_EXPRESS_SAVER',
- 'FEDEX_2_DAY',
- 'FEDEX_2_DAY_AM',
- 'STANDARD_OVERNIGHT',
- 'PRIORITY_OVERNIGHT',
- 'FIRST_OVERNIGHT',
- 'FEDEX_FREIGHT',
- 'FEDEX_1_DAY_FREIGHT',
- 'FEDEX_2_DAY_FREIGHT',
- 'FEDEX_3_DAY_FREIGHT',
- 'FEDEX_NATIONAL_FREIGHT',
- ],
- ],
- 'from_us' => [
- 'method' => [
- 'INTERNATIONAL_FIRST',
- 'INTERNATIONAL_ECONOMY',
- 'INTERNATIONAL_PRIORITY',
- 'INTERNATIONAL_GROUND',
- 'FEDEX_FREIGHT',
- 'FEDEX_1_DAY_FREIGHT',
- 'FEDEX_2_DAY_FREIGHT',
- 'FEDEX_3_DAY_FREIGHT',
- 'FEDEX_NATIONAL_FREIGHT',
- 'INTERNATIONAL_ECONOMY_FREIGHT',
- 'INTERNATIONAL_PRIORITY_FREIGHT',
- ],
+ 'CustomsClearanceDetail' => [
+ 'CustomsValue' => [
+ 'Amount' => $r->getValue(),
+ 'Currency' => $this->getCurrencyCode(),
+ ],
+ ],
+ 'RateRequestTypes' => 'LIST',
+ 'PackageCount' => '1',
+ 'PackageDetail' => 'INDIVIDUAL_PACKAGES',
+ 'RequestedPackageLineItems' => [
+ '0' => [
+ 'Weight' => [
+ 'Value' => (float) $r->getWeight(),
+ 'Units' => $this->getConfigData('unit_of_measure'),
],
+ 'GroupPackageCount' => 1,
],
],
],
+ ];
- 'delivery_confirmation_types' => [
- 'NO_SIGNATURE_REQUIRED' => Mage::helper('usa')->__('Not Required'),
- 'ADULT' => Mage::helper('usa')->__('Adult'),
- 'DIRECT' => Mage::helper('usa')->__('Direct'),
- 'INDIRECT' => Mage::helper('usa')->__('Indirect'),
- ],
+ if ($purpose == self::RATE_REQUEST_GENERAL) {
+ $ratesRequest['RequestedShipment']['RequestedPackageLineItems'][0]['InsuredValue'] = [
+ 'Amount' => $r->getValue(),
+ 'Currency' => $this->getCurrencyCode(),
+ ];
+ } elseif ($purpose == self::RATE_REQUEST_SMARTPOST) {
+ $ratesRequest['RequestedShipment']['ServiceType'] = self::RATE_REQUEST_SMARTPOST;
+ $ratesRequest['RequestedShipment']['SmartPostDetail'] = [
+ 'Indicia' => ((float) $r->getWeight() >= 1) ? 'PARCEL_SELECT' : 'PRESORTED_STANDARD',
+ 'HubId' => $this->getConfigData('smartpost_hubid'),
+ ];
+ }
- 'unit_of_measure' => [
- 'LB' => Mage::helper('usa')->__('Pounds'),
- 'KG' => Mage::helper('usa')->__('Kilograms'),
- ],
- ];
+ return $ratesRequest;
+ }
+
+ /**
+ * Makes remote request to the carrier and returns a response
+ *
+ * @param string $purpose
+ * @return mixed
+ */
+ protected function _doRatesRequest($purpose)
+ {
+ $ratesRequest = $this->_formRateRequest($purpose);
+ $requestString = serialize($ratesRequest);
+ $response = $this->_getCachedQuotes($requestString);
+ $debugData = ['request' => $ratesRequest];
+ if ($response === null) {
+ try {
+ $client = $this->_createRateSoapClient();
+ $response = $client->getRates($ratesRequest);
+ $this->_setCachedQuotes($requestString, serialize($response));
+ $debugData['result'] = $response;
+ } catch (Exception $e) {
+ $debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
+ Mage::logException($e);
+ }
+ } else {
+ $response = unserialize($response);
+ $debugData['result'] = $response;
+ }
+ $this->_debug($debugData);
+ return $response;
+ }
+
+ /**
+ * Do remote request for and handle errors
+ *
+ * @return Mage_Shipping_Model_Rate_Result
+ */
+ protected function _getQuotes()
+ {
+ $this->_result = Mage::getModel('shipping/rate_result');
+ $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
+ if (in_array(self::RATE_REQUEST_SMARTPOST, $allowedMethods)) {
+ $response = $this->_doRatesRequest(self::RATE_REQUEST_SMARTPOST);
+ $preparedSmartpost = $this->_prepareRateResponse($response);
+ $this->_result->append($preparedSmartpost);
+ }
+ $response = $this->_doRatesRequest(self::RATE_REQUEST_GENERAL);
+ $preparedGeneral = $this->_prepareRateResponse($response);
+ if ($this->_result->getError() && $preparedGeneral->getError()) {
+ return $this->_result->getError();
+ }
+ $this->_result->append($preparedGeneral);
+ $this->_removeErrorsIfRateExist();
+
+ return $this->_result;
+ }
+
+ /**
+ * Remove Errors in Case When Rate Exist
+ *
+ * @return Mage_Shipping_Model_Rate_Result
+ */
+ protected function _removeErrorsIfRateExist()
+ {
+ $rateResultExist = false;
+ $rates = [];
+ foreach ($this->_result->getAllRates() as $rate) {
+ if (!($rate instanceof Mage_Shipping_Model_Rate_Result_Error)) {
+ $rateResultExist = true;
+ $rates[] = $rate;
+ }
+ }
+
+ if ($rateResultExist) {
+ $this->_result->reset();
+ $this->_result->setError(false);
+ foreach ($rates as $rate) {
+ $this->_result->append($rate);
+ }
+ }
+
+ return $this->_result;
+ }
+
+ /**
+ * Prepare shipping rate result based on response
+ *
+ * @param mixed $response
+ * @return Mage_Shipping_Model_Rate_Result
+ */
+ protected function _prepareRateResponse($response)
+ {
+ $costArr = [];
+ $priceArr = [];
+ $errorTitle = 'Unable to retrieve tracking';
+
+ if (is_object($response)) {
+ if ($response->HighestSeverity == 'FAILURE' || $response->HighestSeverity == 'ERROR') {
+ if (is_array($response->Notifications)) {
+ $notification = array_pop($response->Notifications);
+ $errorTitle = (string) $notification->Message;
+ } else {
+ $errorTitle = (string) $response->Notifications->Message;
+ }
+ } elseif (isset($response->RateReplyDetails)) {
+ $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
+
+ if (is_array($response->RateReplyDetails)) {
+ foreach ($response->RateReplyDetails as $rate) {
+ $serviceName = (string) $rate->ServiceType;
+ if (in_array($serviceName, $allowedMethods)) {
+ $amount = $this->_getRateAmountOriginBased($rate);
+ $costArr[$serviceName] = $amount;
+ $priceArr[$serviceName] = $this->getMethodPrice($amount, $serviceName);
+ }
+ }
+ asort($priceArr);
+ } else {
+ $rate = $response->RateReplyDetails;
+ $serviceName = (string) $rate->ServiceType;
+ if (in_array($serviceName, $allowedMethods)) {
+ $amount = $this->_getRateAmountOriginBased($rate);
+ $costArr[$serviceName] = $amount;
+ $priceArr[$serviceName] = $this->getMethodPrice($amount, $serviceName);
+ }
+ }
+ }
+ }
+
+ $result = Mage::getModel('shipping/rate_result');
+ if (empty($priceArr)) {
+ $error = Mage::getModel('shipping/rate_result_error');
+ $error->setCarrier($this->_code);
+ $error->setCarrierTitle($this->getConfigData('title'));
+ $error->setErrorMessage($errorTitle);
+ $error->setErrorMessage($this->getConfigData('specificerrmsg'));
+ $result->append($error);
+ } else {
+ foreach ($priceArr as $method => $price) {
+ $rate = Mage::getModel('shipping/rate_result_method');
+ $rate->setCarrier($this->_code);
+ $rate->setCarrierTitle($this->getConfigData('title'));
+ $rate->setMethod($method);
+ $rate->setMethodTitle($this->getCode('method', $method));
+ $rate->setCost($costArr[$method]);
+ $rate->setPrice($price);
+ $result->append($rate);
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * Get origin based amount form response of rate estimation
+ *
+ * @param stdClass $rate
+ * @return null|float
+ */
+ protected function _getRateAmountOriginBased($rate)
+ {
+ $amount = null;
+ $rateTypeAmounts = [];
+
+ if (is_object($rate)) {
+ // The "RATED..." rates are expressed in the currency of the origin country
+ foreach ($rate->RatedShipmentDetails as $ratedShipmentDetail) {
+ $netAmount = (string) $ratedShipmentDetail->ShipmentRateDetail->TotalNetCharge->Amount;
+ $rateType = (string) $ratedShipmentDetail->ShipmentRateDetail->RateType;
+ $rateTypeAmounts[$rateType] = $netAmount;
+ }
+
+ // Order is important
+ $ratesOrder = [
+ 'RATED_ACCOUNT_PACKAGE',
+ 'PAYOR_ACCOUNT_PACKAGE',
+ 'RATED_ACCOUNT_SHIPMENT',
+ 'PAYOR_ACCOUNT_SHIPMENT',
+ 'RATED_LIST_PACKAGE',
+ 'PAYOR_LIST_PACKAGE',
+ 'RATED_LIST_SHIPMENT',
+ 'PAYOR_LIST_SHIPMENT',
+ ];
+ foreach ($ratesOrder as $rateType) {
+ if (!empty($rateTypeAmounts[$rateType])) {
+ $amount = $rateTypeAmounts[$rateType];
+ break;
+ }
+ }
+
+ if (is_null($amount)) {
+ $amount = (string) $rate->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;
+ }
+ }
+
+ return $amount;
+ }
+
+ /**
+ * Set free method request
+ *
+ * @param $freeMethod
+ */
+ protected function _setFreeMethodRequest($freeMethod)
+ {
+ $r = $this->_rawRequest;
+ $weight = $this->getTotalNumOfBoxes($r->getFreeMethodWeight());
+ $r->setWeight($weight);
+ $r->setService($freeMethod);
+ }
+
+ /**
+ * Get xml quotes
+ *
+ * @deprecated
+ * @return Mage_Shipping_Model_Rate_Result
+ */
+ protected function _getXmlQuotes()
+ {
+ $r = $this->_rawRequest;
+ $xml = new SimpleXMLElement('');
+
+ $xml->addAttribute('xmlns:api', 'http://www.fedex.com/fsmapi');
+ $xml->addAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
+ $xml->addAttribute('xsi:noNamespaceSchemaLocation', 'FDXRateAvailableServicesRequest.xsd');
+
+ $requestHeader = $xml->addChild('RequestHeader');
+ $requestHeader->addChild('AccountNumber', $r->getAccount());
+ $requestHeader->addChild('MeterNumber', '0');
+
+ $xml->addChild('ShipDate', date('Y-m-d'));
+ $xml->addChild('DropoffType', $r->getDropoffType());
+ if ($r->hasService()) {
+ $xml->addChild('Service', $r->getService());
+ }
+ $xml->addChild('Packaging', $r->getPackaging());
+ $xml->addChild('WeightUnits', 'LBS');
+ $xml->addChild('Weight', $r->getWeight());
+
+ $originAddress = $xml->addChild('OriginAddress');
+ $originAddress->addChild('PostalCode', $r->getOrigPostal());
+ $originAddress->addChild('CountryCode', $r->getOrigCountry());
+
+ $destinationAddress = $xml->addChild('DestinationAddress');
+ $destinationAddress->addChild('PostalCode', $r->getDestPostal());
+ $destinationAddress->addChild('CountryCode', $r->getDestCountry());
+
+ $payment = $xml->addChild('Payment');
+ $payment->addChild('PayorType', 'SENDER');
+
+ $declaredValue = $xml->addChild('DeclaredValue');
+ $declaredValue->addChild('Value', $r->getValue());
+ $declaredValue->addChild('CurrencyCode', $this->getCurrencyCode());
+
+ if ($this->getConfigData('residence_delivery')) {
+ $specialServices = $xml->addChild('SpecialServices');
+ $specialServices->addChild('ResidentialDelivery', 'true');
+ }
+
+ $xml->addChild('PackageCount', '1');
+
+ $request = $xml->asXML();
+
+ $responseBody = $this->_getCachedQuotes($request);
+ if ($responseBody === null) {
+ $debugData = ['request' => $request];
+ try {
+ $url = $this->getConfigData('gateway_url');
+ if (!$url) {
+ $url = $this->_defaultGatewayUrl;
+ }
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
+ $responseBody = curl_exec($ch);
+ curl_close($ch);
- if (!isset($codes[$type])) {
- return false;
- } elseif ($code === '') {
- return $codes[$type];
+ $debugData['result'] = $responseBody;
+ $this->_setCachedQuotes($request, $responseBody);
+ } catch (Exception $e) {
+ $debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
+ $responseBody = '';
+ }
+ $this->_debug($debugData);
}
-
- return $codes[$type][$code] ?? false;
+ return $this->_parseXmlResponse($responseBody);
}
/**
- * Return FeDex currency ISO code by Magento Base Currency Code
+ * Prepare shipping rate result based on response
*
- * @return string 3-digit currency code
+ * @param mixed $response
+ * @return Mage_Shipping_Model_Rate_Result
*/
- public function getCurrencyCode()
+ protected function _parseXmlResponse($response)
{
- $codes = [
- 'DOP' => 'RDD', // Dominican Peso
- 'XCD' => 'ECD', // Caribbean Dollars
- 'ARS' => 'ARN', // Argentina Peso
- 'SGD' => 'SID', // Singapore Dollars
- 'KRW' => 'WON', // South Korea Won
- 'JMD' => 'JAD', // Jamaican Dollars
- 'CHF' => 'SFR', // Swiss Francs
- 'JPY' => 'JYE', // Japanese Yen
- 'KWD' => 'KUD', // Kuwaiti Dinars
- 'GBP' => 'UKL', // British Pounds
- 'AED' => 'DHS', // UAE Dirhams
- 'MXN' => 'NMP', // Mexican Pesos
- 'UYU' => 'UYP', // Uruguay New Pesos
- 'CLP' => 'CHP', // Chilean Pesos
- 'TWD' => 'NTD', // New Taiwan Dollars
- ];
- $currencyCode = Mage::app()->getStore()->getBaseCurrencyCode();
- return $codes[$currencyCode] ?? $currencyCode;
+ $costArr = [];
+ $priceArr = [];
+
+ if (strlen(trim($response)) > 0) {
+ if ($xml = $this->_parseXml($response)) {
+ if (is_object($xml->Error) && is_object($xml->Error->Message)) {
+ $errorTitle = (string) $xml->Error->Message;
+ } elseif (is_object($xml->SoftError) && is_object($xml->SoftError->Message)) {
+ $errorTitle = (string) $xml->SoftError->Message;
+ } else {
+ $errorTitle = 'Unknown error';
+ }
+
+ $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
+
+ foreach ($xml->Entry as $entry) {
+ if (in_array((string) $entry->Service, $allowedMethods)) {
+ $costArr[(string) $entry->Service] =
+ (string) $entry->EstimatedCharges->DiscountedCharges->NetCharge;
+ $priceArr[(string) $entry->Service] = $this->getMethodPrice(
+ (float) $entry->EstimatedCharges->DiscountedCharges->NetCharge,
+ (string) $entry->Service,
+ );
+ }
+ }
+
+ asort($priceArr);
+ } else {
+ $errorTitle = 'Response is in the wrong format.';
+ }
+ } else {
+ $errorTitle = 'Unable to retrieve tracking';
+ }
+
+ $result = Mage::getModel('shipping/rate_result');
+ if (empty($priceArr)) {
+ $error = Mage::getModel('shipping/rate_result_error');
+ $error->setCarrier('fedex');
+ $error->setCarrierTitle($this->getConfigData('title'));
+ $error->setErrorMessage($this->getConfigData('specificerrmsg'));
+ $result->append($error);
+ } else {
+ foreach ($priceArr as $method => $price) {
+ $rate = Mage::getModel('shipping/rate_result_method');
+ $rate->setCarrier('fedex');
+ $rate->setCarrierTitle($this->getConfigData('title'));
+ $rate->setMethod($method);
+ $rate->setMethodTitle($this->getCode('method', $method));
+ $rate->setCost($costArr[$method]);
+ $rate->setPrice($price);
+ $result->append($rate);
+ }
+ }
+ return $result;
}
/**
- * Get tracking
+ * Parse XML string and return XML document object or false
*
- * @param mixed $trackings
- * @return Mage_Shipping_Model_Rate_Result|null
+ * @param string $xmlContent
+ * @return SimpleXMLElement|bool
*/
- public function getTracking($trackings)
+ protected function _parseXml($xmlContent)
{
- $this->setTrackingReqeust();
-
- if (!is_array($trackings)) {
- $trackings = [$trackings];
- }
-
- foreach ($trackings as $tracking) {
- $this->_getXMLTracking($tracking);
+ try {
+ try {
+ return simplexml_load_string($xmlContent);
+ } catch (Exception $e) {
+ throw new Exception(Mage::helper('usa')->__('Failed to parse xml document: %s', $xmlContent));
+ }
+ } catch (Exception $e) {
+ Mage::logException($e);
+ return false;
}
-
- return $this->_result;
}
/**
@@ -1220,48 +1347,6 @@ protected function _parseXmlTrackingResponse($trackingvalue, $response)
}
}
- /**
- * Get tracking response
- *
- * @return string
- */
- public function getResponse()
- {
- $statuses = '';
- if ($this->_result instanceof Mage_Shipping_Model_Tracking_Result) {
- if ($trackings = $this->_result->getAllTrackings()) {
- foreach ($trackings as $tracking) {
- if ($data = $tracking->getAllData()) {
- if (!empty($data['status'])) {
- $statuses .= Mage::helper('usa')->__($data['status']) . "\n
";
- } else {
- $statuses .= Mage::helper('usa')->__('Empty response') . "\n
";
- }
- }
- }
- }
- }
- if (empty($statuses)) {
- $statuses = Mage::helper('usa')->__('Empty response');
- }
- return $statuses;
- }
-
- /**
- * Get allowed shipping methods
- *
- * @return array
- */
- public function getAllowedMethods()
- {
- $allowed = explode(',', $this->getConfigData('allowed_methods'));
- $arr = [];
- foreach ($allowed as $k) {
- $arr[$k] = $this->getCode('method', $k);
- }
- return $arr;
- }
-
/**
* Return array of authenticated information
*
@@ -1520,89 +1605,4 @@ protected function _doShipmentRequest(Varien_Object $request)
return $result;
}
-
- /**
- * For multi package shipments. Delete requested shipments if the current shipment
- * request is failed
- *
- * @param array $data
- * @return bool
- */
- public function rollBack($data)
- {
- $requestData = $this->_getAuthDetails();
- $requestData['DeletionControl'] = 'DELETE_ONE_PACKAGE';
- foreach ($data as &$item) {
- $requestData['TrackingId'] = $item['tracking_number'];
- $client = $this->_createShipSoapClient();
- $client->deleteShipment($requestData);
- }
- return true;
- }
-
- /**
- * Return container types of carrier
- *
- * @return array|bool
- */
- public function getContainerTypes(?Varien_Object $params = null)
- {
- if ($params == null) {
- return $this->_getAllowedContainers($params);
- }
- $method = $params->getMethod();
- $countryShipper = $params->getCountryShipper();
- $countryRecipient = $params->getCountryRecipient();
-
- if (($countryShipper == self::USA_COUNTRY_ID && $countryRecipient == self::CANADA_COUNTRY_ID
- || $countryShipper == self::CANADA_COUNTRY_ID && $countryRecipient == self::USA_COUNTRY_ID)
- && $method == 'FEDEX_GROUND'
- ) {
- return ['YOUR_PACKAGING' => Mage::helper('usa')->__('Your Packaging')];
- } elseif ($method == 'INTERNATIONAL_ECONOMY' || $method == 'INTERNATIONAL_FIRST') {
- $allTypes = $this->getContainerTypesAll();
- $exclude = ['FEDEX_10KG_BOX' => '', 'FEDEX_25KG_BOX' => ''];
- return array_diff_key($allTypes, $exclude);
- } elseif ($method == 'EUROPE_FIRST_INTERNATIONAL_PRIORITY') {
- $allTypes = $this->getContainerTypesAll();
- $exclude = ['FEDEX_BOX' => '', 'FEDEX_TUBE' => ''];
- return array_diff_key($allTypes, $exclude);
- } elseif ($countryShipper == self::CANADA_COUNTRY_ID && $countryRecipient == self::CANADA_COUNTRY_ID) {
- // hack for Canada domestic. Apply the same filter rules as for US domestic
- $params->setCountryShipper(self::USA_COUNTRY_ID);
- $params->setCountryRecipient(self::USA_COUNTRY_ID);
- }
-
- return $this->_getAllowedContainers($params);
- }
-
- /**
- * Return all container types of carrier
- *
- * @return array|bool
- */
- public function getContainerTypesAll()
- {
- return $this->getCode('packaging');
- }
-
- /**
- * Return structured data of containers witch related with shipping methods
- *
- * @return array|bool
- */
- public function getContainerTypesFilter()
- {
- return $this->getCode('containers_filter');
- }
-
- /**
- * Return delivery confirmation types of carrier
- *
- * @return array
- */
- public function getDeliveryConfirmationTypes(?Varien_Object $params = null)
- {
- return $this->getCode('delivery_confirmation_types');
- }
}
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php
index 7992c7b9521..c8bad3e5ace 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php
@@ -279,30 +279,6 @@ public function setRequest(Mage_Shipping_Model_Rate_Request $request)
return $this;
}
- /**
- * Get correct weight.
- *
- * Namely:
- * Checks the current weight to comply with the minimum weight standards set by the carrier.
- * Then strictly rounds the weight up until the first significant digit after the decimal point.
- *
- * @param float|int $weight
- * @return float
- */
- protected function _getCorrectWeight($weight)
- {
- $minWeight = $this->getConfigData('min_package_weight');
-
- if ($weight < $minWeight) {
- $weight = $minWeight;
- }
-
- //rounds a number to one significant figure
- $weight = ceil($weight * 10) / 10;
-
- return $weight;
- }
-
/**
* Get result of request
*
@@ -313,39 +289,6 @@ public function getResult()
return $this->_result;
}
- /**
- * Do remote request for and handle errors
- *
- * @return Mage_Shipping_Model_Rate_Result
- */
- protected function _getQuotes()
- {
- // this "if" will be removed after XML APIs will be shut down
- if ($this->getConfigData('type') == 'UPS_XML') {
- return $this->_getXmlQuotes();
- }
-
- // REST is default
- return $this->_getRestQuotes();
- }
-
- /**
- * Set free method request
- *
- * @param string $freeMethod
- * @return void
- */
- protected function _setFreeMethodRequest($freeMethod)
- {
- $r = $this->_rawRequest;
-
- $weight = $this->getTotalNumOfBoxes($r->getFreeMethodWeight());
- $weight = $this->_getCorrectWeight($weight);
- $r->setWeight($weight);
- $r->setAction($this->getCode('action', 'single'));
- $r->setProduct($freeMethod);
- }
-
/**
* Get shipment by code
*
@@ -668,6 +611,260 @@ public function getCode($type, $code = '')
return $codes[$type][$code] ?? false;
}
+ /**
+ * Get tracking
+ *
+ * @param mixed $trackings
+ * @return Mage_Shipping_Model_Tracking_Result|null
+ */
+ public function getTracking($trackings)
+ {
+ if (!is_array($trackings)) {
+ $trackings = [$trackings];
+ }
+
+ if ($this->getConfigData('type') === 'UPS_XML') {
+ $this->setXMLAccessRequest();
+ $this->_getXmlTracking($trackings);
+ } else {
+ $this->_getRestTracking($trackings);
+ }
+
+ return $this->_trackingResult;
+ }
+
+ /**
+ * Get tracking response
+ *
+ * @return string
+ */
+ public function getResponse()
+ {
+ if ($this->_trackingResult === null) {
+ $trackings = [];
+ } else {
+ $trackings = $this->_trackingResult->getAllTrackings();
+ }
+
+ $statuses = '';
+ foreach ($trackings as $tracking) {
+ if ($data = $tracking->getAllData()) {
+ if (isset($data['status'])) {
+ $statuses .= Mage::helper('usa')->__($data['status']);
+ } else {
+ $statuses .= Mage::helper('usa')->__($data['error_message']);
+ }
+ }
+ }
+ if (empty($statuses)) {
+ $statuses = Mage::helper('usa')->__('Empty response');
+ }
+ return $statuses;
+ }
+
+ /**
+ * Get allowed shipping methods.
+ *
+ * @return array
+ */
+ public function getAllowedMethods()
+ {
+ $allowedMethods = explode(',', (string) $this->getConfigData('allowed_methods'));
+ $availableByTypeMethods = $this->getCode('originShipment', $this->getConfigData('origin_shipment'));
+
+ $methods = [];
+ foreach ($availableByTypeMethods as $methodCode => $methodData) {
+ if (in_array($methodCode, $allowedMethods)) {
+ $methods[$methodCode] = $methodData;
+ }
+ }
+
+ return $methods;
+ }
+
+ /**
+ * Return container types of carrier
+ *
+ * @return array|bool
+ */
+ public function getContainerTypes(?Varien_Object $params = null)
+ {
+ if ($params == null) {
+ return $this->_getAllowedContainers($params);
+ }
+ $method = $params->getMethod();
+ $countryShipper = $params->getCountryShipper();
+ $countryRecipient = $params->getCountryRecipient();
+
+ if (($countryShipper == self::USA_COUNTRY_ID && $countryRecipient == self::CANADA_COUNTRY_ID)
+ || ($countryShipper == self::CANADA_COUNTRY_ID && $countryRecipient == self::USA_COUNTRY_ID)
+ || ($countryShipper == self::MEXICO_COUNTRY_ID && $countryRecipient == self::USA_COUNTRY_ID)
+ && $method == '11' // UPS Standard
+ ) {
+ $containerTypes = [];
+ if ($method == '07' // Worldwide Express
+ || $method == '08' // Worldwide Expedited
+ || $method == '65' // Worldwide Saver
+ ) {
+ // Worldwide Expedited
+ if ($method != '08') {
+ $containerTypes = [
+ '01' => Mage::helper('usa')->__('UPS Letter Envelope'),
+ '24' => Mage::helper('usa')->__('UPS Worldwide 25 kilo'),
+ '25' => Mage::helper('usa')->__('UPS Worldwide 10 kilo'),
+ ];
+ }
+ $containerTypes = $containerTypes + [
+ '03' => Mage::helper('usa')->__('UPS Tube'),
+ '04' => Mage::helper('usa')->__('PAK'),
+ '2a' => Mage::helper('usa')->__('Small Express Box'),
+ '2b' => Mage::helper('usa')->__('Medium Express Box'),
+ '2c' => Mage::helper('usa')->__('Large Express Box'),
+ ];
+ }
+ return ['00' => Mage::helper('usa')->__('Customer Packaging')] + $containerTypes;
+ } elseif ($countryShipper == self::USA_COUNTRY_ID && $countryRecipient == self::PUERTORICO_COUNTRY_ID
+ && (
+ $method == '03' // UPS Ground
+ || $method == '02' // UPS Second Day Air
+ || $method == '01' // UPS Next Day Air
+ )
+ ) {
+ // Container types should be the same as for domestic
+ $params->setCountryRecipient(self::USA_COUNTRY_ID);
+ $containerTypes = $this->_getAllowedContainers($params);
+ $params->setCountryRecipient($countryRecipient);
+ return $containerTypes;
+ }
+ return $this->_getAllowedContainers($params);
+ }
+
+ /**
+ * Return all container types of carrier
+ *
+ * @return array
+ */
+ public function getContainerTypesAll()
+ {
+ $codes = $this->getCode('container');
+ $descriptions = $this->getCode('container_description');
+ $result = [];
+ foreach ($codes as $key => &$code) {
+ $result[$code] = $descriptions[$key];
+ }
+ return $result;
+ }
+
+ /**
+ * Return structured data of containers witch related with shipping methods
+ *
+ * @return array|false
+ */
+ public function getContainerTypesFilter()
+ {
+ return $this->getCode('containers_filter');
+ }
+
+ /**
+ * Return delivery confirmation types of carrier
+ *
+ * @return array
+ */
+ public function getDeliveryConfirmationTypes(?Varien_Object $params = null)
+ {
+ $countryRecipient = $params != null ? $params->getCountryRecipient() : null;
+ $deliveryConfirmationTypes = [];
+ switch ($this->_getDeliveryConfirmationLevel($countryRecipient)) {
+ case self::DELIVERY_CONFIRMATION_PACKAGE:
+ $deliveryConfirmationTypes = [
+ 1 => Mage::helper('usa')->__('Delivery Confirmation'),
+ 2 => Mage::helper('usa')->__('Signature Required'),
+ 3 => Mage::helper('usa')->__('Adult Signature Required'),
+ ];
+ break;
+ case self::DELIVERY_CONFIRMATION_SHIPMENT:
+ $deliveryConfirmationTypes = [
+ 1 => Mage::helper('usa')->__('Signature Required'),
+ 2 => Mage::helper('usa')->__('Adult Signature Required'),
+ ];
+ }
+ array_unshift($deliveryConfirmationTypes, Mage::helper('usa')->__('Not Required'));
+
+ return $deliveryConfirmationTypes;
+ }
+
+ /**
+ * Get Container Types, that could be customized for UPS carrier
+ *
+ * @return array
+ */
+ public function getCustomizableContainerTypes()
+ {
+ $result = [];
+ $containerTypes = $this->getCode('container');
+ foreach (parent::getCustomizableContainerTypes() as $containerType) {
+ $result[$containerType] = $containerTypes[$containerType];
+ }
+ return $result;
+ }
+
+ /**
+ * Get correct weight.
+ *
+ * Namely:
+ * Checks the current weight to comply with the minimum weight standards set by the carrier.
+ * Then strictly rounds the weight up until the first significant digit after the decimal point.
+ *
+ * @param float|int $weight
+ * @return float
+ */
+ protected function _getCorrectWeight($weight)
+ {
+ $minWeight = $this->getConfigData('min_package_weight');
+
+ if ($weight < $minWeight) {
+ $weight = $minWeight;
+ }
+
+ //rounds a number to one significant figure
+ $weight = ceil($weight * 10) / 10;
+
+ return $weight;
+ }
+
+ /**
+ * Do remote request for and handle errors
+ *
+ * @return Mage_Shipping_Model_Rate_Result
+ */
+ protected function _getQuotes()
+ {
+ // this "if" will be removed after XML APIs will be shut down
+ if ($this->getConfigData('type') == 'UPS_XML') {
+ return $this->_getXmlQuotes();
+ }
+
+ // REST is default
+ return $this->_getRestQuotes();
+ }
+
+ /**
+ * Set free method request
+ *
+ * @param string $freeMethod
+ * @return void
+ */
+ protected function _setFreeMethodRequest($freeMethod)
+ {
+ $r = $this->_rawRequest;
+
+ $weight = $this->getTotalNumOfBoxes($r->getFreeMethodWeight());
+ $weight = $this->_getCorrectWeight($weight);
+ $r->setWeight($weight);
+ $r->setAction($this->getCode('action', 'single'));
+ $r->setProduct($freeMethod);
+ }
+
/**
* Get xml rates
*
@@ -926,28 +1123,6 @@ protected function _parseXmlResponse($xmlResponse)
return $result;
}
- /**
- * Get tracking
- *
- * @param mixed $trackings
- * @return Mage_Shipping_Model_Tracking_Result|null
- */
- public function getTracking($trackings)
- {
- if (!is_array($trackings)) {
- $trackings = [$trackings];
- }
-
- if ($this->getConfigData('type') === 'UPS_XML') {
- $this->setXMLAccessRequest();
- $this->_getXmlTracking($trackings);
- } else {
- $this->_getRestTracking($trackings);
- }
-
- return $this->_trackingResult;
- }
-
/**
* Set xml access request
*
@@ -1260,87 +1435,6 @@ protected function _parseRestTrackingResponse($trackingValue, $jsonResponse)
$this->setTrackingResultData($resultArr, $trackingValue, $errorTitle);
}
- /**
- * Set Tracking Response Data
- *
- * @param array $resultArr
- * @param string $trackingValue
- * @param string $errorTitle
- */
- private function setTrackingResultData($resultArr, $trackingValue, $errorTitle)
- {
- if (!$this->_trackingResult) {
- $this->_trackingResult = Mage::getModel('shipping/tracking_result');
- }
-
- if ($resultArr) {
- /** @var Mage_Shipping_Model_Tracking_Result_Status $tracking */
- $tracking = Mage::getModel('shipping/tracking_result_status');
- $tracking->setCarrier('ups');
- $tracking->setCarrierTitle($this->getConfigData('title'));
- $tracking->setTracking($trackingValue);
- $tracking->addData($resultArr);
- $this->_trackingResult->append($tracking);
- } else {
- /** @var Mage_Shipping_Model_Tracking_Result_Error $error */
- $error = Mage::getModel('shipping/tracking_result_error');
- $error->setCarrier('ups');
- $error->setCarrierTitle($this->getConfigData('title'));
- $error->setTracking($trackingValue);
- $error->setErrorMessage($errorTitle);
- $this->_trackingResult->append($error);
- }
- }
-
- /**
- * Get tracking response
- *
- * @return string
- */
- public function getResponse()
- {
- if ($this->_trackingResult === null) {
- $trackings = [];
- } else {
- $trackings = $this->_trackingResult->getAllTrackings();
- }
-
- $statuses = '';
- foreach ($trackings as $tracking) {
- if ($data = $tracking->getAllData()) {
- if (isset($data['status'])) {
- $statuses .= Mage::helper('usa')->__($data['status']);
- } else {
- $statuses .= Mage::helper('usa')->__($data['error_message']);
- }
- }
- }
- if (empty($statuses)) {
- $statuses = Mage::helper('usa')->__('Empty response');
- }
- return $statuses;
- }
-
- /**
- * Get allowed shipping methods.
- *
- * @return array
- */
- public function getAllowedMethods()
- {
- $allowedMethods = explode(',', (string) $this->getConfigData('allowed_methods'));
- $availableByTypeMethods = $this->getCode('originShipment', $this->getConfigData('origin_shipment'));
-
- $methods = [];
- foreach ($availableByTypeMethods as $methodCode => $methodData) {
- if (in_array($methodCode, $allowedMethods)) {
- $methods[$methodCode] = $methodData;
- }
- }
-
- return $methods;
- }
-
/**
* Form XML for shipment request
*
@@ -1708,43 +1802,15 @@ protected function _doShipmentRequestRest(Varien_Object $request): Varien_Object
}
if ($package !== null) {
- $result->setTrackingNumber($package->TrackingNumber);
- // ShippingLabel is not guaranteed to be set, but if it is, GraphicImage will be set.
- if (isset($package->ShippingLabel->GraphicImage)) {
- $result->setShippingLabelContent(base64_decode($package->ShippingLabel->GraphicImage));
- }
- }
-
- $this->_debug($debugData);
- return $result;
- }
-
- /**
- * Return country code according to UPS
- *
- * @param string $countryCode
- * @param string $regionCode
- * @param string $postCode
- * @return string
- */
- private function getNormalizedCountryCode($countryCode, $regionCode, $postCode)
- {
- //for UPS, puerto rico state for US will assume as puerto rico country
- if ($countryCode == self::USA_COUNTRY_ID && ($postCode == '00912' || $regionCode == self::PUERTORICO_COUNTRY_ID)) {
- $countryCode = self::PUERTORICO_COUNTRY_ID;
- }
-
- // For UPS, Guam state of the USA will be represented by Guam country
- if ($countryCode == self::USA_COUNTRY_ID && $regionCode == self::GUAM_REGION_CODE) {
- $countryCode = self::GUAM_COUNTRY_ID;
- }
-
- // For UPS, Las Palmas and Santa Cruz de Tenerife will be represented by Canary Islands country
- if ($countryCode === 'ES' && ($regionCode === 'Las Palmas' || $regionCode === 'Santa Cruz de Tenerife')) {
- $countryCode = 'IC';
+ $result->setTrackingNumber($package->TrackingNumber);
+ // ShippingLabel is not guaranteed to be set, but if it is, GraphicImage will be set.
+ if (isset($package->ShippingLabel->GraphicImage)) {
+ $result->setShippingLabelContent(base64_decode($package->ShippingLabel->GraphicImage));
+ }
}
- return $countryCode;
+ $this->_debug($debugData);
+ return $result;
}
protected function _formShipmentRestRequest(Varien_Object $request): string
@@ -1932,19 +1998,6 @@ protected function _formShipmentRestRequest(Varien_Object $request): string
return json_encode($shipParams);
}
- private function generateShipmentDescription(array $items): string
- {
- $itemsDesc = [];
- $itemsShipment = $items;
- foreach ($itemsShipment as $itemShipment) {
- $item = new Varien_Object();
- $item->setData($itemShipment);
- $itemsDesc[] = $item->getName();
- }
-
- return substr(implode(' ', $itemsDesc), 0, 35);
- }
-
/**
* Do shipment request to carrier web service, obtain Print Shipping Labels and process errors in response
*/
@@ -2005,132 +2058,6 @@ protected function _doShipmentRequestXML(Varien_Object $request): Varien_Object
}
}
- /**
- * Return container types of carrier
- *
- * @return array|bool
- */
- public function getContainerTypes(?Varien_Object $params = null)
- {
- if ($params == null) {
- return $this->_getAllowedContainers($params);
- }
- $method = $params->getMethod();
- $countryShipper = $params->getCountryShipper();
- $countryRecipient = $params->getCountryRecipient();
-
- if (($countryShipper == self::USA_COUNTRY_ID && $countryRecipient == self::CANADA_COUNTRY_ID)
- || ($countryShipper == self::CANADA_COUNTRY_ID && $countryRecipient == self::USA_COUNTRY_ID)
- || ($countryShipper == self::MEXICO_COUNTRY_ID && $countryRecipient == self::USA_COUNTRY_ID)
- && $method == '11' // UPS Standard
- ) {
- $containerTypes = [];
- if ($method == '07' // Worldwide Express
- || $method == '08' // Worldwide Expedited
- || $method == '65' // Worldwide Saver
- ) {
- // Worldwide Expedited
- if ($method != '08') {
- $containerTypes = [
- '01' => Mage::helper('usa')->__('UPS Letter Envelope'),
- '24' => Mage::helper('usa')->__('UPS Worldwide 25 kilo'),
- '25' => Mage::helper('usa')->__('UPS Worldwide 10 kilo'),
- ];
- }
- $containerTypes = $containerTypes + [
- '03' => Mage::helper('usa')->__('UPS Tube'),
- '04' => Mage::helper('usa')->__('PAK'),
- '2a' => Mage::helper('usa')->__('Small Express Box'),
- '2b' => Mage::helper('usa')->__('Medium Express Box'),
- '2c' => Mage::helper('usa')->__('Large Express Box'),
- ];
- }
- return ['00' => Mage::helper('usa')->__('Customer Packaging')] + $containerTypes;
- } elseif ($countryShipper == self::USA_COUNTRY_ID && $countryRecipient == self::PUERTORICO_COUNTRY_ID
- && (
- $method == '03' // UPS Ground
- || $method == '02' // UPS Second Day Air
- || $method == '01' // UPS Next Day Air
- )
- ) {
- // Container types should be the same as for domestic
- $params->setCountryRecipient(self::USA_COUNTRY_ID);
- $containerTypes = $this->_getAllowedContainers($params);
- $params->setCountryRecipient($countryRecipient);
- return $containerTypes;
- }
- return $this->_getAllowedContainers($params);
- }
-
- /**
- * Return all container types of carrier
- *
- * @return array
- */
- public function getContainerTypesAll()
- {
- $codes = $this->getCode('container');
- $descriptions = $this->getCode('container_description');
- $result = [];
- foreach ($codes as $key => &$code) {
- $result[$code] = $descriptions[$key];
- }
- return $result;
- }
-
- /**
- * Return structured data of containers witch related with shipping methods
- *
- * @return array|false
- */
- public function getContainerTypesFilter()
- {
- return $this->getCode('containers_filter');
- }
-
- /**
- * Return delivery confirmation types of carrier
- *
- * @return array
- */
- public function getDeliveryConfirmationTypes(?Varien_Object $params = null)
- {
- $countryRecipient = $params != null ? $params->getCountryRecipient() : null;
- $deliveryConfirmationTypes = [];
- switch ($this->_getDeliveryConfirmationLevel($countryRecipient)) {
- case self::DELIVERY_CONFIRMATION_PACKAGE:
- $deliveryConfirmationTypes = [
- 1 => Mage::helper('usa')->__('Delivery Confirmation'),
- 2 => Mage::helper('usa')->__('Signature Required'),
- 3 => Mage::helper('usa')->__('Adult Signature Required'),
- ];
- break;
- case self::DELIVERY_CONFIRMATION_SHIPMENT:
- $deliveryConfirmationTypes = [
- 1 => Mage::helper('usa')->__('Signature Required'),
- 2 => Mage::helper('usa')->__('Adult Signature Required'),
- ];
- }
- array_unshift($deliveryConfirmationTypes, Mage::helper('usa')->__('Not Required'));
-
- return $deliveryConfirmationTypes;
- }
-
- /**
- * Get Container Types, that could be customized for UPS carrier
- *
- * @return array
- */
- public function getCustomizableContainerTypes()
- {
- $result = [];
- $containerTypes = $this->getCode('container');
- foreach (parent::getCustomizableContainerTypes() as $containerType) {
- $result[$containerType] = $containerTypes[$containerType];
- }
- return $result;
- }
-
/**
* Get delivery confirmation level based on origin/destination
* Return null if delivery confirmation is not acceptable
@@ -2356,6 +2283,97 @@ protected function _parseRestResponse(string $rateResponse)
return $this->setRatePriceData($priceArr, $costArr, $errorTitle);
}
+ /**
+ * To receive access token
+ *
+ * @return string
+ * @throws Exception
+ */
+ protected function setAPIAccessRequest()
+ {
+ $userId = $this->getConfigData('client_id');
+ $userIdPass = $this->getConfigData('client_secret');
+ if ($this->getConfigFlag('mode_xml')) {
+ $authUrl = $this->_liveUrls['AuthUrl'];
+ } else {
+ $authUrl = $this->_defaultUrls['AuthUrl'];
+ }
+ return Mage::getModel('usa/shipping_carrier_upsAuth')->getAccessToken($userId, $userIdPass, $authUrl);
+ }
+
+ /**
+ * Set Tracking Response Data
+ *
+ * @param array $resultArr
+ * @param string $trackingValue
+ * @param string $errorTitle
+ */
+ private function setTrackingResultData($resultArr, $trackingValue, $errorTitle)
+ {
+ if (!$this->_trackingResult) {
+ $this->_trackingResult = Mage::getModel('shipping/tracking_result');
+ }
+
+ if ($resultArr) {
+ /** @var Mage_Shipping_Model_Tracking_Result_Status $tracking */
+ $tracking = Mage::getModel('shipping/tracking_result_status');
+ $tracking->setCarrier('ups');
+ $tracking->setCarrierTitle($this->getConfigData('title'));
+ $tracking->setTracking($trackingValue);
+ $tracking->addData($resultArr);
+ $this->_trackingResult->append($tracking);
+ } else {
+ /** @var Mage_Shipping_Model_Tracking_Result_Error $error */
+ $error = Mage::getModel('shipping/tracking_result_error');
+ $error->setCarrier('ups');
+ $error->setCarrierTitle($this->getConfigData('title'));
+ $error->setTracking($trackingValue);
+ $error->setErrorMessage($errorTitle);
+ $this->_trackingResult->append($error);
+ }
+ }
+
+ /**
+ * Return country code according to UPS
+ *
+ * @param string $countryCode
+ * @param string $regionCode
+ * @param string $postCode
+ * @return string
+ */
+ private function getNormalizedCountryCode($countryCode, $regionCode, $postCode)
+ {
+ //for UPS, puerto rico state for US will assume as puerto rico country
+ if ($countryCode == self::USA_COUNTRY_ID && ($postCode == '00912' || $regionCode == self::PUERTORICO_COUNTRY_ID)) {
+ $countryCode = self::PUERTORICO_COUNTRY_ID;
+ }
+
+ // For UPS, Guam state of the USA will be represented by Guam country
+ if ($countryCode == self::USA_COUNTRY_ID && $regionCode == self::GUAM_REGION_CODE) {
+ $countryCode = self::GUAM_COUNTRY_ID;
+ }
+
+ // For UPS, Las Palmas and Santa Cruz de Tenerife will be represented by Canary Islands country
+ if ($countryCode === 'ES' && ($regionCode === 'Las Palmas' || $regionCode === 'Santa Cruz de Tenerife')) {
+ $countryCode = 'IC';
+ }
+
+ return $countryCode;
+ }
+
+ private function generateShipmentDescription(array $items): string
+ {
+ $itemsDesc = [];
+ $itemsShipment = $items;
+ foreach ($itemsShipment as $itemShipment) {
+ $item = new Varien_Object();
+ $item->setData($itemShipment);
+ $itemsDesc[] = $item->getName();
+ }
+
+ return substr(implode(' ', $itemsDesc), 0, 35);
+ }
+
private function setRatePriceData(array $priceArr, array $costArr, string $errorTitle): Mage_Shipping_Model_Rate_Result
{
$result = Mage::getModel('shipping/rate_result');
@@ -2463,24 +2481,6 @@ private function processShippingRestRateForItem(
}
}
- /**
- * To receive access token
- *
- * @return string
- * @throws Exception
- */
- protected function setAPIAccessRequest()
- {
- $userId = $this->getConfigData('client_id');
- $userIdPass = $this->getConfigData('client_secret');
- if ($this->getConfigFlag('mode_xml')) {
- $authUrl = $this->_liveUrls['AuthUrl'];
- } else {
- $authUrl = $this->_defaultUrls['AuthUrl'];
- }
- return Mage::getModel('usa/shipping_carrier_upsAuth')->getAccessToken($userId, $userIdPass, $authUrl);
- }
-
/**
* Setting common request params for Rate Request
*/
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/UpsAuth.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/UpsAuth.php
index 628e984136b..710caa2e8bc 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/UpsAuth.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/UpsAuth.php
@@ -96,16 +96,16 @@ public function collectRates(Mage_Shipping_Model_Rate_Request $request)
/**
* @inheritDoc
*/
- protected function _doShipmentRequest(Varien_Object $request)
+ public function getAllowedMethods(): array
{
- return new Varien_Object();
+ return [];
}
/**
* @inheritDoc
*/
- public function getAllowedMethods(): array
+ protected function _doShipmentRequest(Varien_Object $request)
{
- return [];
+ return new Varien_Object();
}
}
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php
index acc2742bfac..54617027906 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php
@@ -278,249 +278,6 @@ public function isShippingLabelsAvailable()
return false;
}
- /**
- * Get quotes
- *
- * @return Mage_Shipping_Model_Rate_Result
- */
- protected function _getQuotes()
- {
- return $this->_getXmlQuotes();
- }
-
- /**
- * Set free method request
- *
- * @param $freeMethod
- */
- protected function _setFreeMethodRequest($freeMethod)
- {
- $r = $this->_rawRequest;
-
- $weight = $this->getTotalNumOfBoxes($r->getFreeMethodWeight());
- $r->setWeightPounds(floor($weight));
- $r->setWeightOunces(round(($weight - floor($weight)) * self::OUNCES_POUND, 1));
- $r->setService($freeMethod);
- }
-
- /**
- * Build RateV3 request, send it to USPS gateway and retrieve quotes in XML format
- *
- * @link http://www.usps.com/webtools/htm/Rate-Calculators-v2-3.htm
- * @return Mage_Shipping_Model_Rate_Result
- */
- protected function _getXmlQuotes()
- {
- $r = $this->_rawRequest;
-
- // The origin address(shipper) must be only in USA
- if (!$this->_isUSCountry($r->getOrigCountryId())) {
- $responseBody = '';
- return $this->_parseXmlResponse($responseBody);
- }
-
- if ($this->_isUSCountry($r->getDestCountryId())) {
- $xml = new SimpleXMLElement('');
- $xml->addAttribute('USERID', $r->getUserId());
- // according to usps v4 documentation
- $xml->addChild('Revision', '2');
-
- $package = $xml->addChild('Package');
- $package->addAttribute('ID', '0');
- $service = $this->getCode('service_to_code', $r->getService());
- if (!$service) {
- $service = $r->getService();
- }
- if ($r->getContainer() == 'FLAT RATE BOX' || $r->getContainer() == 'FLAT RATE ENVELOPE') {
- $service = 'Priority';
- }
- $package->addChild('Service', $service);
-
- // no matter Letter, Flat or Parcel, use Parcel
- if ($r->getService() == 'FIRST CLASS' || $r->getService() == 'FIRST CLASS HFP COMMERCIAL') {
- $package->addChild('FirstClassMailType', 'PARCEL');
- }
- if ($r->getService() == 'FIRST CLASS COMMERCIAL') {
- $package->addChild('FirstClassMailType', 'PACKAGE SERVICE');
- }
-
- $package->addChild('ZipOrigination', $r->getOrigPostal());
- //only 5 chars available
- $package->addChild('ZipDestination', substr($r->getDestPostal(), 0, 5));
- $package->addChild('Pounds', $r->getWeightPounds());
- $package->addChild('Ounces', $r->getWeightOunces());
- // Because some methods don't accept VARIABLE and (NON)RECTANGULAR containers
- $package->addChild('Container', $r->getContainer());
- $package->addChild('Size', $r->getSize());
- if ($r->getSize() == 'LARGE') {
- $package->addChild('Width', $r->getWidth());
- $package->addChild('Length', $r->getLength());
- $package->addChild('Height', $r->getHeight());
- if ($r->getContainer() == 'NONRECTANGULAR' || $r->getContainer() == 'VARIABLE') {
- $package->addChild('Girth', $r->getGirth());
- }
- }
- $package->addChild('Machinable', $r->getMachinable());
-
- $api = 'RateV4';
- } else {
- $xml = new SimpleXMLElement('');
- $xml->addAttribute('USERID', $r->getUserId());
- // according to usps v4 documentation
- $xml->addChild('Revision', '2');
-
- $package = $xml->addChild('Package');
- $package->addAttribute('ID', '0');
- $package->addChild('Pounds', $r->getWeightPounds());
- $package->addChild('Ounces', $r->getWeightOunces());
- $package->addChild('MailType', 'All');
- $package->addChild('ValueOfContents', $r->getValue());
- $package->addChild('Country', $r->getDestCountryName());
- $package->addChild('Container', $r->getContainer());
- $package->addChild('Size', $r->getSize());
- $width = $length = $height = $girth = '';
- if ($r->getSize() == 'LARGE') {
- $width = $r->getWidth();
- $length = $r->getLength();
- $height = $r->getHeight();
- if ($r->getContainer() == 'NONRECTANGULAR') {
- $girth = $r->getGirth();
- }
- }
- $package->addChild('Width', $width);
- $package->addChild('Length', $length);
- $package->addChild('Height', $height);
- $package->addChild('Girth', $girth);
-
- if ($this->_isCanada($r->getDestCountryId())) {
- //only 5 chars available
- $package->addChild('OriginZip', substr($r->getOrigPostal(), 0, 5));
- }
- $api = 'IntlRateV2';
- }
- $request = $xml->asXML();
-
- $responseBody = $this->_getCachedQuotes($request);
- if ($responseBody === null) {
- $debugData = ['request' => $request];
- try {
- $url = $this->getConfigData('gateway_url');
- if (!$url) {
- $url = $this->_defaultGatewayUrl;
- }
- $client = new Zend_Http_Client();
- $client->setUri($url);
- $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
- $client->setParameterGet('API', $api);
- $client->setParameterGet('XML', $request);
- $response = $client->request();
- $responseBody = $response->getBody();
-
- $debugData['result'] = $responseBody;
- $this->_setCachedQuotes($request, $responseBody);
- } catch (Exception $e) {
- $debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
- $responseBody = '';
- }
- $this->_debug($debugData);
- }
- return $this->_parseXmlResponse($responseBody);
- }
-
- /**
- * Parse calculated rates
- *
- * @link http://www.usps.com/webtools/htm/Rate-Calculators-v2-3.htm
- * @param string $response
- * @return Mage_Shipping_Model_Rate_Result|void
- */
- protected function _parseXmlResponse($response)
- {
- $r = $this->_rawRequest;
- $costArr = [];
- $priceArr = [];
- if (strlen(trim($response)) > 0) {
- if (strpos(trim($response), '') !== false) {
- $response = str_replace(
- '',
- '',
- $response,
- );
- }
- $xml = simplexml_load_string($response);
-
- if (is_object($xml)) {
- $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
- $serviceCodeToActualNameMap = [];
- /**
- * US Rates
- */
- if ($this->_isUSCountry($r->getDestCountryId())) {
- if (is_object($xml->Package) && is_object($xml->Package->Postage)) {
- foreach ($xml->Package->Postage as $postage) {
- $serviceName = $this->_filterServiceName((string) $postage->MailService);
- $serviceCodeMethod = $this->getCode('method_to_code', $serviceName);
- $serviceCode = $serviceCodeMethod ?: (string) $postage->attributes()->CLASSID;
- $serviceCodeToActualNameMap[$serviceCode] = $serviceName;
- if (in_array($serviceCode, $allowedMethods)) {
- $costArr[$serviceCode] = (string) $postage->Rate;
- $priceArr[$serviceCode] = $this->getMethodPrice(
- (float) $postage->Rate,
- $serviceCode,
- );
- }
- }
- asort($priceArr);
- }
- } else { // International Rates
- if (is_object($xml->Package) && is_object($xml->Package->Service)) {
- foreach ($xml->Package->Service as $service) {
- // phpcs:ignore Ecg.Performance.Loop.ArraySize
- if ($service->ServiceErrors->count()) {
- continue;
- }
- $serviceName = $this->_filterServiceName((string) $service->SvcDescription);
- $serviceCode = 'INT_' . (string) $service->attributes()->ID;
- $serviceCodeToActualNameMap[$serviceCode] = $serviceName;
- if (in_array($serviceCode, $allowedMethods)) {
- $costArr[$serviceCode] = (string) $service->Postage;
- $priceArr[$serviceCode] = $this->getMethodPrice(
- (float) $service->Postage,
- $serviceCode,
- );
- }
- }
- asort($priceArr);
- }
- }
- }
-
- $result = Mage::getModel('shipping/rate_result');
- if (empty($priceArr)) {
- $error = Mage::getModel('shipping/rate_result_error');
- $error->setCarrier('usps');
- $error->setCarrierTitle($this->getConfigData('title'));
- $error->setErrorMessage($this->getConfigData('specificerrmsg'));
- $result->append($error);
- } else {
- foreach ($priceArr as $method => $price) {
- $rate = Mage::getModel('shipping/rate_result_method');
- $rate->setCarrier('usps');
- $rate->setCarrierTitle($this->getConfigData('title'));
- $rate->setMethod($method);
- $rate->setMethodTitle($serviceCodeToActualNameMap[$method] ?? $this->getCode('method', $method));
- $rate->setCost($costArr[$method]);
- $rate->setPrice($price);
- $result->append($rate);
- }
- }
-
- return $result;
- }
- }
- }
-
/**
* Get configuration data of carrier
*
@@ -880,31 +637,420 @@ public function getCode($type, $code = '')
],
];
- if (!isset($codes[$type])) {
- return false;
- } elseif ($code === '') {
- return $codes[$type];
+ if (!isset($codes[$type])) {
+ return false;
+ } elseif ($code === '') {
+ return $codes[$type];
+ }
+
+ return $codes[$type][$code] ?? false;
+ }
+ /**
+ * Get tracking
+ *
+ * @param mixed $trackingData
+ * @return Mage_Shipping_Model_Rate_Result|null
+ */
+ public function getTracking($trackingData)
+ {
+ $this->setTrackingRequest();
+
+ if (!is_array($trackingData)) {
+ $trackingData = [$trackingData];
+ }
+
+ $this->_getXmlTracking($trackingData);
+
+ return $this->_result;
+ }
+
+ /**
+ * Get tracking response
+ *
+ * @return string
+ */
+ public function getResponse()
+ {
+ $statuses = '';
+ if ($this->_result instanceof Mage_Shipping_Model_Tracking_Result) {
+ if ($trackingData = $this->_result->getAllTrackings()) {
+ foreach ($trackingData as $tracking) {
+ if ($data = $tracking->getAllData()) {
+ if (!empty($data['track_summary'])) {
+ $statuses .= Mage::helper('usa')->__($data['track_summary']);
+ } else {
+ $statuses .= Mage::helper('usa')->__('Empty response');
+ }
+ }
+ }
+ }
+ }
+ if (empty($statuses)) {
+ $statuses = Mage::helper('usa')->__('Empty response');
+ }
+ return $statuses;
+ }
+
+ /**
+ * Get allowed shipping methods
+ *
+ * @return array
+ */
+ public function getAllowedMethods()
+ {
+ $allowed = explode(',', $this->getConfigData('allowed_methods'));
+ $arr = [];
+ foreach ($allowed as $k) {
+ $arr[$k] = $this->getCode('method', $k);
+ }
+ return $arr;
+ }
+
+ /**
+ * Return container types of carrier
+ *
+ * @return array|bool
+ */
+ public function getContainerTypes(?Varien_Object $params = null)
+ {
+ if (is_null($params)) {
+ return $this->_getAllowedContainers();
+ }
+ return $this->_isUSCountry($params->getCountryRecipient()) ? [] : $this->_getAllowedContainers($params);
+ }
+
+ /**
+ * Return all container types of carrier
+ *
+ * @return array|bool
+ */
+ public function getContainerTypesAll()
+ {
+ return $this->getCode('container');
+ }
+
+ /**
+ * Return structured data of containers witch related with shipping methods
+ *
+ * @return array|bool
+ */
+ public function getContainerTypesFilter()
+ {
+ return $this->getCode('containers_filter');
+ }
+
+ /**
+ * Return delivery confirmation types of carrier
+ *
+ * @return array
+ */
+ public function getDeliveryConfirmationTypes(?Varien_Object $params = null)
+ {
+ if ($params == null) {
+ return [];
+ }
+ $countryRecipient = $params->getCountryRecipient();
+ if ($this->_isUSCountry($countryRecipient)) {
+ return $this->getCode('delivery_confirmation_types');
+ } else {
+ return [];
+ }
+ }
+
+ /**
+ * Check whether girth is allowed for the USPS
+ *
+ * @param null|string $countyDest
+ * @return bool
+ */
+ public function isGirthAllowed($countyDest = null)
+ {
+ return $this->_isUSCountry($countyDest) ? false : true;
+ }
+
+ /**
+ * Return content types of package
+ *
+ * @return array
+ */
+ public function getContentTypes(Varien_Object $params)
+ {
+ $countryShipper = $params->getCountryShipper();
+ $countryRecipient = $params->getCountryRecipient();
+
+ if ($countryShipper == self::USA_COUNTRY_ID
+ && $countryRecipient != self::USA_COUNTRY_ID
+ ) {
+ return [
+ 'MERCHANDISE' => Mage::helper('usa')->__('Merchandise'),
+ 'SAMPLE' => Mage::helper('usa')->__('Sample'),
+ 'GIFT' => Mage::helper('usa')->__('Gift'),
+ 'DOCUMENTS' => Mage::helper('usa')->__('Documents'),
+ 'RETURN' => Mage::helper('usa')->__('Return'),
+ 'OTHER' => Mage::helper('usa')->__('Other'),
+ ];
+ }
+ return [];
+ }
+
+ /**
+ * @deprecated
+ */
+ public function getMethodLabel($value)
+ {
+ return $this->_methodsMapper($value, true);
+ }
+
+ /**
+ * Get value of method by its label
+ * @deprecated
+ */
+ public function getMethodValue($label)
+ {
+ return $this->_methodsMapper($label, false);
+ }
+
+ /**
+ * Get quotes
+ *
+ * @return Mage_Shipping_Model_Rate_Result
+ */
+ protected function _getQuotes()
+ {
+ return $this->_getXmlQuotes();
+ }
+
+ /**
+ * Set free method request
+ *
+ * @param $freeMethod
+ */
+ protected function _setFreeMethodRequest($freeMethod)
+ {
+ $r = $this->_rawRequest;
+
+ $weight = $this->getTotalNumOfBoxes($r->getFreeMethodWeight());
+ $r->setWeightPounds(floor($weight));
+ $r->setWeightOunces(round(($weight - floor($weight)) * self::OUNCES_POUND, 1));
+ $r->setService($freeMethod);
+ }
+
+ /**
+ * Build RateV3 request, send it to USPS gateway and retrieve quotes in XML format
+ *
+ * @link http://www.usps.com/webtools/htm/Rate-Calculators-v2-3.htm
+ * @return Mage_Shipping_Model_Rate_Result
+ */
+ protected function _getXmlQuotes()
+ {
+ $r = $this->_rawRequest;
+
+ // The origin address(shipper) must be only in USA
+ if (!$this->_isUSCountry($r->getOrigCountryId())) {
+ $responseBody = '';
+ return $this->_parseXmlResponse($responseBody);
+ }
+
+ if ($this->_isUSCountry($r->getDestCountryId())) {
+ $xml = new SimpleXMLElement('');
+ $xml->addAttribute('USERID', $r->getUserId());
+ // according to usps v4 documentation
+ $xml->addChild('Revision', '2');
+
+ $package = $xml->addChild('Package');
+ $package->addAttribute('ID', '0');
+ $service = $this->getCode('service_to_code', $r->getService());
+ if (!$service) {
+ $service = $r->getService();
+ }
+ if ($r->getContainer() == 'FLAT RATE BOX' || $r->getContainer() == 'FLAT RATE ENVELOPE') {
+ $service = 'Priority';
+ }
+ $package->addChild('Service', $service);
+
+ // no matter Letter, Flat or Parcel, use Parcel
+ if ($r->getService() == 'FIRST CLASS' || $r->getService() == 'FIRST CLASS HFP COMMERCIAL') {
+ $package->addChild('FirstClassMailType', 'PARCEL');
+ }
+ if ($r->getService() == 'FIRST CLASS COMMERCIAL') {
+ $package->addChild('FirstClassMailType', 'PACKAGE SERVICE');
+ }
+
+ $package->addChild('ZipOrigination', $r->getOrigPostal());
+ //only 5 chars available
+ $package->addChild('ZipDestination', substr($r->getDestPostal(), 0, 5));
+ $package->addChild('Pounds', $r->getWeightPounds());
+ $package->addChild('Ounces', $r->getWeightOunces());
+ // Because some methods don't accept VARIABLE and (NON)RECTANGULAR containers
+ $package->addChild('Container', $r->getContainer());
+ $package->addChild('Size', $r->getSize());
+ if ($r->getSize() == 'LARGE') {
+ $package->addChild('Width', $r->getWidth());
+ $package->addChild('Length', $r->getLength());
+ $package->addChild('Height', $r->getHeight());
+ if ($r->getContainer() == 'NONRECTANGULAR' || $r->getContainer() == 'VARIABLE') {
+ $package->addChild('Girth', $r->getGirth());
+ }
+ }
+ $package->addChild('Machinable', $r->getMachinable());
+
+ $api = 'RateV4';
+ } else {
+ $xml = new SimpleXMLElement('');
+ $xml->addAttribute('USERID', $r->getUserId());
+ // according to usps v4 documentation
+ $xml->addChild('Revision', '2');
+
+ $package = $xml->addChild('Package');
+ $package->addAttribute('ID', '0');
+ $package->addChild('Pounds', $r->getWeightPounds());
+ $package->addChild('Ounces', $r->getWeightOunces());
+ $package->addChild('MailType', 'All');
+ $package->addChild('ValueOfContents', $r->getValue());
+ $package->addChild('Country', $r->getDestCountryName());
+ $package->addChild('Container', $r->getContainer());
+ $package->addChild('Size', $r->getSize());
+ $width = $length = $height = $girth = '';
+ if ($r->getSize() == 'LARGE') {
+ $width = $r->getWidth();
+ $length = $r->getLength();
+ $height = $r->getHeight();
+ if ($r->getContainer() == 'NONRECTANGULAR') {
+ $girth = $r->getGirth();
+ }
+ }
+ $package->addChild('Width', $width);
+ $package->addChild('Length', $length);
+ $package->addChild('Height', $height);
+ $package->addChild('Girth', $girth);
+
+ if ($this->_isCanada($r->getDestCountryId())) {
+ //only 5 chars available
+ $package->addChild('OriginZip', substr($r->getOrigPostal(), 0, 5));
+ }
+ $api = 'IntlRateV2';
+ }
+ $request = $xml->asXML();
+
+ $responseBody = $this->_getCachedQuotes($request);
+ if ($responseBody === null) {
+ $debugData = ['request' => $request];
+ try {
+ $url = $this->getConfigData('gateway_url');
+ if (!$url) {
+ $url = $this->_defaultGatewayUrl;
+ }
+ $client = new Zend_Http_Client();
+ $client->setUri($url);
+ $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
+ $client->setParameterGet('API', $api);
+ $client->setParameterGet('XML', $request);
+ $response = $client->request();
+ $responseBody = $response->getBody();
+
+ $debugData['result'] = $responseBody;
+ $this->_setCachedQuotes($request, $responseBody);
+ } catch (Exception $e) {
+ $debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
+ $responseBody = '';
+ }
+ $this->_debug($debugData);
}
-
- return $codes[$type][$code] ?? false;
+ return $this->_parseXmlResponse($responseBody);
}
+
/**
- * Get tracking
+ * Parse calculated rates
*
- * @param mixed $trackingData
- * @return Mage_Shipping_Model_Rate_Result|null
+ * @link http://www.usps.com/webtools/htm/Rate-Calculators-v2-3.htm
+ * @param string $response
+ * @return Mage_Shipping_Model_Rate_Result|void
*/
- public function getTracking($trackingData)
+ protected function _parseXmlResponse($response)
{
- $this->setTrackingRequest();
+ $r = $this->_rawRequest;
+ $costArr = [];
+ $priceArr = [];
+ if (strlen(trim($response)) > 0) {
+ if (strpos(trim($response), '') !== false) {
+ $response = str_replace(
+ '',
+ '',
+ $response,
+ );
+ }
+ $xml = simplexml_load_string($response);
- if (!is_array($trackingData)) {
- $trackingData = [$trackingData];
- }
+ if (is_object($xml)) {
+ $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
+ $serviceCodeToActualNameMap = [];
+ /**
+ * US Rates
+ */
+ if ($this->_isUSCountry($r->getDestCountryId())) {
+ if (is_object($xml->Package) && is_object($xml->Package->Postage)) {
+ foreach ($xml->Package->Postage as $postage) {
+ $serviceName = $this->_filterServiceName((string) $postage->MailService);
+ $serviceCodeMethod = $this->getCode('method_to_code', $serviceName);
+ $serviceCode = $serviceCodeMethod ?: (string) $postage->attributes()->CLASSID;
+ $serviceCodeToActualNameMap[$serviceCode] = $serviceName;
+ if (in_array($serviceCode, $allowedMethods)) {
+ $costArr[$serviceCode] = (string) $postage->Rate;
+ $priceArr[$serviceCode] = $this->getMethodPrice(
+ (float) $postage->Rate,
+ $serviceCode,
+ );
+ }
+ }
+ asort($priceArr);
+ }
+ } else { // International Rates
+ if (is_object($xml->Package) && is_object($xml->Package->Service)) {
+ foreach ($xml->Package->Service as $service) {
+ // phpcs:ignore Ecg.Performance.Loop.ArraySize
+ if ($service->ServiceErrors->count()) {
+ continue;
+ }
+ $serviceName = $this->_filterServiceName((string) $service->SvcDescription);
+ $serviceCode = 'INT_' . (string) $service->attributes()->ID;
+ $serviceCodeToActualNameMap[$serviceCode] = $serviceName;
+ if (in_array($serviceCode, $allowedMethods)) {
+ $costArr[$serviceCode] = (string) $service->Postage;
+ $priceArr[$serviceCode] = $this->getMethodPrice(
+ (float) $service->Postage,
+ $serviceCode,
+ );
+ }
+ }
+ asort($priceArr);
+ }
+ }
+ }
- $this->_getXmlTracking($trackingData);
+ $result = Mage::getModel('shipping/rate_result');
+ if (empty($priceArr)) {
+ $error = Mage::getModel('shipping/rate_result_error');
+ $error->setCarrier('usps');
+ $error->setCarrierTitle($this->getConfigData('title'));
+ $error->setErrorMessage($this->getConfigData('specificerrmsg'));
+ $result->append($error);
+ } else {
+ foreach ($priceArr as $method => $price) {
+ $rate = Mage::getModel('shipping/rate_result_method');
+ $rate->setCarrier('usps');
+ $rate->setCarrierTitle($this->getConfigData('title'));
+ $rate->setMethod($method);
+ $rate->setMethodTitle($serviceCodeToActualNameMap[$method] ?? $this->getCode('method', $method));
+ $rate->setCost($costArr[$method]);
+ $rate->setPrice($price);
+ $result->append($rate);
+ }
+ }
- return $this->_result;
+ return $result;
+ }
+ }
}
/**
@@ -1019,48 +1165,6 @@ protected function _parseXmlTrackingResponse($trackingValue, $response)
}
}
- /**
- * Get tracking response
- *
- * @return string
- */
- public function getResponse()
- {
- $statuses = '';
- if ($this->_result instanceof Mage_Shipping_Model_Tracking_Result) {
- if ($trackingData = $this->_result->getAllTrackings()) {
- foreach ($trackingData as $tracking) {
- if ($data = $tracking->getAllData()) {
- if (!empty($data['track_summary'])) {
- $statuses .= Mage::helper('usa')->__($data['track_summary']);
- } else {
- $statuses .= Mage::helper('usa')->__('Empty response');
- }
- }
- }
- }
- }
- if (empty($statuses)) {
- $statuses = Mage::helper('usa')->__('Empty response');
- }
- return $statuses;
- }
-
- /**
- * Get allowed shipping methods
- *
- * @return array
- */
- public function getAllowedMethods()
- {
- $allowed = explode(',', $this->getConfigData('allowed_methods'));
- $arr = [];
- foreach ($allowed as $k) {
- $arr[$k] = $this->getCode('method', $k);
- }
- return $arr;
- }
-
/**
* Return USPS county name by country ISO 3166-1-alpha-2 code
* Return false for unknown countries
@@ -1795,93 +1899,6 @@ protected function _doShipmentRequest(Varien_Object $request)
return $result;
}
- /**
- * Return container types of carrier
- *
- * @return array|bool
- */
- public function getContainerTypes(?Varien_Object $params = null)
- {
- if (is_null($params)) {
- return $this->_getAllowedContainers();
- }
- return $this->_isUSCountry($params->getCountryRecipient()) ? [] : $this->_getAllowedContainers($params);
- }
-
- /**
- * Return all container types of carrier
- *
- * @return array|bool
- */
- public function getContainerTypesAll()
- {
- return $this->getCode('container');
- }
-
- /**
- * Return structured data of containers witch related with shipping methods
- *
- * @return array|bool
- */
- public function getContainerTypesFilter()
- {
- return $this->getCode('containers_filter');
- }
-
- /**
- * Return delivery confirmation types of carrier
- *
- * @return array
- */
- public function getDeliveryConfirmationTypes(?Varien_Object $params = null)
- {
- if ($params == null) {
- return [];
- }
- $countryRecipient = $params->getCountryRecipient();
- if ($this->_isUSCountry($countryRecipient)) {
- return $this->getCode('delivery_confirmation_types');
- } else {
- return [];
- }
- }
-
- /**
- * Check whether girth is allowed for the USPS
- *
- * @param null|string $countyDest
- * @return bool
- */
- public function isGirthAllowed($countyDest = null)
- {
- return $this->_isUSCountry($countyDest) ? false : true;
- }
-
- /**
- * Return content types of package
- *
- * @return array
- */
- public function getContentTypes(Varien_Object $params)
- {
- $countryShipper = $params->getCountryShipper();
- $countryRecipient = $params->getCountryRecipient();
-
- if ($countryShipper == self::USA_COUNTRY_ID
- && $countryRecipient != self::USA_COUNTRY_ID
- ) {
- return [
- 'MERCHANDISE' => Mage::helper('usa')->__('Merchandise'),
- 'SAMPLE' => Mage::helper('usa')->__('Sample'),
- 'GIFT' => Mage::helper('usa')->__('Gift'),
- 'DOCUMENTS' => Mage::helper('usa')->__('Documents'),
- 'RETURN' => Mage::helper('usa')->__('Return'),
- 'OTHER' => Mage::helper('usa')->__('Other'),
- ];
- }
- return [];
- }
-
/**
* Parse zip from string to zip5-zip4
*
@@ -1920,23 +1937,6 @@ protected function _methodsMapper($method, $valuesToLabels = true)
return $method;
}
- /**
- * @deprecated
- */
- public function getMethodLabel($value)
- {
- return $this->_methodsMapper($value, true);
- }
-
- /**
- * Get value of method by its label
- * @deprecated
- */
- public function getMethodValue($label)
- {
- return $this->_methodsMapper($label, false);
- }
-
/**
* @deprecated
*/
diff --git a/app/code/core/Mage/Weee/Block/Renderer/Weee/Tax.php b/app/code/core/Mage/Weee/Block/Renderer/Weee/Tax.php
index 9168a2862c8..6d429b70f34 100644
--- a/app/code/core/Mage/Weee/Block/Renderer/Weee/Tax.php
+++ b/app/code/core/Mage/Weee/Block/Renderer/Weee/Tax.php
@@ -113,25 +113,6 @@ public function getValues()
return $values;
}
- /**
- * Sorts Weee Taxes
- *
- * @param array $a
- * @param array $b
- *
- * @return int
- */
- protected function _sortWeeeTaxes($a, $b)
- {
- if ($a['website_id'] != $b['website_id']) {
- return $a['website_id'] < $b['website_id'] ? -1 : 1;
- }
- if ($a['country'] != $b['country']) {
- return $a['country'] < $b['country'] ? -1 : 1;
- }
- return 0;
- }
-
/**
* Retrieves number of websites
*
@@ -206,6 +187,35 @@ public function getWebsites()
return $this->_websites;
}
+ /**
+ * Retrieve add button html
+ *
+ * @return string
+ */
+ public function getAddButtonHtml()
+ {
+ return $this->getChildHtml('add_button');
+ }
+
+ /**
+ * Sorts Weee Taxes
+ *
+ * @param array $a
+ * @param array $b
+ *
+ * @return int
+ */
+ protected function _sortWeeeTaxes($a, $b)
+ {
+ if ($a['website_id'] != $b['website_id']) {
+ return $a['website_id'] < $b['website_id'] ? -1 : 1;
+ }
+ if ($a['country'] != $b['country']) {
+ return $a['country'] < $b['country'] ? -1 : 1;
+ }
+ return 0;
+ }
+
/**
* Set add button and its properties
*/
@@ -221,14 +231,4 @@ protected function _setAddButton()
]),
);
}
-
- /**
- * Retrieve add button html
- *
- * @return string
- */
- public function getAddButtonHtml()
- {
- return $this->getChildHtml('add_button');
- }
}
diff --git a/app/code/core/Mage/Weee/Model/Attribute/Backend/Weee/Tax.php b/app/code/core/Mage/Weee/Model/Attribute/Backend/Weee/Tax.php
index 03da17c1307..c5c8092c2bd 100644
--- a/app/code/core/Mage/Weee/Model/Attribute/Backend/Weee/Tax.php
+++ b/app/code/core/Mage/Weee/Model/Attribute/Backend/Weee/Tax.php
@@ -23,16 +23,6 @@ public static function getBackendModelName()
return 'weee/attribute_backend_weee_tax';
}
- /**
- * Retrieve resource model
- *
- * @return Mage_Weee_Model_Resource_Attribute_Backend_Weee_Tax
- */
- protected function _getResource()
- {
- return Mage::getResourceSingleton(self::getBackendModelName());
- }
-
/**
* Validate data
*
@@ -151,4 +141,14 @@ public function getTable()
{
return $this->_getResource()->getTable('weee/tax');
}
+
+ /**
+ * Retrieve resource model
+ *
+ * @return Mage_Weee_Model_Resource_Attribute_Backend_Weee_Tax
+ */
+ protected function _getResource()
+ {
+ return Mage::getResourceSingleton(self::getBackendModelName());
+ }
}
diff --git a/app/code/core/Mage/Weee/Model/Observer.php b/app/code/core/Mage/Weee/Model/Observer.php
index 0b86eab3b76..fb4f603d41d 100644
--- a/app/code/core/Mage/Weee/Model/Observer.php
+++ b/app/code/core/Mage/Weee/Model/Observer.php
@@ -160,16 +160,6 @@ public function prepareCatalogIndexSelect(Varien_Event_Observer $observer)
return $this;
}
- /**
- * Get empty select object
- *
- * @return Varien_Db_Select
- */
- protected function _getSelect()
- {
- return Mage::getSingleton('weee/tax')->getResource()->getReadConnection()->select();
- }
-
/**
* Add new attribute type to manage attributes interface
*
@@ -385,4 +375,14 @@ public function setSessionQuoteStore(Varien_Event_Observer $observer)
return $this;
}
+
+ /**
+ * Get empty select object
+ *
+ * @return Varien_Db_Select
+ */
+ protected function _getSelect()
+ {
+ return Mage::getSingleton('weee/tax')->getResource()->getReadConnection()->select();
+ }
}
diff --git a/app/code/core/Mage/Weee/Model/Resource/Attribute/Backend/Weee/Tax.php b/app/code/core/Mage/Weee/Model/Resource/Attribute/Backend/Weee/Tax.php
index f66c6f5add1..b65a73faa80 100644
--- a/app/code/core/Mage/Weee/Model/Resource/Attribute/Backend/Weee/Tax.php
+++ b/app/code/core/Mage/Weee/Model/Resource/Attribute/Backend/Weee/Tax.php
@@ -22,15 +22,6 @@
*/
class Mage_Weee_Model_Resource_Attribute_Backend_Weee_Tax extends Mage_Core_Model_Resource_Db_Abstract
{
- /**
- * Defines main resource table and table identifier field
- *
- */
- protected function _construct()
- {
- $this->_init('weee/tax', 'value_id');
- }
-
/**
* Load product data
*
@@ -100,4 +91,12 @@ public function insertProductData($product, $data)
$this->_getWriteAdapter()->insert($this->getMainTable(), $data);
return $this;
}
+ /**
+ * Defines main resource table and table identifier field
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('weee/tax', 'value_id');
+ }
}
diff --git a/app/code/core/Mage/Weee/Model/Resource/Tax.php b/app/code/core/Mage/Weee/Model/Resource/Tax.php
index d11ef452cde..613ab3c7e5d 100644
--- a/app/code/core/Mage/Weee/Model/Resource/Tax.php
+++ b/app/code/core/Mage/Weee/Model/Resource/Tax.php
@@ -22,11 +22,6 @@
*/
class Mage_Weee_Model_Resource_Tax extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('weee/tax', 'value_id');
- }
-
/**
* Fetch one
*
@@ -70,6 +65,29 @@ public function updateProductsDiscountPercent($condition)
return $this->_updateDiscountPercents($condition);
}
+ /**
+ * Retrieve product discount percent
+ *
+ * @param int $productId
+ * @param int $websiteId
+ * @param int $customerGroupId
+ * @return string
+ */
+ public function getProductDiscountPercent($productId, $websiteId, $customerGroupId)
+ {
+ $select = $this->_getReadAdapter()->select();
+ $select->from($this->getTable('weee/discount'), 'value')
+ ->where('website_id = ?', (int) $websiteId)
+ ->where('entity_id = ?', (int) $productId)
+ ->where('customer_group_id = ?', (int) $customerGroupId);
+
+ return $this->_getReadAdapter()->fetchOne($select);
+ }
+ protected function _construct()
+ {
+ $this->_init('weee/tax', 'value_id');
+ }
+
/**
* Update tax percents for WEEE based on products condition
*
@@ -146,23 +164,4 @@ protected function _updateDiscountPercents($productCondition = null)
return $this;
}
-
- /**
- * Retrieve product discount percent
- *
- * @param int $productId
- * @param int $websiteId
- * @param int $customerGroupId
- * @return string
- */
- public function getProductDiscountPercent($productId, $websiteId, $customerGroupId)
- {
- $select = $this->_getReadAdapter()->select();
- $select->from($this->getTable('weee/discount'), 'value')
- ->where('website_id = ?', (int) $websiteId)
- ->where('entity_id = ?', (int) $productId)
- ->where('customer_group_id = ?', (int) $customerGroupId);
-
- return $this->_getReadAdapter()->fetchOne($select);
- }
}
diff --git a/app/code/core/Mage/Weee/Model/Tax.php b/app/code/core/Mage/Weee/Model/Tax.php
index 06a1c3b462d..bdeb5814d3e 100644
--- a/app/code/core/Mage/Weee/Model/Tax.php
+++ b/app/code/core/Mage/Weee/Model/Tax.php
@@ -63,14 +63,6 @@ class Mage_Weee_Model_Tax extends Mage_Core_Model_Abstract
*/
protected $_taxHelper;
- /**
- * Initialize resource
- */
- protected function _construct()
- {
- $this->_init('weee/tax', 'weee/tax');
- }
-
/**
* Initialize tax helper
*/
@@ -265,29 +257,6 @@ public function getProductWeeeAttributes(
return $result;
}
- /**
- * Get discount percentage for a product
- *
- * @param Mage_Catalog_Model_Product $product
- * @return int
- */
- protected function _getDiscountPercentForProduct($product)
- {
- $website = Mage::app()->getStore()->getWebsiteId();
- $group = Mage::getSingleton('customer/session')->getCustomerGroupId();
- $key = implode('-', [$website, $group, $product->getId()]);
- if (!isset($this->_productDiscounts[$key])) {
- $this->_productDiscounts[$key] = (int) $this->getResource()
- ->getProductDiscountPercent($product->getId(), $website, $group);
- }
- $value = $this->_productDiscounts[$key];
- if ($value) {
- return 100 - min(100, max(0, $value));
- } else {
- return 0;
- }
- }
-
/**
* Update discounts for FPT amounts of all products
*
@@ -310,4 +279,35 @@ public function updateProductsDiscountPercent($products)
$this->getResource()->updateProductsDiscountPercent($products);
return $this;
}
+
+ /**
+ * Initialize resource
+ */
+ protected function _construct()
+ {
+ $this->_init('weee/tax', 'weee/tax');
+ }
+
+ /**
+ * Get discount percentage for a product
+ *
+ * @param Mage_Catalog_Model_Product $product
+ * @return int
+ */
+ protected function _getDiscountPercentForProduct($product)
+ {
+ $website = Mage::app()->getStore()->getWebsiteId();
+ $group = Mage::getSingleton('customer/session')->getCustomerGroupId();
+ $key = implode('-', [$website, $group, $product->getId()]);
+ if (!isset($this->_productDiscounts[$key])) {
+ $this->_productDiscounts[$key] = (int) $this->getResource()
+ ->getProductDiscountPercent($product->getId(), $website, $group);
+ }
+ $value = $this->_productDiscounts[$key];
+ if ($value) {
+ return 100 - min(100, max(0, $value));
+ } else {
+ return 0;
+ }
+ }
}
diff --git a/app/code/core/Mage/Weee/Model/Total/Quote/Weee.php b/app/code/core/Mage/Weee/Model/Total/Quote/Weee.php
index 63536207fb3..2d1cfa02af2 100644
--- a/app/code/core/Mage/Weee/Model/Total/Quote/Weee.php
+++ b/app/code/core/Mage/Weee/Model/Total/Quote/Weee.php
@@ -104,6 +104,59 @@ public function collect(Mage_Sales_Model_Quote_Address $address)
return $this;
}
+ /**
+ * Fetch FPT data to address object for display in totals block
+ *
+ * @return $this
+ */
+ public function fetch(Mage_Sales_Model_Quote_Address $address)
+ {
+ return $this;
+ }
+
+ /**
+ * Process model configuration array.
+ * This method can be used for changing totals collect sort order
+ *
+ * @param array $config
+ * @param Mage_Core_Model_Store $store
+ * @return array
+ */
+ public function processConfigArray($config, $store)
+ {
+ return $config;
+ }
+
+ /**
+ * Set the helper object.
+ *
+ * @param Mage_Weee_Helper_Data $helper
+ */
+ public function setHelper($helper)
+ {
+ $this->_helper = $helper;
+ }
+
+ /**
+ * Set the store Object
+ *
+ * @param Mage_Core_Model_Store $store
+ */
+ public function setStore($store)
+ {
+ $this->_store = $store;
+ }
+
+ /**
+ * No aggregated label for fixed product tax
+ *
+ * TODO: fix
+ */
+ public function getLabel()
+ {
+ return '';
+ }
+
/**
* Calculate item fixed tax and prepare information for discount and recular taxation
*
@@ -362,29 +415,6 @@ protected function _resetItemData($item)
$item->setWeeeTaxAppliedRowAmount(0);
}
- /**
- * Fetch FPT data to address object for display in totals block
- *
- * @return $this
- */
- public function fetch(Mage_Sales_Model_Quote_Address $address)
- {
- return $this;
- }
-
- /**
- * Process model configuration array.
- * This method can be used for changing totals collect sort order
- *
- * @param array $config
- * @param Mage_Core_Model_Store $store
- * @return array
- */
- public function processConfigArray($config, $store)
- {
- return $config;
- }
-
/**
* Process item fixed taxes
*
@@ -608,34 +638,4 @@ protected function _getCalculator()
{
return Mage::getSingleton('tax/calculation');
}
-
- /**
- * Set the helper object.
- *
- * @param Mage_Weee_Helper_Data $helper
- */
- public function setHelper($helper)
- {
- $this->_helper = $helper;
- }
-
- /**
- * Set the store Object
- *
- * @param Mage_Core_Model_Store $store
- */
- public function setStore($store)
- {
- $this->_store = $store;
- }
-
- /**
- * No aggregated label for fixed product tax
- *
- * TODO: fix
- */
- public function getLabel()
- {
- return '';
- }
}
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit.php
index 8e55e480226..8291fbb98b1 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit.php
@@ -22,14 +22,6 @@
*/
class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
- protected function _construct()
- {
- parent::_construct();
- $this->_objectId = 'instance_id';
- $this->_blockGroup = 'widget';
- $this->_controller = 'adminhtml_widget_instance';
- }
-
/**
* Getter
*
@@ -40,30 +32,6 @@ public function getWidgetInstance()
return Mage::registry('current_widget_instance');
}
- /**
- * Prepare layout.
- * Adding save_and_continue button
- *
- * @inheritDoc
- */
- protected function _preparelayout()
- {
- if ($this->getWidgetInstance()->isCompleteToCreate()) {
- $this->_addButton(
- 'save_and_edit_button',
- [
- 'label' => Mage::helper('widget')->__('Save and Continue Edit'),
- 'class' => 'save',
- 'onclick' => 'saveAndContinueEdit()',
- ],
- 100,
- );
- } else {
- $this->removeButton('save');
- }
- return parent::_prepareLayout();
- }
-
/**
* Return translated header text depending on creating/editing action
*
@@ -96,4 +64,35 @@ public function getSaveUrl()
{
return $this->getUrl('*/*/save', ['_current' => true, 'back' => null]);
}
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_objectId = 'instance_id';
+ $this->_blockGroup = 'widget';
+ $this->_controller = 'adminhtml_widget_instance';
+ }
+
+ /**
+ * Prepare layout.
+ * Adding save_and_continue button
+ *
+ * @inheritDoc
+ */
+ protected function _preparelayout()
+ {
+ if ($this->getWidgetInstance()->isCompleteToCreate()) {
+ $this->_addButton(
+ 'save_and_edit_button',
+ [
+ 'label' => Mage::helper('widget')->__('Save and Continue Edit'),
+ 'class' => 'save',
+ 'onclick' => 'saveAndContinueEdit()',
+ ],
+ 100,
+ );
+ } else {
+ $this->removeButton('save');
+ }
+ return parent::_prepareLayout();
+ }
}
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Block.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Block.php
index ff41f830a7f..035e3a5a9ff 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Block.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Block.php
@@ -145,23 +145,6 @@ public function getTheme()
return $this->_getData('theme');
}
- /**
- * Prepare html output
- *
- * @return string
- */
- protected function _toHtml()
- {
- $selectBlock = $this->getLayout()->createBlock('core/html_select')
- ->setName('block')
- ->setClass('required-entry select')
- ->setExtraParams('onchange="WidgetInstance.loadSelectBoxByType(\'block_template\','
- . ' this.up(\'div.group_container\'), this.value)"')
- ->setOptions($this->getBlocks())
- ->setValue($this->getSelected());
- return parent::_toHtml() . $selectBlock->toHtml();
- }
-
/**
* Retrieve blocks array
*
@@ -186,18 +169,6 @@ public function getBlocks()
return $this->_blocks;
}
- /**
- * Merging layout handles and create xml of merged layout handles
- */
- protected function _collectLayoutHandles()
- {
- foreach ($this->getLayoutHandle() as $handle) {
- $this->_mergeLayoutHandles($handle);
- }
- $updatesStr = '<' . '?xml version="1.0"?' . '>' . implode('', $this->_layoutHandleUpdates) . '';
- $this->_layoutHandleUpdatesXml = simplexml_load_string($updatesStr, 'Varien_Simplexml_Element');
- }
-
/**
* Adding layout handle that specified in node 'update' to general layout handles
*
@@ -215,6 +186,35 @@ public function _mergeLayoutHandles($handle)
}
}
+ /**
+ * Prepare html output
+ *
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ $selectBlock = $this->getLayout()->createBlock('core/html_select')
+ ->setName('block')
+ ->setClass('required-entry select')
+ ->setExtraParams('onchange="WidgetInstance.loadSelectBoxByType(\'block_template\','
+ . ' this.up(\'div.group_container\'), this.value)"')
+ ->setOptions($this->getBlocks())
+ ->setValue($this->getSelected());
+ return parent::_toHtml() . $selectBlock->toHtml();
+ }
+
+ /**
+ * Merging layout handles and create xml of merged layout handles
+ */
+ protected function _collectLayoutHandles()
+ {
+ foreach ($this->getLayoutHandle() as $handle) {
+ $this->_mergeLayoutHandles($handle);
+ }
+ $updatesStr = '<' . '?xml version="1.0"?' . '>' . implode('', $this->_layoutHandleUpdates) . '';
+ $this->_layoutHandleUpdatesXml = simplexml_load_string($updatesStr, 'Varien_Simplexml_Element');
+ }
+
/**
* Filter and collect blocks into array
*/
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Layout.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Layout.php
index 71acf7b6673..745416dee40 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Layout.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Layout.php
@@ -103,6 +103,25 @@ public function getTheme()
return $this->_getData('theme');
}
+ /**
+ * Retrieve layout handles
+ *
+ * @param string $area
+ * @param string $package
+ * @param string $theme
+ * @return array
+ */
+ public function getLayoutHandles($area, $package, $theme)
+ {
+ if (empty($this->_layoutHandles)) {
+ /** @var Mage_Core_Model_Layout_Update $update */
+ $update = Mage::getModel('core/layout')->getUpdate();
+ $this->_layoutHandles[''] = Mage::helper('widget')->__('-- Please Select --');
+ $this->_collectLayoutHandles($update->getFileLayoutUpdatesXml($area, $package, $theme));
+ }
+ return $this->_layoutHandles;
+ }
+
/**
* Prepare html output
*
@@ -124,25 +143,6 @@ protected function _toHtml()
return parent::_toHtml() . $selectBlock->toHtml();
}
- /**
- * Retrieve layout handles
- *
- * @param string $area
- * @param string $package
- * @param string $theme
- * @return array
- */
- public function getLayoutHandles($area, $package, $theme)
- {
- if (empty($this->_layoutHandles)) {
- /** @var Mage_Core_Model_Layout_Update $update */
- $update = Mage::getModel('core/layout')->getUpdate();
- $this->_layoutHandles[''] = Mage::helper('widget')->__('-- Please Select --');
- $this->_collectLayoutHandles($update->getFileLayoutUpdatesXml($area, $package, $theme));
- }
- return $this->_layoutHandles;
- }
-
/**
* Filter and collect layout handles into array
*
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main.php
index 82db4d77318..a4dfc3d78b0 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main.php
@@ -22,12 +22,6 @@
*/
class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
- protected function _construct()
- {
- parent::_construct();
- $this->setActive(true);
- }
-
/**
* Prepare label for tab
*
@@ -78,6 +72,32 @@ public function getWidgetInstance()
return Mage::registry('current_widget_instance');
}
+ /**
+ * Retrieve array (widget_type => widget_name) of available widgets
+ *
+ * @return array
+ */
+ public function getTypesOptionsArray()
+ {
+ return $this->getWidgetInstance()->getWidgetsOptionArray();
+ }
+
+ /**
+ * Retrieve design package/theme options array
+ *
+ * @return array
+ */
+ public function getPackegeThemeOptionsArray()
+ {
+ return Mage::getModel('core/design_source_design')
+ ->setIsFullLabel(true)->getAllOptions(true);
+ }
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setActive(true);
+ }
+
/**
* Prepare form before rendering HTML
*
@@ -167,27 +187,6 @@ protected function _prepareForm()
return parent::_prepareForm();
}
- /**
- * Retrieve array (widget_type => widget_name) of available widgets
- *
- * @return array
- */
- public function getTypesOptionsArray()
- {
- return $this->getWidgetInstance()->getWidgetsOptionArray();
- }
-
- /**
- * Retrieve design package/theme options array
- *
- * @return array
- */
- public function getPackegeThemeOptionsArray()
- {
- return Mage::getModel('core/design_source_design')
- ->setIsFullLabel(true)->getAllOptions(true);
- }
-
/**
* Initialize form fields values
*
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/Layout.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/Layout.php
index c3bb8285b6b..86d5f1d914f 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/Layout.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/Layout.php
@@ -30,15 +30,6 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout extends M
*/
protected $_element = null;
- /**
- * Internal constructor
- */
- protected function _construct()
- {
- parent::_construct();
- $this->setTemplate('widget/instance/edit/layout.phtml');
- }
-
/**
* Render given element (return html of element)
*
@@ -127,64 +118,6 @@ public function getDisplayOnSelectHtml()
return $selectBlock->toHtml();
}
- /**
- * Retrieve Display On options array.
- * - Categories (anchor and not anchor)
- * - Products (product types depend on configuration)
- * - Generic (predefined) pages (all pages and single layout update)
- *
- * @return array
- */
- protected function _getDisplayOnOptions()
- {
- $options = [];
- $options[] = [
- 'value' => '',
- 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('-- Please Select --')),
- ];
- $options[] = [
- 'label' => Mage::helper('widget')->__('Categories'),
- 'value' => [
- [
- 'value' => 'anchor_categories',
- 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Anchor Categories')),
- ],
- [
- 'value' => 'notanchor_categories',
- 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Non-Anchor Categories')),
- ],
- ],
- ];
- foreach (Mage_Catalog_Model_Product_Type::getTypes() as $typeId => $type) {
- $productsOptions[] = [
- 'value' => $typeId . '_products',
- 'label' => $this->helper('core')->jsQuoteEscape($type['label']),
- ];
- }
- array_unshift($productsOptions, [
- 'value' => 'all_products',
- 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('All Product Types')),
- ]);
- $options[] = [
- 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Products')),
- 'value' => $productsOptions,
- ];
- $options[] = [
- 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Generic Pages')),
- 'value' => [
- [
- 'value' => 'all_pages',
- 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('All Pages')),
- ],
- [
- 'value' => 'pages',
- 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Specified Page')),
- ],
- ],
- ];
- return $options;
- }
-
/**
* Generate array of parameters for every container type to create html template
*
@@ -302,4 +235,71 @@ public function getPageGroups()
}
return $pageGroups;
}
+
+ /**
+ * Internal constructor
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('widget/instance/edit/layout.phtml');
+ }
+
+ /**
+ * Retrieve Display On options array.
+ * - Categories (anchor and not anchor)
+ * - Products (product types depend on configuration)
+ * - Generic (predefined) pages (all pages and single layout update)
+ *
+ * @return array
+ */
+ protected function _getDisplayOnOptions()
+ {
+ $options = [];
+ $options[] = [
+ 'value' => '',
+ 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('-- Please Select --')),
+ ];
+ $options[] = [
+ 'label' => Mage::helper('widget')->__('Categories'),
+ 'value' => [
+ [
+ 'value' => 'anchor_categories',
+ 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Anchor Categories')),
+ ],
+ [
+ 'value' => 'notanchor_categories',
+ 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Non-Anchor Categories')),
+ ],
+ ],
+ ];
+ foreach (Mage_Catalog_Model_Product_Type::getTypes() as $typeId => $type) {
+ $productsOptions[] = [
+ 'value' => $typeId . '_products',
+ 'label' => $this->helper('core')->jsQuoteEscape($type['label']),
+ ];
+ }
+ array_unshift($productsOptions, [
+ 'value' => 'all_products',
+ 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('All Product Types')),
+ ]);
+ $options[] = [
+ 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Products')),
+ 'value' => $productsOptions,
+ ];
+ $options[] = [
+ 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Generic Pages')),
+ 'value' => [
+ [
+ 'value' => 'all_pages',
+ 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('All Pages')),
+ ],
+ [
+ 'value' => 'pages',
+ 'label' => $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Specified Page')),
+ ],
+ ],
+ ];
+ return $options;
+ }
}
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php
index efe02e63cc8..2029c9935e7 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php
@@ -22,12 +22,6 @@
*/
class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Settings extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
- protected function _construct()
- {
- parent::_construct();
- $this->setActive(true);
- }
-
/**
* Prepare label for tab
*
@@ -78,6 +72,52 @@ public function getWidgetInstance()
return Mage::registry('current_widget_instance');
}
+ /**
+ * Return url for continue button
+ *
+ * @return string
+ */
+ public function getContinueUrl()
+ {
+ return $this->getUrl('*/*/*', [
+ '_current' => true,
+ 'type' => '{{type}}',
+ 'package' => '{{package}}',
+ 'theme' => '{{theme}}',
+ ]);
+ }
+
+ /**
+ * Retrieve array (widget_type => widget_name) of available widgets
+ *
+ * @return array
+ */
+ public function getTypesOptionsArray()
+ {
+ $widgets = $this->getWidgetInstance()->getWidgetsOptionArray();
+ array_unshift($widgets, [
+ 'value' => '',
+ 'label' => Mage::helper('widget')->__('-- Please Select --'),
+ ]);
+ return $widgets;
+ }
+
+ /**
+ * Retrieve package/theme options array
+ *
+ * @return array
+ */
+ public function getPackegeThemeOptionsArray()
+ {
+ return Mage::getModel('core/design_source_design')
+ ->setIsFullLabel(true)->getAllOptions(true);
+ }
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->setActive(true);
+ }
+
/**
* Prepare form before rendering HTML
*
@@ -130,36 +170,6 @@ protected function _prepareForm()
return parent::_prepareForm();
}
- /**
- * Return url for continue button
- *
- * @return string
- */
- public function getContinueUrl()
- {
- return $this->getUrl('*/*/*', [
- '_current' => true,
- 'type' => '{{type}}',
- 'package' => '{{package}}',
- 'theme' => '{{theme}}',
- ]);
- }
-
- /**
- * Retrieve array (widget_type => widget_name) of available widgets
- *
- * @return array
- */
- public function getTypesOptionsArray()
- {
- $widgets = $this->getWidgetInstance()->getWidgetsOptionArray();
- array_unshift($widgets, [
- 'value' => '',
- 'label' => Mage::helper('widget')->__('-- Please Select --'),
- ]);
- return $widgets;
- }
-
/**
* User-defined widgets sorting by Name
*
@@ -171,15 +181,4 @@ protected function _sortWidgets($a, $b)
{
return strcmp($a['label'], $b['label']);
}
-
- /**
- * Retrieve package/theme options array
- *
- * @return array
- */
- public function getPackegeThemeOptionsArray()
- {
- return Mage::getModel('core/design_source_design')
- ->setIsFullLabel(true)->getAllOptions(true);
- }
}
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Grid.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Grid.php
index 86afc855543..48dca349a2b 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Grid.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Grid.php
@@ -22,6 +22,53 @@
*/
class Mage_Widget_Block_Adminhtml_Widget_Instance_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
+ /**
+ * Retrieve array (widget_type => widget_name) of available widgets
+ *
+ * @return array
+ */
+ public function getTypesOptionsArray()
+ {
+ $widgets = [];
+ $widgetsOptionsArr = Mage::getModel('widget/widget_instance')->getWidgetsOptionArray();
+ foreach ($widgetsOptionsArr as $widget) {
+ $widgets[$widget['value']] = $widget['label'];
+ }
+ return $widgets;
+ }
+
+ /**
+ * Retrieve design package/theme options array
+ *
+ * @return array
+ */
+ public function getPackageThemeOptionsArray()
+ {
+ $packageThemeArray = [];
+ $packageThemeOptions = Mage::getModel('core/design_source_design')
+ ->setIsFullLabel(true)->getAllOptions(false);
+ foreach ($packageThemeOptions as $item) {
+ if (is_array($item['value'])) {
+ foreach ($item['value'] as $valueItem) {
+ $packageThemeArray[$valueItem['value']] = $valueItem['label'];
+ }
+ } else {
+ $packageThemeArray[$item['value']] = $item['label'];
+ }
+ }
+ return $packageThemeArray;
+ }
+
+ /**
+ * Row click url
+ *
+ * @param Mage_Widget_Model_Widget_Instance $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', ['instance_id' => $row->getId()]);
+ }
/**
* Internal constructor
*
@@ -91,52 +138,4 @@ protected function _prepareColumns()
return parent::_prepareColumns();
}
-
- /**
- * Retrieve array (widget_type => widget_name) of available widgets
- *
- * @return array
- */
- public function getTypesOptionsArray()
- {
- $widgets = [];
- $widgetsOptionsArr = Mage::getModel('widget/widget_instance')->getWidgetsOptionArray();
- foreach ($widgetsOptionsArr as $widget) {
- $widgets[$widget['value']] = $widget['label'];
- }
- return $widgets;
- }
-
- /**
- * Retrieve design package/theme options array
- *
- * @return array
- */
- public function getPackageThemeOptionsArray()
- {
- $packageThemeArray = [];
- $packageThemeOptions = Mage::getModel('core/design_source_design')
- ->setIsFullLabel(true)->getAllOptions(false);
- foreach ($packageThemeOptions as $item) {
- if (is_array($item['value'])) {
- foreach ($item['value'] as $valueItem) {
- $packageThemeArray[$valueItem['value']] = $valueItem['label'];
- }
- } else {
- $packageThemeArray[$item['value']] = $item['label'];
- }
- }
- return $packageThemeArray;
- }
-
- /**
- * Row click url
- *
- * @param Mage_Widget_Model_Widget_Instance $row
- * @return string
- */
- public function getRowUrl($row)
- {
- return $this->getUrl('*/*/edit', ['instance_id' => $row->getId()]);
- }
}
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Options.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Options.php
index fd1ec16a7d4..4845aaefced 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Options.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Options.php
@@ -39,21 +39,6 @@ class Mage_Widget_Block_Adminhtml_Widget_Options extends Mage_Adminhtml_Block_Wi
*/
protected $_translationHelper = null;
- /**
- * Prepare Widget Options Form and values according to specified type
- *
- * widget_type must be set in data before
- * widget_values may be set before to render element values
- *
- * @return $this
- */
- protected function _prepareForm()
- {
- $this->getForm()->setUseContainer(false);
- $this->addFields();
- return $this;
- }
-
/**
* Form getter/instantiation
*
@@ -118,6 +103,21 @@ public function addFields()
return $this;
}
+ /**
+ * Prepare Widget Options Form and values according to specified type
+ *
+ * widget_type must be set in data before
+ * widget_values may be set before to render element values
+ *
+ * @return $this
+ */
+ protected function _prepareForm()
+ {
+ $this->getForm()->setUseContainer(false);
+ $this->addFields();
+ return $this;
+ }
+
/**
* Add field to Options form based on parameter configuration
*
diff --git a/app/code/core/Mage/Widget/Model/Resource/Widget.php b/app/code/core/Mage/Widget/Model/Resource/Widget.php
index 2d5356ea89d..a293aa38b18 100644
--- a/app/code/core/Mage/Widget/Model/Resource/Widget.php
+++ b/app/code/core/Mage/Widget/Model/Resource/Widget.php
@@ -22,11 +22,6 @@
*/
class Mage_Widget_Model_Resource_Widget extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('widget/widget', 'widget_id');
- }
-
/**
* Retrieves pre-configured parameters for widget
*
@@ -49,4 +44,8 @@ public function loadPreconfiguredWidget($widgetId)
}
return false;
}
+ protected function _construct()
+ {
+ $this->_init('widget/widget', 'widget_id');
+ }
}
diff --git a/app/code/core/Mage/Widget/Model/Resource/Widget/Instance.php b/app/code/core/Mage/Widget/Model/Resource/Widget/Instance.php
index 0d65f9ab166..3c7fbdfa009 100644
--- a/app/code/core/Mage/Widget/Model/Resource/Widget/Instance.php
+++ b/app/code/core/Mage/Widget/Model/Resource/Widget/Instance.php
@@ -22,6 +22,21 @@
*/
class Mage_Widget_Model_Resource_Widget_Instance extends Mage_Core_Model_Resource_Db_Abstract
{
+ /**
+ * Get store ids to which specified item is assigned
+ *
+ * @param int $id
+ * @return array
+ */
+ public function lookupStoreIds($id)
+ {
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from($this->getMainTable(), 'store_ids')
+ ->where("{$this->getIdFieldName()} = ?", (int) $id);
+ $storeIds = $adapter->fetchOne($select);
+ return $storeIds ? explode(',', $storeIds) : [];
+ }
protected function _construct()
{
$this->_init('widget/widget_instance', 'instance_id');
@@ -247,20 +262,4 @@ protected function _deleteLayoutUpdates($layoutUpdateIds)
}
return $this;
}
-
- /**
- * Get store ids to which specified item is assigned
- *
- * @param int $id
- * @return array
- */
- public function lookupStoreIds($id)
- {
- $adapter = $this->_getReadAdapter();
- $select = $adapter->select()
- ->from($this->getMainTable(), 'store_ids')
- ->where("{$this->getIdFieldName()} = ?", (int) $id);
- $storeIds = $adapter->fetchOne($select);
- return $storeIds ? explode(',', $storeIds) : [];
- }
}
diff --git a/app/code/core/Mage/Widget/Model/Resource/Widget/Instance/Collection.php b/app/code/core/Mage/Widget/Model/Resource/Widget/Instance/Collection.php
index d1531471b19..e5e82476eb2 100644
--- a/app/code/core/Mage/Widget/Model/Resource/Widget/Instance/Collection.php
+++ b/app/code/core/Mage/Widget/Model/Resource/Widget/Instance/Collection.php
@@ -29,12 +29,6 @@ class Mage_Widget_Model_Resource_Widget_Instance_Collection extends Mage_Core_Mo
*/
protected $_map = ['fields' => ['type' => 'instance_type']];
- protected function _construct()
- {
- parent::_construct();
- $this->_init('widget/widget_instance');
- }
-
/**
* Filter by store ids
*
@@ -59,4 +53,10 @@ public function addStoreFilter($storeIds = [], $withDefaultStore = true)
return $this;
}
+
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->_init('widget/widget_instance');
+ }
}
diff --git a/app/code/core/Mage/Widget/Model/Widget/Instance.php b/app/code/core/Mage/Widget/Model/Widget/Instance.php
index b275f301ddf..a0cff661b20 100644
--- a/app/code/core/Mage/Widget/Model/Widget/Instance.php
+++ b/app/code/core/Mage/Widget/Model/Widget/Instance.php
@@ -64,109 +64,6 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
*/
protected $_eventPrefix = 'widget_widget_instance';
- /**
- * Internal Constructor
- */
- protected function _construct()
- {
- $this->_cacheTag = 'widget_instance';
- parent::_construct();
- $this->_init('widget/widget_instance');
- $this->_layoutHandles = [
- 'anchor_categories' => self::ANCHOR_CATEGORY_LAYOUT_HANDLE,
- 'notanchor_categories' => self::NOTANCHOR_CATEGORY_LAYOUT_HANDLE,
- 'all_products' => self::PRODUCT_LAYOUT_HANDLE,
- 'all_pages' => self::DEFAULT_LAYOUT_HANDLE,
- ];
- $this->_specificEntitiesLayoutHandles = [
- 'anchor_categories' => self::SINGLE_CATEGORY_LAYOUT_HANDLE,
- 'notanchor_categories' => self::SINGLE_CATEGORY_LAYOUT_HANDLE,
- 'all_products' => self::SINGLE_PRODUCT_LAYOUT_HANLDE,
- ];
- foreach (Mage_Catalog_Model_Product_Type::getTypes() as $typeId => $type) {
- $layoutHandle = str_replace('{{TYPE}}', $typeId, self::PRODUCT_TYPE_LAYOUT_HANDLE);
- $this->_layoutHandles[$typeId . '_products'] = $layoutHandle;
- $this->_specificEntitiesLayoutHandles[$typeId . '_products'] = self::SINGLE_PRODUCT_LAYOUT_HANLDE;
- }
- }
-
- /**
- * Init mapping array of short fields to
- * its full names
- *
- * @return Varien_Object
- */
- protected function _initOldFieldsMap()
- {
- $this->_oldFieldsMap = [
- 'type' => 'instance_type',
- ];
- return $this;
- }
-
- /**
- * Processing object before save data
- *
- * @inheritDoc
- */
- protected function _beforeSave()
- {
- $pageGroupIds = [];
- $tmpPageGroups = [];
- $pageGroups = $this->getData('page_groups');
- if ($pageGroups) {
- foreach ($pageGroups as $pageGroup) {
- if (isset($pageGroup[$pageGroup['page_group']])) {
- $pageGroupData = $pageGroup[$pageGroup['page_group']];
- if ($pageGroupData['page_id']) {
- $pageGroupIds[] = $pageGroupData['page_id'];
- }
- if ($pageGroup['page_group'] == 'pages') {
- $layoutHandle = $pageGroupData['layout_handle'];
- } else {
- $layoutHandle = $this->_layoutHandles[$pageGroup['page_group']];
- }
- if (!isset($pageGroupData['template'])) {
- $pageGroupData['template'] = '';
- }
- $tmpPageGroup = [
- 'page_id' => $pageGroupData['page_id'],
- 'group' => $pageGroup['page_group'],
- 'layout_handle' => $layoutHandle,
- 'for' => $pageGroupData['for'],
- 'block_reference' => $pageGroupData['block'],
- 'entities' => '',
- 'layout_handle_updates' => [$layoutHandle],
- 'template' => $pageGroupData['template'] ? $pageGroupData['template'] : '',
- ];
- if ($pageGroupData['for'] == self::SPECIFIC_ENTITIES) {
- $layoutHandleUpdates = [];
- foreach (explode(',', $pageGroupData['entities']) as $entity) {
- $layoutHandleUpdates[] = str_replace(
- '{{ID}}',
- $entity,
- $this->_specificEntitiesLayoutHandles[$pageGroup['page_group']],
- );
- }
- $tmpPageGroup['entities'] = $pageGroupData['entities'];
- $tmpPageGroup['layout_handle_updates'] = $layoutHandleUpdates;
- }
- $tmpPageGroups[] = $tmpPageGroup;
- }
- }
- }
- if (is_array($this->getData('store_ids'))) {
- $this->setData('store_ids', implode(',', $this->getData('store_ids')));
- }
- if (is_array($this->getData('widget_parameters'))) {
- $this->setData('widget_parameters', serialize($this->getData('widget_parameters')));
- }
- $this->setData('page_groups', $tmpPageGroups);
- $this->setData('page_group_ids', $pageGroupIds);
-
- return parent::_beforeSave();
- }
-
/**
* Validate widget instance data
*
@@ -216,19 +113,6 @@ public function getType()
return $this->_getData('type');
}
- /**
- * Replace '-' to '/', if was passed from request(GET request)
- *
- * @return $this
- */
- protected function _prepareType()
- {
- if (str_contains((string) $this->_getData('type'), '-')) {
- $this->setData('type', str_replace('-', '/', $this->_getData('type')));
- }
- return $this;
- }
-
/**
* Setter
* Prepare widget package theme
@@ -253,18 +137,6 @@ public function getPackageTheme()
return $this->_getData('package_theme');
}
- /**
- * Replace '_' to '/', if was set from request(GET request)
- *
- * @deprecated after 1.6.1.0-alpha1
- *
- * @return $this
- */
- protected function _preparePackageTheme()
- {
- return $this;
- }
-
/**
* Getter.
* If not set return default
@@ -305,21 +177,6 @@ public function getTheme()
return $this->_getData('theme');
}
- /**
- * Parse packageTheme and set parsed package and theme
- *
- * @return $this
- */
- protected function _parsePackageTheme()
- {
- if ($this->getPackageTheme() && strpos($this->getPackageTheme(), '/')) {
- list($package, $theme) = explode('/', $this->getPackageTheme());
- $this->setData('package', $package);
- $this->setData('theme', $theme);
- }
- return $this;
- }
-
/**
* Getter
* Explode to array if string is set
@@ -527,6 +384,149 @@ public function generateLayoutUpdateXml($blockReference, $templatePath = '')
return $xml . '';
}
+ /**
+ * Internal Constructor
+ */
+ protected function _construct()
+ {
+ $this->_cacheTag = 'widget_instance';
+ parent::_construct();
+ $this->_init('widget/widget_instance');
+ $this->_layoutHandles = [
+ 'anchor_categories' => self::ANCHOR_CATEGORY_LAYOUT_HANDLE,
+ 'notanchor_categories' => self::NOTANCHOR_CATEGORY_LAYOUT_HANDLE,
+ 'all_products' => self::PRODUCT_LAYOUT_HANDLE,
+ 'all_pages' => self::DEFAULT_LAYOUT_HANDLE,
+ ];
+ $this->_specificEntitiesLayoutHandles = [
+ 'anchor_categories' => self::SINGLE_CATEGORY_LAYOUT_HANDLE,
+ 'notanchor_categories' => self::SINGLE_CATEGORY_LAYOUT_HANDLE,
+ 'all_products' => self::SINGLE_PRODUCT_LAYOUT_HANLDE,
+ ];
+ foreach (Mage_Catalog_Model_Product_Type::getTypes() as $typeId => $type) {
+ $layoutHandle = str_replace('{{TYPE}}', $typeId, self::PRODUCT_TYPE_LAYOUT_HANDLE);
+ $this->_layoutHandles[$typeId . '_products'] = $layoutHandle;
+ $this->_specificEntitiesLayoutHandles[$typeId . '_products'] = self::SINGLE_PRODUCT_LAYOUT_HANLDE;
+ }
+ }
+
+ /**
+ * Init mapping array of short fields to
+ * its full names
+ *
+ * @return Varien_Object
+ */
+ protected function _initOldFieldsMap()
+ {
+ $this->_oldFieldsMap = [
+ 'type' => 'instance_type',
+ ];
+ return $this;
+ }
+
+ /**
+ * Processing object before save data
+ *
+ * @inheritDoc
+ */
+ protected function _beforeSave()
+ {
+ $pageGroupIds = [];
+ $tmpPageGroups = [];
+ $pageGroups = $this->getData('page_groups');
+ if ($pageGroups) {
+ foreach ($pageGroups as $pageGroup) {
+ if (isset($pageGroup[$pageGroup['page_group']])) {
+ $pageGroupData = $pageGroup[$pageGroup['page_group']];
+ if ($pageGroupData['page_id']) {
+ $pageGroupIds[] = $pageGroupData['page_id'];
+ }
+ if ($pageGroup['page_group'] == 'pages') {
+ $layoutHandle = $pageGroupData['layout_handle'];
+ } else {
+ $layoutHandle = $this->_layoutHandles[$pageGroup['page_group']];
+ }
+ if (!isset($pageGroupData['template'])) {
+ $pageGroupData['template'] = '';
+ }
+ $tmpPageGroup = [
+ 'page_id' => $pageGroupData['page_id'],
+ 'group' => $pageGroup['page_group'],
+ 'layout_handle' => $layoutHandle,
+ 'for' => $pageGroupData['for'],
+ 'block_reference' => $pageGroupData['block'],
+ 'entities' => '',
+ 'layout_handle_updates' => [$layoutHandle],
+ 'template' => $pageGroupData['template'] ? $pageGroupData['template'] : '',
+ ];
+ if ($pageGroupData['for'] == self::SPECIFIC_ENTITIES) {
+ $layoutHandleUpdates = [];
+ foreach (explode(',', $pageGroupData['entities']) as $entity) {
+ $layoutHandleUpdates[] = str_replace(
+ '{{ID}}',
+ $entity,
+ $this->_specificEntitiesLayoutHandles[$pageGroup['page_group']],
+ );
+ }
+ $tmpPageGroup['entities'] = $pageGroupData['entities'];
+ $tmpPageGroup['layout_handle_updates'] = $layoutHandleUpdates;
+ }
+ $tmpPageGroups[] = $tmpPageGroup;
+ }
+ }
+ }
+ if (is_array($this->getData('store_ids'))) {
+ $this->setData('store_ids', implode(',', $this->getData('store_ids')));
+ }
+ if (is_array($this->getData('widget_parameters'))) {
+ $this->setData('widget_parameters', serialize($this->getData('widget_parameters')));
+ }
+ $this->setData('page_groups', $tmpPageGroups);
+ $this->setData('page_group_ids', $pageGroupIds);
+
+ return parent::_beforeSave();
+ }
+
+ /**
+ * Replace '-' to '/', if was passed from request(GET request)
+ *
+ * @return $this
+ */
+ protected function _prepareType()
+ {
+ if (str_contains((string) $this->_getData('type'), '-')) {
+ $this->setData('type', str_replace('-', '/', $this->_getData('type')));
+ }
+ return $this;
+ }
+
+ /**
+ * Replace '_' to '/', if was set from request(GET request)
+ *
+ * @deprecated after 1.6.1.0-alpha1
+ *
+ * @return $this
+ */
+ protected function _preparePackageTheme()
+ {
+ return $this;
+ }
+
+ /**
+ * Parse packageTheme and set parsed package and theme
+ *
+ * @return $this
+ */
+ protected function _parsePackageTheme()
+ {
+ if ($this->getPackageTheme() && strpos($this->getPackageTheme(), '/')) {
+ list($package, $theme) = explode('/', $this->getPackageTheme());
+ $this->setData('package', $package);
+ $this->setData('theme', $theme);
+ }
+ return $this;
+ }
+
/**
* Invalidate related cache types
*
diff --git a/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php b/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php
index f513de4a090..1181eb9309c 100644
--- a/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php
+++ b/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php
@@ -28,69 +28,6 @@ class Mage_Widget_Adminhtml_Widget_InstanceController extends Mage_Adminhtml_Con
*/
public const ADMIN_RESOURCE = 'cms/widget_instance';
- /**
- * Session getter
- *
- * @return Mage_Adminhtml_Model_Session
- */
- protected function _getSession()
- {
- return Mage::getSingleton('adminhtml/session');
- }
-
- /**
- * Load layout, set active menu and breadcrumbs
- *
- * @return $this
- */
- protected function _initAction()
- {
- $this->loadLayout()
- ->_setActiveMenu('cms/widget_instance')
- ->_addBreadcrumb(
- Mage::helper('widget')->__('CMS'),
- Mage::helper('widget')->__('CMS'),
- )
- ->_addBreadcrumb(
- Mage::helper('widget')->__('Manage Widget Instances'),
- Mage::helper('widget')->__('Manage Widget Instances'),
- );
- return $this;
- }
-
- /**
- * Init widget instance object and set it to registry
- *
- * @return Mage_Widget_Model_Widget_Instance|bool
- * @throws Mage_Core_Exception
- */
- protected function _initWidgetInstance()
- {
- $this->_title($this->__('CMS'))->_title($this->__('Widgets'));
-
- /** @var Mage_Widget_Model_Widget_Instance $widgetInstance */
- $widgetInstance = Mage::getModel('widget/widget_instance');
-
- $instanceId = $this->getRequest()->getParam('instance_id', null);
- $type = $this->getRequest()->getParam('type', null);
- $package = $this->getRequest()->getParam('package', null);
- $theme = $this->getRequest()->getParam('theme', null);
-
- if ($instanceId) {
- $widgetInstance->load($instanceId);
- if (!$widgetInstance->getId()) {
- $this->_getSession()->addError(Mage::helper('widget')->__('Wrong widget instance specified.'));
- return false;
- }
- } else {
- $packageTheme = $package . '/' . $theme == '/' ? null : $package . '/' . $theme;
- $widgetInstance->setType($type)
- ->setPackageTheme($packageTheme);
- }
- Mage::register('current_widget_instance', $widgetInstance);
- return $widgetInstance;
- }
-
/**
* Widget Instances Grid
*/
@@ -127,17 +64,6 @@ public function editAction()
$this->renderLayout();
}
- /**
- * Set body to response
- *
- * @param string $body
- */
- private function setBody($body)
- {
- Mage::getSingleton('core/translate_inline')->processResponseBody($body);
- $this->getResponse()->setBody($body);
- }
-
/**
* Validate action
*/
@@ -297,6 +223,69 @@ public function preDispatch()
return parent::preDispatch();
}
+ /**
+ * Session getter
+ *
+ * @return Mage_Adminhtml_Model_Session
+ */
+ protected function _getSession()
+ {
+ return Mage::getSingleton('adminhtml/session');
+ }
+
+ /**
+ * Load layout, set active menu and breadcrumbs
+ *
+ * @return $this
+ */
+ protected function _initAction()
+ {
+ $this->loadLayout()
+ ->_setActiveMenu('cms/widget_instance')
+ ->_addBreadcrumb(
+ Mage::helper('widget')->__('CMS'),
+ Mage::helper('widget')->__('CMS'),
+ )
+ ->_addBreadcrumb(
+ Mage::helper('widget')->__('Manage Widget Instances'),
+ Mage::helper('widget')->__('Manage Widget Instances'),
+ );
+ return $this;
+ }
+
+ /**
+ * Init widget instance object and set it to registry
+ *
+ * @return Mage_Widget_Model_Widget_Instance|bool
+ * @throws Mage_Core_Exception
+ */
+ protected function _initWidgetInstance()
+ {
+ $this->_title($this->__('CMS'))->_title($this->__('Widgets'));
+
+ /** @var Mage_Widget_Model_Widget_Instance $widgetInstance */
+ $widgetInstance = Mage::getModel('widget/widget_instance');
+
+ $instanceId = $this->getRequest()->getParam('instance_id', null);
+ $type = $this->getRequest()->getParam('type', null);
+ $package = $this->getRequest()->getParam('package', null);
+ $theme = $this->getRequest()->getParam('theme', null);
+
+ if ($instanceId) {
+ $widgetInstance->load($instanceId);
+ if (!$widgetInstance->getId()) {
+ $this->_getSession()->addError(Mage::helper('widget')->__('Wrong widget instance specified.'));
+ return false;
+ }
+ } else {
+ $packageTheme = $package . '/' . $theme == '/' ? null : $package . '/' . $theme;
+ $widgetInstance->setType($type)
+ ->setPackageTheme($packageTheme);
+ }
+ Mage::register('current_widget_instance', $widgetInstance);
+ return $widgetInstance;
+ }
+
/**
* Prepare widget parameters
*
@@ -352,4 +341,15 @@ protected function _validatePostData($widgetInstance, $data)
}
return $errorNo;
}
+
+ /**
+ * Set body to response
+ *
+ * @param string $body
+ */
+ private function setBody($body)
+ {
+ Mage::getSingleton('core/translate_inline')->processResponseBody($body);
+ $this->getResponse()->setBody($body);
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Block/Abstract.php b/app/code/core/Mage/Wishlist/Block/Abstract.php
index 7081e6cc6b4..6f8c1ea4558 100644
--- a/app/code/core/Mage/Wishlist/Block/Abstract.php
+++ b/app/code/core/Mage/Wishlist/Block/Abstract.php
@@ -50,67 +50,6 @@ abstract class Mage_Wishlist_Block_Abstract extends Mage_Catalog_Block_Product_A
*/
protected $_cachedItemPriceBlocks = [];
- /**
- * Internal constructor, that is called from real constructor
- *
- */
- protected function _construct()
- {
- parent::_construct();
- $this->addItemPriceBlockType('default', 'wishlist/render_item_price', 'wishlist/render/item/price.phtml');
- }
-
- /**
- * Retrieve Wishlist Data Helper
- *
- * @return Mage_Wishlist_Helper_Data
- */
- protected function _getHelper()
- {
- return Mage::helper('wishlist');
- }
-
- /**
- * Retrieve Customer Session instance
- *
- * @return Mage_Customer_Model_Session
- */
- protected function _getCustomerSession()
- {
- return Mage::getSingleton('customer/session');
- }
-
- /**
- * Retrieve Wishlist model
- *
- * @return Mage_Wishlist_Model_Wishlist
- */
- protected function _getWishlist()
- {
- return $this->_getHelper()->getWishlist();
- }
-
- /**
- * Prepare additional conditions to collection
- *
- * @param Mage_Wishlist_Model_Resource_Item_Collection $collection
- * @return $this
- */
- protected function _prepareCollection($collection)
- {
- return $this;
- }
-
- /**
- * Create wishlist item collection
- *
- * @return Mage_Wishlist_Model_Resource_Item_Collection
- */
- protected function _createWishlistItemCollection()
- {
- return $this->_getWishlist()->getItemCollection();
- }
-
/**
* Retrieve Wishlist Product Items collection
*
@@ -315,28 +254,6 @@ public function addItemPriceBlockType($type, $block = '', $template = '')
}
}
- /**
- * Returns block to render item with some product type
- *
- * @param string $productType
- * @return Mage_Core_Block_Template
- */
- protected function _getItemPriceBlock($productType)
- {
- if (!isset($this->_itemPriceBlockTypes[$productType])) {
- $productType = 'default';
- }
-
- if (!isset($this->_cachedItemPriceBlocks[$productType])) {
- $blockType = $this->_itemPriceBlockTypes[$productType]['block'];
- $template = $this->_itemPriceBlockTypes[$productType]['template'];
- $block = $this->getLayout()->createBlock($blockType)
- ->setTemplate($template);
- $this->_cachedItemPriceBlocks[$productType] = $block;
- }
- return $this->_cachedItemPriceBlocks[$productType];
- }
-
/**
* Returns product price block html
* Overwrites parent price html return to be ready to show configured, partially configured and
@@ -440,4 +357,87 @@ public function getItemAddToCartUrlCustom($item, $addFormKey = true)
}
return $this->_getHelper()->getAddToCartUrl($item);
}
+
+ /**
+ * Internal constructor, that is called from real constructor
+ *
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ $this->addItemPriceBlockType('default', 'wishlist/render_item_price', 'wishlist/render/item/price.phtml');
+ }
+
+ /**
+ * Retrieve Wishlist Data Helper
+ *
+ * @return Mage_Wishlist_Helper_Data
+ */
+ protected function _getHelper()
+ {
+ return Mage::helper('wishlist');
+ }
+
+ /**
+ * Retrieve Customer Session instance
+ *
+ * @return Mage_Customer_Model_Session
+ */
+ protected function _getCustomerSession()
+ {
+ return Mage::getSingleton('customer/session');
+ }
+
+ /**
+ * Retrieve Wishlist model
+ *
+ * @return Mage_Wishlist_Model_Wishlist
+ */
+ protected function _getWishlist()
+ {
+ return $this->_getHelper()->getWishlist();
+ }
+
+ /**
+ * Prepare additional conditions to collection
+ *
+ * @param Mage_Wishlist_Model_Resource_Item_Collection $collection
+ * @return $this
+ */
+ protected function _prepareCollection($collection)
+ {
+ return $this;
+ }
+
+ /**
+ * Create wishlist item collection
+ *
+ * @return Mage_Wishlist_Model_Resource_Item_Collection
+ */
+ protected function _createWishlistItemCollection()
+ {
+ return $this->_getWishlist()->getItemCollection();
+ }
+
+ /**
+ * Returns block to render item with some product type
+ *
+ * @param string $productType
+ * @return Mage_Core_Block_Template
+ */
+ protected function _getItemPriceBlock($productType)
+ {
+ if (!isset($this->_itemPriceBlockTypes[$productType])) {
+ $productType = 'default';
+ }
+
+ if (!isset($this->_cachedItemPriceBlocks[$productType])) {
+ $blockType = $this->_itemPriceBlockTypes[$productType]['block'];
+ $template = $this->_itemPriceBlockTypes[$productType]['template'];
+ $block = $this->getLayout()->createBlock($blockType)
+ ->setTemplate($template);
+ $this->_cachedItemPriceBlocks[$productType] = $block;
+ }
+ return $this->_cachedItemPriceBlocks[$productType];
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Sharing.php b/app/code/core/Mage/Wishlist/Block/Customer/Sharing.php
index 36a22a37b51..8c468b4139e 100644
--- a/app/code/core/Mage/Wishlist/Block/Customer/Sharing.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Sharing.php
@@ -29,20 +29,6 @@ class Mage_Wishlist_Block_Customer_Sharing extends Mage_Core_Block_Template
*/
protected $_enteredData = null;
- /**
- * Prepare Global Layout
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('Wishlist Sharing'));
- }
- return $this;
- }
-
/**
* Retrieve Send Form Action URL
*
@@ -82,4 +68,18 @@ public function getBackUrl()
{
return $this->getUrl('*/*/index');
}
+
+ /**
+ * Prepare Global Layout
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('Wishlist Sharing'));
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php b/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
index 1cdc473c4a8..767b0302edd 100644
--- a/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
@@ -32,36 +32,6 @@ public function getTitle()
return $this->__('My Wishlist (%d)', $this->getItemCount());
}
- /**
- * Add sidebar conditions to collection
- *
- * @param Mage_Wishlist_Model_Resource_Item_Collection $collection
- * @return $this
- */
- protected function _prepareCollection($collection)
- {
- $collection->setCurPage(1)
- ->setPageSize(3)
- ->setInStockFilter(true)
- ->setOrder('added_at');
-
- return $this;
- }
-
- /**
- * Prepare before to html
- *
- * @return string
- */
- protected function _toHtml()
- {
- if ($this->getItemCount()) {
- return parent::_toHtml();
- }
-
- return '';
- }
-
/**
* Can Display wishlist
*
@@ -145,4 +115,34 @@ public function getCacheTags()
}
return parent::getCacheTags();
}
+
+ /**
+ * Add sidebar conditions to collection
+ *
+ * @param Mage_Wishlist_Model_Resource_Item_Collection $collection
+ * @return $this
+ */
+ protected function _prepareCollection($collection)
+ {
+ $collection->setCurPage(1)
+ ->setPageSize(3)
+ ->setInStockFilter(true)
+ ->setOrder('added_at');
+
+ return $this;
+ }
+
+ /**
+ * Prepare before to html
+ *
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ if ($this->getItemCount()) {
+ return parent::_toHtml();
+ }
+
+ return '';
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist.php
index 7693b5a9249..075c5e8d5e8 100644
--- a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist.php
@@ -27,33 +27,6 @@ class Mage_Wishlist_Block_Customer_Wishlist extends Mage_Wishlist_Block_Abstract
*/
protected $_optionsCfg = [];
- /**
- * Add wishlist conditions to collection
- *
- * @param Mage_Wishlist_Model_Resource_Item_Collection $collection
- * @return $this
- */
- protected function _prepareCollection($collection)
- {
- $collection->setInStockFilter(true)->setOrder('added_at', 'ASC');
- return $this;
- }
-
- /**
- * Preparing global layout
- *
- * @return $this
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->__('My Wishlist'));
- }
- return $this;
- }
-
/**
* Retrieve Back URL
*
@@ -170,4 +143,31 @@ public function getAddToCartQty(Mage_Wishlist_Model_Item $item)
$qty = $this->getQty($item);
return $qty ? $qty : 1;
}
+
+ /**
+ * Add wishlist conditions to collection
+ *
+ * @param Mage_Wishlist_Model_Resource_Item_Collection $collection
+ * @return $this
+ */
+ protected function _prepareCollection($collection)
+ {
+ $collection->setInStockFilter(true)->setOrder('added_at', 'ASC');
+ return $this;
+ }
+
+ /**
+ * Preparing global layout
+ *
+ * @return $this
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->__('My Wishlist'));
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column.php
index 589d17a6aef..8e6b8321e61 100644
--- a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column.php
@@ -32,6 +32,20 @@ public function isEnabled()
return true;
}
+ /**
+ * Retrieve column related javascript code
+ *
+ * @return string
+ */
+ public function getJs()
+ {
+ $js = '';
+ foreach ($this->getSortedChildBlocks() as $child) {
+ $js .= $child->getJs();
+ }
+ return $js;
+ }
+
/**
* Retrieve block html
*
@@ -55,18 +69,4 @@ protected function _beforeChildToHtml($name, $child)
{
$child->setItem($this->getItem());
}
-
- /**
- * Retrieve column related javascript code
- *
- * @return string
- */
- public function getJs()
- {
- $js = '';
- foreach ($this->getSortedChildBlocks() as $child) {
- $js .= $child->getJs();
- }
- return $js;
- }
}
diff --git a/app/code/core/Mage/Wishlist/Block/Links.php b/app/code/core/Mage/Wishlist/Block/Links.php
index 28717c83b2a..656cb2b6cd2 100644
--- a/app/code/core/Mage/Wishlist/Block/Links.php
+++ b/app/code/core/Mage/Wishlist/Block/Links.php
@@ -28,6 +28,48 @@ class Mage_Wishlist_Block_Links extends Mage_Page_Block_Template_Links_Block
*/
protected $_position = 30;
+ /**
+ * Define label, title and url for wishlist link
+ *
+ * @deprecated after 1.6.2.0
+ */
+ public function initLinkProperties()
+ {
+ $text = $this->_createLabel($this->_getItemCount());
+ $this->_label = $text;
+ $this->_title = $text;
+ $this->_url = $this->getUrl('wishlist');
+ }
+
+ /**
+ * @return Mage_Wishlist_Block_Links
+ * @see Mage_Wishlist_Block_Links::__construct
+ *
+ * @deprecated after 1.4.2.0
+ */
+ public function addWishlistLink()
+ {
+ return $this;
+ }
+
+ /**
+ * Retrieve block cache tags
+ *
+ * @return array
+ * @throws Mage_Core_Model_Store_Exception
+ */
+ public function getCacheTags()
+ {
+ /** @var Mage_Wishlist_Helper_Data $helper */
+ $helper = $this->helper('wishlist');
+ $wishlist = $helper->getWishlist();
+ $this->addModelTags($wishlist);
+ foreach ($wishlist->getItemCollection() as $item) {
+ $this->addModelTags($item);
+ }
+ return parent::getCacheTags();
+ }
+
/**
* @return string
*/
@@ -45,19 +87,6 @@ protected function _toHtml()
return '';
}
- /**
- * Define label, title and url for wishlist link
- *
- * @deprecated after 1.6.2.0
- */
- public function initLinkProperties()
- {
- $text = $this->_createLabel($this->_getItemCount());
- $this->_label = $text;
- $this->_title = $text;
- $this->_url = $this->getUrl('wishlist');
- }
-
/**
* Count items in wishlist
*
@@ -88,33 +117,4 @@ protected function _createLabel($count)
return $this->__('My Wishlist');
}
-
- /**
- * @return Mage_Wishlist_Block_Links
- * @see Mage_Wishlist_Block_Links::__construct
- *
- * @deprecated after 1.4.2.0
- */
- public function addWishlistLink()
- {
- return $this;
- }
-
- /**
- * Retrieve block cache tags
- *
- * @return array
- * @throws Mage_Core_Model_Store_Exception
- */
- public function getCacheTags()
- {
- /** @var Mage_Wishlist_Helper_Data $helper */
- $helper = $this->helper('wishlist');
- $wishlist = $helper->getWishlist();
- $this->addModelTags($wishlist);
- foreach ($wishlist->getItemCollection() as $item) {
- $this->addModelTags($item);
- }
- return parent::getCacheTags();
- }
}
diff --git a/app/code/core/Mage/Wishlist/Block/Share/Wishlist.php b/app/code/core/Mage/Wishlist/Block/Share/Wishlist.php
index 6c23171e22e..d668c621d94 100644
--- a/app/code/core/Mage/Wishlist/Block/Share/Wishlist.php
+++ b/app/code/core/Mage/Wishlist/Block/Share/Wishlist.php
@@ -29,23 +29,6 @@ class Mage_Wishlist_Block_Share_Wishlist extends Mage_Wishlist_Block_Abstract
*/
protected $_customer = null;
- /**
- * Prepare global layout
- *
- * @return $this
- *
- */
- protected function _prepareLayout()
- {
- parent::_prepareLayout();
-
- $headBlock = $this->getLayout()->getBlock('head');
- if ($headBlock) {
- $headBlock->setTitle($this->getHeader());
- }
- return $this;
- }
-
/**
* Retrieve Shared Wishlist Customer instance
*
@@ -70,4 +53,21 @@ public function getHeader()
{
return Mage::helper('wishlist')->__("%s's Wishlist", $this->escapeHtml($this->getWishlistCustomer()->getFirstname()));
}
+
+ /**
+ * Prepare global layout
+ *
+ * @return $this
+ *
+ */
+ protected function _prepareLayout()
+ {
+ parent::_prepareLayout();
+
+ $headBlock = $this->getLayout()->getBlock('head');
+ if ($headBlock) {
+ $headBlock->setTitle($this->getHeader());
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Controller/Abstract.php b/app/code/core/Mage/Wishlist/Controller/Abstract.php
index 022b62b9881..e5dc2074c0e 100644
--- a/app/code/core/Mage/Wishlist/Controller/Abstract.php
+++ b/app/code/core/Mage/Wishlist/Controller/Abstract.php
@@ -34,29 +34,6 @@ abstract class Mage_Wishlist_Controller_Abstract extends Mage_Core_Controller_Fr
*/
protected $_isCheckFormKey = true;
- /**
- * Processes localized qty (entered by user at frontend) into internal php format
- *
- * @param string $qty
- * @return float|int|null
- * @deprecated
- */
- protected function _processLocalizedQty($qty)
- {
- $qty = (float) $qty;
- if ($qty < 0) {
- $qty = null;
- }
- return $qty;
- }
-
- /**
- * Retrieve current wishlist instance
- *
- * @return Mage_Wishlist_Model_Wishlist|false
- */
- abstract protected function _getWishlist();
-
/**
* Add all items from wishlist to shopping cart
*
@@ -198,4 +175,27 @@ public function allcartAction()
$this->_redirectUrl($redirectUrl);
}
+
+ /**
+ * Processes localized qty (entered by user at frontend) into internal php format
+ *
+ * @param string $qty
+ * @return float|int|null
+ * @deprecated
+ */
+ protected function _processLocalizedQty($qty)
+ {
+ $qty = (float) $qty;
+ if ($qty < 0) {
+ $qty = null;
+ }
+ return $qty;
+ }
+
+ /**
+ * Retrieve current wishlist instance
+ *
+ * @return Mage_Wishlist_Model_Wishlist|false
+ */
+ abstract protected function _getWishlist();
}
diff --git a/app/code/core/Mage/Wishlist/Helper/Data.php b/app/code/core/Mage/Wishlist/Helper/Data.php
index ca70f7a563f..2ca1a00a8b2 100644
--- a/app/code/core/Mage/Wishlist/Helper/Data.php
+++ b/app/code/core/Mage/Wishlist/Helper/Data.php
@@ -60,36 +60,6 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
*/
protected $_wishlistItemCollection = null;
- /**
- * Retrieve customer session
- *
- * @return Mage_Customer_Model_Session
- */
- protected function _getCustomerSession()
- {
- return Mage::getSingleton('customer/session');
- }
-
- /**
- * Retrieve customer login status
- *
- * @return bool
- */
- protected function _isCustomerLogIn()
- {
- return $this->_getCustomerSession()->isLoggedIn();
- }
-
- /**
- * Retrieve logged in customer
- *
- * @return Mage_Customer_Model_Customer
- */
- protected function _getCurrentCustomer()
- {
- return $this->getCustomer();
- }
-
/**
* Set current customer
*/
@@ -184,16 +154,6 @@ public function getItemCollection()
return $this->getProductCollection();
}
- /**
- * Create wishlist item collection
- *
- * @return Mage_Wishlist_Model_Resource_Item_Collection
- */
- protected function _createWishlistItemCollection()
- {
- return $this->getWishlist()->getItemCollection();
- }
-
/**
* Retrieve wishlist items collection
*
@@ -227,31 +187,6 @@ public function getProductCollection()
return $this->_productCollection;
}
- /**
- * Retrieve Item Store for URL
- *
- * @param Mage_Catalog_Model_Product|Mage_Wishlist_Model_Item $item
- * @return Mage_Core_Model_Store
- */
- protected function _getUrlStore($item)
- {
- $storeId = null;
- $product = null;
- if ($item instanceof Mage_Wishlist_Model_Item) {
- $product = $item->getProduct();
- } elseif ($item instanceof Mage_Catalog_Model_Product) {
- $product = $item;
- }
- if ($product) {
- if ($product->isVisibleInSiteVisibility()) {
- $storeId = $product->getStoreId();
- } elseif ($product->hasUrlDataObject()) {
- $storeId = $product->getUrlDataObject()->getStoreId();
- }
- }
- return Mage::app()->getStore($storeId);
- }
-
/**
* Retrieve URL for removing item from wishlist
*
@@ -347,29 +282,6 @@ public function getAddToCartUrl($item)
return $this->getAddToCartUrlCustom($item);
}
- /**
- * Return helper instance
- *
- * @param string $helperName
- * @return Mage_Core_Helper_Abstract
- */
- protected function _getHelperInstance($helperName)
- {
- return Mage::helper($helperName);
- }
-
- /**
- * Return model instance
- *
- * @param string $className
- * @param array $arguments
- * @return Mage_Core_Model_Abstract
- */
- protected function _getSingletonModel($className, $arguments = [])
- {
- return Mage::getSingleton($className, $arguments);
- }
-
/**
* Retrieve URL for adding item to shoping cart from shared wishlist
*
@@ -620,4 +532,92 @@ public function getAddToCartUrlCustom($item, $addFormKey = true)
}
return $this->_getUrlStore($item)->getUrl('wishlist/index/cart', $params);
}
+
+ /**
+ * Retrieve customer session
+ *
+ * @return Mage_Customer_Model_Session
+ */
+ protected function _getCustomerSession()
+ {
+ return Mage::getSingleton('customer/session');
+ }
+
+ /**
+ * Retrieve customer login status
+ *
+ * @return bool
+ */
+ protected function _isCustomerLogIn()
+ {
+ return $this->_getCustomerSession()->isLoggedIn();
+ }
+
+ /**
+ * Retrieve logged in customer
+ *
+ * @return Mage_Customer_Model_Customer
+ */
+ protected function _getCurrentCustomer()
+ {
+ return $this->getCustomer();
+ }
+
+ /**
+ * Create wishlist item collection
+ *
+ * @return Mage_Wishlist_Model_Resource_Item_Collection
+ */
+ protected function _createWishlistItemCollection()
+ {
+ return $this->getWishlist()->getItemCollection();
+ }
+
+ /**
+ * Retrieve Item Store for URL
+ *
+ * @param Mage_Catalog_Model_Product|Mage_Wishlist_Model_Item $item
+ * @return Mage_Core_Model_Store
+ */
+ protected function _getUrlStore($item)
+ {
+ $storeId = null;
+ $product = null;
+ if ($item instanceof Mage_Wishlist_Model_Item) {
+ $product = $item->getProduct();
+ } elseif ($item instanceof Mage_Catalog_Model_Product) {
+ $product = $item;
+ }
+ if ($product) {
+ if ($product->isVisibleInSiteVisibility()) {
+ $storeId = $product->getStoreId();
+ } elseif ($product->hasUrlDataObject()) {
+ $storeId = $product->getUrlDataObject()->getStoreId();
+ }
+ }
+ return Mage::app()->getStore($storeId);
+ }
+
+ /**
+ * Return helper instance
+ *
+ * @param string $helperName
+ * @return Mage_Core_Helper_Abstract
+ */
+ protected function _getHelperInstance($helperName)
+ {
+ return Mage::helper($helperName);
+ }
+
+ /**
+ * Return model instance
+ *
+ * @param string $className
+ * @param array $arguments
+ * @return Mage_Core_Model_Abstract
+ */
+ protected function _getSingletonModel($className, $arguments = [])
+ {
+ return Mage::getSingleton($className, $arguments);
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Item.php b/app/code/core/Mage/Wishlist/Model/Item.php
index 43863a1a1d5..47d24e85ca8 100644
--- a/app/code/core/Mage/Wishlist/Model/Item.php
+++ b/app/code/core/Mage/Wishlist/Model/Item.php
@@ -104,12 +104,6 @@ class Mage_Wishlist_Model_Item extends Mage_Core_Model_Abstract implements Mage_
*/
protected $_flagOptionsSaved = null;
- protected function _construct()
- {
- $this->_cacheTag = 'wishlist_item';
- $this->_init('wishlist/item');
- }
-
/**
* Set quantity. If quantity is less than 0 - set it to 1
*
@@ -122,82 +116,6 @@ public function setQty($qty)
return $this;
}
- /**
- * Check if two options array are identical
- *
- * @param array $options1
- * @param array $options2
- * @return bool
- */
- protected function _compareOptions($options1, $options2)
- {
- $skipOptions = ['id', 'qty', 'return_url'];
- foreach ($options1 as $code => $value) {
- if (in_array($code, $skipOptions)) {
- continue;
- }
- if (!isset($options2[$code]) || $options2[$code] != $value) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Register option code
- *
- * @param Mage_Wishlist_Model_Item_Option $option
- * @return $this
- */
- protected function _addOptionCode($option)
- {
- if (!isset($this->_optionsByCode[$option->getCode()])) {
- $this->_optionsByCode[$option->getCode()] = $option;
- } else {
- Mage::throwException(Mage::helper('sales')->__('An item option with code %s already exists.', $option->getCode()));
- }
- return $this;
- }
-
- /**
- * Checks that item model has data changes.
- * Call save item options if model isn't need to save in DB
- *
- * @return bool
- */
- protected function _hasModelChanged()
- {
- if (!$this->hasDataChanges()) {
- return false;
- }
-
- return $this->_getResource()->hasDataChanged($this);
- }
-
- /**
- * Save item options
- *
- * @return $this
- */
- protected function _saveItemOptions()
- {
- foreach ($this->_options as $index => $option) {
- if ($option->isDeleted()) {
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $option->delete();
- unset($this->_options[$index]);
- unset($this->_optionsByCode[$option->getCode()]);
- } else {
- // phpcs:ignore Ecg.Performance.Loop.ModelLSD
- $option->save();
- }
- }
-
- $this->_flagOptionsSaved = true; // Report to watchers that options were saved
-
- return $this;
- }
-
/**
* Save model plus its options
* Ensures saving options in case when resource model was not changed
@@ -216,17 +134,6 @@ public function save()
return $this;
}
- /**
- * Save item options after item saved
- *
- * @inheritDoc
- */
- protected function _afterSave()
- {
- $this->_saveItemOptions();
- return parent::_afterSave();
- }
-
/**
* Validate wish list item data
*
@@ -245,31 +152,6 @@ public function validate()
return true;
}
- /**
- * Check required data
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
-
- // validate required item data
- $this->validate();
-
- // set current store id if it is not defined
- if (is_null($this->getStoreId())) {
- $this->setStoreId(Mage::app()->getStore()->getId());
- }
-
- // set current date if added at data is not defined
- if (is_null($this->getAddedAt())) {
- $this->setAddedAt(Mage::getSingleton('core/date')->gmtDate());
- }
-
- return $this;
- }
-
/**
* Retrieve wishlist item data as array
*
@@ -719,4 +601,122 @@ public function loadWithOptions($id, $optionsFilter = null)
$this->setOptions($options->getOptionsByItem($this));
return $this;
}
+
+ protected function _construct()
+ {
+ $this->_cacheTag = 'wishlist_item';
+ $this->_init('wishlist/item');
+ }
+
+ /**
+ * Check if two options array are identical
+ *
+ * @param array $options1
+ * @param array $options2
+ * @return bool
+ */
+ protected function _compareOptions($options1, $options2)
+ {
+ $skipOptions = ['id', 'qty', 'return_url'];
+ foreach ($options1 as $code => $value) {
+ if (in_array($code, $skipOptions)) {
+ continue;
+ }
+ if (!isset($options2[$code]) || $options2[$code] != $value) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Register option code
+ *
+ * @param Mage_Wishlist_Model_Item_Option $option
+ * @return $this
+ */
+ protected function _addOptionCode($option)
+ {
+ if (!isset($this->_optionsByCode[$option->getCode()])) {
+ $this->_optionsByCode[$option->getCode()] = $option;
+ } else {
+ Mage::throwException(Mage::helper('sales')->__('An item option with code %s already exists.', $option->getCode()));
+ }
+ return $this;
+ }
+
+ /**
+ * Checks that item model has data changes.
+ * Call save item options if model isn't need to save in DB
+ *
+ * @return bool
+ */
+ protected function _hasModelChanged()
+ {
+ if (!$this->hasDataChanges()) {
+ return false;
+ }
+
+ return $this->_getResource()->hasDataChanged($this);
+ }
+
+ /**
+ * Save item options
+ *
+ * @return $this
+ */
+ protected function _saveItemOptions()
+ {
+ foreach ($this->_options as $index => $option) {
+ if ($option->isDeleted()) {
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $option->delete();
+ unset($this->_options[$index]);
+ unset($this->_optionsByCode[$option->getCode()]);
+ } else {
+ // phpcs:ignore Ecg.Performance.Loop.ModelLSD
+ $option->save();
+ }
+ }
+
+ $this->_flagOptionsSaved = true; // Report to watchers that options were saved
+
+ return $this;
+ }
+
+ /**
+ * Save item options after item saved
+ *
+ * @inheritDoc
+ */
+ protected function _afterSave()
+ {
+ $this->_saveItemOptions();
+ return parent::_afterSave();
+ }
+
+ /**
+ * Check required data
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+
+ // validate required item data
+ $this->validate();
+
+ // set current store id if it is not defined
+ if (is_null($this->getStoreId())) {
+ $this->setStoreId(Mage::app()->getStore()->getId());
+ }
+
+ // set current date if added at data is not defined
+ if (is_null($this->getAddedAt())) {
+ $this->setAddedAt(Mage::getSingleton('core/date')->gmtDate());
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Item/Option.php b/app/code/core/Mage/Wishlist/Model/Item/Option.php
index 967df847f08..45f0133a939 100644
--- a/app/code/core/Mage/Wishlist/Model/Item/Option.php
+++ b/app/code/core/Mage/Wishlist/Model/Item/Option.php
@@ -33,23 +33,13 @@ class Mage_Wishlist_Model_Item_Option extends Mage_Core_Model_Abstract implement
protected $_item;
protected $_product;
- protected function _construct()
- {
- $this->_init('wishlist/item_option');
- }
-
/**
- * Checks that item option model has data changes
- *
- * @return bool
+ * Clone option object
*/
- protected function _hasModelChanged()
+ public function __clone()
{
- if (!$this->hasDataChanges()) {
- return false;
- }
-
- return $this->_getResource()->hasDataChanged($this);
+ $this->setId(null);
+ $this->_item = null;
}
/**
@@ -112,6 +102,25 @@ public function getValue()
return $this->_getData('value');
}
+ protected function _construct()
+ {
+ $this->_init('wishlist/item_option');
+ }
+
+ /**
+ * Checks that item option model has data changes
+ *
+ * @return bool
+ */
+ protected function _hasModelChanged()
+ {
+ if (!$this->hasDataChanges()) {
+ return false;
+ }
+
+ return $this->_getResource()->hasDataChanged($this);
+ }
+
/**
* Initialize item identifier before save data
*
@@ -124,13 +133,4 @@ protected function _beforeSave()
}
return parent::_beforeSave();
}
-
- /**
- * Clone option object
- */
- public function __clone()
- {
- $this->setId(null);
- $this->_item = null;
- }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Observer.php b/app/code/core/Mage/Wishlist/Model/Observer.php
index 4f858ff7f0f..cb922d8c128 100644
--- a/app/code/core/Mage/Wishlist/Model/Observer.php
+++ b/app/code/core/Mage/Wishlist/Model/Observer.php
@@ -22,20 +22,6 @@
*/
class Mage_Wishlist_Model_Observer extends Mage_Core_Model_Abstract
{
- /**
- * Get customer wishlist model instance
- *
- * @param int $customerId
- * @return Mage_Wishlist_Model_Wishlist|false
- */
- protected function _getWishlist($customerId)
- {
- if (!$customerId) {
- return false;
- }
- return Mage::getModel('wishlist/wishlist')->loadByCustomer($customerId, true);
- }
-
/**
* Check move quote item to wishlist request
*
@@ -157,4 +143,17 @@ public function customerLogout(Varien_Event_Observer $observer)
return $this;
}
+ /**
+ * Get customer wishlist model instance
+ *
+ * @param int $customerId
+ * @return Mage_Wishlist_Model_Wishlist|false
+ */
+ protected function _getWishlist($customerId)
+ {
+ if (!$customerId) {
+ return false;
+ }
+ return Mage::getModel('wishlist/wishlist')->loadByCustomer($customerId, true);
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Item.php b/app/code/core/Mage/Wishlist/Model/Resource/Item.php
index 192d92fa39c..08fe0afd7c6 100644
--- a/app/code/core/Mage/Wishlist/Model/Resource/Item.php
+++ b/app/code/core/Mage/Wishlist/Model/Resource/Item.php
@@ -22,11 +22,6 @@
*/
class Mage_Wishlist_Model_Resource_Item extends Mage_Core_Model_Resource_Db_Abstract
{
- protected function _construct()
- {
- $this->_init('wishlist/item', 'wishlist_item_id');
- }
-
/**
* Load item by wishlist, product and shared stores
*
@@ -57,4 +52,8 @@ public function loadByProductWishlist($object, $wishlistId, $productId, $sharedS
return $this;
}
+ protected function _construct()
+ {
+ $this->_init('wishlist/item', 'wishlist_item_id');
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php b/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php
index 5de7dafe43c..69895d6688e 100644
--- a/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php
+++ b/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php
@@ -101,123 +101,6 @@ public function _construct()
$this->addFilterToMap('store_id', 'main_table.store_id');
}
- /**
- * After load processing
- *
- * @return $this
- */
- protected function _afterLoad()
- {
- parent::_afterLoad();
-
- /**
- * Assign products
- */
- $this->_assignOptions();
- $this->_assignProducts();
- $this->resetItemsDataChanged();
-
- $this->getPageSize();
-
- return $this;
- }
-
- /**
- * Add options to items
- *
- * @return $this
- */
- protected function _assignOptions()
- {
- $itemIds = array_keys($this->_items);
- /** @var Mage_Wishlist_Model_Resource_Item_Option_Collection $optionCollection */
- $optionCollection = Mage::getModel('wishlist/item_option')->getCollection();
- $optionCollection->addItemFilter($itemIds);
-
- /** @var Mage_Wishlist_Model_Item $item */
- foreach ($this as $item) {
- $item->setOptions($optionCollection->getOptionsByItem($item));
- }
- $productIds = $optionCollection->getProductIds();
- $this->_productIds = array_merge($this->_productIds, $productIds);
-
- return $this;
- }
-
- /**
- * Add products to items and item options
- *
- * @return $this
- */
- protected function _assignProducts()
- {
- Varien_Profiler::start('WISHLIST:' . __METHOD__);
- $productIds = [];
-
- $isStoreAdmin = Mage::app()->getStore()->isAdmin();
-
- $storeIds = [];
- foreach ($this as $item) {
- $productIds[$item->getProductId()] = 1;
- if ($isStoreAdmin && !in_array($item->getStoreId(), $storeIds)) {
- $storeIds[] = $item->getStoreId();
- }
- }
- if (!$isStoreAdmin) {
- $storeIds = $this->_storeIds;
- }
-
- $this->_productIds = array_merge($this->_productIds, array_keys($productIds));
- $attributes = Mage::getSingleton('wishlist/config')->getProductAttributes();
- $productCollection = Mage::getModel('catalog/product')->getCollection();
- foreach ($storeIds as $id) {
- $productCollection->addWebsiteFilter(Mage::app()->getStore($id)->getWebsiteId());
- }
-
- if ($this->_productVisible) {
- Mage::getSingleton('catalog/product_visibility')->addVisibleInSiteFilterToCollection($productCollection);
- }
-
- $productCollection->addPriceData($this->_customerGroupId, $this->_websiteId)
- ->addTaxPercents()
- ->addIdFilter($this->_productIds)
- ->addAttributeToSelect($attributes)
- ->addOptionsToResult()
- ->addUrlRewrite();
-
- if ($this->_productSalable) {
- $productCollection = Mage::helper('adminhtml/sales')->applySalableProductTypesFilter($productCollection);
- }
-
- Mage::dispatchEvent('wishlist_item_collection_products_after_load', [
- 'product_collection' => $productCollection,
- ]);
-
- $checkInStock = $this->_productInStock && !Mage::helper('cataloginventory')->isShowOutOfStock();
-
- foreach ($this as $item) {
- /** @var Mage_Catalog_Model_Product $product */
- $product = $productCollection->getItemById($item->getProductId());
- if ($product) {
- if ($checkInStock && !$product->isInStock()) {
- $this->removeItemByKey($item->getId());
- } else {
- $product->setCustomOptions([]);
- $item->setProduct($product);
- $item->setProductName($product->getName());
- $item->setName($product->getName());
- $item->setPrice($product->getPrice());
- }
- } else {
- $item->isDeleted(true);
- }
- }
-
- Varien_Profiler::stop('WISHLIST:' . __METHOD__);
-
- return $this;
- }
-
/**
* Add filter by wishlist object
*
@@ -415,36 +298,6 @@ public function addDaysFilter($constraints)
return $this;
}
- /**
- * Joins product name attribute value to use it in WHERE and ORDER clauses
- *
- * @return $this
- */
- protected function _joinProductNameTable()
- {
- if (!$this->_isProductNameJoined) {
- $entityTypeId = Mage::getResourceModel('catalog/config')
- ->getEntityTypeId();
- $attribute = Mage::getModel('catalog/entity_attribute')
- ->loadByCode($entityTypeId, 'name');
-
- $storeId = Mage::app()->getStore()->getId();
-
- $this->getSelect()
- ->join(
- ['product_name_table' => $attribute->getBackendTable()],
- 'product_name_table.entity_id=main_table.product_id' .
- ' AND product_name_table.store_id=' . $storeId .
- ' AND product_name_table.attribute_id=' . $attribute->getId() .
- ' AND product_name_table.entity_type_id=' . $entityTypeId,
- [],
- );
-
- $this->_isProductNameJoined = true;
- }
- return $this;
- }
-
/**
* Adds filter on product name
*
@@ -514,4 +367,151 @@ public function setCustomerGroupId($customerGroupId)
$this->_customerGroupId = $customerGroupId;
return $this;
}
+
+ /**
+ * After load processing
+ *
+ * @return $this
+ */
+ protected function _afterLoad()
+ {
+ parent::_afterLoad();
+
+ /**
+ * Assign products
+ */
+ $this->_assignOptions();
+ $this->_assignProducts();
+ $this->resetItemsDataChanged();
+
+ $this->getPageSize();
+
+ return $this;
+ }
+
+ /**
+ * Add options to items
+ *
+ * @return $this
+ */
+ protected function _assignOptions()
+ {
+ $itemIds = array_keys($this->_items);
+ /** @var Mage_Wishlist_Model_Resource_Item_Option_Collection $optionCollection */
+ $optionCollection = Mage::getModel('wishlist/item_option')->getCollection();
+ $optionCollection->addItemFilter($itemIds);
+
+ /** @var Mage_Wishlist_Model_Item $item */
+ foreach ($this as $item) {
+ $item->setOptions($optionCollection->getOptionsByItem($item));
+ }
+ $productIds = $optionCollection->getProductIds();
+ $this->_productIds = array_merge($this->_productIds, $productIds);
+
+ return $this;
+ }
+
+ /**
+ * Add products to items and item options
+ *
+ * @return $this
+ */
+ protected function _assignProducts()
+ {
+ Varien_Profiler::start('WISHLIST:' . __METHOD__);
+ $productIds = [];
+
+ $isStoreAdmin = Mage::app()->getStore()->isAdmin();
+
+ $storeIds = [];
+ foreach ($this as $item) {
+ $productIds[$item->getProductId()] = 1;
+ if ($isStoreAdmin && !in_array($item->getStoreId(), $storeIds)) {
+ $storeIds[] = $item->getStoreId();
+ }
+ }
+ if (!$isStoreAdmin) {
+ $storeIds = $this->_storeIds;
+ }
+
+ $this->_productIds = array_merge($this->_productIds, array_keys($productIds));
+ $attributes = Mage::getSingleton('wishlist/config')->getProductAttributes();
+ $productCollection = Mage::getModel('catalog/product')->getCollection();
+ foreach ($storeIds as $id) {
+ $productCollection->addWebsiteFilter(Mage::app()->getStore($id)->getWebsiteId());
+ }
+
+ if ($this->_productVisible) {
+ Mage::getSingleton('catalog/product_visibility')->addVisibleInSiteFilterToCollection($productCollection);
+ }
+
+ $productCollection->addPriceData($this->_customerGroupId, $this->_websiteId)
+ ->addTaxPercents()
+ ->addIdFilter($this->_productIds)
+ ->addAttributeToSelect($attributes)
+ ->addOptionsToResult()
+ ->addUrlRewrite();
+
+ if ($this->_productSalable) {
+ $productCollection = Mage::helper('adminhtml/sales')->applySalableProductTypesFilter($productCollection);
+ }
+
+ Mage::dispatchEvent('wishlist_item_collection_products_after_load', [
+ 'product_collection' => $productCollection,
+ ]);
+
+ $checkInStock = $this->_productInStock && !Mage::helper('cataloginventory')->isShowOutOfStock();
+
+ foreach ($this as $item) {
+ /** @var Mage_Catalog_Model_Product $product */
+ $product = $productCollection->getItemById($item->getProductId());
+ if ($product) {
+ if ($checkInStock && !$product->isInStock()) {
+ $this->removeItemByKey($item->getId());
+ } else {
+ $product->setCustomOptions([]);
+ $item->setProduct($product);
+ $item->setProductName($product->getName());
+ $item->setName($product->getName());
+ $item->setPrice($product->getPrice());
+ }
+ } else {
+ $item->isDeleted(true);
+ }
+ }
+
+ Varien_Profiler::stop('WISHLIST:' . __METHOD__);
+
+ return $this;
+ }
+
+ /**
+ * Joins product name attribute value to use it in WHERE and ORDER clauses
+ *
+ * @return $this
+ */
+ protected function _joinProductNameTable()
+ {
+ if (!$this->_isProductNameJoined) {
+ $entityTypeId = Mage::getResourceModel('catalog/config')
+ ->getEntityTypeId();
+ $attribute = Mage::getModel('catalog/entity_attribute')
+ ->loadByCode($entityTypeId, 'name');
+
+ $storeId = Mage::app()->getStore()->getId();
+
+ $this->getSelect()
+ ->join(
+ ['product_name_table' => $attribute->getBackendTable()],
+ 'product_name_table.entity_id=main_table.product_id' .
+ ' AND product_name_table.store_id=' . $storeId .
+ ' AND product_name_table.attribute_id=' . $attribute->getId() .
+ ' AND product_name_table.entity_type_id=' . $entityTypeId,
+ [],
+ );
+
+ $this->_isProductNameJoined = true;
+ }
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Item/Option/Collection.php b/app/code/core/Mage/Wishlist/Model/Resource/Item/Option/Collection.php
index 86a75c865ce..7374ad87c1b 100644
--- a/app/code/core/Mage/Wishlist/Model/Resource/Item/Option/Collection.php
+++ b/app/code/core/Mage/Wishlist/Model/Resource/Item/Option/Collection.php
@@ -36,42 +36,6 @@ class Mage_Wishlist_Model_Resource_Item_Option_Collection extends Mage_Core_Mode
*/
protected $_optionsByProduct = [];
- /**
- * Define resource model for collection
- */
- protected function _construct()
- {
- $this->_init('wishlist/item_option');
- }
-
- /**
- * Fill array of options by item and product
- *
- * @return $this
- */
- protected function _afterLoad()
- {
- parent::_afterLoad();
-
- foreach ($this as $option) {
- $optionId = $option->getId();
- $itemId = $option->getWishlistItemId();
- $productId = $option->getProductId();
- if (isset($this->_optionsByItem[$itemId])) {
- $this->_optionsByItem[$itemId][] = $optionId;
- } else {
- $this->_optionsByItem[$itemId] = [$optionId];
- }
- if (isset($this->_optionsByProduct[$productId])) {
- $this->_optionsByProduct[$productId][] = $optionId;
- } else {
- $this->_optionsByProduct[$productId] = [$optionId];
- }
- }
-
- return $this;
- }
-
/**
* Apply quote item(s) filter to collection
*
@@ -157,4 +121,40 @@ public function getOptionsByProduct($product)
return $options;
}
+
+ /**
+ * Define resource model for collection
+ */
+ protected function _construct()
+ {
+ $this->_init('wishlist/item_option');
+ }
+
+ /**
+ * Fill array of options by item and product
+ *
+ * @return $this
+ */
+ protected function _afterLoad()
+ {
+ parent::_afterLoad();
+
+ foreach ($this as $option) {
+ $optionId = $option->getId();
+ $itemId = $option->getWishlistItemId();
+ $productId = $option->getProductId();
+ if (isset($this->_optionsByItem[$itemId])) {
+ $this->_optionsByItem[$itemId][] = $optionId;
+ } else {
+ $this->_optionsByItem[$itemId] = [$optionId];
+ }
+ if (isset($this->_optionsByProduct[$productId])) {
+ $this->_optionsByProduct[$productId][] = $optionId;
+ } else {
+ $this->_optionsByProduct[$productId] = [$optionId];
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Product/Collection.php b/app/code/core/Mage/Wishlist/Model/Resource/Product/Collection.php
index f74ad1739f2..d2ebcbf8e79 100644
--- a/app/code/core/Mage/Wishlist/Model/Resource/Product/Collection.php
+++ b/app/code/core/Mage/Wishlist/Model/Resource/Product/Collection.php
@@ -145,19 +145,6 @@ public function addStoreData()
return $this;
}
- /**
- * Rewrite retrieve attribute field name for wishlist attributes
- *
- * @inheritDoc
- */
- protected function _getAttributeFieldName($attributeCode)
- {
- if ($attributeCode === 'days_in_wishlist') {
- return $this->_joinFields[$attributeCode]['field'];
- }
- return parent::_getAttributeFieldName($attributeCode);
- }
-
/**
* Prevent loading collection because after Magento 1.4.2.0 it's impossible
* to use product collection in wishlist
@@ -170,4 +157,17 @@ public function load($printQuery = false, $logQuery = false)
{
return $this;
}
+
+ /**
+ * Rewrite retrieve attribute field name for wishlist attributes
+ *
+ * @inheritDoc
+ */
+ protected function _getAttributeFieldName($attributeCode)
+ {
+ if ($attributeCode === 'days_in_wishlist') {
+ return $this->_joinFields[$attributeCode]['field'];
+ }
+ return parent::_getAttributeFieldName($attributeCode);
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php
index b21dda17ef0..6c610d1cb0e 100644
--- a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php
+++ b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php
@@ -36,32 +36,6 @@ class Mage_Wishlist_Model_Resource_Wishlist extends Mage_Core_Model_Resource_Db_
*/
protected $_customerIdFieldName = 'customer_id';
- /**
- * Set main entity table name and primary key field name
- */
- protected function _construct()
- {
- $this->_init('wishlist/wishlist', 'wishlist_id');
- }
-
- /**
- * Prepare wishlist load select query
- *
- * @param string $field
- * @param mixed $value
- * @param mixed $object
- * @return Zend_Db_Select
- */
- protected function _getLoadSelect($field, $value, $object)
- {
- $select = parent::_getLoadSelect($field, $value, $object);
- if ($field == $this->_customerIdFieldName) {
- $select->order('wishlist_id ' . Zend_Db_Select::SQL_ASC)
- ->limit(1);
- }
- return $select;
- }
-
/**
* Getter for customer ID field name
*
@@ -101,4 +75,30 @@ public function fetchItemsCount(Mage_Wishlist_Model_Wishlist $wishlist)
return $this->_itemsCount;
}
+
+ /**
+ * Set main entity table name and primary key field name
+ */
+ protected function _construct()
+ {
+ $this->_init('wishlist/wishlist', 'wishlist_id');
+ }
+
+ /**
+ * Prepare wishlist load select query
+ *
+ * @param string $field
+ * @param mixed $value
+ * @param mixed $object
+ * @return Zend_Db_Select
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ $select = parent::_getLoadSelect($field, $value, $object);
+ if ($field == $this->_customerIdFieldName) {
+ $select->order('wishlist_id ' . Zend_Db_Select::SQL_ASC)
+ ->limit(1);
+ }
+ return $select;
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist/Collection.php b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist/Collection.php
index ed4a0e027c8..45c90dba73b 100644
--- a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist/Collection.php
+++ b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist/Collection.php
@@ -24,15 +24,6 @@
*/
class Mage_Wishlist_Model_Resource_Wishlist_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
- /**
- * Initialize resource
- *
- */
- protected function _construct()
- {
- $this->_init('wishlist/wishlist');
- }
-
/**
* Filter collection by customer
*
@@ -65,4 +56,12 @@ public function filterByCustomerIds(array $customerIds)
$this->addFieldToFilter('customer_id', ['in' => $customerIds]);
return $this;
}
+ /**
+ * Initialize resource
+ *
+ */
+ protected function _construct()
+ {
+ $this->_init('wishlist/wishlist');
+ }
}
diff --git a/app/code/core/Mage/Wishlist/Model/Wishlist.php b/app/code/core/Mage/Wishlist/Model/Wishlist.php
index 8dd3d2eada8..c856048b64b 100644
--- a/app/code/core/Mage/Wishlist/Model/Wishlist.php
+++ b/app/code/core/Mage/Wishlist/Model/Wishlist.php
@@ -68,14 +68,6 @@ class Mage_Wishlist_Model_Wishlist extends Mage_Core_Model_Abstract
*/
protected $_cacheTag = 'wishlist';
- /**
- * Initialize resource model
- */
- protected function _construct()
- {
- $this->_init('wishlist/wishlist');
- }
-
/**
* Load wishlist by customer
*
@@ -142,88 +134,6 @@ public function loadByCode($code)
return $this;
}
- /**
- * Retrieve sharing code (random string)
- *
- * @return string
- */
- protected function _getSharingRandomCode()
- {
- return Mage::helper('core')->uniqHash();
- }
-
- /**
- * Set date of last update for wishlist
- *
- * @return $this
- */
- protected function _beforeSave()
- {
- parent::_beforeSave();
- $this->setUpdatedAt(Mage::getSingleton('core/date')->gmtDate());
- return $this;
- }
-
- /**
- * Save related items
- *
- * @return $this
- */
- protected function _afterSave()
- {
- parent::_afterSave();
-
- if ($this->_itemCollection !== null) {
- $this->getItemCollection()->save();
- }
- return $this;
- }
-
- /**
- * Add catalog product object data to wishlist
- *
- * @param int $qty
- * @param bool $forciblySetQty
- * @return Mage_Wishlist_Model_Item
- */
- protected function _addCatalogProduct(Mage_Catalog_Model_Product $product, $qty = 1, $forciblySetQty = false)
- {
- $item = null;
- foreach ($this->getItemCollection() as $wishlistItem) {
- if ($wishlistItem->representProduct($product)) {
- $item = $wishlistItem;
- break;
- }
- }
-
- if ($item === null) {
- $storeId = $product->hasWishlistStoreId() ? $product->getWishlistStoreId() : $this->getStore()->getId();
- $item = Mage::getModel('wishlist/item');
- $item->setProductId($product->getId())
- ->setWishlistId($this->getId())
- ->setAddedAt(Varien_Date::now())
- ->setStoreId($storeId)
- ->setOptions($product->getCustomOptions())
- ->setProduct($product)
- ->setQty($qty)
- ->save();
-
- Mage::dispatchEvent('wishlist_item_add_after', ['wishlist' => $this]);
-
- if ($item->getId()) {
- $this->getItemCollection()->addItem($item);
- }
- } else {
- $qty = $forciblySetQty ? $qty : $item->getQty() + $qty;
- $item->setQty($qty)
- ->save();
- }
-
- $this->addItem($item);
-
- return $item;
- }
-
/**
* Retrieve wishlist item collection
*
@@ -603,4 +513,94 @@ public function save()
$this->_hasDataChanges = true;
return parent::save();
}
+
+ /**
+ * Initialize resource model
+ */
+ protected function _construct()
+ {
+ $this->_init('wishlist/wishlist');
+ }
+
+ /**
+ * Retrieve sharing code (random string)
+ *
+ * @return string
+ */
+ protected function _getSharingRandomCode()
+ {
+ return Mage::helper('core')->uniqHash();
+ }
+
+ /**
+ * Set date of last update for wishlist
+ *
+ * @return $this
+ */
+ protected function _beforeSave()
+ {
+ parent::_beforeSave();
+ $this->setUpdatedAt(Mage::getSingleton('core/date')->gmtDate());
+ return $this;
+ }
+
+ /**
+ * Save related items
+ *
+ * @return $this
+ */
+ protected function _afterSave()
+ {
+ parent::_afterSave();
+
+ if ($this->_itemCollection !== null) {
+ $this->getItemCollection()->save();
+ }
+ return $this;
+ }
+
+ /**
+ * Add catalog product object data to wishlist
+ *
+ * @param int $qty
+ * @param bool $forciblySetQty
+ * @return Mage_Wishlist_Model_Item
+ */
+ protected function _addCatalogProduct(Mage_Catalog_Model_Product $product, $qty = 1, $forciblySetQty = false)
+ {
+ $item = null;
+ foreach ($this->getItemCollection() as $wishlistItem) {
+ if ($wishlistItem->representProduct($product)) {
+ $item = $wishlistItem;
+ break;
+ }
+ }
+
+ if ($item === null) {
+ $storeId = $product->hasWishlistStoreId() ? $product->getWishlistStoreId() : $this->getStore()->getId();
+ $item = Mage::getModel('wishlist/item');
+ $item->setProductId($product->getId())
+ ->setWishlistId($this->getId())
+ ->setAddedAt(Varien_Date::now())
+ ->setStoreId($storeId)
+ ->setOptions($product->getCustomOptions())
+ ->setProduct($product)
+ ->setQty($qty)
+ ->save();
+
+ Mage::dispatchEvent('wishlist_item_add_after', ['wishlist' => $this]);
+
+ if ($item->getId()) {
+ $this->getItemCollection()->addItem($item);
+ }
+ } else {
+ $qty = $forciblySetQty ? $qty : $item->getQty() + $qty;
+ $item->setQty($qty)
+ ->save();
+ }
+
+ $this->addItem($item);
+
+ return $item;
+ }
}
diff --git a/app/code/core/Mage/Wishlist/controllers/IndexController.php b/app/code/core/Mage/Wishlist/controllers/IndexController.php
index 73634edfaa4..12289f2f0a9 100644
--- a/app/code/core/Mage/Wishlist/controllers/IndexController.php
+++ b/app/code/core/Mage/Wishlist/controllers/IndexController.php
@@ -73,52 +73,6 @@ public function skipAuthentication()
return $this;
}
- /**
- * Retrieve wishlist object
- * @param int $wishlistId
- * @return Mage_Wishlist_Model_Wishlist|false
- */
- protected function _getWishlist($wishlistId = null)
- {
- $wishlist = Mage::registry('wishlist');
- if ($wishlist) {
- return $wishlist;
- }
-
- try {
- if (!$wishlistId) {
- $wishlistId = $this->getRequest()->getParam('wishlist_id');
- }
- $customerId = Mage::getSingleton('customer/session')->getCustomerId();
- $wishlist = Mage::getModel('wishlist/wishlist');
- if ($wishlistId) {
- $wishlist->load($wishlistId);
- } else {
- $wishlist->loadByCustomer($customerId, true);
- }
-
- if (!$wishlist->getId() || $wishlist->getCustomerId() != $customerId) {
- $wishlist = null;
- Mage::throwException(
- Mage::helper('wishlist')->__("Requested wishlist doesn't exist"),
- );
- }
-
- Mage::register('wishlist', $wishlist);
- } catch (Mage_Core_Exception $e) {
- Mage::getSingleton('wishlist/session')->addError($e->getMessage());
- return false;
- } catch (Exception $e) {
- Mage::getSingleton('wishlist/session')->addException(
- $e,
- Mage::helper('wishlist')->__('Wishlist could not be created.'),
- );
- return false;
- }
-
- return $wishlist;
- }
-
/**
* Display customer wishlist
*
@@ -170,87 +124,6 @@ public function addAction()
$this->_addItemToWishList();
}
- /**
- * Add the item to wish list
- *
- * @return void
- * @throws Throwable
- */
- protected function _addItemToWishList()
- {
- $wishlist = $this->_getWishlist();
- if (!$wishlist) {
- $this->norouteAction();
- return;
- }
-
- $session = Mage::getSingleton('customer/session');
-
- $productId = (int) $this->getRequest()->getParam('product');
- if (!$productId) {
- $this->_redirect('*/');
- return;
- }
-
- $product = Mage::getModel('catalog/product')->load($productId);
- if (!$product->getId() || !$product->isVisibleInCatalog()) {
- $session->addError($this->__('Cannot specify product.'));
- $this->_redirect('*/');
- return;
- }
-
- try {
- $requestParams = $this->getRequest()->getParams();
- if ($session->getBeforeWishlistRequest()) {
- $requestParams = $session->getBeforeWishlistRequest();
- $session->unsBeforeWishlistRequest();
- }
- $buyRequest = new Varien_Object($requestParams);
-
- $result = $wishlist->addNewItem($product, $buyRequest);
- if (is_string($result)) {
- Mage::throwException($result);
- }
- $wishlist->save();
-
- Mage::dispatchEvent(
- 'wishlist_add_product',
- [
- 'wishlist' => $wishlist,
- 'product' => $product,
- 'item' => $result,
- ],
- );
-
- $referer = $session->getBeforeWishlistUrl();
- if ($referer) {
- $session->setBeforeWishlistUrl(null);
- } else {
- $referer = $this->_getRefererUrl();
- }
-
- /**
- * Set referer to avoid referring to the compare popup window
- */
- $session->setAddActionReferer($referer);
-
- Mage::helper('wishlist')->calculate();
-
- $message = $this->__(
- '%1$s has been added to your wishlist. Click here to continue shopping.',
- $product->getName(),
- Mage::helper('core')->escapeUrl($referer),
- );
- $session->addSuccess($message);
- } catch (Mage_Core_Exception $e) {
- $session->addError($this->__('An error occurred while adding item to wishlist: %s', $e->getMessage()));
- } catch (Exception $e) {
- $session->addError($this->__('An error occurred while adding item to wishlist.'));
- }
-
- $this->_redirect('*', ['wishlist_id' => $wishlist->getId()]);
- }
-
/**
* Action to reconfigure wishlist item
*
@@ -779,4 +652,131 @@ public function downloadCustomOptionAction()
}
exit(0);
}
+
+ /**
+ * Retrieve wishlist object
+ * @param int $wishlistId
+ * @return Mage_Wishlist_Model_Wishlist|false
+ */
+ protected function _getWishlist($wishlistId = null)
+ {
+ $wishlist = Mage::registry('wishlist');
+ if ($wishlist) {
+ return $wishlist;
+ }
+
+ try {
+ if (!$wishlistId) {
+ $wishlistId = $this->getRequest()->getParam('wishlist_id');
+ }
+ $customerId = Mage::getSingleton('customer/session')->getCustomerId();
+ $wishlist = Mage::getModel('wishlist/wishlist');
+ if ($wishlistId) {
+ $wishlist->load($wishlistId);
+ } else {
+ $wishlist->loadByCustomer($customerId, true);
+ }
+
+ if (!$wishlist->getId() || $wishlist->getCustomerId() != $customerId) {
+ $wishlist = null;
+ Mage::throwException(
+ Mage::helper('wishlist')->__("Requested wishlist doesn't exist"),
+ );
+ }
+
+ Mage::register('wishlist', $wishlist);
+ } catch (Mage_Core_Exception $e) {
+ Mage::getSingleton('wishlist/session')->addError($e->getMessage());
+ return false;
+ } catch (Exception $e) {
+ Mage::getSingleton('wishlist/session')->addException(
+ $e,
+ Mage::helper('wishlist')->__('Wishlist could not be created.'),
+ );
+ return false;
+ }
+
+ return $wishlist;
+ }
+
+ /**
+ * Add the item to wish list
+ *
+ * @return void
+ * @throws Throwable
+ */
+ protected function _addItemToWishList()
+ {
+ $wishlist = $this->_getWishlist();
+ if (!$wishlist) {
+ $this->norouteAction();
+ return;
+ }
+
+ $session = Mage::getSingleton('customer/session');
+
+ $productId = (int) $this->getRequest()->getParam('product');
+ if (!$productId) {
+ $this->_redirect('*/');
+ return;
+ }
+
+ $product = Mage::getModel('catalog/product')->load($productId);
+ if (!$product->getId() || !$product->isVisibleInCatalog()) {
+ $session->addError($this->__('Cannot specify product.'));
+ $this->_redirect('*/');
+ return;
+ }
+
+ try {
+ $requestParams = $this->getRequest()->getParams();
+ if ($session->getBeforeWishlistRequest()) {
+ $requestParams = $session->getBeforeWishlistRequest();
+ $session->unsBeforeWishlistRequest();
+ }
+ $buyRequest = new Varien_Object($requestParams);
+
+ $result = $wishlist->addNewItem($product, $buyRequest);
+ if (is_string($result)) {
+ Mage::throwException($result);
+ }
+ $wishlist->save();
+
+ Mage::dispatchEvent(
+ 'wishlist_add_product',
+ [
+ 'wishlist' => $wishlist,
+ 'product' => $product,
+ 'item' => $result,
+ ],
+ );
+
+ $referer = $session->getBeforeWishlistUrl();
+ if ($referer) {
+ $session->setBeforeWishlistUrl(null);
+ } else {
+ $referer = $this->_getRefererUrl();
+ }
+
+ /**
+ * Set referer to avoid referring to the compare popup window
+ */
+ $session->setAddActionReferer($referer);
+
+ Mage::helper('wishlist')->calculate();
+
+ $message = $this->__(
+ '%1$s has been added to your wishlist. Click here to continue shopping.',
+ $product->getName(),
+ Mage::helper('core')->escapeUrl($referer),
+ );
+ $session->addSuccess($message);
+ } catch (Mage_Core_Exception $e) {
+ $session->addError($this->__('An error occurred while adding item to wishlist: %s', $e->getMessage()));
+ } catch (Exception $e) {
+ $session->addError($this->__('An error occurred while adding item to wishlist.'));
+ }
+
+ $this->_redirect('*', ['wishlist_id' => $wishlist->getId()]);
+ }
}
diff --git a/app/code/core/Mage/Wishlist/controllers/SharedController.php b/app/code/core/Mage/Wishlist/controllers/SharedController.php
index 42c5db5e336..59c94893f32 100644
--- a/app/code/core/Mage/Wishlist/controllers/SharedController.php
+++ b/app/code/core/Mage/Wishlist/controllers/SharedController.php
@@ -28,28 +28,6 @@ class Mage_Wishlist_SharedController extends Mage_Wishlist_Controller_Abstract
*/
protected $_isCheckFormKey = false;
- /**
- * Retrieve wishlist instance by requested code
- *
- * @return Mage_Wishlist_Model_Wishlist|false
- */
- protected function _getWishlist()
- {
- $code = (string) $this->getRequest()->getParam('code');
- if (empty($code)) {
- return false;
- }
-
- $wishlist = Mage::getModel('wishlist/wishlist')->loadByCode($code);
- if (!$wishlist->getId()) {
- return false;
- }
-
- Mage::getSingleton('checkout/session')->setSharedWishlist($code);
-
- return $wishlist;
- }
-
/**
* Shared wishlist view page
*
@@ -124,4 +102,26 @@ public function cartAction()
return $this->_redirectUrl($redirectUrl);
}
+
+ /**
+ * Retrieve wishlist instance by requested code
+ *
+ * @return Mage_Wishlist_Model_Wishlist|false
+ */
+ protected function _getWishlist()
+ {
+ $code = (string) $this->getRequest()->getParam('code');
+ if (empty($code)) {
+ return false;
+ }
+
+ $wishlist = Mage::getModel('wishlist/wishlist')->loadByCode($code);
+ if (!$wishlist->getId()) {
+ return false;
+ }
+
+ Mage::getSingleton('checkout/session')->setSharedWishlist($code);
+
+ return $wishlist;
+ }
}
diff --git a/errors/processor.php b/errors/processor.php
index 99b117c7e4d..240a6c9a4c6 100644
--- a/errors/processor.php
+++ b/errors/processor.php
@@ -47,9 +47,6 @@ class Error_Processor
/** @var string */
public $reportUrl;
- /** @var string report file name */
- protected $_reportFile;
-
/** @var bool */
public $showErrorMsg;
@@ -63,6 +60,9 @@ class Error_Processor
/** @var bool */
public $showSendForm;
+ /** @var string report file name */
+ protected $_reportFile;
+
/**
* Server script name
*
@@ -203,6 +203,114 @@ public function getBaseUrl(bool $param = false): string
return $this->getHostUrl() . ($basePath === '/' ? '' : $basePath) . '/';
}
+ /**
+ * @throws Exception
+ */
+ public function saveReport(array $reportData)
+ {
+ $this->reportData = $reportData;
+ $this->reportId = abs((int) (microtime(true) * random_int(100, 1000)));
+ $this->_reportFile = $this->_reportDir . '/' . $this->reportId;
+ $this->_setReportData($reportData);
+
+ if (!file_exists($this->_reportDir)) {
+ @mkdir($this->_reportDir, 0750, true);
+ }
+
+ $reportData = array_map('strip_tags', $reportData);
+ @file_put_contents($this->_reportFile, serialize($reportData));
+ @chmod($this->_reportFile, 0640);
+
+ if (isset($reportData['skin']) && self::DEFAULT_SKIN !== $reportData['skin']) {
+ $this->_setSkin($reportData['skin']);
+ }
+ $this->_setReportUrl();
+
+ if (headers_sent()) {
+ echo '';
+ exit();
+ }
+ }
+
+ /**
+ * @return void|no-return
+ */
+ public function loadReport(int $reportId)
+ {
+ $reportData = false;
+ $this->reportId = $reportId;
+ $this->_reportFile = $this->_reportDir . '/' . $reportId;
+
+ if (!file_exists($this->_reportFile) || !is_readable($this->_reportFile)) {
+ header('Location: ' . $this->getBaseUrl());
+ exit();
+ }
+
+ $reportContent = file_get_contents($this->_reportFile);
+ if (!preg_match('/[oc]:[+\-]?\d+:"/i', $reportContent)) {
+ $reportData = unserialize($reportContent, ['allowed_classes' => false]);
+ }
+ if (is_array($reportData)) {
+ $this->_setReportData($reportData);
+ }
+ }
+
+ /**
+ * @return void
+ */
+ public function sendReport()
+ {
+ $this->pageTitle = 'Error Submission Form';
+
+ $this->postData['firstName'] = (isset($_POST['firstname'])) ? trim(htmlspecialchars($_POST['firstname'])) : '';
+ $this->postData['lastName'] = (isset($_POST['lastname'])) ? trim(htmlspecialchars($_POST['lastname'])) : '';
+ $this->postData['email'] = (isset($_POST['email'])) ? trim(htmlspecialchars($_POST['email'])) : '';
+ $this->postData['telephone'] = (isset($_POST['telephone'])) ? trim(htmlspecialchars($_POST['telephone'])) : '';
+ $this->postData['comment'] = (isset($_POST['comment'])) ? trim(htmlspecialchars($_POST['comment'])) : '';
+ $url = htmlspecialchars($this->reportData['url'], ENT_COMPAT | ENT_HTML401);
+
+ if (isset($_POST['submit'])) {
+ if ($this->_validate()) {
+ $msg = "URL: {$url}\n"
+ . "IP Address: {$this->_getClientIp()}\n"
+ . "First Name: {$this->postData['firstName']}\n"
+ . "Last Name: {$this->postData['lastName']}\n"
+ . "E-mail Address: {$this->postData['email']}\n";
+ if ($this->postData['telephone']) {
+ $msg .= "Telephone: {$this->postData['telephone']}\n";
+ }
+ if ($this->postData['comment']) {
+ $msg .= "Comment: {$this->postData['comment']}\n";
+ }
+
+ $subject = sprintf('%s [%s]', $this->_config->subject, $this->reportId);
+ @mail($this->_config->email_address, $subject, $msg);
+
+ $this->showSendForm = false;
+ $this->showSentMsg = true;
+ } else {
+ $this->showErrorMsg = true;
+ }
+ } else {
+ $time = gmdate('Y-m-d H:i:s \G\M\T');
+
+ $msg = "URL: {$url}\n"
+ . "IP Address: {$this->_getClientIp()}\n"
+ . "Time: {$time}\n"
+ . "Error:\n{$this->reportData[0]}\n\n"
+ . "Trace:\n{$this->reportData[1]}";
+
+ $subject = sprintf('%s [%s]', $this->_config->subject, $this->reportId);
+ @mail($this->_config->email_address, $subject, $msg);
+
+ if ($this->_config->trash === 'delete') {
+ @unlink($this->_reportFile);
+ }
+ }
+ }
+
/**
* Retrieve client IP address
*/
@@ -375,114 +483,6 @@ protected function _setReportData(array $reportData)
}
}
- /**
- * @throws Exception
- */
- public function saveReport(array $reportData)
- {
- $this->reportData = $reportData;
- $this->reportId = abs((int) (microtime(true) * random_int(100, 1000)));
- $this->_reportFile = $this->_reportDir . '/' . $this->reportId;
- $this->_setReportData($reportData);
-
- if (!file_exists($this->_reportDir)) {
- @mkdir($this->_reportDir, 0750, true);
- }
-
- $reportData = array_map('strip_tags', $reportData);
- @file_put_contents($this->_reportFile, serialize($reportData));
- @chmod($this->_reportFile, 0640);
-
- if (isset($reportData['skin']) && self::DEFAULT_SKIN !== $reportData['skin']) {
- $this->_setSkin($reportData['skin']);
- }
- $this->_setReportUrl();
-
- if (headers_sent()) {
- echo '';
- exit();
- }
- }
-
- /**
- * @return void|no-return
- */
- public function loadReport(int $reportId)
- {
- $reportData = false;
- $this->reportId = $reportId;
- $this->_reportFile = $this->_reportDir . '/' . $reportId;
-
- if (!file_exists($this->_reportFile) || !is_readable($this->_reportFile)) {
- header('Location: ' . $this->getBaseUrl());
- exit();
- }
-
- $reportContent = file_get_contents($this->_reportFile);
- if (!preg_match('/[oc]:[+\-]?\d+:"/i', $reportContent)) {
- $reportData = unserialize($reportContent, ['allowed_classes' => false]);
- }
- if (is_array($reportData)) {
- $this->_setReportData($reportData);
- }
- }
-
- /**
- * @return void
- */
- public function sendReport()
- {
- $this->pageTitle = 'Error Submission Form';
-
- $this->postData['firstName'] = (isset($_POST['firstname'])) ? trim(htmlspecialchars($_POST['firstname'])) : '';
- $this->postData['lastName'] = (isset($_POST['lastname'])) ? trim(htmlspecialchars($_POST['lastname'])) : '';
- $this->postData['email'] = (isset($_POST['email'])) ? trim(htmlspecialchars($_POST['email'])) : '';
- $this->postData['telephone'] = (isset($_POST['telephone'])) ? trim(htmlspecialchars($_POST['telephone'])) : '';
- $this->postData['comment'] = (isset($_POST['comment'])) ? trim(htmlspecialchars($_POST['comment'])) : '';
- $url = htmlspecialchars($this->reportData['url'], ENT_COMPAT | ENT_HTML401);
-
- if (isset($_POST['submit'])) {
- if ($this->_validate()) {
- $msg = "URL: {$url}\n"
- . "IP Address: {$this->_getClientIp()}\n"
- . "First Name: {$this->postData['firstName']}\n"
- . "Last Name: {$this->postData['lastName']}\n"
- . "E-mail Address: {$this->postData['email']}\n";
- if ($this->postData['telephone']) {
- $msg .= "Telephone: {$this->postData['telephone']}\n";
- }
- if ($this->postData['comment']) {
- $msg .= "Comment: {$this->postData['comment']}\n";
- }
-
- $subject = sprintf('%s [%s]', $this->_config->subject, $this->reportId);
- @mail($this->_config->email_address, $subject, $msg);
-
- $this->showSendForm = false;
- $this->showSentMsg = true;
- } else {
- $this->showErrorMsg = true;
- }
- } else {
- $time = gmdate('Y-m-d H:i:s \G\M\T');
-
- $msg = "URL: {$url}\n"
- . "IP Address: {$this->_getClientIp()}\n"
- . "Time: {$time}\n"
- . "Error:\n{$this->reportData[0]}\n\n"
- . "Trace:\n{$this->reportData[1]}";
-
- $subject = sprintf('%s [%s]', $this->_config->subject, $this->reportId);
- @mail($this->_config->email_address, $subject, $msg);
-
- if ($this->_config->trash === 'delete') {
- @unlink($this->_reportFile);
- }
- }
- }
-
/**
* Validate submitted post data
*/
diff --git a/lib/Mage/Archive.php b/lib/Mage/Archive.php
index 68643cd627a..c27a3de1402 100644
--- a/lib/Mage/Archive.php
+++ b/lib/Mage/Archive.php
@@ -59,43 +59,6 @@ class Mage_Archive
'tbz2' => 'tar.bz',
'tbzip2' => 'tar.bz'];
- /**
- * Create object of current archiver by $extension.
- *
- * @param string $extension
- * @return Mage_Archive_Tar|Mage_Archive_Gz|Mage_Archive_Bz
- */
- protected function _getArchiver($extension)
- {
- if (array_key_exists(strtolower($extension), $this->_formats)) {
- $format = $this->_formats[$extension];
- } else {
- $format = self::DEFAULT_ARCHIVER;
- }
- $class = 'Mage_Archive_' . ucfirst($format);
- $this->_archiver = new $class();
- return $this->_archiver;
- }
-
- /**
- * Split current format to list of archivers.
- *
- * @param string $source
- * @return array
- */
- protected function _getArchivers($source)
- {
- $ext = pathinfo($source, PATHINFO_EXTENSION);
- if (!isset($this->_formats[$ext])) {
- return [];
- }
- $format = $this->_formats[$ext];
- if ($format) {
- return explode('.', $format);
- }
- return [];
- }
-
/**
* Pack file or directory to archivers are parsed from extension.
*
@@ -204,4 +167,41 @@ public function isTar($file)
}
return false;
}
+
+ /**
+ * Create object of current archiver by $extension.
+ *
+ * @param string $extension
+ * @return Mage_Archive_Tar|Mage_Archive_Gz|Mage_Archive_Bz
+ */
+ protected function _getArchiver($extension)
+ {
+ if (array_key_exists(strtolower($extension), $this->_formats)) {
+ $format = $this->_formats[$extension];
+ } else {
+ $format = self::DEFAULT_ARCHIVER;
+ }
+ $class = 'Mage_Archive_' . ucfirst($format);
+ $this->_archiver = new $class();
+ return $this->_archiver;
+ }
+
+ /**
+ * Split current format to list of archivers.
+ *
+ * @param string $source
+ * @return array
+ */
+ protected function _getArchivers($source)
+ {
+ $ext = pathinfo($source, PATHINFO_EXTENSION);
+ if (!isset($this->_formats[$ext])) {
+ return [];
+ }
+ $format = $this->_formats[$ext];
+ if ($format) {
+ return explode('.', $format);
+ }
+ return [];
+ }
}
diff --git a/lib/Mage/Archive/Abstract.php b/lib/Mage/Archive/Abstract.php
index 8ad6365cbfc..f6e63bb7674 100644
--- a/lib/Mage/Archive/Abstract.php
+++ b/lib/Mage/Archive/Abstract.php
@@ -22,6 +22,21 @@
*/
class Mage_Archive_Abstract
{
+ /**
+ * Get file name from source (URI) without last extension.
+ *
+ * @param string $source
+ * @param bool $withExtension
+ * @return mixed|string
+ */
+ public function getFilename($source, $withExtension = false)
+ {
+ $file = str_replace(dirname($source) . DS, '', $source);
+ if (!$withExtension) {
+ $file = substr($file, 0, strrpos($file, '.'));
+ }
+ return $file;
+ }
/**
* Write data to file. If file can't be opened - throw exception
*
@@ -59,20 +74,4 @@ protected function _readFile($source)
}
return $data;
}
-
- /**
- * Get file name from source (URI) without last extension.
- *
- * @param string $source
- * @param bool $withExtension
- * @return mixed|string
- */
- public function getFilename($source, $withExtension = false)
- {
- $file = str_replace(dirname($source) . DS, '', $source);
- if (!$withExtension) {
- $file = substr($file, 0, strrpos($file, '.'));
- }
- return $file;
- }
}
diff --git a/lib/Mage/Archive/Tar.php b/lib/Mage/Archive/Tar.php
index 8b5218c7ed2..e4f213f6ff5 100644
--- a/lib/Mage/Archive/Tar.php
+++ b/lib/Mage/Archive/Tar.php
@@ -72,6 +72,83 @@ class Mage_Archive_Tar extends Mage_Archive_Abstract implements Mage_Archive_Int
*/
protected $_destinationFilePath;
+ /**
+ * Pack file to TAR (Tape Archiver).
+ *
+ * @param string $source
+ * @param string $destination
+ * @param boolean $skipRoot
+ * @return string
+ */
+ public function pack($source, $destination, $skipRoot = false)
+ {
+ $this->_setSkipRoot($skipRoot);
+ $source = realpath($source);
+ $tarData = $this->_setCurrentPath($source)
+ ->_setDestinationFilePath($destination)
+ ->_setCurrentFile($source);
+
+ $this->_initWriter();
+ $this->_createTar($skipRoot, true);
+ $this->_destroyWriter();
+
+ return $destination;
+ }
+
+ /**
+ * Unpack file from TAR (Tape Archiver).
+ *
+ * @param string $source
+ * @param string $destination
+ * @return string
+ */
+ public function unpack($source, $destination)
+ {
+ $this->_setCurrentFile($source)
+ ->_setCurrentPath($source);
+
+ $this->_initReader();
+ $this->_unpackCurrentTar($destination);
+ $this->_destroyReader();
+
+ return $destination;
+ }
+
+ /**
+ * Extract one file from TAR (Tape Archiver).
+ *
+ * @param string $file
+ * @param string $source
+ * @param string $destination
+ * @return string
+ */
+ public function extract($file, $source, $destination)
+ {
+ $this->_setCurrentFile($source);
+ $this->_initReader();
+
+ $archiveReader = $this->_getReader();
+ $extractedFile = '';
+
+ while (!$archiveReader->eof()) {
+ $header = $this->_extractFileHeader();
+ if ($header['name'] == $file) {
+ $extractedFile = $destination . basename($header['name']);
+ $this->_extractAndWriteFile($header, $extractedFile);
+ break;
+ }
+
+ if ($header['type'] != 5) {
+ $skipBytes = (int) (($header['size'] + self::TAR_BLOCK_SIZE - 1) / self::TAR_BLOCK_SIZE)
+ * self::TAR_BLOCK_SIZE;
+ $archiveReader->read($skipBytes);
+ }
+ }
+
+ $this->_destroyReader();
+ return $extractedFile;
+ }
+
/**
* Initialize tarball writer
*
@@ -589,81 +666,4 @@ protected function _extractAndWriteFile($fileHeader, $destination)
$bytesExtracted += strlen($block);
}
}
-
- /**
- * Pack file to TAR (Tape Archiver).
- *
- * @param string $source
- * @param string $destination
- * @param boolean $skipRoot
- * @return string
- */
- public function pack($source, $destination, $skipRoot = false)
- {
- $this->_setSkipRoot($skipRoot);
- $source = realpath($source);
- $tarData = $this->_setCurrentPath($source)
- ->_setDestinationFilePath($destination)
- ->_setCurrentFile($source);
-
- $this->_initWriter();
- $this->_createTar($skipRoot, true);
- $this->_destroyWriter();
-
- return $destination;
- }
-
- /**
- * Unpack file from TAR (Tape Archiver).
- *
- * @param string $source
- * @param string $destination
- * @return string
- */
- public function unpack($source, $destination)
- {
- $this->_setCurrentFile($source)
- ->_setCurrentPath($source);
-
- $this->_initReader();
- $this->_unpackCurrentTar($destination);
- $this->_destroyReader();
-
- return $destination;
- }
-
- /**
- * Extract one file from TAR (Tape Archiver).
- *
- * @param string $file
- * @param string $source
- * @param string $destination
- * @return string
- */
- public function extract($file, $source, $destination)
- {
- $this->_setCurrentFile($source);
- $this->_initReader();
-
- $archiveReader = $this->_getReader();
- $extractedFile = '';
-
- while (!$archiveReader->eof()) {
- $header = $this->_extractFileHeader();
- if ($header['name'] == $file) {
- $extractedFile = $destination . basename($header['name']);
- $this->_extractAndWriteFile($header, $extractedFile);
- break;
- }
-
- if ($header['type'] != 5) {
- $skipBytes = (int) (($header['size'] + self::TAR_BLOCK_SIZE - 1) / self::TAR_BLOCK_SIZE)
- * self::TAR_BLOCK_SIZE;
- $archiveReader->read($skipBytes);
- }
- }
-
- $this->_destroyReader();
- return $extractedFile;
- }
}
diff --git a/lib/Mage/Cache/Backend/File.php b/lib/Mage/Cache/Backend/File.php
index 379580a38a5..14566126979 100644
--- a/lib/Mage/Cache/Backend/File.php
+++ b/lib/Mage/Cache/Backend/File.php
@@ -119,6 +119,17 @@ public function __construct(array $options = [])
$this->_options['cache_file_umask'] = $this->_options['file_mode'];
}
+ /**
+ * For unit testing only
+ *
+ * @param $id
+ */
+ public function ___expire($id)
+ {
+ $metadata = $this->_getMetadatas($id);
+ $this->touch($id, 1 - $metadata['expire']);
+ }
+
/**
* Trying to load cached value by id, in case of failure will return false, in other case will return cached string
*
@@ -780,15 +791,4 @@ protected function _recursiveMkdirAndChmod($id)
}
return true;
}
-
- /**
- * For unit testing only
- *
- * @param $id
- */
- public function ___expire($id)
- {
- $metadata = $this->_getMetadatas($id);
- $this->touch($id, 1 - $metadata['expire']);
- }
}
diff --git a/lib/Mage/DB/Mysqli.php b/lib/Mage/DB/Mysqli.php
index 4bcf146306f..85e7390ff6a 100644
--- a/lib/Mage/DB/Mysqli.php
+++ b/lib/Mage/DB/Mysqli.php
@@ -293,16 +293,6 @@ public function escapeFieldValues(array $arrNames)
return $out;
}
- /**
- * Throw connect exception
- * @throws Mage_DB_Exception
- * @return never
- */
- protected function throwConnectException()
- {
- throw new Mage_DB_Exception($this->conn->connect_error);
- }
-
/**
* Query - perform with throwing exception on error
* @param string $sql query
@@ -506,4 +496,14 @@ public function lastInsertId()
$data = $this->fetchOne($sql);
return $data['id'];
}
+
+ /**
+ * Throw connect exception
+ * @throws Mage_DB_Exception
+ * @return never
+ */
+ protected function throwConnectException()
+ {
+ throw new Mage_DB_Exception($this->conn->connect_error);
+ }
}
diff --git a/lib/Mage/HTTP/Client/Curl.php b/lib/Mage/HTTP/Client/Curl.php
index fbcf2238a53..191e75865bc 100644
--- a/lib/Mage/HTTP/Client/Curl.php
+++ b/lib/Mage/HTTP/Client/Curl.php
@@ -109,6 +109,11 @@ class Mage_HTTP_Client_Curl implements Mage_HTTP_IClient
*/
protected $_headerCount = 0;
+ /**
+ * Constructor
+ */
+ public function __construct() {}
+
/**
* Set request timeout in seconds
*
@@ -119,11 +124,6 @@ public function setTimeout($value)
$this->_timeout = (int) $value;
}
- /**
- * Constructor
- */
- public function __construct() {}
-
/**
* Set headers from hash
@@ -316,6 +316,33 @@ public function getStatus()
return $this->_responseStatus;
}
+ /**
+ * Throw error exception
+ * @param $string
+ * @throws Exception
+ * @return never
+ */
+ public function doError($string)
+ {
+ throw new Exception($string);
+ }
+
+ /**
+ * Set CURL options ovverides array *
+ */
+ public function setOptions($arr)
+ {
+ $this->_curlUserOptions = $arr;
+ }
+
+ /**
+ * Set curl option
+ */
+ public function setOption($name, $value)
+ {
+ $this->_curlUserOptions[$name] = $value;
+ }
+
/**
* Make request
* @param string $method
@@ -379,17 +406,6 @@ protected function makeRequest($method, $uri, $params = [])
curl_close($this->_ch);
}
- /**
- * Throw error exception
- * @param $string
- * @throws Exception
- * @return never
- */
- public function doError($string)
- {
- throw new Exception($string);
- }
-
/**
* Parse headers - CURL callback function
*
@@ -461,20 +477,4 @@ protected function curlOptions($array)
{
curl_setopt_array($this->_ch, $array);
}
-
- /**
- * Set CURL options ovverides array *
- */
- public function setOptions($arr)
- {
- $this->_curlUserOptions = $arr;
- }
-
- /**
- * Set curl option
- */
- public function setOption($name, $value)
- {
- $this->_curlUserOptions[$name] = $value;
- }
}
diff --git a/lib/Mage/HTTP/Client/Socket.php b/lib/Mage/HTTP/Client/Socket.php
index f8f99428acf..60bd8eb1f43 100644
--- a/lib/Mage/HTTP/Client/Socket.php
+++ b/lib/Mage/HTTP/Client/Socket.php
@@ -88,16 +88,6 @@ class Mage_HTTP_Client_Socket implements Mage_HTTP_IClient
*/
private $_redirectCount = 0;
- /**
- * Set request timeout, msec
- *
- * @param int $value
- */
- public function setTimeout($value)
- {
- $this->_timeout = (int) $value;
- }
-
/**
* Constructor
* @param string $host
@@ -110,6 +100,16 @@ public function __construct($host = null, $port = 80)
}
}
+ /**
+ * Set request timeout, msec
+ *
+ * @param int $value
+ */
+ public function setTimeout($value)
+ {
+ $this->_timeout = (int) $value;
+ }
+
/**
* Set connection params
*
@@ -225,40 +225,6 @@ public function get($uri)
$this->makeRequest('GET', $this->parseUrl($uri));
}
- /**
- * Set host, port from full url
- * and return relative url
- *
- * @param string $uri ex. http://google.com/index.php?a=b
- * @return string ex. /index.php?a=b
- */
- protected function parseUrl($uri)
- {
- $parts = parse_url($uri);
- if (!empty($parts['user']) && !empty($parts['pass'])) {
- $this->setCredentials($parts['user'], $parts['pass']);
- }
- if (!empty($parts['port'])) {
- $this->_port = (int) $parts['port'];
- }
-
- if (!empty($parts['host'])) {
- $this->_host = $parts['host'];
- } else {
- throw new InvalidArgumentException("Uri doesn't contain host part");
- }
-
- if (!empty($parts['path'])) {
- $requestUri = $parts['path'];
- } else {
- throw new InvalidArgumentException("Uri doesn't contain path part");
- }
- if (!empty($parts['query'])) {
- $requestUri .= '?' . $parts['query'];
- }
- return $requestUri;
- }
-
/**
* Make POST request
*/
@@ -348,6 +314,76 @@ public function getCookiesFull()
return $out;
}
+ /**
+ * Get response status code
+ * @see Mage_HTTP_Client::getStatus()
+ */
+ public function getStatus()
+ {
+ return $this->_responseStatus;
+ }
+
+ /**
+ * Throw error exception
+ * @param $string
+ * @throws Exception
+ * @return never
+ */
+ public function doError($string)
+ {
+ throw new Exception($string);
+ }
+
+ /**
+ * TODO
+ */
+ public function setOptions($arr)
+ {
+ // Stub
+ }
+
+ /**
+ * TODO
+ */
+ public function setOption($name, $value)
+ {
+ // Stub
+ }
+
+ /**
+ * Set host, port from full url
+ * and return relative url
+ *
+ * @param string $uri ex. http://google.com/index.php?a=b
+ * @return string ex. /index.php?a=b
+ */
+ protected function parseUrl($uri)
+ {
+ $parts = parse_url($uri);
+ if (!empty($parts['user']) && !empty($parts['pass'])) {
+ $this->setCredentials($parts['user'], $parts['pass']);
+ }
+ if (!empty($parts['port'])) {
+ $this->_port = (int) $parts['port'];
+ }
+
+ if (!empty($parts['host'])) {
+ $this->_host = $parts['host'];
+ } else {
+ throw new InvalidArgumentException("Uri doesn't contain host part");
+ }
+
+ if (!empty($parts['path'])) {
+ $requestUri = $parts['path'];
+ } else {
+ throw new InvalidArgumentException("Uri doesn't contain path part");
+ }
+ if (!empty($parts['query'])) {
+ $requestUri .= '?' . $parts['query'];
+ }
+ return $requestUri;
+ }
+
/**
* Process response headers
*/
@@ -421,15 +457,6 @@ protected function processRedirect()
// TODO: implement redircets support
}
- /**
- * Get response status code
- * @see Mage_HTTP_Client::getStatus()
- */
- public function getStatus()
- {
- return $this->_responseStatus;
- }
-
/**
* Make request
* @param string $method
@@ -468,17 +495,6 @@ protected function makeRequest($method, $uri, $params = [])
$this->processResponse();
}
- /**
- * Throw error exception
- * @param $string
- * @throws Exception
- * @return never
- */
- public function doError($string)
- {
- throw new Exception($string);
- }
-
/**
* Convert headers hash to string
* @param $delimiter
@@ -497,20 +513,4 @@ protected function headersToString($append = [])
}
return implode($str);
}
-
- /**
- * TODO
- */
- public function setOptions($arr)
- {
- // Stub
- }
-
- /**
- * TODO
- */
- public function setOption($name, $value)
- {
- // Stub
- }
}
diff --git a/lib/Mage/System/Args.php b/lib/Mage/System/Args.php
index 90e1c3436fd..09dfd6e3841 100644
--- a/lib/Mage/System/Args.php
+++ b/lib/Mage/System/Args.php
@@ -22,24 +22,6 @@ class Mage_System_Args
public $flags;
public $filtered;
- /**
- * Get flags/named options
- * @return array
- */
- public function getFlags()
- {
- return $this->flags;
- }
-
- /**
- * Get filtered args
- * @return array
- */
- public function getFiltered()
- {
- return $this->filtered;
- }
-
/**
* Constructor
* @param array|false $argv, if false $GLOBALS['argv'] is taken
@@ -82,4 +64,22 @@ public function __construct($argv = false)
}
}
}
+
+ /**
+ * Get flags/named options
+ * @return array
+ */
+ public function getFlags()
+ {
+ return $this->flags;
+ }
+
+ /**
+ * Get filtered args
+ * @return array
+ */
+ public function getFiltered()
+ {
+ return $this->filtered;
+ }
}
diff --git a/lib/Mage/System/Ftp.php b/lib/Mage/System/Ftp.php
index e3c51dc21fb..5dccac1d3f0 100644
--- a/lib/Mage/System/Ftp.php
+++ b/lib/Mage/System/Ftp.php
@@ -29,19 +29,6 @@ class Mage_System_Ftp
*/
protected $_conn = false;
- /**
- * Check connected, throw exception if not
- *
- * @throws Exception
- * @return void
- */
- protected function checkConnected()
- {
- if (!$this->_conn) {
- throw new Exception(__CLASS__ . ' - no connection established with server');
- }
- }
-
/**
* ftp_mkdir wrapper
*
@@ -526,4 +513,17 @@ public function delete($file)
$file = $this->correctFilePath($file);
return @ftp_delete($this->_conn, $file);
}
+
+ /**
+ * Check connected, throw exception if not
+ *
+ * @throws Exception
+ * @return void
+ */
+ protected function checkConnected()
+ {
+ if (!$this->_conn) {
+ throw new Exception(__CLASS__ . ' - no connection established with server');
+ }
+ }
}
diff --git a/lib/Mage/Xml/Generator.php b/lib/Mage/Xml/Generator.php
index 9cf2da77696..32d518c86cc 100644
--- a/lib/Mage/Xml/Generator.php
+++ b/lib/Mage/Xml/Generator.php
@@ -26,29 +26,19 @@ public function __construct()
}
/**
- * @return DOMDocument|null
- */
- public function getDom()
- {
- return $this->_dom;
- }
-
- /**
- * @return DOMDocument
+ * @return string
*/
- protected function _getCurrentDom()
+ public function __toString()
{
- return $this->_currentDom;
+ return $this->getDom()->saveXML();
}
/**
- * @param DOMElement $node
- * @return $this
+ * @return DOMDocument|null
*/
- protected function _setCurrentDom($node)
+ public function getDom()
{
- $this->_currentDom = $node;
- return $this;
+ return $this->_dom;
}
/**
@@ -100,20 +90,30 @@ public function arrayToXml($content)
}
/**
- * @return string
+ * @param string $file
+ * @return $this
*/
- public function __toString()
+ public function save($file)
{
- return $this->getDom()->saveXML();
+ $this->getDom()->save($file);
+ return $this;
}
/**
- * @param string $file
+ * @return DOMDocument
+ */
+ protected function _getCurrentDom()
+ {
+ return $this->_currentDom;
+ }
+
+ /**
+ * @param DOMElement $node
* @return $this
*/
- public function save($file)
+ protected function _setCurrentDom($node)
{
- $this->getDom()->save($file);
+ $this->_currentDom = $node;
return $this;
}
}
diff --git a/lib/Mage/Xml/Parser.php b/lib/Mage/Xml/Parser.php
index 09fae8bc206..f38021312d9 100644
--- a/lib/Mage/Xml/Parser.php
+++ b/lib/Mage/Xml/Parser.php
@@ -30,6 +30,24 @@ public function getDom()
return $this->_dom;
}
+ public function xmlToArray()
+ {
+ $this->_content = $this->_xmlToArray();
+ return $this->_content;
+ }
+
+ public function load($file)
+ {
+ $this->getDom()->load($file);
+ return $this;
+ }
+
+ public function loadXML($string)
+ {
+ $this->getDom()->loadXML($string);
+ return $this;
+ }
+
protected function _getCurrentDom()
{
return $this->_currentDom;
@@ -41,12 +59,6 @@ protected function _setCurrentDom($node)
return $this;
}
- public function xmlToArray()
- {
- $this->_content = $this->_xmlToArray();
- return $this->_content;
- }
-
protected function _xmlToArray($currentNode = false)
{
if (!$currentNode) {
@@ -87,16 +99,4 @@ protected function _xmlToArray($currentNode = false)
}
return $content;
}
-
- public function load($file)
- {
- $this->getDom()->load($file);
- return $this;
- }
-
- public function loadXML($string)
- {
- $this->getDom()->loadXML($string);
- return $this;
- }
}
diff --git a/lib/Magento/Db/Adapter/Pdo/Mysql.php b/lib/Magento/Db/Adapter/Pdo/Mysql.php
index f933c3fc8e7..9e7caf266c0 100644
--- a/lib/Magento/Db/Adapter/Pdo/Mysql.php
+++ b/lib/Magento/Db/Adapter/Pdo/Mysql.php
@@ -92,24 +92,6 @@ public function splitSelect(Varien_Db_Select $select, $entityIdField = '*', $ste
return $bunches;
}
- /**
- * Quote a raw string.
- *
- * @param string|float $value Raw string
- * @return string|float Quoted string
- */
- protected function _quote($value)
- {
- if (is_float($value)) {
- return $this->_convertFloat($value);
- }
- // Fix for null-byte injection
- if (is_string($value)) {
- $value = addcslashes($value, "\000\032");
- }
- return parent::_quote($value);
- }
-
/**
* Safely quotes a value for an SQL statement.
*
@@ -137,6 +119,24 @@ public function quote($value, $type = null)
return parent::quote($value, $type);
}
+ /**
+ * Quote a raw string.
+ *
+ * @param string|float $value Raw string
+ * @return string|float Quoted string
+ */
+ protected function _quote($value)
+ {
+ if (is_float($value)) {
+ return $this->_convertFloat($value);
+ }
+ // Fix for null-byte injection
+ if (is_string($value)) {
+ $value = addcslashes($value, "\000\032");
+ }
+ return parent::_quote($value);
+ }
+
/**
* Convert float values that are not supported by MySQL to alternative representation value.
* Value 99999999.9999 is a maximum value that may be stored in Magento decimal columns in DB.
diff --git a/lib/Magento/Db/Object.php b/lib/Magento/Db/Object.php
index d4117419d29..9b80cabf74d 100644
--- a/lib/Magento/Db/Object.php
+++ b/lib/Magento/Db/Object.php
@@ -64,16 +64,6 @@ public function getDbType()
return $this->_dbType;
}
- /**
- * Returns current schema name
- *
- * @return string
- */
- protected function _getCurrentSchema()
- {
- return $this->_adapter->fetchOne('SELECT SCHEMA()');
- }
-
/**
* Returns schema name
*
@@ -121,4 +111,14 @@ public function getObjectName()
{
return $this->_objectName;
}
+
+ /**
+ * Returns current schema name
+ *
+ * @return string
+ */
+ protected function _getCurrentSchema()
+ {
+ return $this->_adapter->fetchOne('SELECT SCHEMA()');
+ }
}
diff --git a/lib/Magento/Db/Sql/Trigger.php b/lib/Magento/Db/Sql/Trigger.php
index 5366ff085dd..02383dd6a91 100644
--- a/lib/Magento/Db/Sql/Trigger.php
+++ b/lib/Magento/Db/Sql/Trigger.php
@@ -90,53 +90,13 @@ public function __construct()
}
/**
- * Validate where all trigger parts set?
- *
- * @return Magento_Db_Sql_Trigger
- * @throws Exception
- */
- protected function _validateIsComplete()
- {
- foreach (array_keys(self::$_partsInit) as $part) {
- if (empty($this->_parts[$part])) {
- throw new Exception('Part [' . $part . '] should be set');
- }
- }
- return $this;
- }
-
- /**
- * Set trigger part
- *
- * @param $part
- * @param $value
- * @return Magento_Db_Sql_Trigger
- * @throws InvalidArgumentException
- */
- protected function _setPart($part, $value)
- {
- if ($value != null) {
- $this->_parts[$part] = $value;
- } else {
- throw new InvalidArgumentException('Part [' . $part . '] can not be empty');
- }
- return $this;
- }
-
- /**
- * Set trigger part
+ * Implement magic method
*
- * @param $part
- * @return string|array
- * @throws Exception
+ * @return string
*/
- protected function _getPart($part)
+ public function __toString()
{
- if (isset($this->_parts[$part])) {
- return $this->_parts[$part];
- }
-
- throw new Exception('Part [' . $part . '] does\'t exists');
+ return $this->assemble();
}
/**
@@ -173,18 +133,6 @@ public function getBodyPart($part)
throw new Exception('Part [' . $part . '] does\'t exists');
}
- /**
- * Generate trigger name
- *
- * @return string
- */
- protected function _generateTriggerName()
- {
- return strtolower('trg_' . $this->_parts[self::TARGET]
- . '_' . $this->_parts[self::TIME]
- . '_' . $this->_parts[self::EVENT]);
- }
-
/**
* Set trigger time {BEFORE/AFTER}
* @param $time
@@ -298,16 +246,6 @@ public function assemble()
. "END;\n";
}
- /**
- * Implement magic method
- *
- * @return string
- */
- public function __toString()
- {
- return $this->assemble();
- }
-
/**
* Retrieve list of allowed events
*
@@ -338,4 +276,66 @@ public function reset()
$this->_parts = self::$_partsInit;
return $this;
}
+
+ /**
+ * Validate where all trigger parts set?
+ *
+ * @return Magento_Db_Sql_Trigger
+ * @throws Exception
+ */
+ protected function _validateIsComplete()
+ {
+ foreach (array_keys(self::$_partsInit) as $part) {
+ if (empty($this->_parts[$part])) {
+ throw new Exception('Part [' . $part . '] should be set');
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Set trigger part
+ *
+ * @param $part
+ * @param $value
+ * @return Magento_Db_Sql_Trigger
+ * @throws InvalidArgumentException
+ */
+ protected function _setPart($part, $value)
+ {
+ if ($value != null) {
+ $this->_parts[$part] = $value;
+ } else {
+ throw new InvalidArgumentException('Part [' . $part . '] can not be empty');
+ }
+ return $this;
+ }
+
+ /**
+ * Set trigger part
+ *
+ * @param $part
+ * @return string|array
+ * @throws Exception
+ */
+ protected function _getPart($part)
+ {
+ if (isset($this->_parts[$part])) {
+ return $this->_parts[$part];
+ }
+
+ throw new Exception('Part [' . $part . '] does\'t exists');
+ }
+
+ /**
+ * Generate trigger name
+ *
+ * @return string
+ */
+ protected function _generateTriggerName()
+ {
+ return strtolower('trg_' . $this->_parts[self::TARGET]
+ . '_' . $this->_parts[self::TIME]
+ . '_' . $this->_parts[self::EVENT]);
+ }
}
diff --git a/lib/Magento/Profiler.php b/lib/Magento/Profiler.php
index 075dcbe04b3..2981f4d2b84 100644
--- a/lib/Magento/Profiler.php
+++ b/lib/Magento/Profiler.php
@@ -81,21 +81,6 @@ class Magento_Profiler
self::FETCH_REALMEM,
];
- /**
- * Retrieve unique identifier among all timers
- *
- * @param string|null $timerName Timer name
- * @return string
- */
- private static function _getTimerId($timerName = null)
- {
- $currentPath = self::$_currentPath;
- if ($timerName) {
- $currentPath[] = $timerName;
- }
- return implode(self::NESTING_SEPARATOR, $currentPath);
- }
-
/**
* Enable profiling.
* Any call to profiler does nothing until profiler is enabled.
@@ -274,4 +259,19 @@ public static function display()
$output->display();
}
}
+
+ /**
+ * Retrieve unique identifier among all timers
+ *
+ * @param string|null $timerName Timer name
+ * @return string
+ */
+ private static function _getTimerId($timerName = null)
+ {
+ $currentPath = self::$_currentPath;
+ if ($timerName) {
+ $currentPath[] = $timerName;
+ }
+ return implode(self::NESTING_SEPARATOR, $currentPath);
+ }
}
diff --git a/lib/Magento/Profiler/OutputAbstract.php b/lib/Magento/Profiler/OutputAbstract.php
index 4c88db733d0..2405eb655e1 100644
--- a/lib/Magento/Profiler/OutputAbstract.php
+++ b/lib/Magento/Profiler/OutputAbstract.php
@@ -55,6 +55,22 @@ public function __construct($filter = null)
*/
abstract public function display();
+ /**
+ * Set threshold (minimal allowed) value for timer column.
+ * Timer is being rendered if at least one of its columns is not less than the minimal allowed value.
+ *
+ * @param string $fetchKey
+ * @param int|float|null $minAllowedValue
+ */
+ public function setThreshold($fetchKey, $minAllowedValue)
+ {
+ if ($minAllowedValue === null) {
+ unset($this->_thresholds[$fetchKey]);
+ } else {
+ $this->_thresholds[$fetchKey] = $minAllowedValue;
+ }
+ }
+
/**
* Retrieve the list of (column_label; column_id) pairs
*
@@ -103,6 +119,48 @@ protected function _renderTimerId($timerId)
return $timerId;
}
+ /**
+ * Retrieve the list of timer Ids
+ *
+ * @return array
+ */
+ protected function _getTimers()
+ {
+ $pattern = $this->_filter;
+ $timerIds = $this->_getSortedTimers();
+ $result = [];
+ foreach ($timerIds as $timerId) {
+ /* Filter by timer id pattern */
+ if ($pattern && !preg_match($pattern, $timerId)) {
+ continue;
+ }
+ /* Filter by column value thresholds */
+ $skip = false;
+ foreach ($this->_thresholds as $fetchKey => $minAllowedValue) {
+ $skip = (Magento_Profiler::fetch($timerId, $fetchKey) < $minAllowedValue);
+ /* First value not less than the allowed one forces to include timer to the result */
+ if (!$skip) {
+ break;
+ }
+ }
+ if (!$skip) {
+ $result[] = $timerId;
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * Render a caption for the profiling results
+ *
+ * @return string
+ */
+ protected function _renderCaption()
+ {
+ $result = 'Code Profiler (Memory usage: real - %s, emalloc - %s)';
+ return sprintf($result, memory_get_usage(true), memory_get_usage());
+ }
+
/**
* Retrieve timer ids sorted to correspond the nesting
*
@@ -153,62 +211,4 @@ private function _getSortedTimers()
}
return $result;
}
-
- /**
- * Retrieve the list of timer Ids
- *
- * @return array
- */
- protected function _getTimers()
- {
- $pattern = $this->_filter;
- $timerIds = $this->_getSortedTimers();
- $result = [];
- foreach ($timerIds as $timerId) {
- /* Filter by timer id pattern */
- if ($pattern && !preg_match($pattern, $timerId)) {
- continue;
- }
- /* Filter by column value thresholds */
- $skip = false;
- foreach ($this->_thresholds as $fetchKey => $minAllowedValue) {
- $skip = (Magento_Profiler::fetch($timerId, $fetchKey) < $minAllowedValue);
- /* First value not less than the allowed one forces to include timer to the result */
- if (!$skip) {
- break;
- }
- }
- if (!$skip) {
- $result[] = $timerId;
- }
- }
- return $result;
- }
-
- /**
- * Render a caption for the profiling results
- *
- * @return string
- */
- protected function _renderCaption()
- {
- $result = 'Code Profiler (Memory usage: real - %s, emalloc - %s)';
- return sprintf($result, memory_get_usage(true), memory_get_usage());
- }
-
- /**
- * Set threshold (minimal allowed) value for timer column.
- * Timer is being rendered if at least one of its columns is not less than the minimal allowed value.
- *
- * @param string $fetchKey
- * @param int|float|null $minAllowedValue
- */
- public function setThreshold($fetchKey, $minAllowedValue)
- {
- if ($minAllowedValue === null) {
- unset($this->_thresholds[$fetchKey]);
- } else {
- $this->_thresholds[$fetchKey] = $minAllowedValue;
- }
- }
}
diff --git a/lib/Varien/Cache/Backend/Database.php b/lib/Varien/Cache/Backend/Database.php
index 5e18cdb0b05..fbcdda104a1 100644
--- a/lib/Varien/Cache/Backend/Database.php
+++ b/lib/Varien/Cache/Backend/Database.php
@@ -75,48 +75,6 @@ public function __construct($options = [])
}
}
- /**
- * Get DB adapter
- *
- * @return Zend_Db_Adapter_Abstract
- */
- protected function _getAdapter()
- {
- if (!$this->_adapter) {
- if (!empty($this->_options['adapter_callback'])) {
- $adapter = call_user_func($this->_options['adapter_callback']);
- } else {
- $adapter = $this->_options['adapter'];
- }
- if (!($adapter instanceof Zend_Db_Adapter_Abstract)) {
- Zend_Cache::throwException('DB Adapter should be declared and extend Zend_Db_Adapter_Abstract');
- } else {
- $this->_adapter = $adapter;
- }
- }
- return $this->_adapter;
- }
-
- /**
- * Get table name where data is stored
- *
- * @return string
- */
- protected function _getDataTable()
- {
- return $this->_options['data_table'];
- }
-
- /**
- * Get table name where tags are stored
- *
- * @return string
- */
- protected function _getTagsTable()
- {
- return $this->_options['tags_table'];
- }
-
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
@@ -222,28 +180,6 @@ public function remove($id)
return $result && $adapter->delete($this->_getTagsTable(), ['cache_id = ?' => $id]);
}
- /**
- * Delete cache rows from Data table
- *
- * @param $cacheIdsToRemove
- * @return int
- */
- protected function _deleteCachesFromDataTable($cacheIdsToRemove)
- {
- return $this->_getAdapter()->delete($this->_getDataTable(), ['id IN (?)' => $cacheIdsToRemove]);
- }
-
- /**
- * Delete cache rows from Tags table
- *
- * @param $cacheIdsToRemove
- * @return int
- */
- protected function _deleteCachesFromTagsTable($cacheIdsToRemove)
- {
- return $this->_getAdapter()->delete($this->_getTagsTable(), ['cache_id IN (?)' => $cacheIdsToRemove]);
- }
-
/**
* Clean some cache records
*
@@ -291,47 +227,6 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = [])
return $result;
}
- /**
- * Clean old cache data and related cache tag data
- *
- * @return bool
- */
- protected function _cleanOldCache()
- {
- $time = time();
- $counter = 0;
- $result = true;
- $adapter = $this->_getAdapter();
- $cacheIdsToRemove = [];
-
- $select = $adapter->select()
- ->from($this->_getDataTable(), 'id')
- ->where('expire_time > ?', 0)
- ->where('expire_time <= ?', $time)
- ;
-
- $statement = $adapter->query($select);
- while ($row = $statement->fetch()) {
- if (!$result) {
- break;
- }
- $cacheIdsToRemove[] = $row['id'];
- $counter++;
- if ($counter > 100) {
- $result = $result && $this->_deleteCachesFromDataTable($cacheIdsToRemove);
- $result = $result && $this->_deleteCachesFromTagsTable($cacheIdsToRemove);
- $cacheIdsToRemove = [];
- $counter = 0;
- }
- }
- if (!empty($cacheIdsToRemove)) {
- $result = $result && $this->_deleteCachesFromDataTable($cacheIdsToRemove);
- $result = $result && $this->_deleteCachesFromTagsTable($cacheIdsToRemove);
- }
-
- return $result;
- }
-
/**
* Return an array of stored cache ids
*
@@ -499,6 +394,111 @@ public function getCapabilities()
];
}
+ /**
+ * Get DB adapter
+ *
+ * @return Zend_Db_Adapter_Abstract
+ */
+ protected function _getAdapter()
+ {
+ if (!$this->_adapter) {
+ if (!empty($this->_options['adapter_callback'])) {
+ $adapter = call_user_func($this->_options['adapter_callback']);
+ } else {
+ $adapter = $this->_options['adapter'];
+ }
+ if (!($adapter instanceof Zend_Db_Adapter_Abstract)) {
+ Zend_Cache::throwException('DB Adapter should be declared and extend Zend_Db_Adapter_Abstract');
+ } else {
+ $this->_adapter = $adapter;
+ }
+ }
+ return $this->_adapter;
+ }
+
+ /**
+ * Get table name where data is stored
+ *
+ * @return string
+ */
+ protected function _getDataTable()
+ {
+ return $this->_options['data_table'];
+ }
+
+ /**
+ * Get table name where tags are stored
+ *
+ * @return string
+ */
+ protected function _getTagsTable()
+ {
+ return $this->_options['tags_table'];
+ }
+
+ /**
+ * Delete cache rows from Data table
+ *
+ * @param $cacheIdsToRemove
+ * @return int
+ */
+ protected function _deleteCachesFromDataTable($cacheIdsToRemove)
+ {
+ return $this->_getAdapter()->delete($this->_getDataTable(), ['id IN (?)' => $cacheIdsToRemove]);
+ }
+
+ /**
+ * Delete cache rows from Tags table
+ *
+ * @param $cacheIdsToRemove
+ * @return int
+ */
+ protected function _deleteCachesFromTagsTable($cacheIdsToRemove)
+ {
+ return $this->_getAdapter()->delete($this->_getTagsTable(), ['cache_id IN (?)' => $cacheIdsToRemove]);
+ }
+
+ /**
+ * Clean old cache data and related cache tag data
+ *
+ * @return bool
+ */
+ protected function _cleanOldCache()
+ {
+ $time = time();
+ $counter = 0;
+ $result = true;
+ $adapter = $this->_getAdapter();
+ $cacheIdsToRemove = [];
+
+ $select = $adapter->select()
+ ->from($this->_getDataTable(), 'id')
+ ->where('expire_time > ?', 0)
+ ->where('expire_time <= ?', $time)
+ ;
+
+ $statement = $adapter->query($select);
+ while ($row = $statement->fetch()) {
+ if (!$result) {
+ break;
+ }
+ $cacheIdsToRemove[] = $row['id'];
+ $counter++;
+ if ($counter > 100) {
+ $result = $result && $this->_deleteCachesFromDataTable($cacheIdsToRemove);
+ $result = $result && $this->_deleteCachesFromTagsTable($cacheIdsToRemove);
+ $cacheIdsToRemove = [];
+ $counter = 0;
+ }
+ }
+ if (!empty($cacheIdsToRemove)) {
+ $result = $result && $this->_deleteCachesFromDataTable($cacheIdsToRemove);
+ $result = $result && $this->_deleteCachesFromTagsTable($cacheIdsToRemove);
+ }
+
+ return $result;
+ }
+
/**
* Save tags related to specific id
*
diff --git a/lib/Varien/Cache/Backend/Memcached.php b/lib/Varien/Cache/Backend/Memcached.php
index d95cde414f6..724b8f55f99 100644
--- a/lib/Varien/Cache/Backend/Memcached.php
+++ b/lib/Varien/Cache/Backend/Memcached.php
@@ -52,33 +52,6 @@ public function __construct(array $options = [])
}
}
- /**
- * Returns ID of a specific chunk on the basis of data's ID
- *
- * @param string $id Main data's ID
- * @param int $index Particular chunk number to return ID for
- * @return string
- */
- protected function _getChunkId($id, $index)
- {
- return "{$id}[{$index}]";
- }
-
- /**
- * Remove saved chunks in case something gone wrong (e.g. some chunk from the chain can not be found)
- *
- * @param string $id ID of data's info cell
- * @param int $chunks Number of chunks to remove (basically, the number after '{splitted}|')
- */
- protected function _cleanTheMess($id, $chunks)
- {
- for ($i = 0; $i < $chunks; $i++) {
- $this->remove($this->_getChunkId($id, $i));
- }
-
- $this->remove($id);
- }
-
/**
* Save data to memcached, split it into chunks if data size is bigger than memcached slab size.
*
@@ -148,4 +121,31 @@ public function load($id, $doNotTestCacheValidity = false)
// Data has not been split to chunks on save
return $data;
}
+
+ /**
+ * Returns ID of a specific chunk on the basis of data's ID
+ *
+ * @param string $id Main data's ID
+ * @param int $index Particular chunk number to return ID for
+ * @return string
+ */
+ protected function _getChunkId($id, $index)
+ {
+ return "{$id}[{$index}]";
+ }
+
+ /**
+ * Remove saved chunks in case something gone wrong (e.g. some chunk from the chain can not be found)
+ *
+ * @param string $id ID of data's info cell
+ * @param int $chunks Number of chunks to remove (basically, the number after '{splitted}|')
+ */
+ protected function _cleanTheMess($id, $chunks)
+ {
+ for ($i = 0; $i < $chunks; $i++) {
+ $this->remove($this->_getChunkId($id, $i));
+ }
+
+ $this->remove($id);
+ }
}
diff --git a/lib/Varien/Cache/Core.php b/lib/Varien/Cache/Core.php
index 7c3e23986ea..a39b290c0d5 100644
--- a/lib/Varien/Cache/Core.php
+++ b/lib/Varien/Cache/Core.php
@@ -16,6 +16,10 @@
class Varien_Cache_Core extends Zend_Cache_Core
{
+ /**
+ * Used to tell chunked data from ordinary
+ */
+ public const CODE_WORD = '{splitted}';
/**
* Specific slab size = 1Mb minus overhead
*
@@ -23,11 +27,6 @@ class Varien_Cache_Core extends Zend_Cache_Core
*/
protected $_specificOptions = ['slab_size' => 0];
- /**
- * Used to tell chunked data from ordinary
- */
- public const CODE_WORD = '{splitted}';
-
/**
* Constructor
*
@@ -42,66 +41,6 @@ public function __construct($options = [])
}
}
- /**
- * Returns ID of a specific chunk on the basis of data's ID
- *
- * @param string $id Main data's ID
- * @param int $index Particular chunk number to return ID for
- * @return string
- */
- protected function _getChunkId($id, $index)
- {
- return "{$id}[{$index}]";
- }
-
- /**
- * Remove saved chunks in case something gone wrong (e.g. some chunk from the chain can not be found)
- *
- * @param string $id ID of data's info cell
- * @param int $chunks Number of chunks to remove (basically, the number after '{splitted}|')
- */
- protected function _cleanTheMess($id, $chunks)
- {
- for ($i = 0; $i < $chunks; $i++) {
- $this->remove($this->_getChunkId($id, $i));
- }
-
- $this->remove($id);
- }
-
- /**
- * Make and return a cache id
- *
- * Checks 'cache_id_prefix' and returns new id with prefix or simply the id if null
- *
- * @param string $id Cache id
- * @return string Cache id (with or without prefix)
- */
- protected function _id($id)
- {
- if ($id !== null) {
- $id = preg_replace('/([^a-zA-Z0-9_]{1,1})/', '_', $id);
- if (isset($this->_options['cache_id_prefix'])) {
- $id = $this->_options['cache_id_prefix'] . $id;
- }
- }
- return $id;
- }
-
- /**
- * Prepare tags
- *
- * @param array $tags
- * @return array
- */
- protected function _tags($tags)
- {
- foreach ($tags as $key => $tag) {
- $tags[$key] = $this->_id($tag);
- }
- return $tags;
- }
-
/**
* Save some data in a cache
*
@@ -227,4 +166,64 @@ public function getIdsNotMatchingTags($tags = [])
$tags = $this->_tags($tags);
return parent::getIdsNotMatchingTags($tags);
}
+
+ /**
+ * Returns ID of a specific chunk on the basis of data's ID
+ *
+ * @param string $id Main data's ID
+ * @param int $index Particular chunk number to return ID for
+ * @return string
+ */
+ protected function _getChunkId($id, $index)
+ {
+ return "{$id}[{$index}]";
+ }
+
+ /**
+ * Remove saved chunks in case something gone wrong (e.g. some chunk from the chain can not be found)
+ *
+ * @param string $id ID of data's info cell
+ * @param int $chunks Number of chunks to remove (basically, the number after '{splitted}|')
+ */
+ protected function _cleanTheMess($id, $chunks)
+ {
+ for ($i = 0; $i < $chunks; $i++) {
+ $this->remove($this->_getChunkId($id, $i));
+ }
+
+ $this->remove($id);
+ }
+
+ /**
+ * Make and return a cache id
+ *
+ * Checks 'cache_id_prefix' and returns new id with prefix or simply the id if null
+ *
+ * @param string $id Cache id
+ * @return string Cache id (with or without prefix)
+ */
+ protected function _id($id)
+ {
+ if ($id !== null) {
+ $id = preg_replace('/([^a-zA-Z0-9_]{1,1})/', '_', $id);
+ if (isset($this->_options['cache_id_prefix'])) {
+ $id = $this->_options['cache_id_prefix'] . $id;
+ }
+ }
+ return $id;
+ }
+
+ /**
+ * Prepare tags
+ *
+ * @param array $tags
+ * @return array
+ */
+ protected function _tags($tags)
+ {
+ foreach ($tags as $key => $tag) {
+ $tags[$key] = $this->_id($tag);
+ }
+ return $tags;
+ }
}
diff --git a/lib/Varien/Data/Collection.php b/lib/Varien/Data/Collection.php
index eccb00c78db..fd2c41571c8 100644
--- a/lib/Varien/Data/Collection.php
+++ b/lib/Varien/Data/Collection.php
@@ -172,18 +172,6 @@ public function isLoaded()
return $this->_isCollectionLoaded;
}
- /**
- * Set collection loading status flag
- *
- * @param bool $flag
- * @return $this
- */
- protected function _setIsLoaded($flag = true)
- {
- $this->_isCollectionLoaded = $flag;
- return $this;
- }
-
/**
* Get current collection page
*
@@ -362,28 +350,6 @@ public function addItem(Varien_Object $item)
return $this;
}
- /**
- * Add item that has no id to collection
- *
- * @param Varien_Object $item
- * @return $this
- */
- protected function _addItem($item)
- {
- $this->_items[] = $item;
- return $this;
- }
-
- /**
- * Retrieve item id
- *
- * @return mixed
- */
- protected function _getItemId(Varien_Object $item)
- {
- return $item->getId();
- }
-
/**
* Retrieve ids of all tems
*
@@ -547,36 +513,6 @@ public function getNewEmptyItem()
return new $this->_itemObjectClass();
}
- /**
- * Render sql select conditions
- *
- * @return Varien_Data_Collection
- */
- protected function _renderFilters()
- {
- return $this;
- }
-
- /**
- * Render sql select orders
- *
- * @return Varien_Data_Collection
- */
- protected function _renderOrders()
- {
- return $this;
- }
-
- /**
- * Render sql select limit
- *
- * @return Varien_Data_Collection
- */
- protected function _renderLimit()
- {
- return $this;
- }
-
/**
* Set select distinct
*
@@ -649,38 +585,6 @@ public function toArray($arrRequiredFields = [])
return $arrItems;
}
- /**
- * Convert items array to array for select options
- *
- * return items array
- * array(
- * $index => array(
- * 'value' => mixed
- * 'label' => mixed
- * )
- * )
- *
- * @param string $valueField
- * @param string $labelField
- * @param array $additional
- * @return array
- */
- protected function _toOptionArray($valueField = 'id', $labelField = 'name', $additional = [])
- {
- $data = [];
- $res = [];
- $additional['value'] = $valueField;
- $additional['label'] = $labelField;
-
- foreach ($this as $item) {
- foreach ($additional as $code => $field) {
- $data[$code] = $item->getData($field);
- }
- $res[] = $data;
- }
- return $res;
- }
-
/**
* @return array
*/
@@ -697,25 +601,6 @@ public function toOptionHash()
return $this->_toOptionHash();
}
- /**
- * Convert items array to hash for select options
- *
- * return items hash
- * array($value => $label)
- *
- * @param string $valueField
- * @param string $labelField
- * @return array
- */
- protected function _toOptionHash($valueField = 'id', $labelField = 'name')
- {
- $res = [];
- foreach ($this as $item) {
- $res[$item->getData($valueField)] = $item->getData($labelField);
- }
- return $res;
- }
-
/**
* Retrieve item by id
*
@@ -831,4 +716,119 @@ public function hasFlag($flag)
{
return array_key_exists($flag, $this->_flags);
}
+
+ /**
+ * Set collection loading status flag
+ *
+ * @param bool $flag
+ * @return $this
+ */
+ protected function _setIsLoaded($flag = true)
+ {
+ $this->_isCollectionLoaded = $flag;
+ return $this;
+ }
+
+ /**
+ * Add item that has no id to collection
+ *
+ * @param Varien_Object $item
+ * @return $this
+ */
+ protected function _addItem($item)
+ {
+ $this->_items[] = $item;
+ return $this;
+ }
+
+ /**
+ * Retrieve item id
+ *
+ * @return mixed
+ */
+ protected function _getItemId(Varien_Object $item)
+ {
+ return $item->getId();
+ }
+
+ /**
+ * Render sql select conditions
+ *
+ * @return Varien_Data_Collection
+ */
+ protected function _renderFilters()
+ {
+ return $this;
+ }
+
+ /**
+ * Render sql select orders
+ *
+ * @return Varien_Data_Collection
+ */
+ protected function _renderOrders()
+ {
+ return $this;
+ }
+
+ /**
+ * Render sql select limit
+ *
+ * @return Varien_Data_Collection
+ */
+ protected function _renderLimit()
+ {
+ return $this;
+ }
+
+ /**
+ * Convert items array to array for select options
+ *
+ * return items array
+ * array(
+ * $index => array(
+ * 'value' => mixed
+ * 'label' => mixed
+ * )
+ * )
+ *
+ * @param string $valueField
+ * @param string $labelField
+ * @param array $additional
+ * @return array
+ */
+ protected function _toOptionArray($valueField = 'id', $labelField = 'name', $additional = [])
+ {
+ $data = [];
+ $res = [];
+ $additional['value'] = $valueField;
+ $additional['label'] = $labelField;
+
+ foreach ($this as $item) {
+ foreach ($additional as $code => $field) {
+ $data[$code] = $item->getData($field);
+ }
+ $res[] = $data;
+ }
+ return $res;
+ }
+
+ /**
+ * Convert items array to hash for select options
+ *
+ * return items hash
+ * array($value => $label)
+ *
+ * @param string $valueField
+ * @param string $labelField
+ * @return array
+ */
+ protected function _toOptionHash($valueField = 'id', $labelField = 'name')
+ {
+ $res = [];
+ foreach ($this as $item) {
+ $res[$item->getData($valueField)] = $item->getData($labelField);
+ }
+ return $res;
+ }
}
diff --git a/lib/Varien/Data/Collection/Db.php b/lib/Varien/Data/Collection/Db.php
index 59e720e6615..e7602f19f73 100644
--- a/lib/Varien/Data/Collection/Db.php
+++ b/lib/Varien/Data/Collection/Db.php
@@ -96,6 +96,18 @@ public function __construct($conn = null)
}
}
+ /**
+ * Magic clone function
+ *
+ * Clone also Zend_Db_Select
+ *
+ * @return void
+ */
+ public function __clone()
+ {
+ $this->_select = clone $this->_select;
+ }
+
/**
* Add variable to bind list
*
@@ -127,18 +139,6 @@ public function initCache($object, $idPrefix, $tags)
return $this;
}
- /**
- * Specify collection objects id field name
- *
- * @param string $fieldName
- * @return $this
- */
- protected function _setIdFieldName($fieldName)
- {
- $this->_idFieldName = $fieldName;
- return $this;
- }
-
/**
* Id field name getter
*
@@ -149,19 +149,6 @@ public function getIdFieldName()
return $this->_idFieldName;
}
- /**
- * Get collection item identifier
- *
- * @return mixed
- */
- protected function _getItemId(Varien_Object $item)
- {
- if ($field = $this->getIdFieldName()) {
- return $item->getData($field);
- }
- return parent::_getItemId($item);
- }
-
/**
* Set database connection adapter
*
@@ -331,32 +318,219 @@ public function unshiftOrder($field, $direction = self::SORT_ORDER_DESC)
}
/**
- * Add ORDERBY to the end or to the beginning
+ * Add field filter to collection
*
- * @param string $field
- * @param string $direction
- * @param bool $unshift
- * @return $this
+ * @see self::_getConditionSql for $condition
+ *
+ * @param string|array $field
+ * @param int|string|array|null $condition
+ * @return $this
*/
- private function _setOrder($field, $direction, $unshift = false)
+ public function addFieldToFilter($field, $condition = null)
{
- $this->_isOrdersRendered = false;
- $field = (string) $this->_getMappedField($field);
- $direction = (strtoupper($direction) == self::SORT_ORDER_ASC) ? self::SORT_ORDER_ASC : self::SORT_ORDER_DESC;
+ if (!is_array($field)) {
+ $resultCondition = $this->_translateCondition($field, $condition);
+ } else {
+ $conditions = [];
+ foreach ($field as $key => $currField) {
+ $conditions[] = $this->_translateCondition(
+ $currField,
+ isset($condition[$key]) ? $condition[$key] : null,
+ );
+ }
- unset($this->_orders[$field]); // avoid ordering by the same field twice
- if ($unshift) {
- $orders = [$field => $direction];
- foreach ($this->_orders as $key => $dir) {
- $orders[$key] = $dir;
+ $resultCondition = '(' . implode(') ' . Zend_Db_Select::SQL_OR . ' (', $conditions) . ')';
+ }
+
+ $this->_select->where($resultCondition);
+
+ return $this;
+ }
+
+ /**
+ * Set select distinct
+ *
+ * @param bool $flag
+ *
+ * @return $this
+ */
+ public function distinct($flag)
+ {
+ $this->_select->distinct($flag);
+ return $this;
+ }
+
+ /**
+ * Load data
+ *
+ * @param bool $printQuery
+ * @param bool $logQuery
+ *
+ * @return $this
+ */
+ public function load($printQuery = false, $logQuery = false)
+ {
+ if ($this->isLoaded()) {
+ return $this;
+ }
+
+ $this->_beforeLoad();
+
+ $this->_renderFilters()
+ ->_renderOrders()
+ ->_renderLimit();
+
+ $this->printLogQuery($printQuery, $logQuery);
+ $data = $this->getData();
+ $this->resetData();
+
+ if (is_array($data)) {
+ foreach ($data as $row) {
+ $item = $this->getNewEmptyItem();
+ if ($this->getIdFieldName()) {
+ $item->setIdFieldName($this->getIdFieldName());
+ }
+ $item->addData($row);
+ $item->setDataChanges(false);
+ $this->addItem($item);
}
- $this->_orders = $orders;
- } else {
- $this->_orders[$field] = $direction;
}
+
+ $this->_setIsLoaded();
+ $this->_afterLoad();
+ return $this;
+ }
+
+ /**
+ * Returns a collection item that corresponds to the fetched row
+ * and moves the internal data pointer ahead
+ *
+ * @return Varien_Object|bool
+ */
+ public function fetchItem()
+ {
+ if (null === $this->_fetchStmt) {
+ $this->_fetchStmt = $this->getConnection()
+ ->query($this->getSelect());
+ }
+ $data = $this->_fetchStmt->fetch();
+ if (!empty($data) && is_array($data)) {
+ $item = $this->getNewEmptyItem();
+ if ($this->getIdFieldName()) {
+ $item->setIdFieldName($this->getIdFieldName());
+ }
+ $item->setData($data);
+
+ return $item;
+ }
+ return false;
+ }
+
+ /**
+ * Get all data array for collection
+ *
+ * @return array
+ */
+ public function getData()
+ {
+ if ($this->_data === null) {
+ $this->_renderFilters()
+ ->_renderOrders()
+ ->_renderLimit();
+ $this->_data = $this->_fetchAll($this->_select);
+ $this->_afterLoadData();
+ }
+ return $this->_data;
+ }
+
+ /**
+ * Reset loaded for collection data array
+ *
+ * @return $this
+ */
+ public function resetData()
+ {
+ $this->_data = null;
+ return $this;
+ }
+
+ /**
+ * @param bool $printQuery
+ * @param bool $logQuery
+ * @return Varien_Data_Collection|Varien_Data_Collection_Db
+ */
+ public function loadData($printQuery = false, $logQuery = false)
+ {
+ return $this->load($printQuery, $logQuery);
+ }
+
+ /**
+ * Print and/or log query
+ *
+ * @param bool $printQuery
+ * @param bool $logQuery
+ * @param string $sql
+ *
+ * @return $this
+ */
+ public function printLogQuery($printQuery = false, $logQuery = false, $sql = null)
+ {
+ if ($printQuery) {
+ echo is_null($sql) ? $this->getSelect()->__toString() : $sql;
+ }
+
+ if ($logQuery) {
+ Mage::log(is_null($sql) ? $this->getSelect()->__toString() : $sql);
+ }
+ return $this;
+ }
+
+ /**
+ * Add filter to Map
+ *
+ * @param string $filter
+ * @param string $alias
+ * @param string $group default 'fields'
+ *
+ * @return $this
+ */
+ public function addFilterToMap($filter, $alias, $group = 'fields')
+ {
+ if (is_null($this->_map)) {
+ $this->_map = [$group => []];
+ } elseif (is_null($this->_map[$group])) {
+ $this->_map[$group] = [];
+ }
+ $this->_map[$group][$filter] = $alias;
+
+ return $this;
+ }
+
+ /**
+ * Specify collection objects id field name
+ *
+ * @param string $fieldName
+ * @return $this
+ */
+ protected function _setIdFieldName($fieldName)
+ {
+ $this->_idFieldName = $fieldName;
return $this;
}
+ /**
+ * Get collection item identifier
+ *
+ * @return mixed
+ */
+ protected function _getItemId(Varien_Object $item)
+ {
+ if ($field = $this->getIdFieldName()) {
+ return $item->getData($field);
+ }
+ return parent::_getItemId($item);
+ }
+
/**
* Render sql select conditions
*
@@ -404,36 +578,6 @@ protected function _renderFilters()
*/
protected function _renderFiltersBefore() {}
- /**
- * Add field filter to collection
- *
- * @see self::_getConditionSql for $condition
- *
- * @param string|array $field
- * @param int|string|array|null $condition
- * @return $this
- */
- public function addFieldToFilter($field, $condition = null)
- {
- if (!is_array($field)) {
- $resultCondition = $this->_translateCondition($field, $condition);
- } else {
- $conditions = [];
- foreach ($field as $key => $currField) {
- $conditions[] = $this->_translateCondition(
- $currField,
- isset($condition[$key]) ? $condition[$key] : null,
- );
- }
-
- $resultCondition = '(' . implode(') ' . Zend_Db_Select::SQL_OR . ' (', $conditions) . ')';
- }
-
- $this->_select->where($resultCondition);
-
- return $this;
- }
-
/**
* Build sql where condition part
*
@@ -563,19 +707,6 @@ protected function _renderLimit()
return $this;
}
- /**
- * Set select distinct
- *
- * @param bool $flag
- *
- * @return $this
- */
- public function distinct($flag)
- {
- $this->_select->distinct($flag);
- return $this;
- }
-
/**
* Before load action
*
@@ -586,72 +717,6 @@ protected function _beforeLoad()
return $this;
}
- /**
- * Load data
- *
- * @param bool $printQuery
- * @param bool $logQuery
- *
- * @return $this
- */
- public function load($printQuery = false, $logQuery = false)
- {
- if ($this->isLoaded()) {
- return $this;
- }
-
- $this->_beforeLoad();
-
- $this->_renderFilters()
- ->_renderOrders()
- ->_renderLimit();
-
- $this->printLogQuery($printQuery, $logQuery);
- $data = $this->getData();
- $this->resetData();
-
- if (is_array($data)) {
- foreach ($data as $row) {
- $item = $this->getNewEmptyItem();
- if ($this->getIdFieldName()) {
- $item->setIdFieldName($this->getIdFieldName());
- }
- $item->addData($row);
- $item->setDataChanges(false);
- $this->addItem($item);
- }
- }
-
- $this->_setIsLoaded();
- $this->_afterLoad();
- return $this;
- }
-
- /**
- * Returns a collection item that corresponds to the fetched row
- * and moves the internal data pointer ahead
- *
- * @return Varien_Object|bool
- */
- public function fetchItem()
- {
- if (null === $this->_fetchStmt) {
- $this->_fetchStmt = $this->getConnection()
- ->query($this->getSelect());
- }
- $data = $this->_fetchStmt->fetch();
- if (!empty($data) && is_array($data)) {
- $item = $this->getNewEmptyItem();
- if ($this->getIdFieldName()) {
- $item->setIdFieldName($this->getIdFieldName());
- }
- $item->setData($data);
-
- return $item;
- }
- return false;
- }
-
/**
* Convert items array to hash for select options
* unsing fetchItem method
@@ -676,23 +741,6 @@ protected function _toOptionHashOptimized($valueField = 'id', $labelField = 'nam
return $result;
}
- /**
- * Get all data array for collection
- *
- * @return array
- */
- public function getData()
- {
- if ($this->_data === null) {
- $this->_renderFilters()
- ->_renderOrders()
- ->_renderLimit();
- $this->_data = $this->_fetchAll($this->_select);
- $this->_afterLoadData();
- }
- return $this->_data;
- }
-
/**
* Process loaded collection data
*
@@ -703,17 +751,6 @@ protected function _afterLoadData()
return $this;
}
- /**
- * Reset loaded for collection data array
- *
- * @return $this
- */
- public function resetData()
- {
- $this->_data = null;
- return $this;
- }
-
/**
* @return $this
*/
@@ -722,37 +759,6 @@ protected function _afterLoad()
return $this;
}
- /**
- * @param bool $printQuery
- * @param bool $logQuery
- * @return Varien_Data_Collection|Varien_Data_Collection_Db
- */
- public function loadData($printQuery = false, $logQuery = false)
- {
- return $this->load($printQuery, $logQuery);
- }
-
- /**
- * Print and/or log query
- *
- * @param bool $printQuery
- * @param bool $logQuery
- * @param string $sql
- *
- * @return $this
- */
- public function printLogQuery($printQuery = false, $logQuery = false, $sql = null)
- {
- if ($printQuery) {
- echo is_null($sql) ? $this->getSelect()->__toString() : $sql;
- }
-
- if ($logQuery) {
- Mage::log(is_null($sql) ? $this->getSelect()->__toString() : $sql);
- }
- return $this;
- }
-
/**
* Reset collection
*
@@ -872,35 +878,29 @@ protected function _getCacheTags()
}
/**
- * Add filter to Map
- *
- * @param string $filter
- * @param string $alias
- * @param string $group default 'fields'
+ * Add ORDERBY to the end or to the beginning
*
+ * @param string $field
+ * @param string $direction
+ * @param bool $unshift
* @return $this
*/
- public function addFilterToMap($filter, $alias, $group = 'fields')
+ private function _setOrder($field, $direction, $unshift = false)
{
- if (is_null($this->_map)) {
- $this->_map = [$group => []];
- } elseif (is_null($this->_map[$group])) {
- $this->_map[$group] = [];
- }
- $this->_map[$group][$filter] = $alias;
+ $this->_isOrdersRendered = false;
+ $field = (string) $this->_getMappedField($field);
+ $direction = (strtoupper($direction) == self::SORT_ORDER_ASC) ? self::SORT_ORDER_ASC : self::SORT_ORDER_DESC;
+ unset($this->_orders[$field]); // avoid ordering by the same field twice
+ if ($unshift) {
+ $orders = [$field => $direction];
+ foreach ($this->_orders as $key => $dir) {
+ $orders[$key] = $dir;
+ }
+ $this->_orders = $orders;
+ } else {
+ $this->_orders[$field] = $direction;
+ }
return $this;
}
-
- /**
- * Magic clone function
- *
- * Clone also Zend_Db_Select
- *
- * @return void
- */
- public function __clone()
- {
- $this->_select = clone $this->_select;
- }
}
diff --git a/lib/Varien/Data/Collection/Filesystem.php b/lib/Varien/Data/Collection/Filesystem.php
index f202e3d1c77..9e75c487f9b 100644
--- a/lib/Varien/Data/Collection/Filesystem.php
+++ b/lib/Varien/Data/Collection/Filesystem.php
@@ -87,6 +87,14 @@ class Varien_Data_Collection_Filesystem extends Varien_Data_Collection
*/
protected $_disallowedFilesMask = '';
+ /**
+ * Collecting items helper variables
+ *
+ * @var array
+ */
+ protected $_collectedDirs = [];
+ protected $_collectedFiles = [];
+
/**
* Filter rendering helper variables
*
@@ -97,14 +105,6 @@ class Varien_Data_Collection_Filesystem extends Varien_Data_Collection
private $_filterBrackets = [];
private $_filterEvalRendered = '';
- /**
- * Collecting items helper variables
- *
- * @var array
- */
- protected $_collectedDirs = [];
- protected $_collectedFiles = [];
-
/**
* Allowed dirs mask setter
* Set empty to not filter
@@ -209,49 +209,6 @@ public function setDirsFirst($value)
return $this;
}
- /**
- * Get files from specified directory recursively (if needed)
- *
- * @param string|array $dir
- */
- protected function _collectRecursive($dir)
- {
- $collectedResult = [];
- if (!is_array($dir)) {
- $dir = [$dir];
- }
- foreach ($dir as $folder) {
- if ($nodes = glob($folder . DIRECTORY_SEPARATOR . '*')) {
- foreach ($nodes as $node) {
- $collectedResult[] = $node;
- }
- }
- }
- if (empty($collectedResult)) {
- return;
- }
-
- foreach ($collectedResult as $item) {
- if (is_dir($item) && (!$this->_allowedDirsMask || preg_match($this->_allowedDirsMask, basename($item)))) {
- if ($this->_collectDirs) {
- if ($this->_dirsFirst) {
- $this->_collectedDirs[] = $item;
- } else {
- $this->_collectedFiles[] = $item;
- }
- }
- if ($this->_collectRecursively) {
- $this->_collectRecursive($item);
- }
- } elseif ($this->_collectFiles && is_file($item)
- && (!$this->_allowedFilesMask || preg_match($this->_allowedFilesMask, basename($item)))
- && (!$this->_disallowedFilesMask || !preg_match($this->_disallowedFilesMask, basename($item)))
- ) {
- $this->_collectedFiles[] = $item;
- }
- }
- }
-
/**
* Launch data collecting
*
@@ -302,52 +259,6 @@ public function loadData($printQuery = false, $logQuery = false)
return $this;
}
- /**
- * With specified collected items:
- * - generate data
- * - apply filters
- * - sort
- *
- * @param string $attributeName '_collectedFiles' | '_collectedDirs'
- */
- private function _generateAndFilterAndSort($attributeName)
- {
- // generate custom data (as rows with columns) basing on the filenames
- foreach ($this->$attributeName as $key => $filename) {
- $this->{$attributeName}[$key] = $this->_generateRow($filename);
- }
-
- // apply filters on generated data
- if (!empty($this->_filters)) {
- foreach ($this->$attributeName as $key => $row) {
- if (!$this->_filterRow($row)) {
- unset($this->{$attributeName}[$key]);
- }
- }
- }
-
- // sort (keys are lost!)
- if (!empty($this->_orders)) {
- usort($this->$attributeName, [$this, '_usort']);
- }
- }
-
- /**
- * Callback for sorting items
- * Currently supports only sorting by one column
- *
- * @param array $a
- * @param array $b
- * @return int|void
- */
- protected function _usort($a, $b)
- {
- foreach ($this->_orders as $key => $direction) {
- $result = $a[$key] > $b[$key] ? 1 : ($a[$key] < $b[$key] ? -1 : 0);
- return (self::SORT_ORDER_ASC === strtoupper($direction) ? $result : -$result);
- }
- }
-
/**
* Set select order
* Currently supports only sorting by one column
@@ -362,20 +273,6 @@ public function setOrder($field, $direction = self::SORT_ORDER_DESC)
return $this;
}
- /**
- * Generate item row basing on the filename
- *
- * @param string $filename
- * @return array
- */
- protected function _generateRow($filename)
- {
- return [
- 'filename' => $filename,
- 'basename' => basename($filename),
- ];
- }
-
/**
* Set a custom filter with callback
* The callback must take 3 params:
@@ -403,56 +300,6 @@ public function addCallbackFilter($field, $value, $type, $callback, $isInverted
return $this;
}
- /**
- * The filters renderer and caller
- * Aplies to each row, renders once.
- *
- * @param array $row
- * @return bool
- */
- protected function _filterRow($row)
- {
- // render filters once
- if (!$this->_isFiltersRendered) {
- $eval = '';
- for ($i = 0; $i < $this->_filterIncrement; $i++) {
- if (isset($this->_filterBrackets[$i])) {
- $eval .= $this->_renderConditionBeforeFilterElement($i, $this->_filterBrackets[$i]['is_and'])
- . $this->_filterBrackets[$i]['value'];
- } else {
- $f = '$this->_filters[' . $i . ']';
- $eval .= $this->_renderConditionBeforeFilterElement($i, $this->_filters[$i]['is_and'])
- . ($this->_filters[$i]['is_inverted'] ? '!' : '')
- . '$this->_invokeFilter(' . "{$f}['callback'], array({$f}['field'], {$f}['value'], " . '$row))';
- }
- }
- $this->_filterEvalRendered = $eval;
- $this->_isFiltersRendered = true;
- }
- $result = false;
- if ($this->_filterEvalRendered) {
- eval('$result = ' . $this->_filterEvalRendered . ';');
- }
- return $result;
- }
-
- /**
- * Invokes specified callback
- * Skips, if there is no filtered key in the row
- *
- * @param callback $callback
- * @param array $callbackParams
- * @return bool
- */
- protected function _invokeFilter($callback, $callbackParams)
- {
- list($field, $value, $row) = $callbackParams;
- if (!array_key_exists($field, $row)) {
- return false;
- }
- return call_user_func_array($callback, $callbackParams);
- }
-
/**
* Fancy field filter
*
@@ -535,46 +382,6 @@ public function addFieldToFilter($field, $cond, $type = 'and')
return $this;
}
- /**
- * Prepare a bracket into filters
- *
- * @param string $bracket
- * @param bool $isAnd
- * @return $this
- */
- protected function _addFilterBracket($bracket = '(', $isAnd = true)
- {
- $this->_filterBrackets[$this->_filterIncrement] = [
- 'value' => $bracket === ')' ? ')' : '(',
- 'is_and' => $isAnd,
- ];
- $this->_filterIncrement++;
- return $this;
- }
-
- /**
- * Render condition sign before element, if required
- *
- * @param int $increment
- * @param bool $isAnd
- * @return string
- */
- protected function _renderConditionBeforeFilterElement($increment, $isAnd)
- {
- if (isset($this->_filterBrackets[$increment]) && ')' === $this->_filterBrackets[$increment]['value']) {
- return '';
- }
- $prevIncrement = $increment - 1;
- $prevBracket = false;
- if (isset($this->_filterBrackets[$prevIncrement])) {
- $prevBracket = $this->_filterBrackets[$prevIncrement]['value'];
- }
- if ($prevIncrement < 0 || $prevBracket === '(') {
- return '';
- }
- return ($isAnd ? ' && ' : ' || ');
- }
-
/**
* Does nothing. Intentionally disabled parent method
*
@@ -688,4 +495,197 @@ public function filterCallbackIsLessThan($field, $filterValue, $row)
{
return $row[$field] < $filterValue;
}
+
+ /**
+ * Get files from specified directory recursively (if needed)
+ *
+ * @param string|array $dir
+ */
+ protected function _collectRecursive($dir)
+ {
+ $collectedResult = [];
+ if (!is_array($dir)) {
+ $dir = [$dir];
+ }
+ foreach ($dir as $folder) {
+ if ($nodes = glob($folder . DIRECTORY_SEPARATOR . '*')) {
+ foreach ($nodes as $node) {
+ $collectedResult[] = $node;
+ }
+ }
+ }
+ if (empty($collectedResult)) {
+ return;
+ }
+
+ foreach ($collectedResult as $item) {
+ if (is_dir($item) && (!$this->_allowedDirsMask || preg_match($this->_allowedDirsMask, basename($item)))) {
+ if ($this->_collectDirs) {
+ if ($this->_dirsFirst) {
+ $this->_collectedDirs[] = $item;
+ } else {
+ $this->_collectedFiles[] = $item;
+ }
+ }
+ if ($this->_collectRecursively) {
+ $this->_collectRecursive($item);
+ }
+ } elseif ($this->_collectFiles && is_file($item)
+ && (!$this->_allowedFilesMask || preg_match($this->_allowedFilesMask, basename($item)))
+ && (!$this->_disallowedFilesMask || !preg_match($this->_disallowedFilesMask, basename($item)))
+ ) {
+ $this->_collectedFiles[] = $item;
+ }
+ }
+ }
+
+ /**
+ * Callback for sorting items
+ * Currently supports only sorting by one column
+ *
+ * @param array $a
+ * @param array $b
+ * @return int|void
+ */
+ protected function _usort($a, $b)
+ {
+ foreach ($this->_orders as $key => $direction) {
+ $result = $a[$key] > $b[$key] ? 1 : ($a[$key] < $b[$key] ? -1 : 0);
+ return (self::SORT_ORDER_ASC === strtoupper($direction) ? $result : -$result);
+ }
+ }
+
+ /**
+ * Generate item row basing on the filename
+ *
+ * @param string $filename
+ * @return array
+ */
+ protected function _generateRow($filename)
+ {
+ return [
+ 'filename' => $filename,
+ 'basename' => basename($filename),
+ ];
+ }
+
+ /**
+ * The filters renderer and caller
+ * Aplies to each row, renders once.
+ *
+ * @param array $row
+ * @return bool
+ */
+ protected function _filterRow($row)
+ {
+ // render filters once
+ if (!$this->_isFiltersRendered) {
+ $eval = '';
+ for ($i = 0; $i < $this->_filterIncrement; $i++) {
+ if (isset($this->_filterBrackets[$i])) {
+ $eval .= $this->_renderConditionBeforeFilterElement($i, $this->_filterBrackets[$i]['is_and'])
+ . $this->_filterBrackets[$i]['value'];
+ } else {
+ $f = '$this->_filters[' . $i . ']';
+ $eval .= $this->_renderConditionBeforeFilterElement($i, $this->_filters[$i]['is_and'])
+ . ($this->_filters[$i]['is_inverted'] ? '!' : '')
+ . '$this->_invokeFilter(' . "{$f}['callback'], array({$f}['field'], {$f}['value'], " . '$row))';
+ }
+ }
+ $this->_filterEvalRendered = $eval;
+ $this->_isFiltersRendered = true;
+ }
+ $result = false;
+ if ($this->_filterEvalRendered) {
+ eval('$result = ' . $this->_filterEvalRendered . ';');
+ }
+ return $result;
+ }
+
+ /**
+ * Invokes specified callback
+ * Skips, if there is no filtered key in the row
+ *
+ * @param callback $callback
+ * @param array $callbackParams
+ * @return bool
+ */
+ protected function _invokeFilter($callback, $callbackParams)
+ {
+ list($field, $value, $row) = $callbackParams;
+ if (!array_key_exists($field, $row)) {
+ return false;
+ }
+ return call_user_func_array($callback, $callbackParams);
+ }
+
+ /**
+ * Prepare a bracket into filters
+ *
+ * @param string $bracket
+ * @param bool $isAnd
+ * @return $this
+ */
+ protected function _addFilterBracket($bracket = '(', $isAnd = true)
+ {
+ $this->_filterBrackets[$this->_filterIncrement] = [
+ 'value' => $bracket === ')' ? ')' : '(',
+ 'is_and' => $isAnd,
+ ];
+ $this->_filterIncrement++;
+ return $this;
+ }
+
+ /**
+ * Render condition sign before element, if required
+ *
+ * @param int $increment
+ * @param bool $isAnd
+ * @return string
+ */
+ protected function _renderConditionBeforeFilterElement($increment, $isAnd)
+ {
+ if (isset($this->_filterBrackets[$increment]) && ')' === $this->_filterBrackets[$increment]['value']) {
+ return '';
+ }
+ $prevIncrement = $increment - 1;
+ $prevBracket = false;
+ if (isset($this->_filterBrackets[$prevIncrement])) {
+ $prevBracket = $this->_filterBrackets[$prevIncrement]['value'];
+ }
+ if ($prevIncrement < 0 || $prevBracket === '(') {
+ return '';
+ }
+ return ($isAnd ? ' && ' : ' || ');
+ }
+
+ /**
+ * With specified collected items:
+ * - generate data
+ * - apply filters
+ * - sort
+ *
+ * @param string $attributeName '_collectedFiles' | '_collectedDirs'
+ */
+ private function _generateAndFilterAndSort($attributeName)
+ {
+ // generate custom data (as rows with columns) basing on the filenames
+ foreach ($this->$attributeName as $key => $filename) {
+ $this->{$attributeName}[$key] = $this->_generateRow($filename);
+ }
+
+ // apply filters on generated data
+ if (!empty($this->_filters)) {
+ foreach ($this->$attributeName as $key => $row) {
+ if (!$this->_filterRow($row)) {
+ unset($this->{$attributeName}[$key]);
+ }
+ }
+ }
+
+ // sort (keys are lost!)
+ if (!empty($this->_orders)) {
+ usort($this->$attributeName, [$this, '_usort']);
+ }
+ }
}
diff --git a/lib/Varien/Data/Form.php b/lib/Varien/Data/Form.php
index 52fc4fd6aa2..092c5071bf5 100644
--- a/lib/Varien/Data/Form.php
+++ b/lib/Varien/Data/Form.php
@@ -119,17 +119,6 @@ public function addElement(Varien_Data_Form_Element_Abstract $element, $after =
return $this;
}
- /**
- * Check existing element
- *
- * @param string $elementId
- * @return bool
- */
- protected function _elementIdExists($elementId)
- {
- return isset($this->_elementsIndex[$elementId]);
- }
-
/**
* @param Varien_Data_Form_Element_Abstract $element
* @return $this
@@ -309,4 +298,15 @@ public function getHtml()
{
return $this->toHtml();
}
+
+ /**
+ * Check existing element
+ *
+ * @param string $elementId
+ * @return bool
+ */
+ protected function _elementIdExists($elementId)
+ {
+ return isset($this->_elementsIndex[$elementId]);
+ }
}
diff --git a/lib/Varien/Data/Form/Abstract.php b/lib/Varien/Data/Form/Abstract.php
index 0e1243eb59d..8c2697fa51a 100644
--- a/lib/Varien/Data/Form/Abstract.php
+++ b/lib/Varien/Data/Form/Abstract.php
@@ -54,6 +54,20 @@ public function __construct($attributes = [])
parent::__construct($attributes);
}
+ /**
+ * @return array
+ */
+ public function __toArray(array $arrAttributes = [])
+ {
+ $res = [];
+ $res['config'] = $this->getData();
+ $res['formElements'] = [];
+ foreach ($this->getElements() as $element) {
+ $res['formElements'][] = $element->toArray();
+ }
+ return $res;
+ }
+
/**
* @param string $type
* @param string $className
@@ -181,18 +195,4 @@ public function addColumn($elementId, $config)
$this->addElement($element);
return $element;
}
-
- /**
- * @return array
- */
- public function __toArray(array $arrAttributes = [])
- {
- $res = [];
- $res['config'] = $this->getData();
- $res['formElements'] = [];
- foreach ($this->getElements() as $element) {
- $res['formElements'][] = $element->toArray();
- }
- return $res;
- }
}
diff --git a/lib/Varien/Data/Form/Element/Abstract.php b/lib/Varien/Data/Form/Element/Abstract.php
index 8c8bc0fa05f..79687648eb5 100644
--- a/lib/Varien/Data/Form/Element/Abstract.php
+++ b/lib/Varien/Data/Form/Element/Abstract.php
@@ -196,15 +196,6 @@ public function removeClass($class)
return $this;
}
- /**
- * @param string $string
- * @return string
- */
- protected function _escape($string)
- {
- return htmlspecialchars((string) $string, ENT_COMPAT);
- }
-
/**
* @param string|null $index
* @return string
@@ -382,4 +373,13 @@ public function addElementValues($values, $overwrite = false)
return $this;
}
+
+ /**
+ * @param string $string
+ * @return string
+ */
+ protected function _escape($string)
+ {
+ return htmlspecialchars((string) $string, ENT_COMPAT);
+ }
}
diff --git a/lib/Varien/Data/Form/Element/Checkboxes.php b/lib/Varien/Data/Form/Element/Checkboxes.php
index 722f0ae836a..a9e9b8a4f98 100644
--- a/lib/Varien/Data/Form/Element/Checkboxes.php
+++ b/lib/Varien/Data/Form/Element/Checkboxes.php
@@ -46,45 +46,6 @@ public function getHtmlAttributes()
return ['type', 'name', 'class', 'style', 'checked', 'onclick', 'onchange', 'disabled'];
}
- /**
- * Prepare value list
- *
- * @return array
- */
- protected function _prepareValues()
- {
- $options = [];
- $values = [];
-
- if ($this->getValues()) {
- if (!is_array($this->getValues())) {
- $options = [$this->getValues()];
- } else {
- $options = $this->getValues();
- }
- } elseif ($this->getOptions() && is_array($this->getOptions())) {
- $options = $this->getOptions();
- }
- foreach ($options as $k => $v) {
- if (is_string($v)) {
- $values[] = [
- 'label' => $v,
- 'value' => $k,
- ];
- } elseif (isset($v['value'])) {
- if (!isset($v['label'])) {
- $v['label'] = $v['value'];
- }
- $values[] = [
- 'label' => $v['label'],
- 'value' => $v['value'],
- ];
- }
- }
-
- return $values;
- }
-
/**
* Retrieve HTML
*
@@ -176,6 +137,45 @@ public function getOnchange($value)
return;
}
+ /**
+ * Prepare value list
+ *
+ * @return array
+ */
+ protected function _prepareValues()
+ {
+ $options = [];
+ $values = [];
+
+ if ($this->getValues()) {
+ if (!is_array($this->getValues())) {
+ $options = [$this->getValues()];
+ } else {
+ $options = $this->getValues();
+ }
+ } elseif ($this->getOptions() && is_array($this->getOptions())) {
+ $options = $this->getOptions();
+ }
+ foreach ($options as $k => $v) {
+ if (is_string($v)) {
+ $values[] = [
+ 'label' => $v,
+ 'value' => $k,
+ ];
+ } elseif (isset($v['value'])) {
+ if (!isset($v['label'])) {
+ $v['label'] = $v['value'];
+ }
+ $values[] = [
+ 'label' => $v['label'],
+ 'value' => $v['value'],
+ ];
+ }
+ }
+
+ return $values;
+ }
+
// public function getName($value)
// {
// if ($name = $this->getData('name')) {
diff --git a/lib/Varien/Data/Form/Element/Date.php b/lib/Varien/Data/Form/Element/Date.php
index b1a35f88169..f5f1a2e5681 100644
--- a/lib/Varien/Data/Form/Element/Date.php
+++ b/lib/Varien/Data/Form/Element/Date.php
@@ -48,23 +48,6 @@ public function __construct($attributes = [])
}
}
- /**
- * If script executes on x64 system, converts large
- * numeric values to timestamp limit
- *
- * @param string $value
- * @return int
- */
- protected function _toTimestamp($value)
- {
- $value = (int) $value;
- if ($value > 3155760000) {
- $value = 0;
- }
-
- return $value;
- }
-
/**
* Set date value
* If Zend_Date instance is provided instead of value, other params will be ignored.
@@ -194,4 +177,21 @@ public function getElementHtml()
return $html . $this->getAfterElementHtml();
}
+
+ /**
+ * If script executes on x64 system, converts large
+ * numeric values to timestamp limit
+ *
+ * @param string $value
+ * @return int
+ */
+ protected function _toTimestamp($value)
+ {
+ $value = (int) $value;
+ if ($value > 3155760000) {
+ $value = 0;
+ }
+
+ return $value;
+ }
}
diff --git a/lib/Varien/Data/Form/Element/Editor.php b/lib/Varien/Data/Form/Element/Editor.php
index 23415889c5f..7a71f3664e1 100644
--- a/lib/Varien/Data/Form/Element/Editor.php
+++ b/lib/Varien/Data/Form/Element/Editor.php
@@ -144,6 +144,66 @@ public function getTheme()
return $this->_getData('theme');
}
+ /**
+ * Editor config retriever
+ *
+ * @param string $key Config var key
+ * @return mixed
+ */
+ public function getConfig($key = null)
+ {
+ if (!($this->_getData('config') instanceof Varien_Object)) {
+ $config = new Varien_Object();
+ $this->setConfig($config);
+ }
+ if ($key !== null) {
+ return $this->_getData('config')->getData($key);
+ }
+ return $this->_getData('config');
+ }
+
+ /**
+ * Translate string using defined helper
+ *
+ * @param string $string String to be translated
+ * @return string
+ */
+ public function translate($string)
+ {
+ $translator = $this->getConfig('translator');
+ if ($translator && method_exists($translator, '__')) {
+ $result = $translator->__($string);
+ if (is_string($result)) {
+ return $result;
+ }
+ }
+
+ return $string;
+ }
+
+ /**
+ * Check whether Wysiwyg is enabled or not
+ *
+ * @return bool
+ */
+ public function isEnabled()
+ {
+ if ($this->hasData('wysiwyg')) {
+ return $this->getWysiwyg();
+ }
+ return $this->getConfig('enabled');
+ }
+
+ /**
+ * Check whether Wysiwyg is loaded on demand or not
+ *
+ * @return bool
+ */
+ public function isHidden()
+ {
+ return $this->getConfig('hidden');
+ }
+
/**
* Return Editor top Buttons HTML
*
@@ -324,64 +384,4 @@ protected function _wrapIntoContainer($html)
. $html
. '';
}
-
- /**
- * Editor config retriever
- *
- * @param string $key Config var key
- * @return mixed
- */
- public function getConfig($key = null)
- {
- if (!($this->_getData('config') instanceof Varien_Object)) {
- $config = new Varien_Object();
- $this->setConfig($config);
- }
- if ($key !== null) {
- return $this->_getData('config')->getData($key);
- }
- return $this->_getData('config');
- }
-
- /**
- * Translate string using defined helper
- *
- * @param string $string String to be translated
- * @return string
- */
- public function translate($string)
- {
- $translator = $this->getConfig('translator');
- if ($translator && method_exists($translator, '__')) {
- $result = $translator->__($string);
- if (is_string($result)) {
- return $result;
- }
- }
-
- return $string;
- }
-
- /**
- * Check whether Wysiwyg is enabled or not
- *
- * @return bool
- */
- public function isEnabled()
- {
- if ($this->hasData('wysiwyg')) {
- return $this->getWysiwyg();
- }
- return $this->getConfig('enabled');
- }
-
- /**
- * Check whether Wysiwyg is loaded on demand or not
- *
- * @return bool
- */
- public function isHidden()
- {
- return $this->getConfig('hidden');
- }
}
diff --git a/lib/Varien/Data/Form/Element/Image.php b/lib/Varien/Data/Form/Element/Image.php
index 7407144d215..e726a0b5a8b 100644
--- a/lib/Varien/Data/Form/Element/Image.php
+++ b/lib/Varien/Data/Form/Element/Image.php
@@ -63,6 +63,16 @@ public function getElementHtml()
return $html . $this->_getDeleteCheckbox();
}
+ /**
+ * Return name
+ *
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->getData('name');
+ }
+
/**
* Return html code of delete checkbox element
*
@@ -106,14 +116,4 @@ protected function _getUrl()
{
return $this->getValue();
}
-
- /**
- * Return name
- *
- * @return string
- */
- public function getName()
- {
- return $this->getData('name');
- }
}
diff --git a/lib/Varien/Data/Form/Element/Select.php b/lib/Varien/Data/Form/Element/Select.php
index b54264ceca8..73e6e24c4b5 100644
--- a/lib/Varien/Data/Form/Element/Select.php
+++ b/lib/Varien/Data/Form/Element/Select.php
@@ -75,6 +75,14 @@ public function getElementHtml()
return $html . $this->getAfterElementHtml();
}
+ /**
+ * @return array
+ */
+ public function getHtmlAttributes()
+ {
+ return ['title', 'class', 'style', 'onclick', 'onchange', 'disabled', 'readonly', 'tabindex'];
+ }
+
/**
* @param array $option
* @param string|array $selected
@@ -116,12 +124,4 @@ protected function _prepareOptions()
$this->setValues($values);
}
}
-
- /**
- * @return array
- */
- public function getHtmlAttributes()
- {
- return ['title', 'class', 'style', 'onclick', 'onchange', 'disabled', 'readonly', 'tabindex'];
- }
}
diff --git a/lib/Varien/Data/Tree/Db.php b/lib/Varien/Data/Tree/Db.php
index a28cf2dac4b..2ba43ae3092 100644
--- a/lib/Varien/Data/Tree/Db.php
+++ b/lib/Varien/Data/Tree/Db.php
@@ -244,6 +244,35 @@ public function moveNodeTo($node, $parentNode, $prevNode = null)
}
}
+ /**
+ * @param Varien_Data_Tree_Node $node
+ * @return $this|Varien_Data_Tree
+ * @throws Exception
+ */
+ public function removeNode($node)
+ {
+ // For reorder old node branch
+ $dataReorderOld = [
+ $this->_orderField => new Zend_Db_Expr($this->_conn->quoteIdentifier($this->_orderField) . '-1'),
+ ];
+ $conditionReorderOld = $this->_conn->quoteIdentifier($this->_parentField) . '=' . $node->getData($this->_parentField) .
+ ' AND ' . $this->_conn->quoteIdentifier($this->_orderField) . '>' . $node->getData($this->_orderField);
+
+ $this->_conn->beginTransaction();
+ try {
+ $condition = $this->_conn->quoteInto("$this->_idField=?", $node->getId());
+ $this->_conn->delete($this->_table, $condition);
+ // Update old node branch
+ $this->_conn->update($this->_table, $dataReorderOld, $conditionReorderOld);
+ $this->_conn->commit();
+ } catch (Exception $e) {
+ $this->_conn->rollBack();
+ throw new Exception('Can\'t remove tree node');
+ }
+ parent::removeNode($node);
+ return $this;
+ }
+
/**
* @param int $parentId
* @param int $parentLevel
@@ -289,33 +318,4 @@ protected function _loadFullTree()
return $this;
}
-
- /**
- * @param Varien_Data_Tree_Node $node
- * @return $this|Varien_Data_Tree
- * @throws Exception
- */
- public function removeNode($node)
- {
- // For reorder old node branch
- $dataReorderOld = [
- $this->_orderField => new Zend_Db_Expr($this->_conn->quoteIdentifier($this->_orderField) . '-1'),
- ];
- $conditionReorderOld = $this->_conn->quoteIdentifier($this->_parentField) . '=' . $node->getData($this->_parentField) .
- ' AND ' . $this->_conn->quoteIdentifier($this->_orderField) . '>' . $node->getData($this->_orderField);
-
- $this->_conn->beginTransaction();
- try {
- $condition = $this->_conn->quoteInto("$this->_idField=?", $node->getId());
- $this->_conn->delete($this->_table, $condition);
- // Update old node branch
- $this->_conn->update($this->_table, $dataReorderOld, $conditionReorderOld);
- $this->_conn->commit();
- } catch (Exception $e) {
- $this->_conn->rollBack();
- throw new Exception('Can\'t remove tree node');
- }
- parent::removeNode($node);
- return $this;
- }
}
diff --git a/lib/Varien/Date.php b/lib/Varien/Date.php
index 4bd4378304e..30b58aae1c1 100644
--- a/lib/Varien/Date.php
+++ b/lib/Varien/Date.php
@@ -88,21 +88,6 @@ public static function convertZendToStrftime($value, $convertDate = true, $conve
}
return $value;
}
-
- /**
- * Convert value by dictionary
- *
- * @param string $value
- * @param array $dictionary
- * @return string
- */
- protected static function _convert($value, $dictionary)
- {
- foreach ($dictionary as $search => $replace) {
- $value = preg_replace('/(^|[^%])' . $search . '/', '$1' . $replace, $value);
- }
- return $value;
- }
/**
* Convert date to UNIX timestamp
* Returns current UNIX timestamp if date is true
@@ -167,4 +152,19 @@ public static function formatDate($date, $includeTime = true)
$format = $includeTime ? self::DATETIME_PHP_FORMAT : self::DATE_PHP_FORMAT;
return date($format, $date);
}
+
+ /**
+ * Convert value by dictionary
+ *
+ * @param string $value
+ * @param array $dictionary
+ * @return string
+ */
+ protected static function _convert($value, $dictionary)
+ {
+ foreach ($dictionary as $search => $replace) {
+ $value = preg_replace('/(^|[^%])' . $search . '/', '$1' . $replace, $value);
+ }
+ return $value;
+ }
}
diff --git a/lib/Varien/Db/Adapter/Mysqli.php b/lib/Varien/Db/Adapter/Mysqli.php
index 3cf02e2515a..a839340ccfa 100644
--- a/lib/Varien/Db/Adapter/Mysqli.php
+++ b/lib/Varien/Db/Adapter/Mysqli.php
@@ -19,61 +19,6 @@ class Varien_Db_Adapter_Mysqli extends Zend_Db_Adapter_Mysqli
public const ISO_DATE_FORMAT = 'yyyy-MM-dd';
public const ISO_DATETIME_FORMAT = 'yyyy-MM-dd HH-mm-ss';
- /**
- * Creates a real connection to the database with multi-query capability.
- *
- * @return void
- * @throws Zend_Db_Adapter_Mysqli_Exception
- *
- * @SuppressWarnings("PHPMD.ErrorControlOperator")
- */
- protected function _connect()
- {
- if ($this->_connection) {
- return;
- }
- if (!extension_loaded('mysqli')) {
- throw new Zend_Db_Adapter_Exception('mysqli extension is not installed');
- }
- // Suppress connection warnings here.
- // Throw an exception instead.
- @$conn = new mysqli();
- if (mysqli_connect_errno()) {
- throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_errno());
- }
-
- $conn->init();
- $conn->options(MYSQLI_OPT_LOCAL_INFILE, true);
- #$conn->options(MYSQLI_CLIENT_MULTI_QUERIES, true);
-
- $port = !empty($this->_config['port']) ? $this->_config['port'] : null;
- $socket = !empty($this->_config['unix_socket']) ? $this->_config['unix_socket'] : null;
- // socket specified in host config
- if (strpos($this->_config['host'], '/') !== false) {
- $socket = $this->_config['host'];
- $this->_config['host'] = null;
- } elseif (strpos($this->_config['host'], ':') !== false) {
- list($this->_config['host'], $port) = explode(':', $this->_config['host']);
- }
-
- $connectionSuccessful = @$conn->real_connect(
- $this->_config['host'],
- $this->_config['username'],
- $this->_config['password'],
- $this->_config['dbname'],
- $port,
- $socket,
- );
- if (!$connectionSuccessful) {
- throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_error());
- }
-
- $this->_connection = $conn;
-
- /** @link http://bugs.mysql.com/bug.php?id=18551 */
- $this->_connection->query("SET SQL_MODE=''");
- }
-
/**
* Run RAW Query
*
@@ -281,4 +226,59 @@ public function select()
{
return new Varien_Db_Select($this);
}
+
+ /**
+ * Creates a real connection to the database with multi-query capability.
+ *
+ * @return void
+ * @throws Zend_Db_Adapter_Mysqli_Exception
+ *
+ * @SuppressWarnings("PHPMD.ErrorControlOperator")
+ */
+ protected function _connect()
+ {
+ if ($this->_connection) {
+ return;
+ }
+ if (!extension_loaded('mysqli')) {
+ throw new Zend_Db_Adapter_Exception('mysqli extension is not installed');
+ }
+ // Suppress connection warnings here.
+ // Throw an exception instead.
+ @$conn = new mysqli();
+ if (mysqli_connect_errno()) {
+ throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_errno());
+ }
+
+ $conn->init();
+ $conn->options(MYSQLI_OPT_LOCAL_INFILE, true);
+ #$conn->options(MYSQLI_CLIENT_MULTI_QUERIES, true);
+
+ $port = !empty($this->_config['port']) ? $this->_config['port'] : null;
+ $socket = !empty($this->_config['unix_socket']) ? $this->_config['unix_socket'] : null;
+ // socket specified in host config
+ if (strpos($this->_config['host'], '/') !== false) {
+ $socket = $this->_config['host'];
+ $this->_config['host'] = null;
+ } elseif (strpos($this->_config['host'], ':') !== false) {
+ list($this->_config['host'], $port) = explode(':', $this->_config['host']);
+ }
+
+ $connectionSuccessful = @$conn->real_connect(
+ $this->_config['host'],
+ $this->_config['username'],
+ $this->_config['password'],
+ $this->_config['dbname'],
+ $port,
+ $socket,
+ );
+ if (!$connectionSuccessful) {
+ throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_error());
+ }
+
+ $this->_connection = $conn;
+
+ /** @link http://bugs.mysql.com/bug.php?id=18551 */
+ $this->_connection->query("SET SQL_MODE=''");
+ }
}
diff --git a/lib/Varien/Db/Adapter/Pdo/Mysql.php b/lib/Varien/Db/Adapter/Pdo/Mysql.php
index 01bbad0d727..c96d2759341 100644
--- a/lib/Varien/Db/Adapter/Pdo/Mysql.php
+++ b/lib/Varien/Db/Adapter/Pdo/Mysql.php
@@ -212,6 +212,16 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
*/
protected $_queryHook = null;
+ /**
+ * Check if all transactions have been committed
+ */
+ public function __destruct()
+ {
+ if ($this->_transactionLevel > 0) {
+ trigger_error('Some transactions have not been committed or rolled back', E_USER_ERROR);
+ }
+ }
+
/**
* Begin new DB transaction for connection
*
@@ -296,97 +306,6 @@ public function convertDateTime($datetime)
return $this->formatDate($datetime);
}
- /**
- * Parse a source hostname and generate a host info
- * @param $hostName
- *
- * @return Varien_Object
- */
- protected function _getHostInfo($hostName)
- {
- $hostInfo = new Varien_Object();
- $matches = [];
- if (str_contains($hostName, '/')) {
- $hostInfo->setAddressType(self::ADDRESS_TYPE_UNIX_SOCKET)
- ->setUnixSocket($hostName);
- } elseif (preg_match('/^\[(([0-9a-f]{1,4})?(:([0-9a-f]{1,4})?){1,}:([0-9a-f]{1,4}))(%[0-9a-z]+)?\](:([0-9]+))?$/i', $hostName, $matches)) {
- $hostName = $matches[1];
- $hostName .= $matches[6] ?? '';
- $hostInfo->setAddressType(self::ADDRESS_TYPE_IPV6_ADDRESS)
- ->setHostName($hostName)
- ->setPort($matches[8] ?? null);
- } elseif (preg_match('/^(([0-9a-f]{1,4})?(:([0-9a-f]{1,4})?){1,}:([0-9a-f]{1,4}))(%[0-9a-z]+)?$/i', $hostName, $matches)) {
- $hostName = $matches[1];
- $hostName .= $matches[6] ?? '';
- $hostInfo->setAddressType(self::ADDRESS_TYPE_IPV6_ADDRESS)
- ->setHostName($hostName);
- } elseif (str_contains($hostName, ':')) {
- list($hostAddress, $hostPort) = explode(':', $hostName);
- $hostInfo->setAddressType(
- filter_var($hostAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
- ? self::ADDRESS_TYPE_IPV4_ADDRESS
- : self::ADDRESS_TYPE_HOSTNAME,
- )->setHostName($hostAddress)
- ->setPort($hostPort);
- } else {
- $hostInfo->setAddressType(
- filter_var($hostName, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
- ? self::ADDRESS_TYPE_IPV4_ADDRESS
- : self::ADDRESS_TYPE_HOSTNAME,
- )->setHostName($hostName);
- }
-
- return $hostInfo;
- }
-
- /**
- * Creates a PDO object and connects to the database.
- *
- * @throws Zend_Db_Adapter_Exception
- */
- protected function _connect()
- {
- if ($this->_connection) {
- return;
- }
-
- if (!extension_loaded('pdo_mysql')) {
- throw new Zend_Db_Adapter_Exception('pdo_mysql extension is not installed');
- }
-
- $hostInfo = $this->_getHostInfo($this->_config['host'] ?? $this->_config['unix_socket'] ?? null);
-
- switch ($hostInfo->getAddressType()) {
- case self::ADDRESS_TYPE_UNIX_SOCKET:
- $this->_config['unix_socket'] = $hostInfo->getUnixSocket();
- unset($this->_config['host']);
- break;
- case self::ADDRESS_TYPE_IPV6_ADDRESS: // break intentionally omitted
- case self::ADDRESS_TYPE_IPV4_ADDRESS: // break intentionally omitted
- case self::ADDRESS_TYPE_HOSTNAME:
- $this->_config['host'] = $hostInfo->getHostName();
- if ($hostInfo->getPort()) {
- $this->_config['port'] = $hostInfo->getPort();
- }
- break;
- default:
- break;
- }
-
- $this->_debugTimer();
- parent::_connect();
- $this->_debugStat(self::DEBUG_CONNECT, '');
-
- /** @link http://bugs.mysql.com/bug.php?id=18551 */
- $this->_connection->query("SET SQL_MODE=''");
-
- if (!$this->_connectionFlagsSet) {
- $this->_connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
- $this->_connection->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
- $this->_connectionFlagsSet = true;
- }
- }
-
/**
* Run RAW Query
*
@@ -451,24 +370,6 @@ public function raw_fetchRow($sql, $field = null)
}
}
- /**
- * Check transaction level in case of DDL query
- *
- * @param string|Zend_Db_Select $sql
- * @throws Zend_Db_Adapter_Exception
- */
- protected function _checkDdlTransaction($sql)
- {
- if (is_string($sql) && $this->getTransactionLevel() > 0) {
- $startSql = strtolower(substr(ltrim($sql), 0, 3));
- if (in_array($startSql, $this->_ddlRoutines)
- && (preg_match($this->_tempRoutines, $sql) !== 1)
- ) {
- trigger_error(Varien_Db_Adapter_Interface::ERROR_DDL_MESSAGE, E_USER_ERROR);
- }
- }
- }
-
/**
* Special handling for PDO query().
* All bind parameter names must begin with ':'.
@@ -506,47 +407,6 @@ public function query($sql, $bind = [])
return $result;
}
- /**
- * Prepares SQL query by moving to bind all special parameters that can be confused with bind placeholders
- * (e.g. "foo:bar"). And also changes named bind to positional one, because underlying library has problems
- * with named binds.
- *
- * @param Zend_Db_Select|string $sql
- * @param-out string $sql
- * @param mixed $bind
- * @return $this
- */
- protected function _prepareQuery(&$sql, &$bind = [])
- {
- $sql = (string) $sql;
- if (!is_array($bind)) {
- $bind = [$bind];
- }
-
- // Mixed bind is not supported - so remember whether it is named bind, to normalize later if required
- $isNamedBind = false;
- if ($bind) {
- foreach ($bind as $k => $v) {
- if (!is_int($k)) {
- $isNamedBind = true;
- if ($k[0] != ':') {
- $bind[":{$k}"] = $v;
- unset($bind[$k]);
- }
- }
- }
- }
-
- // Special query hook
- if ($this->_queryHook) {
- $object = $this->_queryHook['object'];
- $method = $this->_queryHook['method'];
- $object->$method($sql, $bind);
- }
-
- return $this;
- }
-
/**
* Callback function for preparation of query and bind by regexp.
* Checks query parameters for special symbols and moves such parameters to bind array as named ones.
@@ -572,80 +432,6 @@ public function proccessBindCallback($matches)
return $matches[0];
}
- /**
- * Unquote raw string (use for auto-bind)
- *
- * @param string $string
- * @return string
- */
- protected function _unQuote($string)
- {
- $translate = [
- '\\000' => "\000",
- '\\n' => "\n",
- '\\r' => "\r",
- '\\\\' => '\\',
- "\'" => "'",
- '\\"' => '"',
- '\\032' => "\032",
- ];
- return strtr($string, $translate);
- }
-
- /**
- * Normalizes mixed positional-named bind to positional bind, and replaces named placeholders in query to
- * '?' placeholders.
- *
- * @param string $sql
- * @param array $bind
- * @return $this
- */
- protected function _convertMixedBind(&$sql, &$bind)
- {
- $positions = [];
- $offset = 0;
- // get positions
- while (true) {
- $pos = strpos($sql, '?', $offset);
- if ($pos !== false) {
- $positions[] = $pos;
- $offset = ++$pos;
- } else {
- break;
- }
- }
-
- $bindResult = [];
- $map = [];
- foreach ($bind as $k => $v) {
- // positional
- if (is_int($k)) {
- if (!isset($positions[$k])) {
- continue;
- }
- $bindResult[$positions[$k]] = $v;
- } else {
- $offset = 0;
- while (true) {
- $pos = strpos($sql, $k, $offset);
- if ($pos === false) {
- break;
- } else {
- $offset = $pos + strlen($k);
- $bindResult[$pos] = $v;
- }
- }
- $map[$k] = '?';
- }
- }
-
- ksort($bindResult);
- $bind = array_values($bindResult);
- $sql = strtr($sql, $map);
-
- return $this;
- }
-
/**
* Sets (removes) query hook.
*
@@ -704,75 +490,14 @@ public function multi_query($sql)
}
/**
- * Split multi statement query
+ * Drop the Foreign Key from table
*
- * @param string $sql
- * @return array
+ * @param string $tableName
+ * @param string $fkName
+ * @param string $schemaName
+ * @return $this
*/
- protected function _splitMultiQuery($sql)
- {
- $parts = preg_split(
- '#(;|\'|"|\\\\|//|--|\n|/\*|\*/)#',
- $sql,
- -1,
- PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE,
- );
-
- $q = false;
- $c = false;
- $stmts = [];
- $s = '';
-
- foreach ($parts as $i => $part) {
- // strings
- if (($part === "'" || $part === '"') && ($i === 0 || $parts[$i - 1] !== '\\')) {
- if ($q === false) {
- $q = $part;
- } elseif ($q === $part) {
- $q = false;
- }
- }
-
- // single line comments
- if (($part === '//' || $part === '--') && ($i === 0 || $parts[$i - 1] === "\n")) {
- $c = $part;
- } elseif ($part === "\n" && ($c === '//' || $c === '--')) {
- $c = false;
- }
-
- // multi line comments
- if ($part === '/*' && $c === false) {
- $c = '/*';
- } elseif ($part === '*/' && $c === '/*') {
- $c = false;
- }
-
- // statements
- if ($part === ';' && $q === false && $c === false) {
- if (trim($s) !== '') {
- $stmts[] = trim($s);
- $s = '';
- }
- } else {
- $s .= $part;
- }
- }
- if (trim($s) !== '') {
- $stmts[] = trim($s);
- }
-
- return $stmts;
- }
-
- /**
- * Drop the Foreign Key from table
- *
- * @param string $tableName
- * @param string $fkName
- * @param string $schemaName
- * @return $this
- */
- public function dropForeignKey($tableName, $fkName, $schemaName = null)
+ public function dropForeignKey($tableName, $fkName, $schemaName = null)
{
$foreignKeys = $this->getForeignKeys($tableName, $schemaName);
$fkName = strtoupper($fkName);
@@ -1370,42 +1095,6 @@ public function addKey($tableName, $indexName, $fields, $indexType = 'index', $s
return $this->addIndex($tableName, $indexName, $fields, $indexType, $schemaName);
}
- /**
- * Remove duplicate entry for create key
- *
- * @param string $table
- * @param array $fields
- * @param array $ids
- * @return $this
- */
- protected function _removeDuplicateEntry($table, $fields, $ids)
- {
- $where = [];
- $i = 0;
- foreach ($fields as $field) {
- $where[] = $this->quoteInto($field . '=?', $ids[$i++]);
- }
-
- if (!$where) {
- return $this;
- }
- $whereCond = implode(' AND ', $where);
- $sql = sprintf('SELECT COUNT(*) as `cnt` FROM `%s` WHERE %s', $table, $whereCond);
-
- $cnt = $this->raw_fetchRow($sql, 'cnt');
- if ($cnt > 1) {
- $sql = sprintf(
- 'DELETE FROM `%s` WHERE %s LIMIT %d',
- $table,
- $whereCond,
- $cnt - 1,
- );
- $this->raw_query($sql);
- }
-
- return $this;
- }
-
/**
* Creates and returns a new Zend_Db_Select object for this adapter.
*
@@ -1416,114 +1105,6 @@ public function select()
return new Varien_Db_Select($this);
}
- /**
- * Start debug timer
- *
- * @return $this
- */
- protected function _debugTimer()
- {
- if ($this->_debug) {
- $this->_debugTimer = microtime(true);
- }
-
- return $this;
- }
-
- /**
- * Logging debug information
- *
- * @param int $type
- * @param string $sql
- * @param array $bind
- * @param Zend_Db_Statement_Pdo $result
- * @return $this
- */
- protected function _debugStat($type, $sql, $bind = [], $result = null)
- {
- if (!$this->_debug) {
- return $this;
- }
-
- $code = '## ' . getmypid() . ' ## ';
- $nl = "\n";
- $time = sprintf('%.4f', microtime(true) - $this->_debugTimer);
-
- if (!$this->_logAllQueries && $time < $this->_logQueryTime) {
- return $this;
- }
- switch ($type) {
- case self::DEBUG_CONNECT:
- $code .= 'CONNECT' . $nl;
- break;
- case self::DEBUG_TRANSACTION:
- $code .= 'TRANSACTION ' . $sql . $nl;
- break;
- case self::DEBUG_QUERY:
- $code .= 'QUERY' . $nl;
- $code .= 'SQL: ' . $sql . $nl;
- if ($bind) {
- $code .= 'BIND: ' . var_export($bind, true) . $nl;
- }
- if ($result instanceof Zend_Db_Statement_Pdo) {
- $code .= 'AFF: ' . $result->rowCount() . $nl;
- }
- break;
- }
- $code .= 'TIME: ' . $time . $nl;
-
- if ($this->_logCallStack) {
- $code .= 'TRACE: ' . Varien_Debug::backtrace(true, false) . $nl;
- }
-
- $code .= $nl;
-
- $this->_debugWriteToFile($code);
-
- return $this;
- }
-
- /**
- * Write exception and throw
- *
- * @throws Exception
- */
- protected function _debugException(Exception $e)
- {
- if (!$this->_debug) {
- throw $e;
- }
-
- $nl = "\n";
- $code = 'EXCEPTION ' . $nl . $e . $nl . $nl;
- $this->_debugWriteToFile($code);
-
- throw $e;
- }
-
- /**
- * Debug write to file process
- *
- * @param string $str
- */
- protected function _debugWriteToFile($str)
- {
- $str = '## ' . date(self::TIMESTAMP_FORMAT) . "\r\n" . $str;
- if (!$this->_debugIoAdapter) {
- $this->_debugIoAdapter = new Varien_Io_File();
- $dir = Mage::getBaseDir() . DS . $this->_debugIoAdapter->dirname($this->_debugFile);
- $this->_debugIoAdapter->checkAndCreateFolder($dir);
- $this->_debugIoAdapter->open(['path' => $dir]);
- $this->_debugFile = basename($this->_debugFile);
- }
-
- $this->_debugIoAdapter->streamOpen($this->_debugFile, 'a');
- $this->_debugIoAdapter->streamLock();
- $this->_debugIoAdapter->streamWrite($str);
- $this->_debugIoAdapter->streamUnlock();
- $this->_debugIoAdapter->streamClose();
- }
-
/**
* Quotes a value and places into a piece of text at a placeholder.
*
@@ -1544,29 +1125,6 @@ public function quoteInto($text, $value, $type = null, $count = null)
return parent::quoteInto($text, $value, $type, $count);
}
- /**
- * Retrieve ddl cache name
- *
- * @param string $tableName
- * @param string $schemaName
- */
- protected function _getTableName($tableName, $schemaName = null)
- {
- return ($schemaName ? $schemaName . '.' : '') . $tableName;
- }
-
- /**
- * Retrieve Id for cache
- *
- * @param string $tableKey
- * @param int $ddlType
- * @return string
- */
- protected function _getCacheId($tableKey, $ddlType)
- {
- return sprintf('%s_%s_%s', self::DDL_CACHE_PREFIX, $tableKey, $ddlType);
- }
-
/**
* Load DDL data from cache
* Return false if cache does not exists
@@ -1891,64 +1449,14 @@ public function modifyColumnByDdl($tableName, $columnName, $definition, $flushDa
}
/**
- * Retrieve column data type by data from describe table
+ * Truncate table
*
- * @param array $column
- * @return string|void
+ * @deprecated since 1.4.0.1
+ * @param string $tableName
+ * @param string $schemaName
+ * @return $this
*/
- protected function _getColumnTypeByDdl($column)
- {
- switch ($column['DATA_TYPE']) {
- case 'bool':
- return Varien_Db_Ddl_Table::TYPE_BOOLEAN;
- case 'tinytext':
- case 'char':
- case 'varchar':
- case 'text':
- case 'mediumtext':
- case 'longtext':
- return Varien_Db_Ddl_Table::TYPE_TEXT;
- case 'blob':
- case 'mediumblob':
- case 'longblob':
- return Varien_Db_Ddl_Table::TYPE_BLOB;
- case 'tinyint':
- case 'tinyint unsigned':
- case 'smallint':
- case 'smallint unsigned':
- return Varien_Db_Ddl_Table::TYPE_SMALLINT;
- case 'mediumint':
- case 'int':
- case 'int unsigned':
- return Varien_Db_Ddl_Table::TYPE_INTEGER;
- case 'bigint':
- case 'bigint unsigned':
- return Varien_Db_Ddl_Table::TYPE_BIGINT;
- case 'datetime':
- return Varien_Db_Ddl_Table::TYPE_DATETIME;
- case 'timestamp':
- return Varien_Db_Ddl_Table::TYPE_TIMESTAMP;
- case 'date':
- return Varien_Db_Ddl_Table::TYPE_DATE;
- case 'float':
- return Varien_Db_Ddl_Table::TYPE_FLOAT;
- case 'decimal':
- case 'numeric':
- return Varien_Db_Ddl_Table::TYPE_DECIMAL;
- case 'varbinary':
- return Varien_Db_Ddl_Table::TYPE_VARBINARY;
- }
- }
-
- /**
- * Truncate table
- *
- * @deprecated since 1.4.0.1
- * @param string $tableName
- * @param string $schemaName
- * @return $this
- */
- public function truncate($tableName, $schemaName = null)
+ public function truncate($tableName, $schemaName = null)
{
return $this->truncateTable($tableName, $schemaName);
}
@@ -2288,432 +1796,143 @@ public function createTemporaryTable(Varien_Db_Ddl_Table $table)
}
/**
- * Retrieve columns and primary keys definition array for create table
+ * Get column definition from description
*
- * @return array
- * @throws Zend_Db_Exception
+ * @param array $options
+ * @param null|string $ddlType
+ * @return string
*/
- protected function _getColumnsDefinition(Varien_Db_Ddl_Table $table)
+ public function getColumnDefinitionFromDescribe($options, $ddlType = null)
{
- $definition = [];
- $primary = [];
- $columns = $table->getColumns();
- if (empty($columns)) {
- throw new Zend_Db_Exception('Table columns are not defined');
- }
-
- foreach ($columns as $columnData) {
- $columnDefinition = $this->_getColumnDefinition($columnData);
- if ($columnData['PRIMARY']) {
- $primary[$columnData['COLUMN_NAME']] = $columnData['PRIMARY_POSITION'];
- }
-
- $definition[] = sprintf(
- ' %s %s',
- $this->quoteIdentifier($columnData['COLUMN_NAME']),
- $columnDefinition,
- );
- }
-
- // PRIMARY KEY
- if (!empty($primary)) {
- asort($primary, SORT_NUMERIC);
- $primary = array_map([$this, 'quoteIdentifier'], array_keys($primary));
- $definition[] = sprintf(' PRIMARY KEY (%s)', implode(', ', $primary));
+ $columnInfo = $this->getColumnCreateByDescribe($options);
+ foreach ($columnInfo['options'] as $key => $value) {
+ $columnInfo[$key] = $value;
}
-
- return $definition;
+ return $this->_getColumnDefinition($columnInfo, $ddlType);
}
/**
- * Retrieve table indexes definition array for create table
+ * Drop table from database
*
- * @return array
+ * @param string $tableName
+ * @param string $schemaName
+ * @return boolean
*/
- protected function _getIndexesDefinition(Varien_Db_Ddl_Table $table)
+ public function dropTable($tableName, $schemaName = null)
{
- $definition = [];
- $indexes = $table->getIndexes();
- if (!empty($indexes)) {
- foreach ($indexes as $indexData) {
- if (!empty($indexData['TYPE'])) {
- switch ($indexData['TYPE']) {
- case 'primary':
- $indexType = 'PRIMARY KEY';
- unset($indexData['INDEX_NAME']);
- break;
- default:
- $indexType = strtoupper($indexData['TYPE']);
- break;
- }
- } else {
- $indexType = 'KEY';
- }
-
- $columns = [];
- foreach ($indexData['COLUMNS'] as $columnData) {
- $column = $this->quoteIdentifier($columnData['NAME']);
- if (!empty($columnData['SIZE'])) {
- $column .= sprintf('(%d)', $columnData['SIZE']);
- }
- $columns[] = $column;
- }
- $indexName = isset($indexData['INDEX_NAME']) ? $this->quoteIdentifier($indexData['INDEX_NAME']) : '';
- $definition[] = sprintf(
- ' %s %s (%s)',
- $indexType,
- $indexName,
- implode(', ', $columns),
- );
- }
- }
+ $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
+ $query = 'DROP TABLE IF EXISTS ' . $table;
+ $this->query($query);
- return $definition;
+ return true;
}
/**
- * Retrieve table foreign keys definition array for create table
+ * Drop temporary table from database
*
- * @return array
+ * @param string $tableName
+ * @param string $schemaName
+ * @return $this
*/
- protected function _getForeignKeysDefinition(Varien_Db_Ddl_Table $table)
+ public function dropTemporaryTable($tableName, $schemaName = null)
{
- $definition = [];
- $relations = $table->getForeignKeys();
+ $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
+ $query = 'DROP TEMPORARY TABLE IF EXISTS ' . $table;
+ $this->query($query);
- if (!empty($relations)) {
- foreach ($relations as $fkData) {
- $onDelete = $this->_getDdlAction($fkData['ON_DELETE']);
- $onUpdate = $this->_getDdlAction($fkData['ON_UPDATE']);
+ return $this;
+ }
- $definition[] = sprintf(
- ' CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s) ON DELETE %s ON UPDATE %s',
- $this->quoteIdentifier($fkData['FK_NAME']),
- $this->quoteIdentifier($fkData['COLUMN_NAME']),
- $this->quoteIdentifier($fkData['REF_TABLE_NAME']),
- $this->quoteIdentifier($fkData['REF_COLUMN_NAME']),
- $onDelete,
- $onUpdate,
- );
- }
+ /**
+ * Truncate a table
+ *
+ * @param string $tableName
+ * @param string $schemaName
+ * @return $this
+ * @throws Zend_Db_Exception
+ */
+ public function truncateTable($tableName, $schemaName = null)
+ {
+ if (!$this->isTableExists($tableName, $schemaName)) {
+ throw new Zend_Db_Exception(sprintf('Table "%s" is not exists', $tableName));
}
- return $definition;
+ $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
+ $query = 'TRUNCATE TABLE ' . $table;
+ $this->query($query);
+
+ return $this;
}
/**
- * Retrieve table options definition array for create table
+ * Check is a table exists
*
- * @return array
- * @throws Zend_Db_Exception
+ * @param string $tableName
+ * @param string $schemaName
+ * @return boolean
*/
- protected function _getOptionsDefinition(Varien_Db_Ddl_Table $table)
+ public function isTableExists($tableName, $schemaName = null)
{
- $definition = [];
- $comment = $table->getComment();
- if (empty($comment)) {
- throw new Zend_Db_Exception('Comment for table is required and must be defined');
+ $fromDbName = 'DATABASE()';
+ if ($schemaName !== null) {
+ $fromDbName = $this->quote($schemaName);
}
- $definition[] = $this->quoteInto('COMMENT=?', $comment);
- $tableProps = [
- 'type' => 'ENGINE=%s',
- 'checksum' => 'CHECKSUM=%d',
- 'auto_increment' => 'AUTO_INCREMENT=%d',
- 'avg_row_length' => 'AVG_ROW_LENGTH=%d',
- 'max_rows' => 'MAX_ROWS=%d',
- 'min_rows' => 'MIN_ROWS=%d',
- 'delay_key_write' => 'DELAY_KEY_WRITE=%d',
- 'row_format' => 'row_format=%s',
- 'charset' => 'charset=%s',
- 'collate' => 'COLLATE=%s',
- ];
- foreach ($tableProps as $key => $mask) {
- $v = $table->getOption($key);
- if ($v !== null) {
- $definition[] = sprintf($mask, $v);
- }
+ $sql = sprintf(
+ 'SELECT COUNT(1) AS tbl_exists FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = %s AND TABLE_SCHEMA = %s',
+ $this->quote($tableName),
+ $fromDbName,
+ );
+ $ddl = $this->raw_fetchRow($sql, 'tbl_exists');
+ if ($ddl) {
+ return true;
}
- return $definition;
+ return false;
}
/**
- * Get column definition from description
+ * Rename table
*
- * @param array $options
- * @param null|string $ddlType
- * @return string
+ * @param string $oldTableName
+ * @param string $newTableName
+ * @param string $schemaName
+ * @return boolean
+ * @throws Zend_Db_Exception
*/
- public function getColumnDefinitionFromDescribe($options, $ddlType = null)
+ public function renameTable($oldTableName, $newTableName, $schemaName = null)
{
- $columnInfo = $this->getColumnCreateByDescribe($options);
- foreach ($columnInfo['options'] as $key => $value) {
- $columnInfo[$key] = $value;
+ if (!$this->isTableExists($oldTableName, $schemaName)) {
+ throw new Zend_Db_Exception(sprintf('Table "%s" is not exists', $oldTableName));
}
- return $this->_getColumnDefinition($columnInfo, $ddlType);
+ if ($this->isTableExists($newTableName, $schemaName)) {
+ throw new Zend_Db_Exception(sprintf('Table "%s" already exists', $newTableName));
+ }
+
+ $oldTable = $this->_getTableName($oldTableName, $schemaName);
+ $newTable = $this->_getTableName($newTableName, $schemaName);
+
+ $query = sprintf('ALTER TABLE %s RENAME TO %s', $oldTable, $newTable);
+ $this->query($query);
+
+ $this->resetDdlCache($oldTableName, $schemaName);
+
+ return true;
}
/**
- * Retrieve column definition fragment
+ * Rename several tables
*
- * @param array $options
- * @param string $ddlType Table DDL Column type constant
- * @throws Varien_Exception
- * @return string
+ * @param array $tablePairs array('oldName' => 'Name1', 'newName' => 'Name2')
+ *
+ * @return boolean
* @throws Zend_Db_Exception
*/
- protected function _getColumnDefinition($options, $ddlType = null)
+ public function renameTablesBatch(array $tablePairs)
{
- // convert keys to uppercase
- $options = array_change_key_case($options, CASE_UPPER);
- $cType = null;
- $cUnsigned = false;
- $cNullable = true;
- $cDefault = false;
- $cIdentity = false;
-
- // detect and validate column type
- if ($ddlType === null) {
- $ddlType = $this->_getDdlType($options);
- }
-
- if (empty($ddlType) || !isset($this->_ddlColumnTypes[$ddlType])) {
- throw new Zend_Db_Exception('Invalid column definition data');
- }
-
- // column size
- $cType = $this->_ddlColumnTypes[$ddlType];
- switch ($ddlType) {
- case Varien_Db_Ddl_Table::TYPE_SMALLINT:
- case Varien_Db_Ddl_Table::TYPE_INTEGER:
- case Varien_Db_Ddl_Table::TYPE_BIGINT:
- if (!empty($options['UNSIGNED'])) {
- $cUnsigned = true;
- }
- break;
- case Varien_Db_Ddl_Table::TYPE_DECIMAL:
- case Varien_Db_Ddl_Table::TYPE_NUMERIC:
- $precision = 10;
- $scale = 0;
- $match = [];
- if (!empty($options['LENGTH']) && preg_match('#^\(?(\d+),(\d+)\)?$#', $options['LENGTH'], $match)) {
- $precision = $match[1];
- $scale = $match[2];
- } else {
- if (isset($options['SCALE']) && is_numeric($options['SCALE'])) {
- $scale = $options['SCALE'];
- }
- if (isset($options['PRECISION']) && is_numeric($options['PRECISION'])) {
- $precision = $options['PRECISION'];
- }
- }
- $cType .= sprintf('(%d,%d)', $precision, $scale);
- break;
- case Varien_Db_Ddl_Table::TYPE_TEXT:
- case Varien_Db_Ddl_Table::TYPE_BLOB:
- case Varien_Db_Ddl_Table::TYPE_VARBINARY:
- if (empty($options['LENGTH'])) {
- $length = Varien_Db_Ddl_Table::DEFAULT_TEXT_SIZE;
- } else {
- $length = $this->_parseTextSize($options['LENGTH']);
- }
- if ($length <= 255) {
- $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'varchar' : 'varbinary';
- $cType = sprintf('%s(%d)', $cType, $length);
- } elseif ($length > 255 && $length <= 65536) {
- $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'text' : 'blob';
- } elseif ($length > 65536 && $length <= 16777216) {
- $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'mediumtext' : 'mediumblob';
- } else {
- $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'longtext' : 'longblob';
- }
- break;
- }
-
- if (array_key_exists('DEFAULT', $options)) {
- $cDefault = $options['DEFAULT'];
- }
- if (array_key_exists('NULLABLE', $options)) {
- $cNullable = (bool) $options['NULLABLE'];
- }
- if (!empty($options['IDENTITY']) || !empty($options['AUTO_INCREMENT'])) {
- $cIdentity = true;
- }
-
- /* For cases when tables created from createTableByDdl()
- * where default value can be quoted already.
- * We need to avoid "double-quoting" here
- */
- if ($cDefault !== null && strlen($cDefault)) {
- $cDefault = str_replace("'", '', $cDefault);
- }
-
- // prepare default value string
- if ($ddlType == Varien_Db_Ddl_Table::TYPE_TIMESTAMP) {
- if ($cDefault === null) {
- $cDefault = new Zend_Db_Expr('NULL');
- } elseif ($cDefault == Varien_Db_Ddl_Table::TIMESTAMP_INIT) {
- $cDefault = new Zend_Db_Expr('CURRENT_TIMESTAMP');
- } elseif ($cDefault == Varien_Db_Ddl_Table::TIMESTAMP_UPDATE) {
- $cDefault = new Zend_Db_Expr('0 ON UPDATE CURRENT_TIMESTAMP');
- } elseif ($cDefault == Varien_Db_Ddl_Table::TIMESTAMP_INIT_UPDATE) {
- $cDefault = new Zend_Db_Expr('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
- } elseif ($cNullable && !$cDefault) {
- $cDefault = new Zend_Db_Expr('NULL');
- } else {
- $cDefault = new Zend_Db_Expr('0');
- }
- } elseif (is_null($cDefault) && $cNullable) {
- $cDefault = new Zend_Db_Expr('NULL');
- }
-
- if (empty($options['COMMENT'])) {
- $comment = '';
- } else {
- $comment = $options['COMMENT'];
- }
-
- //set column position
- $after = null;
- if (!empty($options['AFTER'])) {
- $after = $options['AFTER'];
- }
-
- return sprintf(
- '%s%s%s%s%s COMMENT %s %s',
- $cType,
- $cUnsigned ? ' UNSIGNED' : '',
- $cNullable ? ' NULL' : ' NOT NULL',
- $cDefault !== false ? $this->quoteInto(' default ?', $cDefault) : '',
- $cIdentity ? ' auto_increment' : '',
- $this->quote($comment),
- $after ? 'AFTER ' . $this->quoteIdentifier($after) : '',
- );
- }
-
- /**
- * Drop table from database
- *
- * @param string $tableName
- * @param string $schemaName
- * @return boolean
- */
- public function dropTable($tableName, $schemaName = null)
- {
- $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
- $query = 'DROP TABLE IF EXISTS ' . $table;
- $this->query($query);
-
- return true;
- }
-
- /**
- * Drop temporary table from database
- *
- * @param string $tableName
- * @param string $schemaName
- * @return $this
- */
- public function dropTemporaryTable($tableName, $schemaName = null)
- {
- $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
- $query = 'DROP TEMPORARY TABLE IF EXISTS ' . $table;
- $this->query($query);
-
- return $this;
- }
-
- /**
- * Truncate a table
- *
- * @param string $tableName
- * @param string $schemaName
- * @return $this
- * @throws Zend_Db_Exception
- */
- public function truncateTable($tableName, $schemaName = null)
- {
- if (!$this->isTableExists($tableName, $schemaName)) {
- throw new Zend_Db_Exception(sprintf('Table "%s" is not exists', $tableName));
- }
-
- $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
- $query = 'TRUNCATE TABLE ' . $table;
- $this->query($query);
-
- return $this;
- }
-
- /**
- * Check is a table exists
- *
- * @param string $tableName
- * @param string $schemaName
- * @return boolean
- */
- public function isTableExists($tableName, $schemaName = null)
- {
- $fromDbName = 'DATABASE()';
- if ($schemaName !== null) {
- $fromDbName = $this->quote($schemaName);
- }
-
- $sql = sprintf(
- 'SELECT COUNT(1) AS tbl_exists FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = %s AND TABLE_SCHEMA = %s',
- $this->quote($tableName),
- $fromDbName,
- );
- $ddl = $this->raw_fetchRow($sql, 'tbl_exists');
- if ($ddl) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Rename table
- *
- * @param string $oldTableName
- * @param string $newTableName
- * @param string $schemaName
- * @return boolean
- * @throws Zend_Db_Exception
- */
- public function renameTable($oldTableName, $newTableName, $schemaName = null)
- {
- if (!$this->isTableExists($oldTableName, $schemaName)) {
- throw new Zend_Db_Exception(sprintf('Table "%s" is not exists', $oldTableName));
- }
- if ($this->isTableExists($newTableName, $schemaName)) {
- throw new Zend_Db_Exception(sprintf('Table "%s" already exists', $newTableName));
- }
-
- $oldTable = $this->_getTableName($oldTableName, $schemaName);
- $newTable = $this->_getTableName($newTableName, $schemaName);
-
- $query = sprintf('ALTER TABLE %s RENAME TO %s', $oldTable, $newTable);
- $this->query($query);
-
- $this->resetDdlCache($oldTableName, $schemaName);
-
- return true;
- }
-
- /**
- * Rename several tables
- *
- * @param array $tablePairs array('oldName' => 'Name1', 'newName' => 'Name2')
- *
- * @return boolean
- * @throws Zend_Db_Exception
- */
- public function renameTablesBatch(array $tablePairs)
- {
- if (count($tablePairs) == 0) {
- throw new Zend_Db_Exception('Please provide tables for rename');
- }
+ if (count($tablePairs) == 0) {
+ throw new Zend_Db_Exception('Please provide tables for rename');
+ }
$renamesList = [];
$tablesList = [];
@@ -3047,48 +2266,14 @@ public function prepareSqlCondition($fieldName, $condition)
}
/**
- * Prepare Sql condition
+ * Prepare value for save in column
+ * Return converted to column data type value
*
- * @param string $text Condition value
- * @param mixed $value
- * @param string $fieldName
- * @return string
+ * @param array $column the column describe array
+ * @param mixed $value
+ * @return mixed
*/
- protected function _prepareQuotedSqlCondition($text, $value, $fieldName)
- {
- $value = is_string($value) ? str_replace("\0", '', $value) : $value;
- $sql = $this->quoteInto($text, $value);
- return str_replace('{{fieldName}}', (string) $fieldName, $sql);
- }
-
- /**
- * Transforms sql condition key 'seq' / 'sneq' that is used for comparing string values to its analog:
- * - 'null' / 'notnull' for empty strings
- * - 'eq' / 'neq' for non-empty strings
- *
- * @param string $conditionKey
- * @param mixed $value
- * @return string
- */
- protected function _transformStringSqlCondition($conditionKey, $value)
- {
- $value = str_replace("\0", '', (string) $value);
- if ($value == '') {
- return ($conditionKey == 'seq') ? 'null' : 'notnull';
- } else {
- return ($conditionKey == 'seq') ? 'eq' : 'neq';
- }
- }
-
- /**
- * Prepare value for save in column
- * Return converted to column data type value
- *
- * @param array $column the column describe array
- * @param mixed $value
- * @return mixed
- */
- public function prepareColumnValue(array $column, $value)
+ public function prepareColumnValue(array $column, $value)
{
if ($value instanceof Zend_Db_Expr) {
return $value;
@@ -3274,23 +2459,6 @@ public function getGreatestSql(array $data)
return new Zend_Db_Expr(sprintf('GREATEST(%s)', implode(', ', $data)));
}
- /**
- * Get Interval Unit SQL fragment
- *
- * @param int $interval
- * @param string $unit
- * @return string
- * @throws Zend_Db_Exception
- */
- protected function _getIntervalUnitSql($interval, $unit)
- {
- if (!isset($this->_intervalUnits[$unit])) {
- throw new Zend_Db_Exception(sprintf('Undefined interval unit "%s" specified', $unit));
- }
-
- return sprintf('INTERVAL %d %s', $interval, $this->_intervalUnits[$unit]);
- }
-
/**
* Add time values (intervals) to a date value
*
@@ -3403,22 +2571,6 @@ public function getDateExtractSql($date, $unit)
return new Zend_Db_Expr($expr);
}
- /**
- * Minus superfluous characters from hash.
- *
- * @param $hash
- * @param $prefix
- * @param $maxCharacters
- * @return string
- */
- protected function _minusSuperfluous($hash, $prefix, $maxCharacters)
- {
- $diff = strlen($hash) + strlen($prefix) - $maxCharacters;
- $superfluous = $diff / 2;
- $odd = $diff % 2;
- return substr($hash, $superfluous, - ($superfluous + $odd));
- }
-
/**
* Retrieve valid table name
* Check table name length and allowed symbols
@@ -3854,112 +3006,6 @@ public function forUpdate($sql)
return sprintf('%s FOR UPDATE', $sql);
}
- /**
- * Prepare insert data
- *
- * @param mixed $row
- * @param array $bind
- * @return string
- */
- protected function _prepareInsertData($row, &$bind)
- {
- if (is_array($row)) {
- $line = [];
- foreach ($row as $value) {
- if ($value instanceof Zend_Db_Expr) {
- $line[] = $value->__toString();
- } else {
- $line[] = '?';
- $bind[] = $value;
- }
- }
- $line = implode(', ', $line);
- } elseif ($row instanceof Zend_Db_Expr) {
- $line = $row->__toString();
- } else {
- $line = '?';
- $bind[] = $row;
- }
-
- return sprintf('(%s)', $line);
- }
-
- /**
- * Return insert sql query
- *
- * @param string $tableName
- * @return string
- */
- protected function _getInsertSqlQuery($tableName, array $columns, array $values)
- {
- $tableName = $this->quoteIdentifier($tableName, true);
- $columns = array_map([$this, 'quoteIdentifier'], $columns);
- $columns = implode(',', $columns);
- $values = implode(', ', $values);
-
- return sprintf('INSERT INTO %s (%s) VALUES %s', $tableName, $columns, $values);
- }
-
- /**
- * Return ddl type
- *
- * @param array $options
- * @return string
- */
- protected function _getDdlType($options)
- {
- $ddlType = null;
- if (isset($options['TYPE'])) {
- $ddlType = $options['TYPE'];
- } elseif (isset($options['COLUMN_TYPE'])) {
- $ddlType = $options['COLUMN_TYPE'];
- }
-
- return $ddlType;
- }
-
- /**
- * Return DDL action
- *
- * @param string $action
- * @return string
- */
- protected function _getDdlAction($action)
- {
- switch ($action) {
- case Varien_Db_Adapter_Interface::FK_ACTION_CASCADE:
- return Varien_Db_Ddl_Table::ACTION_CASCADE;
- case Varien_Db_Adapter_Interface::FK_ACTION_SET_NULL:
- return Varien_Db_Ddl_Table::ACTION_SET_NULL;
- case Varien_Db_Adapter_Interface::FK_ACTION_RESTRICT:
- return Varien_Db_Ddl_Table::ACTION_RESTRICT;
- default:
- return Varien_Db_Ddl_Table::ACTION_NO_ACTION;
- }
- }
-
- /**
- * Prepare sql date condition
- *
- * @param array $condition
- * @param string $key
- * @return string
- */
- protected function _prepareSqlDateCondition($condition, $key)
- {
- if (empty($condition['date'])) {
- if (empty($condition['datetime'])) {
- $result = $condition[$key];
- } else {
- $result = $this->formatDate($condition[$key]);
- }
- } else {
- $result = $this->formatDate($condition[$key]);
- }
-
- return $result;
- }
-
/**
* Try to find installed primary key name, if not - format new one.
*
@@ -3977,40 +3023,6 @@ public function getPrimaryKeyName($tableName, $schemaName = null)
}
}
- /**
- * Parse text size
- * Returns max allowed size if value great it
- *
- * @param string|int $size
- * @return int
- */
- protected function _parseTextSize($size)
- {
- $size = trim($size);
- $last = strtolower(substr($size, -1));
-
- switch ($last) {
- case 'k':
- $size = (int) $size * 1024;
- break;
- case 'm':
- $size = (int) $size * 1024 * 1024;
- break;
- case 'g':
- $size = (int) $size * 1024 * 1024 * 1024;
- break;
- }
-
- if (empty($size)) {
- return Varien_Db_Ddl_Table::DEFAULT_TEXT_SIZE;
- }
- if ($size >= Varien_Db_Ddl_Table::MAX_TEXT_SIZE) {
- return Varien_Db_Ddl_Table::MAX_TEXT_SIZE;
- }
-
- return (int) $size;
- }
-
/**
* Converts fetched blob into raw binary PHP data.
* The MySQL drivers do it nice, no processing required.
@@ -4038,23 +3050,6 @@ public function getSuggestedZeroDate()
return '0000-00-00 00:00:00';
}
- /**
- * Retrieve Foreign Key name
- *
- * @deprecated after 1.6.0.0
- *
- * @param string $fkName
- * @return string
- */
- protected function _getForeignKeyName($fkName)
- {
- if (substr($fkName, 0, 3) != 'FK_') {
- $fkName = 'FK_' . $fkName;
- }
-
- return $fkName;
- }
-
/**
* Drop trigger
*
@@ -4089,12 +3084,1017 @@ public function createTableFromSelect($tableName, Zend_Db_Select $select, $tempo
}
/**
- * Check if all transactions have been committed
+ * Parse a source hostname and generate a host info
+ * @param $hostName
+ *
+ * @return Varien_Object
*/
- public function __destruct()
+ protected function _getHostInfo($hostName)
{
- if ($this->_transactionLevel > 0) {
- trigger_error('Some transactions have not been committed or rolled back', E_USER_ERROR);
- }
+ $hostInfo = new Varien_Object();
+ $matches = [];
+ if (str_contains($hostName, '/')) {
+ $hostInfo->setAddressType(self::ADDRESS_TYPE_UNIX_SOCKET)
+ ->setUnixSocket($hostName);
+ } elseif (preg_match('/^\[(([0-9a-f]{1,4})?(:([0-9a-f]{1,4})?){1,}:([0-9a-f]{1,4}))(%[0-9a-z]+)?\](:([0-9]+))?$/i', $hostName, $matches)) {
+ $hostName = $matches[1];
+ $hostName .= $matches[6] ?? '';
+ $hostInfo->setAddressType(self::ADDRESS_TYPE_IPV6_ADDRESS)
+ ->setHostName($hostName)
+ ->setPort($matches[8] ?? null);
+ } elseif (preg_match('/^(([0-9a-f]{1,4})?(:([0-9a-f]{1,4})?){1,}:([0-9a-f]{1,4}))(%[0-9a-z]+)?$/i', $hostName, $matches)) {
+ $hostName = $matches[1];
+ $hostName .= $matches[6] ?? '';
+ $hostInfo->setAddressType(self::ADDRESS_TYPE_IPV6_ADDRESS)
+ ->setHostName($hostName);
+ } elseif (str_contains($hostName, ':')) {
+ list($hostAddress, $hostPort) = explode(':', $hostName);
+ $hostInfo->setAddressType(
+ filter_var($hostAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
+ ? self::ADDRESS_TYPE_IPV4_ADDRESS
+ : self::ADDRESS_TYPE_HOSTNAME,
+ )->setHostName($hostAddress)
+ ->setPort($hostPort);
+ } else {
+ $hostInfo->setAddressType(
+ filter_var($hostName, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
+ ? self::ADDRESS_TYPE_IPV4_ADDRESS
+ : self::ADDRESS_TYPE_HOSTNAME,
+ )->setHostName($hostName);
+ }
+
+ return $hostInfo;
+ }
+
+ /**
+ * Creates a PDO object and connects to the database.
+ *
+ * @throws Zend_Db_Adapter_Exception
+ */
+ protected function _connect()
+ {
+ if ($this->_connection) {
+ return;
+ }
+
+ if (!extension_loaded('pdo_mysql')) {
+ throw new Zend_Db_Adapter_Exception('pdo_mysql extension is not installed');
+ }
+
+ $hostInfo = $this->_getHostInfo($this->_config['host'] ?? $this->_config['unix_socket'] ?? null);
+
+ switch ($hostInfo->getAddressType()) {
+ case self::ADDRESS_TYPE_UNIX_SOCKET:
+ $this->_config['unix_socket'] = $hostInfo->getUnixSocket();
+ unset($this->_config['host']);
+ break;
+ case self::ADDRESS_TYPE_IPV6_ADDRESS: // break intentionally omitted
+ case self::ADDRESS_TYPE_IPV4_ADDRESS: // break intentionally omitted
+ case self::ADDRESS_TYPE_HOSTNAME:
+ $this->_config['host'] = $hostInfo->getHostName();
+ if ($hostInfo->getPort()) {
+ $this->_config['port'] = $hostInfo->getPort();
+ }
+ break;
+ default:
+ break;
+ }
+
+ $this->_debugTimer();
+ parent::_connect();
+ $this->_debugStat(self::DEBUG_CONNECT, '');
+
+ /** @link http://bugs.mysql.com/bug.php?id=18551 */
+ $this->_connection->query("SET SQL_MODE=''");
+
+ if (!$this->_connectionFlagsSet) {
+ $this->_connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
+ $this->_connection->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
+ $this->_connectionFlagsSet = true;
+ }
+ }
+
+ /**
+ * Check transaction level in case of DDL query
+ *
+ * @param string|Zend_Db_Select $sql
+ * @throws Zend_Db_Adapter_Exception
+ */
+ protected function _checkDdlTransaction($sql)
+ {
+ if (is_string($sql) && $this->getTransactionLevel() > 0) {
+ $startSql = strtolower(substr(ltrim($sql), 0, 3));
+ if (in_array($startSql, $this->_ddlRoutines)
+ && (preg_match($this->_tempRoutines, $sql) !== 1)
+ ) {
+ trigger_error(Varien_Db_Adapter_Interface::ERROR_DDL_MESSAGE, E_USER_ERROR);
+ }
+ }
+ }
+
+ /**
+ * Prepares SQL query by moving to bind all special parameters that can be confused with bind placeholders
+ * (e.g. "foo:bar"). And also changes named bind to positional one, because underlying library has problems
+ * with named binds.
+ *
+ * @param Zend_Db_Select|string $sql
+ * @param-out string $sql
+ * @param mixed $bind
+ * @return $this
+ */
+ protected function _prepareQuery(&$sql, &$bind = [])
+ {
+ $sql = (string) $sql;
+ if (!is_array($bind)) {
+ $bind = [$bind];
+ }
+
+ // Mixed bind is not supported - so remember whether it is named bind, to normalize later if required
+ $isNamedBind = false;
+ if ($bind) {
+ foreach ($bind as $k => $v) {
+ if (!is_int($k)) {
+ $isNamedBind = true;
+ if ($k[0] != ':') {
+ $bind[":{$k}"] = $v;
+ unset($bind[$k]);
+ }
+ }
+ }
+ }
+
+ // Special query hook
+ if ($this->_queryHook) {
+ $object = $this->_queryHook['object'];
+ $method = $this->_queryHook['method'];
+ $object->$method($sql, $bind);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Unquote raw string (use for auto-bind)
+ *
+ * @param string $string
+ * @return string
+ */
+ protected function _unQuote($string)
+ {
+ $translate = [
+ '\\000' => "\000",
+ '\\n' => "\n",
+ '\\r' => "\r",
+ '\\\\' => '\\',
+ "\'" => "'",
+ '\\"' => '"',
+ '\\032' => "\032",
+ ];
+ return strtr($string, $translate);
+ }
+
+ /**
+ * Normalizes mixed positional-named bind to positional bind, and replaces named placeholders in query to
+ * '?' placeholders.
+ *
+ * @param string $sql
+ * @param array $bind
+ * @return $this
+ */
+ protected function _convertMixedBind(&$sql, &$bind)
+ {
+ $positions = [];
+ $offset = 0;
+ // get positions
+ while (true) {
+ $pos = strpos($sql, '?', $offset);
+ if ($pos !== false) {
+ $positions[] = $pos;
+ $offset = ++$pos;
+ } else {
+ break;
+ }
+ }
+
+ $bindResult = [];
+ $map = [];
+ foreach ($bind as $k => $v) {
+ // positional
+ if (is_int($k)) {
+ if (!isset($positions[$k])) {
+ continue;
+ }
+ $bindResult[$positions[$k]] = $v;
+ } else {
+ $offset = 0;
+ while (true) {
+ $pos = strpos($sql, $k, $offset);
+ if ($pos === false) {
+ break;
+ } else {
+ $offset = $pos + strlen($k);
+ $bindResult[$pos] = $v;
+ }
+ }
+ $map[$k] = '?';
+ }
+ }
+
+ ksort($bindResult);
+ $bind = array_values($bindResult);
+ $sql = strtr($sql, $map);
+
+ return $this;
+ }
+
+ /**
+ * Split multi statement query
+ *
+ * @param string $sql
+ * @return array
+ */
+ protected function _splitMultiQuery($sql)
+ {
+ $parts = preg_split(
+ '#(;|\'|"|\\\\|//|--|\n|/\*|\*/)#',
+ $sql,
+ -1,
+ PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE,
+ );
+
+ $q = false;
+ $c = false;
+ $stmts = [];
+ $s = '';
+
+ foreach ($parts as $i => $part) {
+ // strings
+ if (($part === "'" || $part === '"') && ($i === 0 || $parts[$i - 1] !== '\\')) {
+ if ($q === false) {
+ $q = $part;
+ } elseif ($q === $part) {
+ $q = false;
+ }
+ }
+
+ // single line comments
+ if (($part === '//' || $part === '--') && ($i === 0 || $parts[$i - 1] === "\n")) {
+ $c = $part;
+ } elseif ($part === "\n" && ($c === '//' || $c === '--')) {
+ $c = false;
+ }
+
+ // multi line comments
+ if ($part === '/*' && $c === false) {
+ $c = '/*';
+ } elseif ($part === '*/' && $c === '/*') {
+ $c = false;
+ }
+
+ // statements
+ if ($part === ';' && $q === false && $c === false) {
+ if (trim($s) !== '') {
+ $stmts[] = trim($s);
+ $s = '';
+ }
+ } else {
+ $s .= $part;
+ }
+ }
+ if (trim($s) !== '') {
+ $stmts[] = trim($s);
+ }
+
+ return $stmts;
+ }
+
+ /**
+ * Remove duplicate entry for create key
+ *
+ * @param string $table
+ * @param array $fields
+ * @param array $ids
+ * @return $this
+ */
+ protected function _removeDuplicateEntry($table, $fields, $ids)
+ {
+ $where = [];
+ $i = 0;
+ foreach ($fields as $field) {
+ $where[] = $this->quoteInto($field . '=?', $ids[$i++]);
+ }
+
+ if (!$where) {
+ return $this;
+ }
+ $whereCond = implode(' AND ', $where);
+ $sql = sprintf('SELECT COUNT(*) as `cnt` FROM `%s` WHERE %s', $table, $whereCond);
+
+ $cnt = $this->raw_fetchRow($sql, 'cnt');
+ if ($cnt > 1) {
+ $sql = sprintf(
+ 'DELETE FROM `%s` WHERE %s LIMIT %d',
+ $table,
+ $whereCond,
+ $cnt - 1,
+ );
+ $this->raw_query($sql);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Start debug timer
+ *
+ * @return $this
+ */
+ protected function _debugTimer()
+ {
+ if ($this->_debug) {
+ $this->_debugTimer = microtime(true);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Logging debug information
+ *
+ * @param int $type
+ * @param string $sql
+ * @param array $bind
+ * @param Zend_Db_Statement_Pdo $result
+ * @return $this
+ */
+ protected function _debugStat($type, $sql, $bind = [], $result = null)
+ {
+ if (!$this->_debug) {
+ return $this;
+ }
+
+ $code = '## ' . getmypid() . ' ## ';
+ $nl = "\n";
+ $time = sprintf('%.4f', microtime(true) - $this->_debugTimer);
+
+ if (!$this->_logAllQueries && $time < $this->_logQueryTime) {
+ return $this;
+ }
+ switch ($type) {
+ case self::DEBUG_CONNECT:
+ $code .= 'CONNECT' . $nl;
+ break;
+ case self::DEBUG_TRANSACTION:
+ $code .= 'TRANSACTION ' . $sql . $nl;
+ break;
+ case self::DEBUG_QUERY:
+ $code .= 'QUERY' . $nl;
+ $code .= 'SQL: ' . $sql . $nl;
+ if ($bind) {
+ $code .= 'BIND: ' . var_export($bind, true) . $nl;
+ }
+ if ($result instanceof Zend_Db_Statement_Pdo) {
+ $code .= 'AFF: ' . $result->rowCount() . $nl;
+ }
+ break;
+ }
+ $code .= 'TIME: ' . $time . $nl;
+
+ if ($this->_logCallStack) {
+ $code .= 'TRACE: ' . Varien_Debug::backtrace(true, false) . $nl;
+ }
+
+ $code .= $nl;
+
+ $this->_debugWriteToFile($code);
+
+ return $this;
+ }
+
+ /**
+ * Write exception and throw
+ *
+ * @throws Exception
+ */
+ protected function _debugException(Exception $e)
+ {
+ if (!$this->_debug) {
+ throw $e;
+ }
+
+ $nl = "\n";
+ $code = 'EXCEPTION ' . $nl . $e . $nl . $nl;
+ $this->_debugWriteToFile($code);
+
+ throw $e;
+ }
+
+ /**
+ * Debug write to file process
+ *
+ * @param string $str
+ */
+ protected function _debugWriteToFile($str)
+ {
+ $str = '## ' . date(self::TIMESTAMP_FORMAT) . "\r\n" . $str;
+ if (!$this->_debugIoAdapter) {
+ $this->_debugIoAdapter = new Varien_Io_File();
+ $dir = Mage::getBaseDir() . DS . $this->_debugIoAdapter->dirname($this->_debugFile);
+ $this->_debugIoAdapter->checkAndCreateFolder($dir);
+ $this->_debugIoAdapter->open(['path' => $dir]);
+ $this->_debugFile = basename($this->_debugFile);
+ }
+
+ $this->_debugIoAdapter->streamOpen($this->_debugFile, 'a');
+ $this->_debugIoAdapter->streamLock();
+ $this->_debugIoAdapter->streamWrite($str);
+ $this->_debugIoAdapter->streamUnlock();
+ $this->_debugIoAdapter->streamClose();
+ }
+
+ /**
+ * Retrieve ddl cache name
+ *
+ * @param string $tableName
+ * @param string $schemaName
+ */
+ protected function _getTableName($tableName, $schemaName = null)
+ {
+ return ($schemaName ? $schemaName . '.' : '') . $tableName;
+ }
+
+ /**
+ * Retrieve Id for cache
+ *
+ * @param string $tableKey
+ * @param int $ddlType
+ * @return string
+ */
+ protected function _getCacheId($tableKey, $ddlType)
+ {
+ return sprintf('%s_%s_%s', self::DDL_CACHE_PREFIX, $tableKey, $ddlType);
+ }
+
+ /**
+ * Retrieve column data type by data from describe table
+ *
+ * @param array $column
+ * @return string|void
+ */
+ protected function _getColumnTypeByDdl($column)
+ {
+ switch ($column['DATA_TYPE']) {
+ case 'bool':
+ return Varien_Db_Ddl_Table::TYPE_BOOLEAN;
+ case 'tinytext':
+ case 'char':
+ case 'varchar':
+ case 'text':
+ case 'mediumtext':
+ case 'longtext':
+ return Varien_Db_Ddl_Table::TYPE_TEXT;
+ case 'blob':
+ case 'mediumblob':
+ case 'longblob':
+ return Varien_Db_Ddl_Table::TYPE_BLOB;
+ case 'tinyint':
+ case 'tinyint unsigned':
+ case 'smallint':
+ case 'smallint unsigned':
+ return Varien_Db_Ddl_Table::TYPE_SMALLINT;
+ case 'mediumint':
+ case 'int':
+ case 'int unsigned':
+ return Varien_Db_Ddl_Table::TYPE_INTEGER;
+ case 'bigint':
+ case 'bigint unsigned':
+ return Varien_Db_Ddl_Table::TYPE_BIGINT;
+ case 'datetime':
+ return Varien_Db_Ddl_Table::TYPE_DATETIME;
+ case 'timestamp':
+ return Varien_Db_Ddl_Table::TYPE_TIMESTAMP;
+ case 'date':
+ return Varien_Db_Ddl_Table::TYPE_DATE;
+ case 'float':
+ return Varien_Db_Ddl_Table::TYPE_FLOAT;
+ case 'decimal':
+ case 'numeric':
+ return Varien_Db_Ddl_Table::TYPE_DECIMAL;
+ case 'varbinary':
+ return Varien_Db_Ddl_Table::TYPE_VARBINARY;
+ }
+ }
+
+ /**
+ * Retrieve columns and primary keys definition array for create table
+ *
+ * @return array
+ * @throws Zend_Db_Exception
+ */
+ protected function _getColumnsDefinition(Varien_Db_Ddl_Table $table)
+ {
+ $definition = [];
+ $primary = [];
+ $columns = $table->getColumns();
+ if (empty($columns)) {
+ throw new Zend_Db_Exception('Table columns are not defined');
+ }
+
+ foreach ($columns as $columnData) {
+ $columnDefinition = $this->_getColumnDefinition($columnData);
+ if ($columnData['PRIMARY']) {
+ $primary[$columnData['COLUMN_NAME']] = $columnData['PRIMARY_POSITION'];
+ }
+
+ $definition[] = sprintf(
+ ' %s %s',
+ $this->quoteIdentifier($columnData['COLUMN_NAME']),
+ $columnDefinition,
+ );
+ }
+
+ // PRIMARY KEY
+ if (!empty($primary)) {
+ asort($primary, SORT_NUMERIC);
+ $primary = array_map([$this, 'quoteIdentifier'], array_keys($primary));
+ $definition[] = sprintf(' PRIMARY KEY (%s)', implode(', ', $primary));
+ }
+
+ return $definition;
+ }
+
+ /**
+ * Retrieve table indexes definition array for create table
+ *
+ * @return array
+ */
+ protected function _getIndexesDefinition(Varien_Db_Ddl_Table $table)
+ {
+ $definition = [];
+ $indexes = $table->getIndexes();
+ if (!empty($indexes)) {
+ foreach ($indexes as $indexData) {
+ if (!empty($indexData['TYPE'])) {
+ switch ($indexData['TYPE']) {
+ case 'primary':
+ $indexType = 'PRIMARY KEY';
+ unset($indexData['INDEX_NAME']);
+ break;
+ default:
+ $indexType = strtoupper($indexData['TYPE']);
+ break;
+ }
+ } else {
+ $indexType = 'KEY';
+ }
+
+ $columns = [];
+ foreach ($indexData['COLUMNS'] as $columnData) {
+ $column = $this->quoteIdentifier($columnData['NAME']);
+ if (!empty($columnData['SIZE'])) {
+ $column .= sprintf('(%d)', $columnData['SIZE']);
+ }
+ $columns[] = $column;
+ }
+ $indexName = isset($indexData['INDEX_NAME']) ? $this->quoteIdentifier($indexData['INDEX_NAME']) : '';
+ $definition[] = sprintf(
+ ' %s %s (%s)',
+ $indexType,
+ $indexName,
+ implode(', ', $columns),
+ );
+ }
+ }
+
+ return $definition;
+ }
+
+ /**
+ * Retrieve table foreign keys definition array for create table
+ *
+ * @return array
+ */
+ protected function _getForeignKeysDefinition(Varien_Db_Ddl_Table $table)
+ {
+ $definition = [];
+ $relations = $table->getForeignKeys();
+
+ if (!empty($relations)) {
+ foreach ($relations as $fkData) {
+ $onDelete = $this->_getDdlAction($fkData['ON_DELETE']);
+ $onUpdate = $this->_getDdlAction($fkData['ON_UPDATE']);
+
+ $definition[] = sprintf(
+ ' CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s) ON DELETE %s ON UPDATE %s',
+ $this->quoteIdentifier($fkData['FK_NAME']),
+ $this->quoteIdentifier($fkData['COLUMN_NAME']),
+ $this->quoteIdentifier($fkData['REF_TABLE_NAME']),
+ $this->quoteIdentifier($fkData['REF_COLUMN_NAME']),
+ $onDelete,
+ $onUpdate,
+ );
+ }
+ }
+
+ return $definition;
+ }
+
+ /**
+ * Retrieve table options definition array for create table
+ *
+ * @return array
+ * @throws Zend_Db_Exception
+ */
+ protected function _getOptionsDefinition(Varien_Db_Ddl_Table $table)
+ {
+ $definition = [];
+ $comment = $table->getComment();
+ if (empty($comment)) {
+ throw new Zend_Db_Exception('Comment for table is required and must be defined');
+ }
+ $definition[] = $this->quoteInto('COMMENT=?', $comment);
+
+ $tableProps = [
+ 'type' => 'ENGINE=%s',
+ 'checksum' => 'CHECKSUM=%d',
+ 'auto_increment' => 'AUTO_INCREMENT=%d',
+ 'avg_row_length' => 'AVG_ROW_LENGTH=%d',
+ 'max_rows' => 'MAX_ROWS=%d',
+ 'min_rows' => 'MIN_ROWS=%d',
+ 'delay_key_write' => 'DELAY_KEY_WRITE=%d',
+ 'row_format' => 'row_format=%s',
+ 'charset' => 'charset=%s',
+ 'collate' => 'COLLATE=%s',
+ ];
+ foreach ($tableProps as $key => $mask) {
+ $v = $table->getOption($key);
+ if ($v !== null) {
+ $definition[] = sprintf($mask, $v);
+ }
+ }
+
+ return $definition;
+ }
+
+ /**
+ * Retrieve column definition fragment
+ *
+ * @param array $options
+ * @param string $ddlType Table DDL Column type constant
+ * @throws Varien_Exception
+ * @return string
+ * @throws Zend_Db_Exception
+ */
+ protected function _getColumnDefinition($options, $ddlType = null)
+ {
+ // convert keys to uppercase
+ $options = array_change_key_case($options, CASE_UPPER);
+ $cType = null;
+ $cUnsigned = false;
+ $cNullable = true;
+ $cDefault = false;
+ $cIdentity = false;
+
+ // detect and validate column type
+ if ($ddlType === null) {
+ $ddlType = $this->_getDdlType($options);
+ }
+
+ if (empty($ddlType) || !isset($this->_ddlColumnTypes[$ddlType])) {
+ throw new Zend_Db_Exception('Invalid column definition data');
+ }
+
+ // column size
+ $cType = $this->_ddlColumnTypes[$ddlType];
+ switch ($ddlType) {
+ case Varien_Db_Ddl_Table::TYPE_SMALLINT:
+ case Varien_Db_Ddl_Table::TYPE_INTEGER:
+ case Varien_Db_Ddl_Table::TYPE_BIGINT:
+ if (!empty($options['UNSIGNED'])) {
+ $cUnsigned = true;
+ }
+ break;
+ case Varien_Db_Ddl_Table::TYPE_DECIMAL:
+ case Varien_Db_Ddl_Table::TYPE_NUMERIC:
+ $precision = 10;
+ $scale = 0;
+ $match = [];
+ if (!empty($options['LENGTH']) && preg_match('#^\(?(\d+),(\d+)\)?$#', $options['LENGTH'], $match)) {
+ $precision = $match[1];
+ $scale = $match[2];
+ } else {
+ if (isset($options['SCALE']) && is_numeric($options['SCALE'])) {
+ $scale = $options['SCALE'];
+ }
+ if (isset($options['PRECISION']) && is_numeric($options['PRECISION'])) {
+ $precision = $options['PRECISION'];
+ }
+ }
+ $cType .= sprintf('(%d,%d)', $precision, $scale);
+ break;
+ case Varien_Db_Ddl_Table::TYPE_TEXT:
+ case Varien_Db_Ddl_Table::TYPE_BLOB:
+ case Varien_Db_Ddl_Table::TYPE_VARBINARY:
+ if (empty($options['LENGTH'])) {
+ $length = Varien_Db_Ddl_Table::DEFAULT_TEXT_SIZE;
+ } else {
+ $length = $this->_parseTextSize($options['LENGTH']);
+ }
+ if ($length <= 255) {
+ $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'varchar' : 'varbinary';
+ $cType = sprintf('%s(%d)', $cType, $length);
+ } elseif ($length > 255 && $length <= 65536) {
+ $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'text' : 'blob';
+ } elseif ($length > 65536 && $length <= 16777216) {
+ $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'mediumtext' : 'mediumblob';
+ } else {
+ $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'longtext' : 'longblob';
+ }
+ break;
+ }
+
+ if (array_key_exists('DEFAULT', $options)) {
+ $cDefault = $options['DEFAULT'];
+ }
+ if (array_key_exists('NULLABLE', $options)) {
+ $cNullable = (bool) $options['NULLABLE'];
+ }
+ if (!empty($options['IDENTITY']) || !empty($options['AUTO_INCREMENT'])) {
+ $cIdentity = true;
+ }
+
+ /* For cases when tables created from createTableByDdl()
+ * where default value can be quoted already.
+ * We need to avoid "double-quoting" here
+ */
+ if ($cDefault !== null && strlen($cDefault)) {
+ $cDefault = str_replace("'", '', $cDefault);
+ }
+
+ // prepare default value string
+ if ($ddlType == Varien_Db_Ddl_Table::TYPE_TIMESTAMP) {
+ if ($cDefault === null) {
+ $cDefault = new Zend_Db_Expr('NULL');
+ } elseif ($cDefault == Varien_Db_Ddl_Table::TIMESTAMP_INIT) {
+ $cDefault = new Zend_Db_Expr('CURRENT_TIMESTAMP');
+ } elseif ($cDefault == Varien_Db_Ddl_Table::TIMESTAMP_UPDATE) {
+ $cDefault = new Zend_Db_Expr('0 ON UPDATE CURRENT_TIMESTAMP');
+ } elseif ($cDefault == Varien_Db_Ddl_Table::TIMESTAMP_INIT_UPDATE) {
+ $cDefault = new Zend_Db_Expr('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
+ } elseif ($cNullable && !$cDefault) {
+ $cDefault = new Zend_Db_Expr('NULL');
+ } else {
+ $cDefault = new Zend_Db_Expr('0');
+ }
+ } elseif (is_null($cDefault) && $cNullable) {
+ $cDefault = new Zend_Db_Expr('NULL');
+ }
+
+ if (empty($options['COMMENT'])) {
+ $comment = '';
+ } else {
+ $comment = $options['COMMENT'];
+ }
+
+ //set column position
+ $after = null;
+ if (!empty($options['AFTER'])) {
+ $after = $options['AFTER'];
+ }
+
+ return sprintf(
+ '%s%s%s%s%s COMMENT %s %s',
+ $cType,
+ $cUnsigned ? ' UNSIGNED' : '',
+ $cNullable ? ' NULL' : ' NOT NULL',
+ $cDefault !== false ? $this->quoteInto(' default ?', $cDefault) : '',
+ $cIdentity ? ' auto_increment' : '',
+ $this->quote($comment),
+ $after ? 'AFTER ' . $this->quoteIdentifier($after) : '',
+ );
+ }
+
+ /**
+ * Prepare Sql condition
+ *
+ * @param string $text Condition value
+ * @param mixed $value
+ * @param string $fieldName
+ * @return string
+ */
+ protected function _prepareQuotedSqlCondition($text, $value, $fieldName)
+ {
+ $value = is_string($value) ? str_replace("\0", '', $value) : $value;
+ $sql = $this->quoteInto($text, $value);
+ return str_replace('{{fieldName}}', (string) $fieldName, $sql);
+ }
+
+ /**
+ * Transforms sql condition key 'seq' / 'sneq' that is used for comparing string values to its analog:
+ * - 'null' / 'notnull' for empty strings
+ * - 'eq' / 'neq' for non-empty strings
+ *
+ * @param string $conditionKey
+ * @param mixed $value
+ * @return string
+ */
+ protected function _transformStringSqlCondition($conditionKey, $value)
+ {
+ $value = str_replace("\0", '', (string) $value);
+ if ($value == '') {
+ return ($conditionKey == 'seq') ? 'null' : 'notnull';
+ } else {
+ return ($conditionKey == 'seq') ? 'eq' : 'neq';
+ }
+ }
+
+ /**
+ * Get Interval Unit SQL fragment
+ *
+ * @param int $interval
+ * @param string $unit
+ * @return string
+ * @throws Zend_Db_Exception
+ */
+ protected function _getIntervalUnitSql($interval, $unit)
+ {
+ if (!isset($this->_intervalUnits[$unit])) {
+ throw new Zend_Db_Exception(sprintf('Undefined interval unit "%s" specified', $unit));
+ }
+
+ return sprintf('INTERVAL %d %s', $interval, $this->_intervalUnits[$unit]);
+ }
+
+ /**
+ * Minus superfluous characters from hash.
+ *
+ * @param $hash
+ * @param $prefix
+ * @param $maxCharacters
+ * @return string
+ */
+ protected function _minusSuperfluous($hash, $prefix, $maxCharacters)
+ {
+ $diff = strlen($hash) + strlen($prefix) - $maxCharacters;
+ $superfluous = $diff / 2;
+ $odd = $diff % 2;
+ return substr($hash, $superfluous, - ($superfluous + $odd));
+ }
+
+ /**
+ * Prepare insert data
+ *
+ * @param mixed $row
+ * @param array $bind
+ * @return string
+ */
+ protected function _prepareInsertData($row, &$bind)
+ {
+ if (is_array($row)) {
+ $line = [];
+ foreach ($row as $value) {
+ if ($value instanceof Zend_Db_Expr) {
+ $line[] = $value->__toString();
+ } else {
+ $line[] = '?';
+ $bind[] = $value;
+ }
+ }
+ $line = implode(', ', $line);
+ } elseif ($row instanceof Zend_Db_Expr) {
+ $line = $row->__toString();
+ } else {
+ $line = '?';
+ $bind[] = $row;
+ }
+
+ return sprintf('(%s)', $line);
+ }
+
+ /**
+ * Return insert sql query
+ *
+ * @param string $tableName
+ * @return string
+ */
+ protected function _getInsertSqlQuery($tableName, array $columns, array $values)
+ {
+ $tableName = $this->quoteIdentifier($tableName, true);
+ $columns = array_map([$this, 'quoteIdentifier'], $columns);
+ $columns = implode(',', $columns);
+ $values = implode(', ', $values);
+
+ return sprintf('INSERT INTO %s (%s) VALUES %s', $tableName, $columns, $values);
+ }
+
+ /**
+ * Return ddl type
+ *
+ * @param array $options
+ * @return string
+ */
+ protected function _getDdlType($options)
+ {
+ $ddlType = null;
+ if (isset($options['TYPE'])) {
+ $ddlType = $options['TYPE'];
+ } elseif (isset($options['COLUMN_TYPE'])) {
+ $ddlType = $options['COLUMN_TYPE'];
+ }
+
+ return $ddlType;
+ }
+
+ /**
+ * Return DDL action
+ *
+ * @param string $action
+ * @return string
+ */
+ protected function _getDdlAction($action)
+ {
+ switch ($action) {
+ case Varien_Db_Adapter_Interface::FK_ACTION_CASCADE:
+ return Varien_Db_Ddl_Table::ACTION_CASCADE;
+ case Varien_Db_Adapter_Interface::FK_ACTION_SET_NULL:
+ return Varien_Db_Ddl_Table::ACTION_SET_NULL;
+ case Varien_Db_Adapter_Interface::FK_ACTION_RESTRICT:
+ return Varien_Db_Ddl_Table::ACTION_RESTRICT;
+ default:
+ return Varien_Db_Ddl_Table::ACTION_NO_ACTION;
+ }
+ }
+
+ /**
+ * Prepare sql date condition
+ *
+ * @param array $condition
+ * @param string $key
+ * @return string
+ */
+ protected function _prepareSqlDateCondition($condition, $key)
+ {
+ if (empty($condition['date'])) {
+ if (empty($condition['datetime'])) {
+ $result = $condition[$key];
+ } else {
+ $result = $this->formatDate($condition[$key]);
+ }
+ } else {
+ $result = $this->formatDate($condition[$key]);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Parse text size
+ * Returns max allowed size if value great it
+ *
+ * @param string|int $size
+ * @return int
+ */
+ protected function _parseTextSize($size)
+ {
+ $size = trim($size);
+ $last = strtolower(substr($size, -1));
+
+ switch ($last) {
+ case 'k':
+ $size = (int) $size * 1024;
+ break;
+ case 'm':
+ $size = (int) $size * 1024 * 1024;
+ break;
+ case 'g':
+ $size = (int) $size * 1024 * 1024 * 1024;
+ break;
+ }
+
+ if (empty($size)) {
+ return Varien_Db_Ddl_Table::DEFAULT_TEXT_SIZE;
+ }
+ if ($size >= Varien_Db_Ddl_Table::MAX_TEXT_SIZE) {
+ return Varien_Db_Ddl_Table::MAX_TEXT_SIZE;
+ }
+
+ return (int) $size;
+ }
+
+ /**
+ * Retrieve Foreign Key name
+ *
+ * @deprecated after 1.6.0.0
+ *
+ * @param string $fkName
+ * @return string
+ */
+ protected function _getForeignKeyName($fkName)
+ {
+ if (substr($fkName, 0, 3) != 'FK_') {
+ $fkName = 'FK_' . $fkName;
+ }
+
+ return $fkName;
}
}
diff --git a/lib/Varien/Db/Select.php b/lib/Varien/Db/Select.php
index feaf5a4e399..5a18f12efab 100644
--- a/lib/Varien/Db/Select.php
+++ b/lib/Varien/Db/Select.php
@@ -174,104 +174,6 @@ public function resetJoinLeft()
return $this;
}
- /**
- * Validate LEFT joins, and remove it if not exists
- *
- * @return $this
- */
- protected function _resetJoinLeft()
- {
- foreach ($this->_parts[self::FROM] as $tableId => $tableProp) {
- if ($tableProp['joinType'] == self::LEFT_JOIN) {
- if ($tableProp['useInCond']) {
- continue;
- }
-
- $used = false;
- foreach ($tableProp['joinInTables'] as $table) {
- if (isset($this->_parts[self::FROM][$table])) {
- $used = true;
- break;
- }
- }
-
- if (!$used) {
- unset($this->_parts[self::FROM][$tableId]);
- return $this->_resetJoinLeft();
- }
- }
- }
-
- return $this;
- }
-
- /**
- * Find table name in condition (where, column)
- *
- * @param string $table
- * @param string $cond
- * @return bool
- */
- protected function _findTableInCond($table, $cond)
- {
- $cond = (string) $cond;
- $quote = $this->_adapter->getQuoteIdentifierSymbol();
-
- if (strpos($cond, $quote . $table . $quote . '.') !== false) {
- return true;
- }
-
- $position = 0;
- $result = 0;
- $needle = [];
- while (is_integer($result)) {
- $result = strpos($cond, $table . '.', $position);
- if (is_integer($result)) {
- $needle[] = $result;
- $position = ($result + strlen($table) + 1);
- }
- }
-
- if (!$needle) {
- return false;
- }
-
- foreach ($needle as $position) {
- if ($position == 0) {
- return true;
- }
- if (!preg_match('#[a-z0-9_]#is', substr($cond, $position - 1, 1))) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Populate the {@link $_parts} 'join' key
- *
- * Does the dirty work of populating the join key.
- *
- * The $name and $cols parameters follow the same logic
- * as described in the from() method.
- *
- * @param null|string $type Type of join; inner, left, and null are currently supported
- * @param array|string|Zend_Db_Expr $name Table name
- * @param string $cond Join on this condition
- * @param array|string $cols The columns to select from the joined table
- * @param string $schema The database name to specify, if any.
- * @return Zend_Db_Select This Zend_Db_Select object
- * @throws Zend_Db_Select_Exception
- */
- protected function _join($type, $name, $cond, $cols, $schema = null)
- {
- if ($type == self::INNER_JOIN && empty($cond)) {
- $type = self::CROSS_JOIN;
- }
- return parent::_join($type, $name, $cond, $cols, $schema);
- }
-
/**
* Sets a limit count and offset to the query.
*
@@ -373,6 +275,140 @@ public function useStraightJoin($flag = true)
return $this;
}
+ /**
+ * Adds the random order to query
+ *
+ * @param string $field integer field name
+ * @return $this
+ */
+ public function orderRand($field = null)
+ {
+ $this->_adapter->orderRand($this, $field);
+ return $this;
+ }
+ /**
+ * Add EXISTS clause
+ *
+ * @param Varien_Db_Select $select
+ * @param string $joinCondition
+ * @param bool $isExists
+ * @return $this
+ */
+ public function exists($select, $joinCondition, $isExists = true)
+ {
+ if ($isExists) {
+ $exists = 'EXISTS (%s)';
+ } else {
+ $exists = 'NOT EXISTS (%s)';
+ }
+ $select->reset(self::COLUMNS)
+ ->columns([new Zend_Db_Expr('1')])
+ ->where($joinCondition);
+
+ $exists = sprintf($exists, $select->assemble());
+
+ $this->where($exists);
+ return $this;
+ }
+
+ /**
+ * Validate LEFT joins, and remove it if not exists
+ *
+ * @return $this
+ */
+ protected function _resetJoinLeft()
+ {
+ foreach ($this->_parts[self::FROM] as $tableId => $tableProp) {
+ if ($tableProp['joinType'] == self::LEFT_JOIN) {
+ if ($tableProp['useInCond']) {
+ continue;
+ }
+
+ $used = false;
+ foreach ($tableProp['joinInTables'] as $table) {
+ if (isset($this->_parts[self::FROM][$table])) {
+ $used = true;
+ break;
+ }
+ }
+
+ if (!$used) {
+ unset($this->_parts[self::FROM][$tableId]);
+ return $this->_resetJoinLeft();
+ }
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Find table name in condition (where, column)
+ *
+ * @param string $table
+ * @param string $cond
+ * @return bool
+ */
+ protected function _findTableInCond($table, $cond)
+ {
+ $cond = (string) $cond;
+ $quote = $this->_adapter->getQuoteIdentifierSymbol();
+
+ if (strpos($cond, $quote . $table . $quote . '.') !== false) {
+ return true;
+ }
+
+ $position = 0;
+ $result = 0;
+ $needle = [];
+ while (is_integer($result)) {
+ $result = strpos($cond, $table . '.', $position);
+ if (is_integer($result)) {
+ $needle[] = $result;
+ $position = ($result + strlen($table) + 1);
+ }
+ }
+
+ if (!$needle) {
+ return false;
+ }
+
+ foreach ($needle as $position) {
+ if ($position == 0) {
+ return true;
+ }
+ if (!preg_match('#[a-z0-9_]#is', substr($cond, $position - 1, 1))) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Populate the {@link $_parts} 'join' key
+ *
+ * Does the dirty work of populating the join key.
+ *
+ * The $name and $cols parameters follow the same logic
+ * as described in the from() method.
+ *
+ * @param null|string $type Type of join; inner, left, and null are currently supported
+ * @param array|string|Zend_Db_Expr $name Table name
+ * @param string $cond Join on this condition
+ * @param array|string $cols The columns to select from the joined table
+ * @param string $schema The database name to specify, if any.
+ * @return Zend_Db_Select This Zend_Db_Select object
+ * @throws Zend_Db_Select_Exception
+ */
+ protected function _join($type, $name, $cond, $cols, $schema = null)
+ {
+ if ($type == self::INNER_JOIN && empty($cond)) {
+ $type = self::CROSS_JOIN;
+ }
+ return parent::_join($type, $name, $cond, $cols, $schema);
+ }
+
/**
* Render STRAIGHT_JOIN clause
*
@@ -406,18 +442,6 @@ protected function _tableCols($correlationName, $cols, $afterCorrelationName = n
parent::_tableCols($correlationName, $cols, $afterCorrelationName);
}
- /**
- * Adds the random order to query
- *
- * @param string $field integer field name
- * @return $this
- */
- public function orderRand($field = null)
- {
- $this->_adapter->orderRand($this, $field);
- return $this;
- }
-
/**
* Render FOR UPDATE clause
*
@@ -432,28 +456,4 @@ protected function _renderForupdate($sql)
return $sql;
}
- /**
- * Add EXISTS clause
- *
- * @param Varien_Db_Select $select
- * @param string $joinCondition
- * @param bool $isExists
- * @return $this
- */
- public function exists($select, $joinCondition, $isExists = true)
- {
- if ($isExists) {
- $exists = 'EXISTS (%s)';
- } else {
- $exists = 'NOT EXISTS (%s)';
- }
- $select->reset(self::COLUMNS)
- ->columns([new Zend_Db_Expr('1')])
- ->where($joinCondition);
-
- $exists = sprintf($exists, $select->assemble());
-
- $this->where($exists);
- return $this;
- }
}
diff --git a/lib/Varien/Db/Statement/Parameter.php b/lib/Varien/Db/Statement/Parameter.php
index 13c2834bbd5..d868b2e8f29 100644
--- a/lib/Varien/Db/Statement/Parameter.php
+++ b/lib/Varien/Db/Statement/Parameter.php
@@ -72,6 +72,16 @@ public function __construct($value)
$this->_additional = new Varien_Object();
}
+ /**
+ * Returns representation of a object to be used in string contexts
+ *
+ * @return string
+ */
+ public function __toString()
+ {
+ return (string) $this->_value;
+ }
+
/**
* Sets parameter value.
*
@@ -212,16 +222,6 @@ public function getAdditional()
return $this->_additional;
}
- /**
- * Returns representation of a object to be used in string contexts
- *
- * @return string
- */
- public function __toString()
- {
- return (string) $this->_value;
- }
-
/**
* Returns representation of a object to be used in string contexts
*
diff --git a/lib/Varien/Db/Tree.php b/lib/Varien/Db/Tree.php
index 1838aa0f05e..db898fe00b7 100644
--- a/lib/Varien/Db/Tree.php
+++ b/lib/Varien/Db/Tree.php
@@ -121,6 +121,78 @@ public function __construct($config = [])
}
}
+ public function __moveNode($eId, $pId, $aId = 0)
+ {
+ $eInfo = $this->getNodeInfo($eId);
+ $level = $eInfo[$this->_level];
+ $left_key = $eInfo[$this->_left];
+ $right_key = $eInfo[$this->_right];
+ $right_key_near = 0;
+ $left_key_near = 0;
+ $skew_level = 0;
+
+ if ($pId != 0) {
+ $pInfo = $this->getNodeInfo($pId);
+ $skew_level = $pInfo[$this->_level] - $eInfo[$this->_level] + 1;
+ }
+ if ($aId != 0) {
+ $aInfo = $this->getNodeInfo($aId);
+ }
+
+ if ($pId == 0) { //move to root
+ $right_key_near = $this->_db->fetchOne('SELECT MAX(' . $this->_right . ') FROM ' . $this->_table);
+ } elseif (isset($aInfo) && $aId != 0 && $pId == $eInfo[$this->_pid]) { // if we have after ID
+ $right_key_near = $aInfo[$this->_right];
+ $left_key_near = $aInfo[$this->_left];
+ } elseif (isset($pInfo) && $aId == 0 && $pId == $eInfo[$this->_pid]) { // if we do not have after ID
+ $right_key_near = $pInfo[$this->_left];
+ } elseif (isset($pInfo) && $pId != $eInfo[$this->_pid]) {
+ $right_key_near = $pInfo[$this->_right] - 1;
+ }
+
+ $skew_tree = $eInfo[$this->_right] - $eInfo[$this->_left] + 1;
+ echo "alert('" . $right_key_near . "');";
+
+ if ($right_key_near > $right_key) { // up
+ echo "alert('move up');";
+ $skew_edit = $right_key_near - $left_key + 1;
+ $sql = 'UPDATE ' . $this->_table . '
+ SET
+ ' . $this->_right . ' = IF(' . $this->_left . ' >= ' . $eInfo[$this->_left] . ', ' . $this->_right . ' + ' . $skew_edit . ', IF(' . $this->_right . ' < ' . $eInfo[$this->_left] . ', ' . $this->_right . ' + ' . $skew_tree . ', ' . $this->_right . ')),
+ ' . $this->_level . ' = IF(' . $this->_left . ' >= ' . $eInfo[$this->_left] . ', ' . $this->_level . ' + ' . $skew_level . ', ' . $this->_level . '),
+ ' . $this->_left . ' = IF(' . $this->_left . ' >= ' . $eInfo[$this->_left] . ', ' . $this->_left . ' + ' . $skew_edit . ', IF(' . $this->_left . ' > ' . $right_key_near . ', ' . $this->_left . ' + ' . $skew_tree . ', ' . $this->_left . '))
+ WHERE ' . $this->_right . ' > ' . $right_key_near . ' AND ' . $this->_left . ' < ' . $eInfo[$this->_right];
+ } elseif ($right_key_near < $right_key) { // down
+ echo "alert('move down');";
+ $skew_edit = $right_key_near - $left_key + 1 - $skew_tree;
+ $sql = 'UPDATE ' . $this->_table . '
+ SET
+ ' . $this->_left . ' = IF(' . $this->_right . ' <= ' . $right_key . ', ' . $this->_left . ' + ' . $skew_edit . ', IF(' . $this->_left . ' > ' . $right_key . ', ' . $this->_left . ' - ' . $skew_tree . ', ' . $this->_left . ')),
+ ' . $this->_level . ' = IF(' . $this->_right . ' <= ' . $right_key . ', ' . $this->_level . ' + ' . $skew_level . ', ' . $this->_level . '),
+ ' . $this->_right . ' = IF(' . $this->_right . ' <= ' . $right_key . ', ' . $this->_right . ' + ' . $skew_edit . ', IF(' . $this->_right . ' <= ' . $right_key_near . ', ' . $this->_right . ' - ' . $skew_tree . ', ' . $this->_right . '))
+ WHERE
+ ' . $this->_right . ' > ' . $left_key . ' AND ' . $this->_left . ' <= ' . $right_key_near;
+ }
+
+ if (isset($sql)) {
+ $this->_db->beginTransaction();
+ try {
+ $this->_db->query($sql);
+ //$afrows = $this->_db->get
+ $this->_db->commit();
+ } catch (Exception $e) {
+ $this->_db->rollBack();
+ echo $e->getMessage();
+ echo "
\r\n";
+ echo $sql;
+ echo "
\r\n";
+ exit();
+ }
+ }
+
+ echo "alert('node added')";
+ }
+
/**
* set name of id field
*
@@ -397,78 +469,6 @@ public function moveNode($eId, $pId, $aId = 0)
}
}
- public function __moveNode($eId, $pId, $aId = 0)
- {
- $eInfo = $this->getNodeInfo($eId);
- $level = $eInfo[$this->_level];
- $left_key = $eInfo[$this->_left];
- $right_key = $eInfo[$this->_right];
- $right_key_near = 0;
- $left_key_near = 0;
- $skew_level = 0;
-
- if ($pId != 0) {
- $pInfo = $this->getNodeInfo($pId);
- $skew_level = $pInfo[$this->_level] - $eInfo[$this->_level] + 1;
- }
- if ($aId != 0) {
- $aInfo = $this->getNodeInfo($aId);
- }
-
- if ($pId == 0) { //move to root
- $right_key_near = $this->_db->fetchOne('SELECT MAX(' . $this->_right . ') FROM ' . $this->_table);
- } elseif (isset($aInfo) && $aId != 0 && $pId == $eInfo[$this->_pid]) { // if we have after ID
- $right_key_near = $aInfo[$this->_right];
- $left_key_near = $aInfo[$this->_left];
- } elseif (isset($pInfo) && $aId == 0 && $pId == $eInfo[$this->_pid]) { // if we do not have after ID
- $right_key_near = $pInfo[$this->_left];
- } elseif (isset($pInfo) && $pId != $eInfo[$this->_pid]) {
- $right_key_near = $pInfo[$this->_right] - 1;
- }
-
- $skew_tree = $eInfo[$this->_right] - $eInfo[$this->_left] + 1;
- echo "alert('" . $right_key_near . "');";
-
- if ($right_key_near > $right_key) { // up
- echo "alert('move up');";
- $skew_edit = $right_key_near - $left_key + 1;
- $sql = 'UPDATE ' . $this->_table . '
- SET
- ' . $this->_right . ' = IF(' . $this->_left . ' >= ' . $eInfo[$this->_left] . ', ' . $this->_right . ' + ' . $skew_edit . ', IF(' . $this->_right . ' < ' . $eInfo[$this->_left] . ', ' . $this->_right . ' + ' . $skew_tree . ', ' . $this->_right . ')),
- ' . $this->_level . ' = IF(' . $this->_left . ' >= ' . $eInfo[$this->_left] . ', ' . $this->_level . ' + ' . $skew_level . ', ' . $this->_level . '),
- ' . $this->_left . ' = IF(' . $this->_left . ' >= ' . $eInfo[$this->_left] . ', ' . $this->_left . ' + ' . $skew_edit . ', IF(' . $this->_left . ' > ' . $right_key_near . ', ' . $this->_left . ' + ' . $skew_tree . ', ' . $this->_left . '))
- WHERE ' . $this->_right . ' > ' . $right_key_near . ' AND ' . $this->_left . ' < ' . $eInfo[$this->_right];
- } elseif ($right_key_near < $right_key) { // down
- echo "alert('move down');";
- $skew_edit = $right_key_near - $left_key + 1 - $skew_tree;
- $sql = 'UPDATE ' . $this->_table . '
- SET
- ' . $this->_left . ' = IF(' . $this->_right . ' <= ' . $right_key . ', ' . $this->_left . ' + ' . $skew_edit . ', IF(' . $this->_left . ' > ' . $right_key . ', ' . $this->_left . ' - ' . $skew_tree . ', ' . $this->_left . ')),
- ' . $this->_level . ' = IF(' . $this->_right . ' <= ' . $right_key . ', ' . $this->_level . ' + ' . $skew_level . ', ' . $this->_level . '),
- ' . $this->_right . ' = IF(' . $this->_right . ' <= ' . $right_key . ', ' . $this->_right . ' + ' . $skew_edit . ', IF(' . $this->_right . ' <= ' . $right_key_near . ', ' . $this->_right . ' - ' . $skew_tree . ', ' . $this->_right . '))
- WHERE
- ' . $this->_right . ' > ' . $left_key . ' AND ' . $this->_left . ' <= ' . $right_key_near;
- }
-
- if (isset($sql)) {
- $this->_db->beginTransaction();
- try {
- $this->_db->query($sql);
- //$afrows = $this->_db->get
- $this->_db->commit();
- } catch (Exception $e) {
- $this->_db->rollBack();
- echo $e->getMessage();
- echo "
\r\n";
- echo $sql;
- echo "
\r\n";
- exit();
- }
- }
-
- echo "alert('node added')";
- }
-
public function addTable($tableName, $joinCondition, $fields = '*')
{
$this->_extTables[$tableName] = [
@@ -477,13 +477,6 @@ public function addTable($tableName, $joinCondition, $fields = '*')
];
}
- protected function _addExtTablesToSelect(Zend_Db_Select &$select)
- {
- foreach ($this->_extTables as $tableName => $info) {
- $select->joinInner($tableName, $info['joinCondition'], $info['fields']);
- }
- }
-
public function getChildren($ID, $start_level = 0, $end_level = 0)
{
try {
@@ -534,4 +527,11 @@ public function getNode($nodeId)
return new Varien_Db_Tree_Node($data, $this->getKeys());
}
+
+ protected function _addExtTablesToSelect(Zend_Db_Select &$select)
+ {
+ foreach ($this->_extTables as $tableName => $info) {
+ $select->joinInner($tableName, $info['joinCondition'], $info['fields']);
+ }
+ }
}
diff --git a/lib/Varien/Db/Tree/Node.php b/lib/Varien/Db/Tree/Node.php
index b124567c743..0c638a73306 100644
--- a/lib/Varien/Db/Tree/Node.php
+++ b/lib/Varien/Db/Tree/Node.php
@@ -18,6 +18,8 @@
class Varien_Db_Tree_Node
{
+ public $hasChild = false;
+ public $numChild = 0;
private $left;
private $right;
private $id;
@@ -25,9 +27,6 @@ class Varien_Db_Tree_Node
private $level;
private $data;
- public $hasChild = false;
- public $numChild = 0;
-
/**
* Varien_Db_Tree_Node constructor.
* @param array $nodeData
diff --git a/lib/Varien/Directory/Collection.php b/lib/Varien/Directory/Collection.php
index 7fff91e61ad..95e7c5d905d 100644
--- a/lib/Varien/Directory/Collection.php
+++ b/lib/Varien/Directory/Collection.php
@@ -50,6 +50,29 @@ public function __construct($path, $isRecursion = true, $recursionLevel = 0)
$this->parseDir();
}
}
+ /**
+ * display this collection as array
+ *
+ * @return array
+ */
+ public function __toArray()
+ {
+ $arr = [];
+ $this->toArray($arr);
+ return $arr;
+ }
+ /**
+ * get this collection as xml
+ * @param bool $addOpenTag - add or not header of xml
+ * @param string $rootName - root element name
+ * @return none
+ */
+ public function __toXml($addOpenTag = true, $rootName = 'Struct')
+ {
+ $xml = '';
+ $this->toXml($xml, $addOpenTag, $rootName);
+ return $xml;
+ }
/**
* Get name of this directory
*
@@ -159,23 +182,6 @@ public function addItem(IFactory $item)
{
$this->_items[] = $item;
}
- /**
- * parse this directory
- *
- * @return none
- */
- protected function parseDir()
- {
- $this->clear();
- $iter = new RecursiveDirectoryIterator($this->getPath());
- while ($iter->valid()) {
- $curr = (string) $iter->getSubPathname();
- if (!$iter->isDot() && $curr[0] != '.') {
- $this->addItem(Varien_Directory_Factory::getFactory($iter->current(), $this->getRecursion(), $this->getRecursionLevel()));
- }
- $iter->next();
- }
- }
/**
* set filter using
*
@@ -274,27 +280,6 @@ public function getDirsName(&$dirs)
$dirs[] = $this->getDirName();
}
}
- /**
- * set filters for files
- *
- * @param array $filter - array of filters
- * @return none
- */
- protected function setFilesFilter($filter)
- {
- $this->walk('setFilesFilter', [$filter]);
- }
- /**
- * display this collection as array
- *
- * @return array
- */
- public function __toArray()
- {
- $arr = [];
- $this->toArray($arr);
- return $arr;
- }
/**
* display this collection as array
* @param array &$arr - this collection array
@@ -309,18 +294,6 @@ public function toArray(&$arr)
$this->walk('toArray', [&$arr]);
}
}
- /**
- * get this collection as xml
- * @param bool $addOpenTag - add or not header of xml
- * @param string $rootName - root element name
- * @return none
- */
- public function __toXml($addOpenTag = true, $rootName = 'Struct')
- {
- $xml = '';
- $this->toXml($xml, $addOpenTag, $rootName);
- return $xml;
- }
/**
* get this collection as xml
* @param string &$xml - xml
@@ -345,6 +318,47 @@ public function toXml(&$xml, $recursionLevel = 0, $addOpenTag = true, $rootName
$xml .= '' . $rootName . '>' . "\n";
}
}
+ /**
+ * add filter
+ * @return none
+ */
+ public function addFilter($field, $value)
+ {
+ $filter = [];
+ $filter['field'] = $field;
+ $filter['value'] = $value;
+ $this->_filters[] = $filter;
+ $this->_isFiltersRendered = false;
+ $this->walk('addFilter', [$field, $value]);
+ return $this;
+ }
+ /**
+ * parse this directory
+ *
+ * @return none
+ */
+ protected function parseDir()
+ {
+ $this->clear();
+ $iter = new RecursiveDirectoryIterator($this->getPath());
+ while ($iter->valid()) {
+ $curr = (string) $iter->getSubPathname();
+ if (!$iter->isDot() && $curr[0] != '.') {
+ $this->addItem(Varien_Directory_Factory::getFactory($iter->current(), $this->getRecursion(), $this->getRecursionLevel()));
+ }
+ $iter->next();
+ }
+ }
+ /**
+ * set filters for files
+ *
+ * @param array $filter - array of filters
+ * @return none
+ */
+ protected function setFilesFilter($filter)
+ {
+ $this->walk('setFilesFilter', [$filter]);
+ }
/**
* apply filters
* @return none
@@ -403,20 +417,6 @@ protected function _renderFilters()
}
$this->setFilesFilter($filter);
}
- /**
- * add filter
- * @return none
- */
- public function addFilter($field, $value)
- {
- $filter = [];
- $filter['field'] = $field;
- $filter['value'] = $value;
- $this->_filters[] = $filter;
- $this->_isFiltersRendered = false;
- $this->walk('addFilter', [$field, $value]);
- return $this;
- }
}
/* Example */
diff --git a/lib/Varien/File/Uploader.php b/lib/Varien/File/Uploader.php
index cca0c7ccd7f..6180390191e 100644
--- a/lib/Varien/File/Uploader.php
+++ b/lib/Varien/File/Uploader.php
@@ -36,6 +36,14 @@ class Varien_File_Uploader
UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload',
];
+ public const SINGLE_STYLE = 0;
+ public const MULTIPLE_STYLE = 1;
+
+ /**
+ * @deprecated Use UPLOAD_ERR_NO_FILE instead
+ */
+ public const TMP_NAME_EMPTY = UPLOAD_ERR_NO_FILE;
+
/**
* Uploaded file handle (copy of $_FILES[] element)
*
@@ -138,14 +146,6 @@ class Varien_File_Uploader
*/
protected $_validateCallbacks = [];
- public const SINGLE_STYLE = 0;
- public const MULTIPLE_STYLE = 1;
-
- /**
- * @deprecated Use UPLOAD_ERR_NO_FILE instead
- */
- public const TMP_NAME_EMPTY = UPLOAD_ERR_NO_FILE;
-
/**
* Resulting of uploaded file
*
@@ -167,17 +167,6 @@ public function __construct($fileId)
}
}
- /**
- * After save logic
- *
- * @param array $result
- * @return Varien_File_Uploader
- */
- protected function _afterSave($result)
- {
- return $this;
- }
-
/**
* Used to save uploaded file into destination folder with
* original or new file name (if specified)
@@ -241,49 +230,6 @@ public function save($destinationFolder, $newFileName = null)
return $this->_result;
}
- /**
- * Move files from TMP folder into destination folder
- *
- * @param string $tmpPath
- * @param string $destPath
- * @return bool
- */
- protected function _moveFile($tmpPath, $destPath)
- {
- return move_uploaded_file($tmpPath, $destPath);
- }
-
- /**
- * Validate file before save
- *
- * @access public
- */
- protected function _validateFile()
- {
- if ($this->_fileExists === false) {
- return;
- }
-
- //is file extension allowed
- if (!$this->checkAllowedExtension($this->getFileExtension())) {
- throw new Exception('Disallowed file type.');
- }
-
- /*
- * Validate MIME-Types.
- */
- if (!$this->checkMimeType($this->_validMimeTypes)) {
- throw new Exception('Invalid MIME type.');
- }
-
- //run validate callbacks
- foreach ($this->_validateCallbacks as $params) {
- if (is_object($params['object']) && method_exists($params['object'], $params['method'])) {
- $params['object']->{$params['method']}($this->_file['tmp_name']);
- }
- }
- }
-
/**
* Returns extension of the uploaded file
*
@@ -358,14 +304,6 @@ public function correctFileNameCase($fileName)
return $fileName;
}
- protected static function _addDirSeparator($dir)
- {
- if (substr($dir, -1) != DIRECTORY_SEPARATOR) {
- $dir .= DIRECTORY_SEPARATOR;
- }
- return $dir;
- }
-
/**
* Used to check if uploaded file mime type is valid or not
*
@@ -497,6 +435,103 @@ public function chechAllowedExtension($extension)
return $this->checkAllowedExtension($extension);
}
+ public static function getNewFileName($destFile)
+ {
+ $fileInfo = pathinfo($destFile);
+ if (file_exists($destFile)) {
+ $index = 1;
+ $baseName = $fileInfo['filename'] . '.' . $fileInfo['extension'];
+ while (file_exists($fileInfo['dirname'] . DIRECTORY_SEPARATOR . $baseName)) {
+ $baseName = $fileInfo['filename'] . '_' . $index . '.' . $fileInfo['extension'];
+ $index++;
+ }
+ $destFileName = $baseName;
+ } else {
+ return $fileInfo['basename'];
+ }
+
+ return $destFileName;
+ }
+
+ public static function getDispretionPath($fileName)
+ {
+ $char = 0;
+ $dispretionPath = '';
+ while (($char < 2) && ($char < strlen($fileName))) {
+ if (empty($dispretionPath)) {
+ $dispretionPath = DIRECTORY_SEPARATOR
+ . ('.' == $fileName[$char] ? '_' : $fileName[$char]);
+ } else {
+ $dispretionPath = self::_addDirSeparator($dispretionPath)
+ . ('.' == $fileName[$char] ? '_' : $fileName[$char]);
+ }
+ $char++;
+ }
+ return $dispretionPath;
+ }
+
+ /**
+ * After save logic
+ *
+ * @param array $result
+ * @return Varien_File_Uploader
+ */
+ protected function _afterSave($result)
+ {
+ return $this;
+ }
+
+ /**
+ * Move files from TMP folder into destination folder
+ *
+ * @param string $tmpPath
+ * @param string $destPath
+ * @return bool
+ */
+ protected function _moveFile($tmpPath, $destPath)
+ {
+ return move_uploaded_file($tmpPath, $destPath);
+ }
+
+ /**
+ * Validate file before save
+ *
+ * @access public
+ */
+ protected function _validateFile()
+ {
+ if ($this->_fileExists === false) {
+ return;
+ }
+
+ //is file extension allowed
+ if (!$this->checkAllowedExtension($this->getFileExtension())) {
+ throw new Exception('Disallowed file type.');
+ }
+
+ /*
+ * Validate MIME-Types.
+ */
+ if (!$this->checkMimeType($this->_validMimeTypes)) {
+ throw new Exception('Invalid MIME type.');
+ }
+
+ //run validate callbacks
+ foreach ($this->_validateCallbacks as $params) {
+ if (is_object($params['object']) && method_exists($params['object'], $params['method'])) {
+ $params['object']->{$params['method']}($this->_file['tmp_name']);
+ }
+ }
+ }
+
+ protected static function _addDirSeparator($dir)
+ {
+ if (substr($dir, -1) != DIRECTORY_SEPARATOR) {
+ $dir .= DIRECTORY_SEPARATOR;
+ }
+ return $dir;
+ }
+
private function _getMimeType()
{
return $this->_file['type'];
@@ -552,39 +587,4 @@ private function _createDestinationFolder($destinationFolder)
}
return $this;
}
-
- public static function getNewFileName($destFile)
- {
- $fileInfo = pathinfo($destFile);
- if (file_exists($destFile)) {
- $index = 1;
- $baseName = $fileInfo['filename'] . '.' . $fileInfo['extension'];
- while (file_exists($fileInfo['dirname'] . DIRECTORY_SEPARATOR . $baseName)) {
- $baseName = $fileInfo['filename'] . '_' . $index . '.' . $fileInfo['extension'];
- $index++;
- }
- $destFileName = $baseName;
- } else {
- return $fileInfo['basename'];
- }
-
- return $destFileName;
- }
-
- public static function getDispretionPath($fileName)
- {
- $char = 0;
- $dispretionPath = '';
- while (($char < 2) && ($char < strlen($fileName))) {
- if (empty($dispretionPath)) {
- $dispretionPath = DIRECTORY_SEPARATOR
- . ('.' == $fileName[$char] ? '_' : $fileName[$char]);
- } else {
- $dispretionPath = self::_addDirSeparator($dispretionPath)
- . ('.' == $fileName[$char] ? '_' : $fileName[$char]);
- }
- $char++;
- }
- return $dispretionPath;
- }
}
diff --git a/lib/Varien/Filter/Template/Simple.php b/lib/Varien/Filter/Template/Simple.php
index 218e67ebc23..7ca4621f320 100644
--- a/lib/Varien/Filter/Template/Simple.php
+++ b/lib/Varien/Filter/Template/Simple.php
@@ -47,17 +47,6 @@ public function setTags($start, $end)
return $this;
}
- /**
- * Return result of getData method for matched variables
- *
- * @param array $matches
- * @return mixed
- */
- protected function _filterDataItem($matches)
- {
- return $this->getData($matches[1]);
- }
-
/**
* Insert data to template
*
@@ -72,4 +61,15 @@ public function filter($value)
$value,
);
}
+
+ /**
+ * Return result of getData method for matched variables
+ *
+ * @param array $matches
+ * @return mixed
+ */
+ protected function _filterDataItem($matches)
+ {
+ return $this->getData($matches[1]);
+ }
}
diff --git a/lib/Varien/Http/Adapter/Curl.php b/lib/Varien/Http/Adapter/Curl.php
index e5518fdd6c7..1b0d1d14acc 100644
--- a/lib/Varien/Http/Adapter/Curl.php
+++ b/lib/Varien/Http/Adapter/Curl.php
@@ -57,33 +57,6 @@ class Varien_Http_Adapter_Curl implements Zend_Http_Client_Adapter_Interface
*/
protected $_options = [];
- /**
- * Apply current configuration array to transport resource
- *
- * @return Varien_Http_Adapter_Curl
- */
- protected function _applyConfig()
- {
- curl_setopt_array($this->_getResource(), $this->_options);
-
- if (empty($this->_config)) {
- return $this;
- }
-
- $verifyPeer = isset($this->_config['verifypeer']) ? $this->_config['verifypeer'] : 0;
- curl_setopt($this->_getResource(), CURLOPT_SSL_VERIFYPEER, $verifyPeer);
-
- $verifyHost = isset($this->_config['verifyhost']) ? $this->_config['verifyhost'] : 0;
- curl_setopt($this->_getResource(), CURLOPT_SSL_VERIFYHOST, $verifyHost);
-
- foreach (array_keys($this->_config) as $param) {
- if (array_key_exists($param, $this->_allowedParams)) {
- curl_setopt($this->_getResource(), $this->_allowedParams[$param], $this->_config[$param]);
- }
- }
- return $this;
- }
-
/**
* Set array of additional cURL options
*
@@ -219,19 +192,6 @@ public function close()
return $this;
}
- /**
- * Returns a cURL handle on success
- *
- * @return resource|CurlHandle
- */
- protected function _getResource()
- {
- if (is_null($this->_resource)) {
- $this->_resource = curl_init();
- }
- return $this->_resource;
- }
-
/**
* Get last error number
*
@@ -304,4 +264,44 @@ public function multiRequest($urls, $options = [])
curl_multi_close($multihandle);
return $result;
}
+
+ /**
+ * Apply current configuration array to transport resource
+ *
+ * @return Varien_Http_Adapter_Curl
+ */
+ protected function _applyConfig()
+ {
+ curl_setopt_array($this->_getResource(), $this->_options);
+
+ if (empty($this->_config)) {
+ return $this;
+ }
+
+ $verifyPeer = isset($this->_config['verifypeer']) ? $this->_config['verifypeer'] : 0;
+ curl_setopt($this->_getResource(), CURLOPT_SSL_VERIFYPEER, $verifyPeer);
+
+ $verifyHost = isset($this->_config['verifyhost']) ? $this->_config['verifyhost'] : 0;
+ curl_setopt($this->_getResource(), CURLOPT_SSL_VERIFYHOST, $verifyHost);
+
+ foreach (array_keys($this->_config) as $param) {
+ if (array_key_exists($param, $this->_allowedParams)) {
+ curl_setopt($this->_getResource(), $this->_allowedParams[$param], $this->_config[$param]);
+ }
+ }
+ return $this;
+ }
+
+ /**
+ * Returns a cURL handle on success
+ *
+ * @return resource|CurlHandle
+ */
+ protected function _getResource()
+ {
+ if (is_null($this->_resource)) {
+ $this->_resource = curl_init();
+ }
+ return $this->_resource;
+ }
}
diff --git a/lib/Varien/Http/Client.php b/lib/Varien/Http/Client.php
index 6e40e251ca3..356d277f88c 100644
--- a/lib/Varien/Http/Client.php
+++ b/lib/Varien/Http/Client.php
@@ -36,14 +36,6 @@ public function __construct($uri = null, $config = null)
parent::__construct($uri, $config);
}
- protected function _trySetCurlAdapter()
- {
- if (extension_loaded('curl')) {
- $this->setAdapter(new Varien_Http_Adapter_Curl());
- }
- return $this;
- }
-
public function request($method = null)
{
$this->_trySetCurlAdapter();
@@ -62,6 +54,14 @@ public function setUrlEncodeBody($flag)
return $this;
}
+ protected function _trySetCurlAdapter()
+ {
+ if (extension_loaded('curl')) {
+ $this->setAdapter(new Varien_Http_Adapter_Curl());
+ }
+ return $this;
+ }
+
/**
* Adding custom functionality to decode data after
* standard prepare functionality
diff --git a/lib/Varien/Image.php b/lib/Varien/Image.php
index a620a9b9059..f760f9e8fc5 100644
--- a/lib/Varien/Image.php
+++ b/lib/Varien/Image.php
@@ -285,20 +285,6 @@ public function setWatermarkHeigth($heigth)
return $this;
}
- /**
- * Retrieve image adapter object
- *
- * @param string $adapter
- * @return Varien_Image_Adapter_Abstract
- */
- protected function _getAdapter($adapter = null)
- {
- if (!isset($this->_adapter)) {
- $this->_adapter = Varien_Image_Adapter::factory($adapter);
- }
- return $this->_adapter;
- }
-
/**
* Retrieve original image width
*
@@ -318,4 +304,18 @@ public function getOriginalHeight()
{
return $this->_getAdapter()->getOriginalHeight();
}
+
+ /**
+ * Retrieve image adapter object
+ *
+ * @param string $adapter
+ * @return Varien_Image_Adapter_Abstract
+ */
+ protected function _getAdapter($adapter = null)
+ {
+ if (!isset($this->_adapter)) {
+ $this->_adapter = Varien_Image_Adapter::factory($adapter);
+ }
+ return $this->_adapter;
+ }
}
diff --git a/lib/Varien/Image/Adapter/Abstract.php b/lib/Varien/Image/Adapter/Abstract.php
index 938df7a322e..276a99343a2 100644
--- a/lib/Varien/Image/Adapter/Abstract.php
+++ b/lib/Varien/Image/Adapter/Abstract.php
@@ -20,13 +20,6 @@
abstract class Varien_Image_Adapter_Abstract
{
- public $fileName = null;
-
- /**
- * @var int Color used to fill space when rotating image, do not confuse it with $_backgroundColor
- */
- public $imageBackgroundColor = 0;
-
public const POSITION_TOP_LEFT = 'top-left';
public const POSITION_TOP_RIGHT = 'top-right';
public const POSITION_BOTTOM_LEFT = 'bottom-left';
@@ -34,6 +27,12 @@ abstract class Varien_Image_Adapter_Abstract
public const POSITION_STRETCH = 'stretch';
public const POSITION_TILE = 'tile';
public const POSITION_CENTER = 'center';
+ public $fileName = null;
+
+ /**
+ * @var int Color used to fill space when rotating image, do not confuse it with $_backgroundColor
+ */
+ public $imageBackgroundColor = 0;
/**
* Image file type of the image $this->_fileName
diff --git a/lib/Varien/Image/Adapter/Gd2.php b/lib/Varien/Image/Adapter/Gd2.php
index 0be4facefa8..7abf2b23d9a 100644
--- a/lib/Varien/Image/Adapter/Gd2.php
+++ b/lib/Varien/Image/Adapter/Gd2.php
@@ -17,6 +17,13 @@
class Varien_Image_Adapter_Gd2 extends Varien_Image_Adapter_Abstract
{
protected $_requiredExtensions = ['gd'];
+
+ /**
+ * Whether image was resized or not
+ *
+ * @var bool
+ */
+ protected $_resized = false;
private static $_callbacks = [
IMAGETYPE_WEBP => ['output' => 'imagewebp', 'create' => 'imagecreatefromwebp'],
IMAGETYPE_GIF => ['output' => 'imagegif', 'create' => 'imagecreatefromgif'],
@@ -26,13 +33,6 @@ class Varien_Image_Adapter_Gd2 extends Varien_Image_Adapter_Abstract
IMAGETYPE_WBMP => ['output' => 'imagewbmp', 'create' => 'imagecreatefromwbmp'],
];
- /**
- * Whether image was resized or not
- *
- * @var bool
- */
- protected $_resized = false;
-
public function __construct()
{
// Initialize shutdown function
@@ -65,66 +65,6 @@ public function open($filename)
$this->_imageHandler = call_user_func($this->_getCallback('create'), $this->_fileName);
}
- /**
- * Checks whether memory limit is reached.
- *
- * @deprecated
- * @return bool
- */
- protected function _isMemoryLimitReached()
- {
- $limit = $this->_convertToByte(ini_get('memory_limit'));
- /**
- * In case if memory limit was converted to 0, treat it as unlimited
- */
- if ($limit === 0) {
- return false;
- }
- $size = getimagesize($this->_fileName);
- $requiredMemory = $size[0] * $size[1] * 3;
-
- return (memory_get_usage(true) + $requiredMemory) > $limit;
- }
-
- /**
- * Convert PHP memory limit value into bytes
- * Notation in value is supported only for PHP
- * Shorthand byte options are case insensitive
- *
- * @deprecated
- * @param string $memoryValue
- * @throws Varien_Exception
- * @see http://php.net/manual/en/faq.using.php#faq.using.shorthandbytes
- * @return int
- */
- protected function _convertToByte($memoryValue)
- {
- $memoryValue = trim($memoryValue);
- if (empty($memoryValue)) {
- return 0;
- }
- if (preg_match('~^([1-9][0-9]*)[\s]*(k|m|g)b?$~i', $memoryValue, $matches)) {
- $option = strtolower($matches[2]);
- $memoryValue = (int) $matches[1];
- switch ($option) {
- case 'g':
- $memoryValue *= 1024;
- // no break
- case 'm':
- $memoryValue *= 1024;
- // no break
- case 'k':
- $memoryValue *= 1024;
- break;
- default:
- break;
- }
- }
- $memoryValue = (int) $memoryValue;
-
- return $memoryValue > 0 ? $memoryValue : 0;
- }
-
public function save($destination = null, $newName = null)
{
$fileName = (!isset($destination)) ? $this->_fileName : $destination;
@@ -214,80 +154,6 @@ public function display()
call_user_func($this->_getCallback('output'), $this->_imageHandler);
}
- /**
- * Obtain function name, basing on image type and callback type
- *
- * @param string $callbackType
- * @param int $fileType
- * @return string
- * @throws Exception
- */
- private function _getCallback($callbackType, $fileType = null, $unsupportedText = 'Unsupported image format.')
- {
- if (null === $fileType) {
- $fileType = $this->_fileType;
- }
- if (empty(self::$_callbacks[$fileType])) {
- throw new Exception("{$unsupportedText}. Type: {$fileType}. File: {$this->_fileName}");
- }
- if (empty(self::$_callbacks[$fileType][$callbackType])) {
- throw new Exception("Callback not found. Callbacktype: {$callbackType}. File: {$this->_fileName}");
- }
- return self::$_callbacks[$fileType][$callbackType];
- }
-
- private function _fillBackgroundColor(&$imageResourceTo)
- {
- // try to keep transparency, if any
- if ($this->_keepTransparency) {
- $isAlpha = false;
- $transparentIndex = $this->_getTransparency($this->_imageHandler, $this->_fileType, $isAlpha);
- try {
- // fill truecolor png with alpha transparency
- if ($isAlpha) {
- if (!imagealphablending($imageResourceTo, false)) {
- throw new Exception('Failed to set alpha blending for PNG image. File: {$this->_fileName}');
- }
- $transparentAlphaColor = imagecolorallocatealpha($imageResourceTo, 0, 0, 0, 127);
- if (false === $transparentAlphaColor) {
- throw new Exception('Failed to allocate alpha transparency for PNG image. File: {$this->_fileName}');
- }
- if (!imagefill($imageResourceTo, 0, 0, $transparentAlphaColor)) {
- throw new Exception('Failed to fill PNG image with alpha transparency. File: {$this->_fileName}');
- }
- if (!imagesavealpha($imageResourceTo, true)) {
- throw new Exception('Failed to save alpha transparency into PNG image. File: {$this->_fileName}');
- }
-
- return $transparentAlphaColor;
- } elseif (false !== $transparentIndex) { // fill image with indexed non-alpha transparency
- $transparentColor = false;
- if ($transparentIndex >= 0 && $transparentIndex < imagecolorstotal($this->_imageHandler)) {
- list($r, $g, $b) = array_values(imagecolorsforindex($this->_imageHandler, $transparentIndex));
- $transparentColor = imagecolorallocate($imageResourceTo, (int) $r, (int) $g, (int) $b);
- }
- if (false === $transparentColor) {
- throw new Exception('Failed to allocate transparent color for image.');
- }
- if (!imagefill($imageResourceTo, 0, 0, $transparentColor)) {
- throw new Exception('Failed to fill image with transparency.');
- }
- imagecolortransparent($imageResourceTo, $transparentColor);
- return $transparentColor;
- }
- } catch (Exception $e) {
- // fallback to default background color
- }
- }
- list($r, $g, $b) = $this->_backgroundColor;
- $color = imagecolorallocate($imageResourceTo, (int) $r, (int) $g, (int) $b);
- if (!imagefill($imageResourceTo, 0, 0, $color)) {
- throw new Exception("Failed to fill image background with color {$r} {$g} {$b}. File: {$this->_fileName}");
- }
-
- return $color;
- }
-
/**
* Gives true for a PNG with alpha, false otherwise
*
@@ -299,28 +165,6 @@ public function checkAlpha($fileName)
return ((ord(file_get_contents($fileName, false, null, 25, 1)) & 6) & 4) == 4;
}
- private function _getTransparency($imageResource, $fileType, &$isAlpha = false, &$isTrueColor = false)
- {
- $isAlpha = false;
- $isTrueColor = false;
- // assume that transparency is supported by gif/png/webp only
- if (($fileType === IMAGETYPE_GIF) || ($fileType === IMAGETYPE_PNG) || ($fileType === IMAGETYPE_WEBP)) {
- // check for specific transparent color
- $transparentIndex = imagecolortransparent($imageResource);
- if ($transparentIndex >= 0) {
- return $transparentIndex;
- } elseif ($fileType === IMAGETYPE_PNG || $fileType === IMAGETYPE_WEBP) {
- $isAlpha = $this->checkAlpha($this->_fileName);
- $isTrueColor = true;
- return $transparentIndex; // -1
- }
- }
- if ($fileType === IMAGETYPE_JPEG) {
- $isTrueColor = true;
- }
- return false;
- }
-
/**
* Change the image size
*
@@ -638,6 +482,172 @@ public function checkDependencies()
}
}
+ /**
+ * Gives real mime-type with not considering file type field
+ *
+ * @return string
+ */
+ public function getMimeTypeWithOutFileType()
+ {
+ return $this->_fileMimeType;
+ }
+
+ /**
+ * Checks whether memory limit is reached.
+ *
+ * @deprecated
+ * @return bool
+ */
+ protected function _isMemoryLimitReached()
+ {
+ $limit = $this->_convertToByte(ini_get('memory_limit'));
+ /**
+ * In case if memory limit was converted to 0, treat it as unlimited
+ */
+ if ($limit === 0) {
+ return false;
+ }
+ $size = getimagesize($this->_fileName);
+ $requiredMemory = $size[0] * $size[1] * 3;
+
+ return (memory_get_usage(true) + $requiredMemory) > $limit;
+ }
+
+ /**
+ * Convert PHP memory limit value into bytes
+ * Notation in value is supported only for PHP
+ * Shorthand byte options are case insensitive
+ *
+ * @deprecated
+ * @param string $memoryValue
+ * @throws Varien_Exception
+ * @see http://php.net/manual/en/faq.using.php#faq.using.shorthandbytes
+ * @return int
+ */
+ protected function _convertToByte($memoryValue)
+ {
+ $memoryValue = trim($memoryValue);
+ if (empty($memoryValue)) {
+ return 0;
+ }
+ if (preg_match('~^([1-9][0-9]*)[\s]*(k|m|g)b?$~i', $memoryValue, $matches)) {
+ $option = strtolower($matches[2]);
+ $memoryValue = (int) $matches[1];
+ switch ($option) {
+ case 'g':
+ $memoryValue *= 1024;
+ // no break
+ case 'm':
+ $memoryValue *= 1024;
+ // no break
+ case 'k':
+ $memoryValue *= 1024;
+ break;
+ default:
+ break;
+ }
+ }
+ $memoryValue = (int) $memoryValue;
+
+ return $memoryValue > 0 ? $memoryValue : 0;
+ }
+
+ /**
+ * Obtain function name, basing on image type and callback type
+ *
+ * @param string $callbackType
+ * @param int $fileType
+ * @return string
+ * @throws Exception
+ */
+ private function _getCallback($callbackType, $fileType = null, $unsupportedText = 'Unsupported image format.')
+ {
+ if (null === $fileType) {
+ $fileType = $this->_fileType;
+ }
+ if (empty(self::$_callbacks[$fileType])) {
+ throw new Exception("{$unsupportedText}. Type: {$fileType}. File: {$this->_fileName}");
+ }
+ if (empty(self::$_callbacks[$fileType][$callbackType])) {
+ throw new Exception("Callback not found. Callbacktype: {$callbackType}. File: {$this->_fileName}");
+ }
+ return self::$_callbacks[$fileType][$callbackType];
+ }
+
+ private function _fillBackgroundColor(&$imageResourceTo)
+ {
+ // try to keep transparency, if any
+ if ($this->_keepTransparency) {
+ $isAlpha = false;
+ $transparentIndex = $this->_getTransparency($this->_imageHandler, $this->_fileType, $isAlpha);
+ try {
+ // fill truecolor png with alpha transparency
+ if ($isAlpha) {
+ if (!imagealphablending($imageResourceTo, false)) {
+ throw new Exception('Failed to set alpha blending for PNG image. File: {$this->_fileName}');
+ }
+ $transparentAlphaColor = imagecolorallocatealpha($imageResourceTo, 0, 0, 0, 127);
+ if (false === $transparentAlphaColor) {
+ throw new Exception('Failed to allocate alpha transparency for PNG image. File: {$this->_fileName}');
+ }
+ if (!imagefill($imageResourceTo, 0, 0, $transparentAlphaColor)) {
+ throw new Exception('Failed to fill PNG image with alpha transparency. File: {$this->_fileName}');
+ }
+ if (!imagesavealpha($imageResourceTo, true)) {
+ throw new Exception('Failed to save alpha transparency into PNG image. File: {$this->_fileName}');
+ }
+
+ return $transparentAlphaColor;
+ } elseif (false !== $transparentIndex) { // fill image with indexed non-alpha transparency
+ $transparentColor = false;
+ if ($transparentIndex >= 0 && $transparentIndex < imagecolorstotal($this->_imageHandler)) {
+ list($r, $g, $b) = array_values(imagecolorsforindex($this->_imageHandler, $transparentIndex));
+ $transparentColor = imagecolorallocate($imageResourceTo, (int) $r, (int) $g, (int) $b);
+ }
+ if (false === $transparentColor) {
+ throw new Exception('Failed to allocate transparent color for image.');
+ }
+ if (!imagefill($imageResourceTo, 0, 0, $transparentColor)) {
+ throw new Exception('Failed to fill image with transparency.');
+ }
+ imagecolortransparent($imageResourceTo, $transparentColor);
+ return $transparentColor;
+ }
+ } catch (Exception $e) {
+ // fallback to default background color
+ }
+ }
+ list($r, $g, $b) = $this->_backgroundColor;
+ $color = imagecolorallocate($imageResourceTo, (int) $r, (int) $g, (int) $b);
+ if (!imagefill($imageResourceTo, 0, 0, $color)) {
+ throw new Exception("Failed to fill image background with color {$r} {$g} {$b}. File: {$this->_fileName}");
+ }
+
+ return $color;
+ }
+
+ private function _getTransparency($imageResource, $fileType, &$isAlpha = false, &$isTrueColor = false)
+ {
+ $isAlpha = false;
+ $isTrueColor = false;
+ // assume that transparency is supported by gif/png/webp only
+ if (($fileType === IMAGETYPE_GIF) || ($fileType === IMAGETYPE_PNG) || ($fileType === IMAGETYPE_WEBP)) {
+ // check for specific transparent color
+ $transparentIndex = imagecolortransparent($imageResource);
+ if ($transparentIndex >= 0) {
+ return $transparentIndex;
+ } elseif ($fileType === IMAGETYPE_PNG || $fileType === IMAGETYPE_WEBP) {
+ $isAlpha = $this->checkAlpha($this->_fileName);
+ $isTrueColor = true;
+ return $transparentIndex; // -1
+ }
+ }
+ if ($fileType === IMAGETYPE_JPEG) {
+ $isTrueColor = true;
+ }
+ return false;
+ }
+
private function refreshImageDimensions()
{
$this->_imageSrcWidth = imagesx($this->_imageHandler);
@@ -654,14 +664,4 @@ private function _saveAlpha($imageHandler)
imagealphablending($imageHandler, false);
imagesavealpha($imageHandler, true);
}
-
- /**
- * Gives real mime-type with not considering file type field
- *
- * @return string
- */
- public function getMimeTypeWithOutFileType()
- {
- return $this->_fileMimeType;
- }
}
diff --git a/lib/Varien/Io/File.php b/lib/Varien/Io/File.php
index b431461c29a..b7edab4a509 100644
--- a/lib/Varien/Io/File.php
+++ b/lib/Varien/Io/File.php
@@ -23,32 +23,36 @@
class Varien_Io_File extends Varien_Io_Abstract
{
/**
- * Save initial working directory
+ * Used to grep ls() output
*
- * @var string
+ * @const
*/
- protected $_iwd;
+ public const GREP_FILES = 'files_only';
/**
- * Use virtual current working directory for application integrity
+ * Used to grep ls() output
*
- * @var string
+ * @const
*/
- protected $_cwd;
+ public const GREP_DIRS = 'dirs_only';
/**
- * Used to grep ls() output
+ * @var string[]
+ */
+ public const ALLOWED_IMAGES_EXTENSIONS = ['webp', 'jpg', 'jpeg', 'png', 'gif', 'bmp'];
+ /**
+ * Save initial working directory
*
- * @const
+ * @var string
*/
- public const GREP_FILES = 'files_only';
+ protected $_iwd;
/**
- * Used to grep ls() output
+ * Use virtual current working directory for application integrity
*
- * @const
+ * @var string
*/
- public const GREP_DIRS = 'dirs_only';
+ protected $_cwd;
/**
* If this variable is set to TRUE, our library will be able to automatically create
@@ -92,11 +96,6 @@ class Varien_Io_File extends Varien_Io_Abstract
*/
protected $_streamException;
- /**
- * @var string[]
- */
- public const ALLOWED_IMAGES_EXTENSIONS = ['webp', 'jpg', 'jpeg', 'png', 'gif', 'bmp'];
-
public function __construct()
{
// Initialize shutdown function
@@ -514,82 +513,6 @@ public function write($filename, $src, $mode = null)
return $result;
}
- /**
- * Check source is valid
- *
- * @param string|resource $src
- * @return bool
- *
- * @SuppressWarnings("PHPMD.ErrorControlOperator")
- */
- protected function _isValidSource($src)
- {
- // In case of a string
- if (is_string($src)) {
- // If its a file we check for null byte
- // If it's not a valid path, file_exists() will return a falsey value, and the @ will keep it from complaining about the bad string.
- return !(@file_exists($src) && str_contains($src, chr(0)));
- } elseif (is_resource($src)) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Check filename is writeable
- * If filename not exist check dirname writeable
- *
- * @param string $filename
- * @throws Varien_Io_Exception
- * @return bool
- *
- * @SuppressWarnings("PHPMD.ErrorControlOperator")
- */
- protected function _isFilenameWriteable($filename)
- {
- $error = false;
- if ($this->_cwd) {
- @chdir($this->_cwd);
- }
- if (file_exists($filename)) {
- if (!is_writeable($filename)) {
- $error = "File '{$this->getFilteredPath($filename)}' isn't writeable";
- }
- } else {
- $folder = dirname($filename);
- if (!is_writable($folder)) {
- $error = "Folder '{$this->getFilteredPath($folder)}' isn't writeable";
- }
- }
- if ($this->_iwd) {
- @chdir($this->_iwd);
- }
-
- if ($error) {
- throw new Varien_Io_Exception($error);
- }
- return true;
- }
-
- /**
- * Check source is file
- *
- * @param string $src
- * @return bool
- *
- * @SuppressWarnings("PHPMD.ErrorControlOperator")
- */
- protected function _checkSrcIsFile($src)
- {
- $result = false;
- if (is_string($src) && @is_readable($src) && is_file($src)) {
- $result = true;
- }
-
- return $result;
- }
-
/**
* File put content wrapper
*
@@ -856,6 +779,97 @@ public function ls($grep = null)
return $list;
}
+ public function dirsep()
+ {
+ return DIRECTORY_SEPARATOR;
+ }
+
+ public function dirname($file)
+ {
+ return $this->getCleanPath(dirname($file));
+ }
+
+ public function getStreamHandler()
+ {
+ return $this->_streamHandler;
+ }
+
+ /**
+ * Check source is valid
+ *
+ * @param string|resource $src
+ * @return bool
+ *
+ * @SuppressWarnings("PHPMD.ErrorControlOperator")
+ */
+ protected function _isValidSource($src)
+ {
+ // In case of a string
+ if (is_string($src)) {
+ // If its a file we check for null byte
+ // If it's not a valid path, file_exists() will return a falsey value, and the @ will keep it from complaining about the bad string.
+ return !(@file_exists($src) && str_contains($src, chr(0)));
+ } elseif (is_resource($src)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Check filename is writeable
+ * If filename not exist check dirname writeable
+ *
+ * @param string $filename
+ * @throws Varien_Io_Exception
+ * @return bool
+ *
+ * @SuppressWarnings("PHPMD.ErrorControlOperator")
+ */
+ protected function _isFilenameWriteable($filename)
+ {
+ $error = false;
+ if ($this->_cwd) {
+ @chdir($this->_cwd);
+ }
+ if (file_exists($filename)) {
+ if (!is_writeable($filename)) {
+ $error = "File '{$this->getFilteredPath($filename)}' isn't writeable";
+ }
+ } else {
+ $folder = dirname($filename);
+ if (!is_writable($folder)) {
+ $error = "Folder '{$this->getFilteredPath($folder)}' isn't writeable";
+ }
+ }
+ if ($this->_iwd) {
+ @chdir($this->_iwd);
+ }
+
+ if ($error) {
+ throw new Varien_Io_Exception($error);
+ }
+ return true;
+ }
+
+ /**
+ * Check source is file
+ *
+ * @param string $src
+ * @return bool
+ *
+ * @SuppressWarnings("PHPMD.ErrorControlOperator")
+ */
+ protected function _checkSrcIsFile($src)
+ {
+ $result = false;
+ if (is_string($src) && @is_readable($src) && is_file($src)) {
+ $result = true;
+ }
+
+ return $result;
+ }
+
/**
* Convert integer permissions format into human readable
*
@@ -930,19 +944,4 @@ protected function _getFileOwner($filename)
return $owner['name'] . ' / ' . $groupinfo;
}
-
- public function dirsep()
- {
- return DIRECTORY_SEPARATOR;
- }
-
- public function dirname($file)
- {
- return $this->getCleanPath(dirname($file));
- }
-
- public function getStreamHandler()
- {
- return $this->_streamHandler;
- }
}
diff --git a/lib/Varien/Object.php b/lib/Varien/Object.php
index 7f5452bce72..234bc04cc54 100644
--- a/lib/Varien/Object.php
+++ b/lib/Varien/Object.php
@@ -96,44 +96,129 @@ public function __construct()
$this->_construct();
}
- protected function _addFullNames()
+ /**
+ * Convert object attributes to array
+ *
+ * @param array $arrAttributes array of required attributes
+ * @return array
+ */
+ public function __toArray(array $arrAttributes = [])
{
- if (empty($this->_syncFieldsMap)) {
- return;
+ if (empty($arrAttributes)) {
+ return $this->_data;
}
- $existedShortKeys = array_intersect_key(array_flip($this->_syncFieldsMap), $this->_data);
- foreach ($existedShortKeys as $key => $fullFieldName) {
- $this->_data[$fullFieldName] = $this->_data[$key];
+ $arrRes = [];
+ foreach ($arrAttributes as $attribute) {
+ if (isset($this->_data[$attribute])) {
+ $arrRes[$attribute] = $this->_data[$attribute];
+ } else {
+ $arrRes[$attribute] = null;
+ }
}
+ return $arrRes;
}
/**
- * Inits mapping array of object's previously used fields to new fields.
- * Must be overloaded by descendants to set concrete fields map.
+ * Convert object attributes to XML
+ *
+ * @param array $arrAttributes array of required attributes
+ * @param string $rootName name of the root element
+ * @param bool $addOpenTag
+ * @param bool $addCdata
+ * @return string
*/
- protected function _initOldFieldsMap() {}
+ protected function __toXml(array $arrAttributes = [], $rootName = 'item', $addOpenTag = false, $addCdata = true)
+ {
+ $xml = '';
+ if ($addOpenTag) {
+ $xml .= '' . "\n";
+ }
+ if (!empty($rootName)) {
+ $xml .= '<' . $rootName . '>' . "\n";
+ }
+ $xmlModel = new Varien_Simplexml_Element('');
+ $arrData = $this->toArray($arrAttributes);
+ foreach ($arrData as $fieldName => $fieldValue) {
+ if ($addCdata === true) {
+ $fieldValue = "";
+ } else {
+ $fieldValue = $xmlModel->xmlentities($fieldValue);
+ }
+ $xml .= "<$fieldName>$fieldValue$fieldName>" . "\n";
+ }
+ if (!empty($rootName)) {
+ $xml .= '' . $rootName . '>' . "\n";
+ }
+ return $xml;
+ }
/**
- * Called after old fields are inited. Forms synchronization map to sync old fields and new fields
- * between each other.
+ * Convert object attributes to JSON
*
- * @return $this
+ * @param array $arrAttributes array of required attributes
+ * @return string
*/
- protected function _prepareSyncFieldsMap()
+ protected function __toJson(array $arrAttributes = [])
{
- $old2New = $this->_oldFieldsMap;
- $new2Old = array_flip($this->_oldFieldsMap);
- $this->_syncFieldsMap = array_merge($old2New, $new2Old);
- return $this;
+ $arrData = $this->toArray($arrAttributes);
+ return Zend_Json::encode($arrData);
}
/**
- * Internal constructor not depended on params. Can be used for object initialization
+ * Set/Get attribute wrapper
*
- * @return void
+ * @param string $method
+ * @param array $args
+ * @return mixed
*/
- protected function _construct() {}
+ public function __call($method, $args)
+ {
+ switch (substr($method, 0, 3)) {
+ case 'get':
+ $key = $this->_underscore(substr($method, 3));
+ return $this->getData($key, $args[0] ?? null);
+
+ case 'set':
+ $key = $this->_underscore(substr($method, 3));
+ return $this->setData($key, $args[0] ?? null);
+
+ case 'uns':
+ $key = $this->_underscore(substr($method, 3));
+ return $this->unsetData($key);
+
+ case 'has':
+ $key = $this->_underscore(substr($method, 3));
+ return isset($this->_data[$key]);
+ }
+ throw new Varien_Exception(
+ 'Invalid method ' . get_class($this) . '::' . $method . '(' . print_r($args, true) . ')',
+ );
+ }
+
+ /**
+ * Attribute getter (deprecated)
+ *
+ * @param string $var
+ * @return mixed
+ */
+ public function __get($var)
+ {
+ $var = $this->_underscore($var);
+ return $this->getData($var);
+ }
+
+ /**
+ * Attribute setter (deprecated)
+ *
+ * @param string $var
+ * @param mixed $value
+ */
+ public function __set($var, $value)
+ {
+ $var = $this->_underscore($var);
+ $this->setData($var, $value);
+ }
/**
* Set _isDeleted flag value (if $isDeleted param is defined) and return current flag value
@@ -375,17 +460,6 @@ public function getDataByKey($key)
return $this->_getData($key);
}
- /**
- * Get value from _data array without parse key
- *
- * @param string $key
- * @return mixed
- */
- protected function _getData($key)
- {
- return $this->_data[$key] ?? null;
- }
-
/**
* Set object data with calling setter method
*
@@ -443,29 +517,6 @@ public function hasData($key = '')
return array_key_exists($key, $this->_data);
}
- /**
- * Convert object attributes to array
- *
- * @param array $arrAttributes array of required attributes
- * @return array
- */
- public function __toArray(array $arrAttributes = [])
- {
- if (empty($arrAttributes)) {
- return $this->_data;
- }
-
- $arrRes = [];
- foreach ($arrAttributes as $attribute) {
- if (isset($this->_data[$attribute])) {
- $arrRes[$attribute] = $this->_data[$attribute];
- } else {
- $arrRes[$attribute] = null;
- }
- }
- return $arrRes;
- }
-
/**
* Public wrapper for __toArray
*
@@ -476,56 +527,6 @@ public function toArray(array $arrAttributes = [])
return $this->__toArray($arrAttributes);
}
- /**
- * Set required array elements
- *
- * @param array $arr
- * @return array
- */
- protected function _prepareArray(&$arr, array $elements = [])
- {
- foreach ($elements as $element) {
- if (!isset($arr[$element])) {
- $arr[$element] = null;
- }
- }
- return $arr;
- }
-
- /**
- * Convert object attributes to XML
- *
- * @param array $arrAttributes array of required attributes
- * @param string $rootName name of the root element
- * @param bool $addOpenTag
- * @param bool $addCdata
- * @return string
- */
- protected function __toXml(array $arrAttributes = [], $rootName = 'item', $addOpenTag = false, $addCdata = true)
- {
- $xml = '';
- if ($addOpenTag) {
- $xml .= '' . "\n";
- }
- if (!empty($rootName)) {
- $xml .= '<' . $rootName . '>' . "\n";
- }
- $xmlModel = new Varien_Simplexml_Element('');
- $arrData = $this->toArray($arrAttributes);
- foreach ($arrData as $fieldName => $fieldValue) {
- if ($addCdata === true) {
- $fieldValue = "";
- } else {
- $fieldValue = $xmlModel->xmlentities($fieldValue);
- }
- $xml .= "<$fieldName>$fieldValue$fieldName>" . "\n";
- }
- if (!empty($rootName)) {
- $xml .= '' . $rootName . '>' . "\n";
- }
- return $xml;
- }
-
/**
* Public wrapper for __toXml
*
@@ -539,18 +540,6 @@ public function toXml(array $arrAttributes = [], $rootName = 'item', $addOpenTag
return $this->__toXml($arrAttributes, $rootName, $addOpenTag, $addCdata);
}
- /**
- * Convert object attributes to JSON
- *
- * @param array $arrAttributes array of required attributes
- * @return string
- */
- protected function __toJson(array $arrAttributes = [])
- {
- $arrData = $this->toArray($arrAttributes);
- return Zend_Json::encode($arrData);
- }
-
/**
* Public wrapper for __toJson
*
@@ -596,61 +585,6 @@ public function toString($format = '')
return $str;
}
- /**
- * Set/Get attribute wrapper
- *
- * @param string $method
- * @param array $args
- * @return mixed
- */
- public function __call($method, $args)
- {
- switch (substr($method, 0, 3)) {
- case 'get':
- $key = $this->_underscore(substr($method, 3));
- return $this->getData($key, $args[0] ?? null);
-
- case 'set':
- $key = $this->_underscore(substr($method, 3));
- return $this->setData($key, $args[0] ?? null);
-
- case 'uns':
- $key = $this->_underscore(substr($method, 3));
- return $this->unsetData($key);
-
- case 'has':
- $key = $this->_underscore(substr($method, 3));
- return isset($this->_data[$key]);
- }
- throw new Varien_Exception(
- 'Invalid method ' . get_class($this) . '::' . $method . '(' . print_r($args, true) . ')',
- );
- }
-
- /**
- * Attribute getter (deprecated)
- *
- * @param string $var
- * @return mixed
- */
- public function __get($var)
- {
- $var = $this->_underscore($var);
- return $this->getData($var);
- }
-
- /**
- * Attribute setter (deprecated)
- *
- * @param string $var
- * @param mixed $value
- */
- public function __set($var, $value)
- {
- $var = $this->_underscore($var);
- $this->setData($var, $value);
- }
-
/**
* checks whether the object is empty
*
@@ -664,36 +598,6 @@ public function isEmpty()
return false;
}
- /**
- * Converts field names for setters and getters
- *
- * $this->setMyField($value) === $this->setData('my_field', $value)
- * Uses cache to eliminate unnecessary preg_replace
- *
- * @param string $name
- * @return string
- */
- protected function _underscore($name)
- {
- if (isset(self::$_underscoreCache[$name])) {
- return self::$_underscoreCache[$name];
- }
- #Varien_Profiler::start('underscore');
- $result = strtolower(preg_replace('/([A-Z])/', '_$1', lcfirst($name)));
- #Varien_Profiler::stop('underscore');
- self::$_underscoreCache[$name] = $result;
- return $result;
- }
-
- /**
- * @param string $name
- * @return string
- */
- protected function _camelize($name)
- {
- return uc_words($name, '');
- }
-
/**
* serialize object attributes
*
@@ -842,4 +746,100 @@ public function flagDirty($field, $flag = true)
}
return $this;
}
+
+ protected function _addFullNames()
+ {
+ if (empty($this->_syncFieldsMap)) {
+ return;
+ }
+
+ $existedShortKeys = array_intersect_key(array_flip($this->_syncFieldsMap), $this->_data);
+ foreach ($existedShortKeys as $key => $fullFieldName) {
+ $this->_data[$fullFieldName] = $this->_data[$key];
+ }
+ }
+
+ /**
+ * Inits mapping array of object's previously used fields to new fields.
+ * Must be overloaded by descendants to set concrete fields map.
+ */
+ protected function _initOldFieldsMap() {}
+
+ /**
+ * Called after old fields are inited. Forms synchronization map to sync old fields and new fields
+ * between each other.
+ *
+ * @return $this
+ */
+ protected function _prepareSyncFieldsMap()
+ {
+ $old2New = $this->_oldFieldsMap;
+ $new2Old = array_flip($this->_oldFieldsMap);
+ $this->_syncFieldsMap = array_merge($old2New, $new2Old);
+ return $this;
+ }
+
+ /**
+ * Internal constructor not depended on params. Can be used for object initialization
+ *
+ * @return void
+ */
+ protected function _construct() {}
+
+ /**
+ * Get value from _data array without parse key
+ *
+ * @param string $key
+ * @return mixed
+ */
+ protected function _getData($key)
+ {
+ return $this->_data[$key] ?? null;
+ }
+
+ /**
+ * Set required array elements
+ *
+ * @param array $arr
+ * @return array
+ */
+ protected function _prepareArray(&$arr, array $elements = [])
+ {
+ foreach ($elements as $element) {
+ if (!isset($arr[$element])) {
+ $arr[$element] = null;
+ }
+ }
+ return $arr;
+ }
+
+ /**
+ * Converts field names for setters and getters
+ *
+ * $this->setMyField($value) === $this->setData('my_field', $value)
+ * Uses cache to eliminate unnecessary preg_replace
+ *
+ * @param string $name
+ * @return string
+ */
+ protected function _underscore($name)
+ {
+ if (isset(self::$_underscoreCache[$name])) {
+ return self::$_underscoreCache[$name];
+ }
+ #Varien_Profiler::start('underscore');
+ $result = strtolower(preg_replace('/([A-Z])/', '_$1', lcfirst($name)));
+ #Varien_Profiler::stop('underscore');
+ self::$_underscoreCache[$name] = $result;
+ return $result;
+ }
+
+ /**
+ * @param string $name
+ * @return string
+ */
+ protected function _camelize($name)
+ {
+ return uc_words($name, '');
+ }
}
diff --git a/lib/Varien/Simplexml/Config.php b/lib/Varien/Simplexml/Config.php
index 626e5e9d8f8..1864c7919ed 100644
--- a/lib/Varien/Simplexml/Config.php
+++ b/lib/Varien/Simplexml/Config.php
@@ -383,37 +383,6 @@ public function removeCache()
return $this;
}
- /**
- * @param string $id
- * @return bool
- */
- protected function _loadCache($id)
- {
- return $this->getCache()->load($id);
- }
-
- /**
- * @param string $data
- * @param string $id
- * @param array $tags
- * @param int|boolean $lifetime
- * @return bool
- */
- protected function _saveCache($data, $id, $tags = [], $lifetime = false)
- {
- return $this->getCache()->save($data, $id, $tags, $lifetime);
- }
-
- /**
- * @todo check this, as there are no caches that implement remove() method
- * @param string $id
- * @return mixed
- */
- protected function _removeCache($id)
- {
- return $this->getCache()->remove($id);
- }
-
/**
* Imports XML file
*
@@ -533,4 +502,35 @@ public function extend(Varien_Simplexml_Config $config, $overwrite = true)
$this->getNode()->extend($config->getNode(), $overwrite);
return $this;
}
+
+ /**
+ * @param string $id
+ * @return bool
+ */
+ protected function _loadCache($id)
+ {
+ return $this->getCache()->load($id);
+ }
+
+ /**
+ * @param string $data
+ * @param string $id
+ * @param array $tags
+ * @param int|boolean $lifetime
+ * @return bool
+ */
+ protected function _saveCache($data, $id, $tags = [], $lifetime = false)
+ {
+ return $this->getCache()->save($data, $id, $tags, $lifetime);
+ }
+
+ /**
+ * @todo check this, as there are no caches that implement remove() method
+ * @param string $id
+ * @return mixed
+ */
+ protected function _removeCache($id)
+ {
+ return $this->getCache()->remove($id);
+ }
}
diff --git a/lib/Varien/Simplexml/Element.php b/lib/Varien/Simplexml/Element.php
index 7eaedcc1392..3be094d8ac3 100644
--- a/lib/Varien/Simplexml/Element.php
+++ b/lib/Varien/Simplexml/Element.php
@@ -204,40 +204,6 @@ public function asCanonicalArray()
return $this->_asArray(true);
}
- /**
- * Returns the node and children as an array
- *
- * @param bool $isCanonical - whether to ignore attributes
- * @return array|string
- */
- protected function _asArray($isCanonical = false)
- {
- $result = [];
- if (!$isCanonical) {
- // add attributes
- foreach ($this->attributes() as $attributeName => $attribute) {
- if ($attribute) {
- $result['@'][$attributeName] = (string) $attribute;
- }
- }
- }
- // add children values
- if ($this->hasChildren()) {
- foreach ($this->children() as $childName => $child) {
- $result[$childName] = $child->_asArray($isCanonical);
- }
- } else {
- if (empty($result)) {
- // return as string, if nothing was found
- $result = (string) $this;
- } else {
- // value has zero key element
- $result[0] = (string) $this;
- }
- }
- return $result;
- }
-
/**
* Makes nicely formatted XML from the node
*
@@ -455,4 +421,38 @@ public function setNode($path, $value, $overwrite = true)
}
return $this;
}
+
+ /**
+ * Returns the node and children as an array
+ *
+ * @param bool $isCanonical - whether to ignore attributes
+ * @return array|string
+ */
+ protected function _asArray($isCanonical = false)
+ {
+ $result = [];
+ if (!$isCanonical) {
+ // add attributes
+ foreach ($this->attributes() as $attributeName => $attribute) {
+ if ($attribute) {
+ $result['@'][$attributeName] = (string) $attribute;
+ }
+ }
+ }
+ // add children values
+ if ($this->hasChildren()) {
+ foreach ($this->children() as $childName => $child) {
+ $result[$childName] = $child->_asArray($isCanonical);
+ }
+ } else {
+ if (empty($result)) {
+ // return as string, if nothing was found
+ $result = (string) $this;
+ } else {
+ // value has zero key element
+ $result[0] = (string) $this;
+ }
+ }
+ return $result;
+ }
}
diff --git a/shell/abstract.php b/shell/abstract.php
index 983d82db4e0..ab26da615f7 100644
--- a/shell/abstract.php
+++ b/shell/abstract.php
@@ -83,6 +83,40 @@ public function __construct()
$this->_showHelp();
}
+ /**
+ * Run script
+ *
+ */
+ abstract public function run();
+
+ /**
+ * Retrieve Usage Help Message
+ *
+ */
+ public function usageHelp()
+ {
+ return <<_args[$name])) {
+ return $this->_args[$name];
+ }
+ return false;
+ }
+
/**
* Get Magento Root path (with last directory separator)
*
@@ -171,12 +205,6 @@ protected function _validate()
}
}
- /**
- * Run script
- *
- */
- abstract public function run();
-
/**
* Check is show usage help
*
@@ -187,32 +215,4 @@ protected function _showHelp()
die($this->usageHelp());
}
}
-
- /**
- * Retrieve Usage Help Message
- *
- */
- public function usageHelp()
- {
- return <<_args[$name])) {
- return $this->_args[$name];
- }
- return false;
- }
}
diff --git a/shell/indexer.php b/shell/indexer.php
index 48560754b37..866aad2a0fe 100644
--- a/shell/indexer.php
+++ b/shell/indexer.php
@@ -24,49 +24,6 @@
*/
class Mage_Shell_Indexer extends Mage_Shell_Abstract
{
- /**
- * Get Indexer instance
- *
- * @return Mage_Core_Model_Abstract|Mage_Index_Model_Indexer
- */
- protected function _getIndexer()
- {
- return $this->_factory->getSingleton($this->_factory->getIndexClassAlias());
- }
-
- /**
- * Parse string with indexers and return array of indexer instances
- *
- * @param string $string
- * @return array
- */
- protected function _parseIndexerString($string)
- {
- $processes = [];
- if ($string == 'all') {
- $collection = $this->_getIndexer()->getProcessesCollection();
- foreach ($collection as $process) {
- if ($process->getIndexer()->isVisible() === false) {
- continue;
- }
- $processes[] = $process;
- }
- } elseif (!empty($string)) {
- $codes = explode(',', $string);
- $codes = array_map('trim', $codes);
- $processes = $this->_getIndexer()->getProcessesCollectionByCodes($codes);
- foreach ($processes as $key => $process) {
- if ($process->getIndexer()->getVisibility() === false) {
- unset($processes[$key]);
- }
- }
- if ($this->_getIndexer()->hasErrors()) {
- echo implode(PHP_EOL, $this->_getIndexer()->getErrors()), PHP_EOL;
- }
- }
- return $processes;
- }
-
/**
* Run script
*
@@ -202,6 +159,48 @@ public function usageHelp()
USAGE;
}
+ /**
+ * Get Indexer instance
+ *
+ * @return Mage_Core_Model_Abstract|Mage_Index_Model_Indexer
+ */
+ protected function _getIndexer()
+ {
+ return $this->_factory->getSingleton($this->_factory->getIndexClassAlias());
+ }
+
+ /**
+ * Parse string with indexers and return array of indexer instances
+ *
+ * @param string $string
+ * @return array
+ */
+ protected function _parseIndexerString($string)
+ {
+ $processes = [];
+ if ($string == 'all') {
+ $collection = $this->_getIndexer()->getProcessesCollection();
+ foreach ($collection as $process) {
+ if ($process->getIndexer()->isVisible() === false) {
+ continue;
+ }
+ $processes[] = $process;
+ }
+ } elseif (!empty($string)) {
+ $codes = explode(',', $string);
+ $codes = array_map('trim', $codes);
+ $processes = $this->_getIndexer()->getProcessesCollectionByCodes($codes);
+ foreach ($processes as $key => $process) {
+ if ($process->getIndexer()->getVisibility() === false) {
+ unset($processes[$key]);
+ }
+ }
+ if ($this->_getIndexer()->hasErrors()) {
+ echo implode(PHP_EOL, $this->_getIndexer()->getErrors()), PHP_EOL;
+ }
+ }
+ return $processes;
+ }
}
$shell = new Mage_Shell_Indexer();
diff --git a/shell/log.php b/shell/log.php
index 60c7a24a805..0159e337db5 100644
--- a/shell/log.php
+++ b/shell/log.php
@@ -31,64 +31,6 @@ class Mage_Shell_Log extends Mage_Shell_Abstract
*/
protected $_log;
- /**
- * Retrieve Log instance
- *
- * @return Mage_Log_Model_Log
- */
- protected function _getLog()
- {
- if (is_null($this->_log)) {
- $this->_log = Mage::getModel('log/log');
- }
- return $this->_log;
- }
-
- /**
- * Convert count to human view
- *
- * @param int $number
- * @return string
- */
- protected function _humanCount($number)
- {
- if ($number < 1000) {
- return (string) $number;
- }
- if ($number < 1000000) {
- return sprintf('%.2fK', $number / 1000);
- }
-
- if ($number < 1000000000) {
- return sprintf('%.2fM', $number / 1000000);
- }
-
- return sprintf('%.2fB', $number / 1000000000);
- }
-
- /**
- * Convert size to human view
- *
- * @param int $number
- * @return string
- */
- protected function _humanSize($number)
- {
- if ($number < 1000) {
- return sprintf('%d b', $number);
- }
-
- if ($number < 1000000) {
- return sprintf('%.2fKb', $number / 1000);
- }
-
- if ($number < 1000000000) {
- return sprintf('%.2fMb', $number / 1000000);
- }
-
- return sprintf('%.2fGb', $number / 1000000000);
- }
-
/**
* Run script
*
@@ -181,6 +123,64 @@ public function usageHelp()
USAGE;
}
+
+ /**
+ * Retrieve Log instance
+ *
+ * @return Mage_Log_Model_Log
+ */
+ protected function _getLog()
+ {
+ if (is_null($this->_log)) {
+ $this->_log = Mage::getModel('log/log');
+ }
+ return $this->_log;
+ }
+
+ /**
+ * Convert count to human view
+ *
+ * @param int $number
+ * @return string
+ */
+ protected function _humanCount($number)
+ {
+ if ($number < 1000) {
+ return (string) $number;
+ }
+ if ($number < 1000000) {
+ return sprintf('%.2fK', $number / 1000);
+ }
+
+ if ($number < 1000000000) {
+ return sprintf('%.2fM', $number / 1000000);
+ }
+
+ return sprintf('%.2fB', $number / 1000000000);
+ }
+
+ /**
+ * Convert size to human view
+ *
+ * @param int $number
+ * @return string
+ */
+ protected function _humanSize($number)
+ {
+ if ($number < 1000) {
+ return sprintf('%d b', $number);
+ }
+
+ if ($number < 1000000) {
+ return sprintf('%.2fKb', $number / 1000);
+ }
+
+ if ($number < 1000000000) {
+ return sprintf('%.2fMb', $number / 1000000);
+ }
+
+ return sprintf('%.2fGb', $number / 1000000000);
+ }
}
$shell = new Mage_Shell_Log();