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 81bed891286..e9226fb052d 100644 --- a/app/code/core/Mage/Api2/Model/Acl/Global/Role.php +++ b/app/code/core/Mage/Api2/Model/Acl/Global/Role.php @@ -89,7 +89,7 @@ protected function _beforeSave() } //check and protect guest role - if (Mage_Api2_Model_Acl_Global_Role::isSystemRole($this) + if (self::isSystemRole($this) && $this->getRoleName() != $this->getOrigData('role_name')) { /** @var Mage_Core_Helper_Data $helper */ @@ -111,8 +111,8 @@ protected function _beforeSave() */ protected function _beforeDelete() { - if (Mage_Api2_Model_Acl_Global_Role::isSystemRole($this)) { - /** @var Mage_Core_Helper_Data $helper */ + if (self::isSystemRole($this)) { + /** @var $helper Mage_Core_Helper_Data */ $helper = Mage::helper('core'); Mage::throwException( diff --git a/app/code/core/Mage/Api2/Model/Resource.php b/app/code/core/Mage/Api2/Model/Resource.php index 0ef3bdaabcd..fa721437862 100644 --- a/app/code/core/Mage/Api2/Model/Resource.php +++ b/app/code/core/Mage/Api2/Model/Resource.php @@ -740,7 +740,7 @@ final protected function _applyCollectionModifiers(Varien_Data_Collection_Db $co $orderField = $this->getRequest()->getOrderField(); if (null !== $orderField) { - $operation = Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_READ; + $operation = self::OPERATION_ATTRIBUTE_READ; if (!is_string($orderField) || !array_key_exists($orderField, $this->getAvailableAttributes($this->getUserType(), $operation)) ) { diff --git a/app/code/core/Mage/Captcha/Helper/Data.php b/app/code/core/Mage/Captcha/Helper/Data.php index 681199561a6..d3cfe0ce2b5 100644 --- a/app/code/core/Mage/Captcha/Helper/Data.php +++ b/app/code/core/Mage/Captcha/Helper/Data.php @@ -96,7 +96,7 @@ public function getConfigNode($id, $store = null) */ public function getFonts() { - $node = Mage::getConfig()->getNode(Mage_Captcha_Helper_Data::XML_PATH_CAPTCHA_FONTS); + $node = Mage::getConfig()->getNode(self::XML_PATH_CAPTCHA_FONTS); $fonts = array(); if ($node) { foreach ($node->children() as $fontName => $fontNode) { diff --git a/app/code/core/Mage/Core/Model/Locale.php b/app/code/core/Mage/Core/Model/Locale.php index c0ab8b77a4d..c65abc82a89 100644 --- a/app/code/core/Mage/Core/Model/Locale.php +++ b/app/code/core/Mage/Core/Model/Locale.php @@ -579,7 +579,7 @@ public function utcDate($store = null, $date, $includeTime = false, $format = nu { $dateObj = $this->storeDate($store, $date, $includeTime); $dateObj->set($date, $format); - $dateObj->setTimezone(Mage_Core_Model_Locale::DEFAULT_TIMEZONE); + $dateObj->setTimezone(self::DEFAULT_TIMEZONE); return $dateObj; } diff --git a/app/code/core/Mage/Core/Model/Store.php b/app/code/core/Mage/Core/Model/Store.php index c58e23d0098..dd977237324 100644 --- a/app/code/core/Mage/Core/Model/Store.php +++ b/app/code/core/Mage/Core/Model/Store.php @@ -806,8 +806,8 @@ public function isCurrentlySecure() */ public function getBaseCurrencyCode() { - $configValue = $this->getConfig(Mage_Core_Model_Store::XML_PATH_PRICE_SCOPE); - if ($configValue == Mage_Core_Model_Store::PRICE_SCOPE_GLOBAL) { + $configValue = $this->getConfig(self::XML_PATH_PRICE_SCOPE); + if ($configValue == self::PRICE_SCOPE_GLOBAL) { return Mage::app()->getBaseCurrencyCode(); } else { return $this->getConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE); @@ -1156,7 +1156,7 @@ public function getCurrentUrl($fromStore = true) $storeParsedQuery[$k] = $v; } - if (!Mage::getStoreConfigFlag(Mage_Core_Model_Store::XML_PATH_STORE_IN_URL, $this->getCode())) { + if (!Mage::getStoreConfigFlag(self::XML_PATH_STORE_IN_URL, $this->getCode())) { $storeParsedQuery['___store'] = $this->getCode(); } if ($fromStore !== false) { diff --git a/app/code/core/Mage/Directory/Model/Currency.php b/app/code/core/Mage/Directory/Model/Currency.php index 8dbb3ec4bd5..42fcd8b2d62 100644 --- a/app/code/core/Mage/Directory/Model/Currency.php +++ b/app/code/core/Mage/Directory/Model/Currency.php @@ -137,7 +137,7 @@ public function getRate($toCurrency) { if (is_string($toCurrency)) { $code = $toCurrency; - } elseif ($toCurrency instanceof Mage_Directory_Model_Currency) { + } elseif ($toCurrency instanceof self) { $code = $toCurrency->getCurrencyCode(); } else { throw Mage::exception('Mage_Directory', Mage::helper('directory')->__('Invalid target currency.')); @@ -161,7 +161,7 @@ public function getAnyRate($toCurrency) { if (is_string($toCurrency)) { $code = $toCurrency; - } elseif ($toCurrency instanceof Mage_Directory_Model_Currency) { + } elseif ($toCurrency instanceof self) { $code = $toCurrency->getCurrencyCode(); } else { throw Mage::exception('Mage_Directory', Mage::helper('directory')->__('Invalid target currency.')); @@ -196,7 +196,7 @@ public function convert($price, $toCurrency = null) throw new Exception(Mage::helper('directory')->__( 'Undefined rate from "%s-%s".', $this->getCode(), - $toCurrency instanceof Mage_Directory_Model_Currency ? $toCurrency->getCode() : $toCurrency + $toCurrency instanceof self ? $toCurrency->getCode() : $toCurrency )); } @@ -346,7 +346,7 @@ public function getConfigBaseCurrencies() */ public function getCurrencyRates($currency, $toCurrencies = null) { - if ($currency instanceof Mage_Directory_Model_Currency) { + if ($currency instanceof self) { $currency = $currency->getCode(); } $data = $this->_getResource()->getCurrencyRates($currency, $toCurrencies); 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 34318b5c5e5..544150b63d9 100644 --- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php +++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php @@ -1474,12 +1474,12 @@ protected function _saveProducts() $previousType = $productType; } if (isset($rowData[self::COL_ATTR_SET]) && !is_null($rowData[self::COL_ATTR_SET])) { - $previousAttributeSet = $rowData[Mage_ImportExport_Model_Import_Entity_Product::COL_ATTR_SET]; + $previousAttributeSet = $rowData[self::COL_ATTR_SET]; } if (self::SCOPE_NULL == $rowScope) { // for multiselect attributes only if (!is_null($previousAttributeSet)) { - $rowData[Mage_ImportExport_Model_Import_Entity_Product::COL_ATTR_SET] = $previousAttributeSet; + $rowData[self::COL_ATTR_SET] = $previousAttributeSet; } if (is_null($productType) && !is_null($previousType)) { $productType = $previousType; diff --git a/app/code/core/Mage/Oauth/Model/Token.php b/app/code/core/Mage/Oauth/Model/Token.php index cbae2ab1d37..bc4f03871a1 100644 --- a/app/code/core/Mage/Oauth/Model/Token.php +++ b/app/code/core/Mage/Oauth/Model/Token.php @@ -151,7 +151,7 @@ public function authorize($userId, $userType) */ public function convertToAccess() { - if (Mage_Oauth_Model_Token::TYPE_REQUEST != $this->getType()) { + if (self::TYPE_REQUEST != $this->getType()) { Mage::throwException('Can not convert due to token is not request type'); } /** @var Mage_Oauth_Helper_Data $helper */ diff --git a/app/code/core/Mage/Paypal/Block/Iframe.php b/app/code/core/Mage/Paypal/Block/Iframe.php index 34c7746c304..b5ee61e1b5b 100644 --- a/app/code/core/Mage/Paypal/Block/Iframe.php +++ b/app/code/core/Mage/Paypal/Block/Iframe.php @@ -96,7 +96,7 @@ protected function _getBlock() $this->_block = $this->getAction() ->getLayout() ->createBlock('paypal/'.$this->_paymentMethodCode.'_iframe'); - if (!$this->_block instanceof Mage_Paypal_Block_Iframe) { + if (!$this->_block instanceof self) { Mage::throwException('Invalid block type'); } } diff --git a/app/code/core/Mage/Paypal/Model/Express/Checkout.php b/app/code/core/Mage/Paypal/Model/Express/Checkout.php index 76cd32ca8ca..f3eb41d69ff 100644 --- a/app/code/core/Mage/Paypal/Model/Express/Checkout.php +++ b/app/code/core/Mage/Paypal/Model/Express/Checkout.php @@ -404,7 +404,7 @@ public function start($returnUrl, $cancelUrl, $button = null) public function canSkipOrderReviewStep() { $isOnepageCheckout = !$this->_quote->getPayment() - ->getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_BUTTON); + ->getAdditionalInformation(self::PAYMENT_INFO_BUTTON); return $this->_config->isOrderReviewStepDisabled() && $isOnepageCheckout; } @@ -619,7 +619,7 @@ public function place($token, $shippingMethodCode = null) // commence redirecting to finish payment, if paypal requires it if ($order->getPayment()->getAdditionalInformation( - Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_REDIRECT + self::PAYMENT_INFO_TRANSPORT_REDIRECT )) { $this->_redirectUrl = $this->_config->getExpressCheckoutCompleteUrl($token); } diff --git a/app/code/core/Mage/PaypalUk/Model/Pro.php b/app/code/core/Mage/PaypalUk/Model/Pro.php index 53ea718f8d9..9a9f198b21e 100644 --- a/app/code/core/Mage/PaypalUk/Model/Pro.php +++ b/app/code/core/Mage/PaypalUk/Model/Pro.php @@ -87,7 +87,7 @@ protected function _getParentTransactionId(Varien_Object $payment) { if ($payment->getParentTransactionId()) { return $payment->getTransaction($payment->getParentTransactionId()) - ->getAdditionalInformation(Mage_PaypalUk_Model_Pro::TRANSPORT_PAYFLOW_TXN_ID); + ->getAdditionalInformation(self::TRANSPORT_PAYFLOW_TXN_ID); } return $payment->getParentTransactionId(); } @@ -103,7 +103,7 @@ protected function _importCaptureResultToPayment($api, $payment) $payment->setTransactionId($api->getPaypalTransactionId()) ->setIsTransactionClosed(false) ->setTransactionAdditionalInfo( - Mage_PaypalUk_Model_Pro::TRANSPORT_PAYFLOW_TXN_ID, + self::TRANSPORT_PAYFLOW_TXN_ID, $api->getTransactionId() ); $payment->setPreparedMessage( @@ -140,7 +140,7 @@ protected function _importRefundResultToPayment($api, $payment, $canRefundMore) ->setIsTransactionClosed(1) // refund initiated by merchant ->setShouldCloseParentTransaction(!$canRefundMore) ->setTransactionAdditionalInfo( - Mage_PaypalUk_Model_Pro::TRANSPORT_PAYFLOW_TXN_ID, + self::TRANSPORT_PAYFLOW_TXN_ID, $api->getTransactionId() ); $payment->setPreparedMessage( diff --git a/app/code/core/Mage/Persistent/Model/Session.php b/app/code/core/Mage/Persistent/Model/Session.php index c98d9459622..f6c764efdc2 100644 --- a/app/code/core/Mage/Persistent/Model/Session.php +++ b/app/code/core/Mage/Persistent/Model/Session.php @@ -157,7 +157,7 @@ protected function _afterLoad() public function loadByCookieKey($key = null) { if (is_null($key)) { - $key = Mage::getSingleton('core/cookie')->get(Mage_Persistent_Model_Session::COOKIE_NAME); + $key = Mage::getSingleton('core/cookie')->get(self::COOKIE_NAME); } if ($key) { $this->load($key, 'key'); @@ -200,7 +200,7 @@ public function deleteByCustomerId($customerId, $clearCookie = true) */ public function removePersistentCookie() { - Mage::getSingleton('core/cookie')->delete(Mage_Persistent_Model_Session::COOKIE_NAME); + Mage::getSingleton('core/cookie')->delete(self::COOKIE_NAME); return $this; } diff --git a/app/code/core/Mage/Sales/Model/Order/Item.php b/app/code/core/Mage/Sales/Model/Order/Item.php index a08d3a18249..27d7b9c2ebc 100644 --- a/app/code/core/Mage/Sales/Model/Order/Item.php +++ b/app/code/core/Mage/Sales/Model/Order/Item.php @@ -674,7 +674,7 @@ public function getRealProductType() */ public function addChildItem($item) { - if ($item instanceof Mage_Sales_Model_Order_Item) { + if ($item instanceof self) { $this->_children[] = $item; } elseif (is_array($item)) { $this->_children = array_merge($this->_children, $item); diff --git a/app/code/core/Mage/Sales/Model/Quote/Address.php b/app/code/core/Mage/Sales/Model/Quote/Address.php index afe743c0557..5863345a1d8 100644 --- a/app/code/core/Mage/Sales/Model/Quote/Address.php +++ b/app/code/core/Mage/Sales/Model/Quote/Address.php @@ -374,7 +374,7 @@ protected function _populateBeforeSaveData() */ protected function _isSameAsBilling() { - return ($this->getAddressType() == Mage_Sales_Model_Quote_Address::TYPE_SHIPPING + return ($this->getAddressType() === self::TYPE_SHIPPING && ($this->_isNotRegisteredCustomer() || $this->_isDefaultShippingNullOrSameAsBillingAddress())); } diff --git a/app/code/core/Mage/SalesRule/Helper/Coupon.php b/app/code/core/Mage/SalesRule/Helper/Coupon.php index f813abb7b53..1ea502ea05f 100644 --- a/app/code/core/Mage/SalesRule/Helper/Coupon.php +++ b/app/code/core/Mage/SalesRule/Helper/Coupon.php @@ -142,6 +142,6 @@ public function getCharset($format) */ public function getCodeSeparator() { - return (string)Mage::app()->getConfig()->getNode(Mage_SalesRule_Helper_Coupon::XML_CHARSET_SEPARATOR); + return (string)Mage::app()->getConfig()->getNode(self::XML_CHARSET_SEPARATOR); } } diff --git a/app/code/core/Mage/SalesRule/Model/Rule.php b/app/code/core/Mage/SalesRule/Model/Rule.php index 98985869972..6c348fb098a 100644 --- a/app/code/core/Mage/SalesRule/Model/Rule.php +++ b/app/code/core/Mage/SalesRule/Model/Rule.php @@ -383,8 +383,8 @@ public function getCouponTypes() { if ($this->_couponTypes === null) { $this->_couponTypes = array( - Mage_SalesRule_Model_Rule::COUPON_TYPE_NO_COUPON => Mage::helper('salesrule')->__('No Coupon'), - Mage_SalesRule_Model_Rule::COUPON_TYPE_SPECIFIC => Mage::helper('salesrule')->__('Specific Coupon'), + self::COUPON_TYPE_NO_COUPON => Mage::helper('salesrule')->__('No Coupon'), + self::COUPON_TYPE_SPECIFIC => Mage::helper('salesrule')->__('Specific Coupon'), ); $transport = new Varien_Object(array( 'coupon_types' => $this->_couponTypes, @@ -393,7 +393,7 @@ public function getCouponTypes() Mage::dispatchEvent('salesrule_rule_get_coupon_types', array('transport' => $transport)); $this->_couponTypes = $transport->getCouponTypes(); if ($transport->getIsCouponTypeAutoVisible()) { - $this->_couponTypes[Mage_SalesRule_Model_Rule::COUPON_TYPE_AUTO] = Mage::helper('salesrule')->__('Auto'); + $this->_couponTypes[self::COUPON_TYPE_AUTO] = Mage::helper('salesrule')->__('Auto'); } } return $this->_couponTypes; diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/Label/Pdf/Page.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/Label/Pdf/Page.php index fd2625c6c7c..33e35f35d26 100644 --- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/Label/Pdf/Page.php +++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/Label/Pdf/Page.php @@ -51,7 +51,7 @@ class Mage_Usa_Model_Shipping_Carrier_Dhl_Label_Pdf_Page extends Zend_Pdf_Page */ public function __construct($param1, $param2 = null, $param3 = null) { - if ($param1 instanceof Mage_Usa_Model_Shipping_Carrier_Dhl_Label_Pdf_Page + if ($param1 instanceof self && $param2 === null && $param3 === null ) { $this->_contents = $param1->getContents(); diff --git a/app/code/core/Mage/XmlConnect/Model/Application.php b/app/code/core/Mage/XmlConnect/Model/Application.php new file mode 100644 index 00000000000..6b4438c1e2c --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Application.php @@ -0,0 +1,1305 @@ + + */ +class Mage_XmlConnect_Model_Application extends Mage_Core_Model_Abstract +{ + /** + * Application code cookie name + */ + const APP_CODE_COOKIE_NAME = 'app_code'; + + /** + * Device screen size name + */ + const APP_SCREEN_SIZE_NAME = 'screen_size'; + + /** + * Device screen size name + * + * @deprecated will delete in the next version + */ + const APP_SCREEN_SIZE_DEFAULT = '320x480'; + + /** + * Device screen size source name + */ + const APP_SCREEN_SOURCE_DEFAULT = 'default'; + + /** + * Application status "submitted" value + */ + const APP_STATUS_SUCCESS = 1; + + /** + * Application status "not submitted" value + */ + const APP_STATUS_INACTIVE = 0; + + /** + * Application prefix length of cutted part of deviceType and storeCode + */ + const APP_PREFIX_CUT_LENGTH = 3; + + /** + * Last submitted data from history table + * + * @var null|array + */ + protected $_lastParams; + + /** + * Application submit info + * + * @var array + */ + protected $submit_params = array(); + + /** + * Application submit action type + * + * @var bool + */ + protected $is_resubmit_action = false; + + /** + * Full application code + * + * @var null|string + */ + protected $code; + + /** + * Main configuration of current application + * + * @deprecated Serialized config storage has been removed + * @var null|array + */ + protected $conf; + + /** + * Configuration model + * + * @var Mage_XmlConnect_Model_ConfigData + */ + protected $_configModel; + + /** + * Flag of loaded configuration + * + * @var bool + */ + protected $_isConfigurationLoaded = false; + + /** + * Social networking validation array + * + * Social networking validation array specified as + * array ( + * network id => API key string length + * ) + * + * @var array + */ + protected $_socialNetValidationArray = array( + Mage_XmlConnect_Helper_Data::SOCIAL_NETWORK_TWITTER, + Mage_XmlConnect_Helper_Data::SOCIAL_NETWORK_FACEBOOK, + Mage_XmlConnect_Helper_Data::SOCIAL_NETWORK_LINKEDIN, + ); + + /** + * Submission/Resubmission key max length + */ + const APP_MAX_KEY_LENGTH = 40; + + /** + * XML path to config with an email address + * for contact to receive credentials + * of Urban Airship notifications + */ + const XML_PATH_CONTACT_CREDENTIALS_EMAIL = 'xmlconnect/mobile_application/urbanairship_credentials_email'; + + /** + * XML path to config with Urban Airship Terms of Service URL + */ + const XML_PATH_URBAN_AIRSHIP_TOS_URL = 'xmlconnect/mobile_application/urbanairship_terms_of_service_url'; + + /** + * XML path to config with Urban Airship partner's login URL + */ + const XML_PATH_URBAN_AIRSHIP_PARTNER_LOGIN_URL = 'xmlconnect/mobile_application/urbanairship_login_url'; + + /** + * XML path to config with Urban Airship Push notifications product URL + */ + const XML_PATH_URBAN_AIRSHIP_ABOUT_PUSH_URL = 'xmlconnect/mobile_application/urbanairship_push_url'; + + /** + * XML path to config with Urban Airship Rich Push notifications product URL + */ + const XML_PATH_URBAN_AIRSHIP_ABOUT_RICH_PUSH_URL = 'xmlconnect/mobile_application/urbanairship_rich_push_url'; + + /** + * XML path to config copyright data + */ + const XML_PATH_DESIGN_FOOTER_COPYRIGHT = 'design/footer/copyright'; + + /** + * XML path to config restriction status + * (EE module) + */ + const XML_PATH_GENERAL_RESTRICTION_IS_ACTIVE = 'general/restriction/is_active'; + + /** + * XML path to config restriction mode + * (EE module) + */ + const XML_PATH_GENERAL_RESTRICTION_MODE = 'general/restriction/mode'; + + /** + * XML path to config secure base link URL + */ + const XML_PATH_SECURE_BASE_LINK_URL = 'web/secure/base_link_url'; + + /** + * XML path to config for paypal business account + */ + const XML_PATH_PAYPAL_BUSINESS_ACCOUNT = 'paypal/general/business_account'; + + /** + * XML path to config for default cache time + */ + const XML_PATH_DEFAULT_CACHE_LIFETIME = 'xmlconnect/mobile_application/cache_lifetime'; + + /** + * XML path to How-To URL for twitter + */ + const XML_PATH_HOWTO_TWITTER_URL = 'xmlconnect/social_networking/howto_twitter_url'; + + /** + * XML path to How-To URL for facebook + */ + const XML_PATH_HOWTO_FACEBOOK_URL = 'xmlconnect/social_networking/howto_facebook_url'; + + /** + * XML path to How-To URL for linkedin + */ + const XML_PATH_HOWTO_LINKEDIN_URL = 'xmlconnect/social_networking/howto_linkedin_url'; + + /** + * XML path to XmlConnect module version + */ + const XML_PATH_MODULE_VERSION = 'modules/Mage_XmlConnect/innerVersion'; + + /** + * Deprecated config flag + * + * @deprecated Serialized config storage has been removed + */ + const DEPRECATED_CONFIG_FLAG = 'deprecated'; + + /** + * Pages config flag value + */ + const STATIC_PAGE_CATEGORY = 'pages'; + + /** + * Delete on update paths for config data + * + * @var array + */ + protected $_deleteOnUpdateConfig = array(self::STATIC_PAGE_CATEGORY => 'staticpage'); + + /** + * Current device model + * + * @var Mage_XmlConnect_Model_Device_Abstract + */ + protected $_deviceModel; + + /** + * Image limits model + * + * @var Mage_XmlConnect_Model_ImageLimits + */ + protected $_imageLimitsModel; + + /** + * Image action model + * + * @var Mage_XmlConnect_Model_ImageAction + */ + protected $_imageActionModel; + + /** + * Initialize application + * + * @return null + */ + protected function _construct() + { + $this->_init('xmlconnect/application'); + $this->_configModel = Mage::getModel('xmlconnect/configData'); + $this->_configModel->setDeleteOnUpdate($this->getDeleteOnUpdateConfig()); + } + + /** + * Checks is it app is submitted + * (edit is premitted only before submission) + * + * @return bool + */ + public function getIsSubmitted() + { + return $this->getStatus() === self::APP_STATUS_SUCCESS; + } + + /** + * Load data (flat array) for Varien_Data_Form + * + * @return array + */ + public function getFormData() + { + $data = $this->getData(); + return $this->_flatArray($data); + } + + /** + * Load data (flat array) for Varien_Data_Form + * + * @param array $subTree + * @param string $prefix + * @return array + */ + protected function _flatArray($subTree, $prefix=null) + { + $result = array(); + foreach ($subTree as $key => $value) { + if (is_null($prefix)) { + $name = $key; + } else { + $name = $prefix . '[' . $key . ']'; + } + + if (is_array($value)) { + $result = array_merge($result, $this->_flatArray($value, $name)); + } else { + $result[$name] = $value; + } + } + return $result; + } + + /** + * Like array_merge_recursive(), but string values will be replaced + * + * @param array $array1 + * @param array $array2 + * @return array + */ + protected function _configMerge(array $array1, array $array2) + { + $result = array(); + $keys = array_unique(array_merge(array_keys($array1), array_keys($array2))); + foreach ($keys as $key) { + if (!isset($array1[$key])) { + $result[$key] = $array2[$key]; + } elseif (!isset($array2[$key])) { + $result[$key] = $array1[$key]; + } elseif (is_scalar($array1[$key]) || is_scalar($array2[$key])) { + $result[$key] = $array2[$key]; + } else { + $result[$key] = $this->_configMerge($array1[$key], $array2[$key]); + } + } + return $result; + } + + /** + * Set default configuration data + * + * @return null + */ + public function loadDefaultConfiguration() + { + $this->setCode($this->getCodePrefix()); + $this->setConf(Mage::helper('xmlconnect')->getDeviceHelper()->getDefaultConfiguration()); + } + + /** + * Return first part for application code field + * + * @return string + */ + public function getCodePrefix() + { + return substr(Mage::app()->getStore($this->getStoreId())->getCode(), 0, self::APP_PREFIX_CUT_LENGTH) + . substr($this->getType(), 0, self::APP_PREFIX_CUT_LENGTH); + } + + /** + * Checks if application code field has autoincrement + * + * @return bool + */ + public function isCodePrefixed() + { + $suffix = substr($this->getCode(), self::APP_PREFIX_CUT_LENGTH * 2); + return !empty($suffix); + } + + /** + * Load application configuration + * + * @deprecated Serialized config storage has been removed + * @return array + */ + public function prepareConfiguration() + { + return $this->getData('conf'); + } + + /** + * Get config formatted for rendering + * + * @return array + */ + public function getRenderConf() + { + $result = Mage::helper('xmlconnect')->getDeviceHelper()->getDefaultConfiguration(); + $result = $result['native']; + + if (isset($this->_data['conf'])) { + if (isset($this->_data['conf']['native'])) { + $result = $this->_configMerge($result, $this->_data['conf']['native']); + } + if (isset($this->_data['conf']['extra'])) { + $extra = $this->_data['conf']['extra']; + if (isset($extra['tabs'])) { + $tabs = Mage::getModel('xmlconnect/tabs', $extra['tabs']); + $result['tabBar']['tabs'] = $tabs; + } + if (isset($extra['fontColors'])) { + if (!empty($extra['fontColors']['header'])) { + $result['fonts']['Title1']['color'] = $extra['fontColors']['header']; + } + if (!empty($extra['fontColors']['primary'])) { + $result['fonts']['Title2']['color'] = $extra['fontColors']['primary']; + $result['fonts']['Title3']['color'] = $extra['fontColors']['primary']; + $result['fonts']['Text1']['color'] = $extra['fontColors']['primary']; + $result['fonts']['Text2']['color'] = $extra['fontColors']['primary']; + $result['fonts']['Title7']['color'] = $extra['fontColors']['primary']; + } + if (!empty($extra['fontColors']['secondary'])) { + $result['fonts']['Title4']['color'] = $extra['fontColors']['secondary']; + $result['fonts']['Title6']['color'] = $extra['fontColors']['secondary']; + $result['fonts']['Title8']['color'] = $extra['fontColors']['secondary']; + $result['fonts']['Title9']['color'] = $extra['fontColors']['secondary']; + } + if (!empty($extra['fontColors']['price'])) { + $result['fonts']['Title5']['color'] = $extra['fontColors']['price']; + } + } + } + } + + Mage::getModel('xmlconnect/images')->loadOldImageNodes($result); + + /** + * General configuration + */ + $result['general']['updateTimeUTC'] = strtotime($this->getUpdatedAt()); + $result['general']['browsingMode'] = $this->getBrowsingMode(); + $result['general']['currencyCode'] = Mage::app()->getStore($this->getStoreId())->getDefaultCurrencyCode(); + $result['general']['secureBaseUrl'] = $this->getSecureBaseUrl(); + + $allowGuest = $maxRecipients = 0; + if (Mage::getStoreConfig(Mage_Sendfriend_Helper_Data::XML_PATH_ENABLED)) { + $maxRecipients = (int)Mage::getStoreConfig(Mage_Sendfriend_Helper_Data::XML_PATH_MAX_RECIPIENTS); + $maxRecipients = $maxRecipients > 0 ? $maxRecipients: 1; + $allowGuest = Mage::getStoreConfig(Mage_Sendfriend_Helper_Data::XML_PATH_ALLOW_FOR_GUEST); + } + $result['general']['emailToFriendMaxRecepients'] = $maxRecipients; + $result['general']['emailAllowGuest'] = $allowGuest; + $result['general']['primaryStoreLang'] = Mage::app()->getStore($this->getStoreId()) + ->getConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE); + $result['general']['magentoVersion'] = Mage::getVersion(); + $result['general']['copyright'] = Mage::helper('core')->stripTags( + Mage::getStoreConfig(self::XML_PATH_DESIGN_FOOTER_COPYRIGHT, $this->getStoreId()) + ); + $result['general']['xmlconnectVersion'] = Mage::getConfig()->getNode(self::XML_PATH_MODULE_VERSION); + + $result['general']['isAllowedGuestCheckout'] = (int)Mage::getSingleton('checkout/session')->getQuote() + ->isAllowedGuestCheckout(); + + /** + * Check is guest can post product reviews + */ + $result['general']['isAllowedGuestReview'] = Mage::helper('review')->getIsGuestAllowToWrite() ? '1' : '0'; + + /** + * Check is wishlist enabled in a config + */ + $result['general']['wishlistEnable'] = Mage::getStoreConfigFlag('wishlist/general/active') ? '1' : '0'; + + /** + * "Use Secure URLs in Frontend" flag + */ + $result['general']['useSecureURLInFrontend'] = $this->getUseSecureURLInFrontend(); + + /** + * Set flag is allowed guest checkout if quote contain downloadable product(s) + */ + if ($this->isGuestBuyDownloadableProduct()) { + $result['general']['isAllowedGuestCheckoutForDownloadableProducts'] = '0'; + } else { + $result['general']['isAllowedGuestCheckoutForDownloadableProducts'] = '1'; + } + + /** + * Is enabled Store credit functionality + */ + $isStoreCreditEnable = $canShowHistoryFlag = 0; + if (is_object(Mage::getConfig()->getNode('modules/Enterprise_CustomerBalance'))) { + $storeCreditFlag = Mage::getStoreConfig(Enterprise_CustomerBalance_Helper_Data::XML_PATH_ENABLED); + $isStoreCreditEnable = (int)$storeCreditFlag; + $canShowHistoryFlag = (int)Mage::getStoreConfigFlag('customer/enterprise_customerbalance/show_history'); + } + + $result['general']['isStoreCreditEnabled'] = $isStoreCreditEnable; + $result['general']['isStoreCreditHistoryEnabled'] = $canShowHistoryFlag; + + /** + * Is available Gift Card functionality + */ + $result['general']['isGiftcardEnabled'] = (int) is_object( + Mage::getConfig()->getNode('modules/Enterprise_GiftCard') + ); + + /** + * PayPal configuration + */ + $result['paypal']['businessAccount'] = Mage::getModel('paypal/config')->businessAccount; + $result['paypal']['merchantLabel'] = $this->getData('conf/special/merchantLabel'); + + $isActive = 0; + $paypalMepIsAvailable = Mage::getModel('xmlconnect/payment_method_paypal_mep')->isAvailable(null); + if ($paypalMepIsAvailable && isset($result['paypal']['isActive'])) { + $isActive = (int) $result['paypal']['isActive']; + } + $result['paypal']['isActive'] = $isActive; + + $paypalMeclIsAvailable = Mage::getModel('xmlconnect/payment_method_paypal_mecl')->isAvailable(null); + + /** + * Pages configuration + */ + $pages = Mage::getSingleton('xmlconnect/configuration')->getDeviceStaticPages(); + + if (!empty($pages)) { + $result['pages'] = $pages; + } + + /** + * PayPal Mobile Express Library Checkout + */ + $result['paypalMecl']['isActive'] = (int) ( + $paypalMeclIsAvailable + && $this->getData('config_data/payment/paypalmecl_is_active') + ); + + if ((int)Mage::getStoreConfig(self::XML_PATH_GENERAL_RESTRICTION_IS_ACTIVE)) { + $result['website_restrictions']['mode'] = (int)Mage::getStoreConfig( + self::XML_PATH_GENERAL_RESTRICTION_MODE + ); + } + + ksort($result); + return $result; + } + + /** + * Get secure base url + * + * @return string + */ + public function getSecureBaseUrl() + { + return Mage::getStoreConfig(self::XML_PATH_SECURE_BASE_LINK_URL, $this->getStoreId()); + } + + /** + * Check is allowed guest checkout if quote contain downloadable product(s) + * + * @return bool + */ + public function isGuestBuyDownloadableProduct() + { + return (bool)Mage::getStoreConfigFlag( + Mage_Downloadable_Model_Observer::XML_PATH_DISABLE_GUEST_CHECKOUT, $this->getStoreId() + ); + } + + /** + * Is forced front secure url + * + * @return int + */ + public function getUseSecureURLInFrontend() + { + return (int) Mage::getStoreConfigFlag(Mage_Core_Model_Store::XML_PATH_SECURE_IN_FRONTEND); + } + + /** + * Return current screen_size parameter + * + * @return string + */ + public function getScreenSize() + { + if (!isset($this->_data['screen_size'])) { + $this->_data['screen_size'] = $this->getDeviceModel()->getDefaultScreenSize(); + } + return $this->_data['screen_size']; + } + + /** + * Setter for current screen_size parameter + * + * @param string $screenSize + * @return $this + */ + public function setScreenSize($screenSize) + { + $this->_data['screen_size'] = $screenSize; + return $this; + } + + /** + * Return Enabled Tabs array from actual config + * + * @return array: + */ + public function getEnabledTabsArray() + { + if ($this->getData('conf/extra/tabs')) { + return Mage::getModel('xmlconnect/tabs', $this->getData('conf/extra/tabs'))->getRenderTabs(); + } + return array(); + } + + /** + * Change URLs to absolute + * + * @param array $subTree + * @return array + */ + protected function _absPath($subTree) + { + foreach ($subTree as $key => $value) { + if (!empty($value)) { + if (is_array($value)) { + $subTree[$key] = $this->_absPath($value); + } elseif (strtolower(substr($key, -4)) == 'icon' || strtolower(substr($key, -5)) == 'image') { + $subTree[$key] = Mage::getBaseUrl('media') . 'xmlconnect/' . $value; + } + } + } + return $subTree; + } + + /** + * Return content pages + * + * @return array + */ + public function getPages() + { + if (isset($this->_data['conf']['pages'])) { + return $this->_data['conf']['pages']; + } + return array(); + } + + /** + * Get configuration model + * + * @return Mage_XmlConnect_Model_ConfigData + */ + public function getConfigModel() + { + return $this->_configModel; + } + + /** + * Set last updated datetime string + * + * @return $this + */ + protected function _renewUpdatedAtTime() + { + $this->setUpdatedAt(Mage::getSingleton('core/date')->gmtDate()); + return $this; + } + + /** + * Processing object before save data + * + * @return $this + */ + protected function _beforeSave() + { + $this->_renewUpdatedAtTime(); + return $this; + } + + /** + * Processing object after save data + * + * @return $this + */ + protected function _afterSave() + { + $this->_saveConfigData(); + $this->_saveDeprecatedConfig(); + parent::_afterSave(); + return $this; + } + + /** + * Save configuration data of application model + * + * @return $this + */ + protected function _saveConfigData() + { + $configuration = $this->getData('config_data'); + if (is_array($configuration)) { + $this->getConfigModel()->setConfigData($this->getId(), $configuration)->initSaveConfig(); + } + return $this; + } + + /** + * Save old deprecated config to application config data table + * + * @deprecated Serialized config storage has been removed + * @return $this + */ + private function _saveDeprecatedConfig() + { + $deprecatedConfig = $this->getData('conf'); + if (is_array($deprecatedConfig)) { + $this->getConfigModel()->saveConfig( + $this->getId(), $this->convertOldConfing($deprecatedConfig), self::DEPRECATED_CONFIG_FLAG + ); + } + return $this; + } + + /** + * Convert deprecated configuration array to new standard + * + * @deprecated Serialized config storage has been removed + * @param array $conf + * @param bool $path + * @return array + */ + public function convertOldConfing(array $conf, $path = false) + { + $result = array(); + foreach ($conf as $key => $val) { + $key = $path ? $path . '/' . $key : $key; + if (is_array($val)) { + $result += $this->convertOldConfing($val, $key); + } else { + $result[$key] = $val; + } + } + return $result; + } + + /** + * Load configuration data (from serialized blob) + * + * @return $this + */ + public function loadConfiguration() + { + if (!$this->_isConfigurationLoaded) { + if ($this->getId()) { + $this->_loadDeprecatedConfig()->_loadConfigData(); + $this->_isConfigurationLoaded = true; + } + } + return $this; + } + + /** + * Load configuration data + * + * @internal re-factoring in progress + * @return $this + */ + protected function _loadConfigData() + { + $configuration = $this->getConfigModel()->getCollection()->addArrayFilter(array( + 'application_id' => $this->getId(), + 'category' => 'payment' + ))->toOptionArray(); + $this->setData('config_data', $configuration); + return $this; + } + + /** + * Load deprecated configuration + * + * @deprecated Serialized config storage has been removed + * @return $this + */ + private function _loadDeprecatedConfig() + { + $configuration = $this->_convertConfig( + $this->getConfigModel()->getCollection()->addArrayFilter(array( + 'application_id' => $this->getId(), + 'category' => self::DEPRECATED_CONFIG_FLAG + ))->toOptionArray() + ); + $this->setData('conf', $configuration); + return $this; + } + + /** + * Convert old config data array + * + * @deprecated Serialized config storage has been removed + * @throws Mage_Core_Exception + * @param $config + * @return array + */ + protected function _convertConfig($config) + { + $result = array(); + foreach ($config as $values) { + foreach ($values as $path => $value) { + if (preg_match('@[^\w\/]@', $path)) { + Mage::throwException(Mage::helper('xmlconnect')->__('Unsupported character in path: "%s"', $path)); + } + $keyArray = explode('/', $path); + $keys = '$result["' . implode('"]["', $keyArray) . '"]'; + eval($keys . ' = $value;'); + } + } + return $result; + } + + /** + * Load application by code + * + * @param string $code + * @return $this + */ + public function loadByCode($code) + { + $this->_getResource()->load($this, $code, 'code'); + return $this; + } + + /** + * Loads submit tab data from xmlconnect/history table + * + * @return bool + */ + public function loadSubmit() + { + $isResubmitAction = false; + if ($this->getId()) { + $params = $this->getLastParams(); + if (!empty($params)) { + // Using Pointer ! + $conf = &$this->_data['conf']; + if (!isset($conf['submit_text']) || !is_array($conf['submit_text'])) { + $conf['submit_text'] = array(); + } + if (!isset($conf['submit_restore']) || !is_array($conf['submit_restore'])) { + $conf['submit_restore'] = array(); + } + foreach ($params as $id => $value) { + $deviceImages = Mage::helper('xmlconnect')->getDeviceHelper()->getSubmitImages(); + + if (!in_array($id, $deviceImages)) { + $conf['submit_text'][$id] = $value; + } else { + $conf['submit_restore'][$id] = $value; + } + $isResubmitAction = true; + } + } + } + $this->setIsResubmitAction($isResubmitAction); + return $isResubmitAction; + } + + /** + * Returns ( image[ ID ] => "SRC" ) array + * + * @return array + */ + public function getImages() + { + $images = array(); + $params = $this->getLastParams(); + $deviceImages = Mage::helper('xmlconnect')->getDeviceHelper()->getSubmitImages(); + + foreach ($deviceImages as $id) { + $path = $this->getData('conf/submit/'.$id); + $basename = null; + if (!empty($path)) { + /** + * Fetching data from session restored array + */ + $basename = basename($path); + } elseif (isset($params[$id])) { + /** + * Fetching data from submission history table record + * + * converting : "@\var\somedir\media\xmlconnect\form_icon_6.png" + * to "\var\somedir\media\xmlconnect\forn_icon_6.png" + */ + $basename = basename($params[$id]); + } + if (!empty($basename)) { + $images['conf/submit/'.$id] = Mage::getBaseUrl('media') . 'xmlconnect/' + . Mage::helper('xmlconnect/image')->getFileDefaultSizeSuffixAsUrl($basename); + } + } + return $images; + } + + /** + * Return last submitted data from history table + * + * @return array + */ + public function getLastParams() + { + if (!isset($this->_lastParams)) { + $this->_lastParams = Mage::getModel('xmlconnect/history')->getLastParams($this->getId()); + } + return $this->_lastParams; + } + + /** + * Validate application data + * + * @return array|bool + */ + public function validate() + { + $errors = array(); + + $validateConf = $this->_validateConf(); + if ($validateConf !== true) { + $errors = $validateConf; + } + + if (!Zend_Validate::is($this->getName(), 'NotEmpty')) { + $errors[] = Mage::helper('xmlconnect')->__('Please enter "App Title".'); + } + + if (empty($errors)) { + return true; + } + return $errors; + } + + /** + * Validate submit application data + * + * @param array $params + * @return array|bool + */ + public function validateSubmit($params) + { + $errors = array(); + $validateConf = $this->_validateConf(); + if ($validateConf !== true) { + $errors = $validateConf; + } + + $submitErrors = Mage::helper('xmlconnect')->getDeviceHelper($this)->validateSubmit($params); + + if (count($submitErrors)) { + $errors = array_merge($errors, $submitErrors); + } + if (empty($errors)) { + return true; + } + return $errors; + } + + /** + * Check config for valid values + * + * @return bool|array + */ + protected function _validateConf() + { + $config = $this->getConf(); + $native = isset($config['native']) && is_array($config['native']) ? $config['native'] : false; + $errors = array(); + + foreach ($this->_socialNetValidationArray as $networkKey) { + if (isset($native['socialNetworking'][$networkKey]['isActive']) + && $native['socialNetworking'][$networkKey]['isActive'] + ) { + if ($networkKey !== Mage_XmlConnect_Helper_Data::SOCIAL_NETWORK_FACEBOOK) { + $networkName = ucfirst($networkKey); + if (!isset($native['socialNetworking'][$networkKey]['apiKey']) + || !Zend_Validate::is($native['socialNetworking'][$networkKey]['apiKey'], 'NotEmpty') + ) { + $errors[] = Mage::helper('xmlconnect')->__('%s API Key required.', $networkName); + } + if (!isset($native['socialNetworking'][$networkKey]['secretKey']) + || !Zend_Validate::is($native['socialNetworking'][$networkKey]['secretKey'], 'NotEmpty') + ) { + $errors[] = Mage::helper('xmlconnect')->__('%s Secret Key required.', $networkName); + } + } else { + $networkName = ucfirst($networkKey); + if (!isset($native['socialNetworking'][$networkKey]['appID']) + || !Zend_Validate::is($native['socialNetworking'][$networkKey]['appID'], 'NotEmpty') + ) { + $errors[] = Mage::helper('xmlconnect')->__('%s Application ID required.', $networkName); + } + } + } + } + + if (empty($errors)) { + return true; + } + return $errors; + } + + /** + * Imports post/get data into the model + * + * @param array $data - $_REQUEST[] + * @return array + */ + public function prepareSubmitParams($data) + { + $params = array(); + if (isset($data['conf']) && is_array($data['conf'])) { + + if (isset($data['conf']['submit_text']) && is_array($data['conf']['submit_text'])) { + $params = $data['conf']['submit_text']; + } + + $params['name'] = $this->getName(); + $params['code'] = $this->getCode(); + $params['type'] = $this->getType(); + $params['url'] = Mage::getUrl('xmlconnect/configuration/index', array( + '_store' => $this->getStoreId(), '_nosid' => true, 'app_code' => $this->getCode() + )); + + $params['magentoversion'] = Mage::getVersion(); + + if (isset($params['country']) && is_array($params['country'])) { + $params['country'] = implode(',', $params['country']); + } + if ($this->getIsResubmitAction()) { + if (isset($params['resubmission_activation_key'])) { + $params['resubmission_activation_key'] = trim($params['resubmission_activation_key']); + $params['key'] = $params['resubmission_activation_key']; + } else { + $params['key'] = ''; + } + } else { + $params['key'] = isset($params['key']) ? trim($params['key']) : ''; + } + + // processing files + $submit = array(); + if (isset($this->_data['conf']['submit']) && is_array($this->_data['conf']['submit'])) { + $submit = $this->_data['conf']['submit']; + } + + $submitRestore = array(); + if (isset($this->_data['conf']['submit_restore']) && is_array($this->_data['conf']['submit_restore'])) { + $submitRestore = $this->_data['conf']['submit_restore']; + } + + $deviceImages = Mage::helper('xmlconnect')->getDeviceHelper()->getSubmitImages(); + + foreach ($deviceImages as $id) { + if (isset($submit[$id])) { + $params[$id] = '@' . Mage::helper('xmlconnect/image')->getDefaultSizeUploadDir() . DS + . $submit[$id]; + } elseif (isset($submitRestore[$id])) { + $params[$id] = $submitRestore[$id]; + } + } + } + $this->setSubmitParams($params); + return $params; + } + + /** + * Retrieve Store Id + * + * @return int + */ + public function getStoreId() + { + if ($this->hasData('store_id')) { + return $this->getData('store_id'); + } + return Mage::app()->getStore()->getId(); + } + + /** + * Getter, returns activation key for current application + * + * @return string|null + */ + public function getActivationKey() + { + $key = null; + if (isset($this->_data['conf']['submit_text']['key'])) { + $key = $this->_data['conf']['submit_text']['key']; + } + return $key; + } + + /** + * Perform update for all applications "updated at" parameter with current date + * + * @return $this + */ + public function updateAllAppsUpdatedAtParameter() + { + $this->_renewUpdatedAtTime()->_getResource()->updateUpdatedAtParameter($this); + return $this; + } + + /** + * Checks if notifications is active + * + * @return boolean + */ + public function isNotificationsActive() + { + return (boolean)$this->loadConfiguration()->getData('conf/native/notifications/isActive'); + } + + /** + * Getter return concatenated user and password + * + * @return string + */ + public function getUserpwd() + { + return $this->loadConfiguration()->getAppKey() . ':' . $this->getAppMasterSecret(); + } + + /** + * Getter for Application Key + * + * @return string + */ + public function getAppKey() + { + return $this->getData('conf/native/notifications/applicationKey'); + } + + /** + * Getter for Application Secret + * + * @return string + */ + public function getAppSecret() + { + return $this->getData('conf/native/notifications/applicationSecret'); + } + + /** + * Getter for Application Master Secret + * + * @return string + */ + public function getAppMasterSecret() + { + return $this->getData('conf/native/notifications/applicationMasterSecret'); + } + + /** + * Getter for Application Cache Lifetime + * + * @return int|string + */ + public function getCacheLifetime() + { + $lifetime = (int)$this->loadConfiguration()->getData('conf/native/cacheLifetime'); + return $lifetime <= 0 ? '' : $lifetime; + } + + /** + * Get delete on update paths for config data + * + * @return array + */ + public function getDeleteOnUpdateConfig() + { + return $this->_deleteOnUpdateConfig; + } + + /** + * Set delete on update paths for config data + * + * @param array $pathsToDelete + * @return $this + */ + public function setDeleteOnUpdateConfig(array $pathsToDelete) + { + $this->_deleteOnUpdateConfig = array_merge($this->_deleteOnUpdateConfig, $pathsToDelete); + return $this; + } + + /** + * Get current device model + * + * @return Mage_XmlConnect_Model_Device_Abstract + */ + public function getDeviceModel() + { + if (null === $this->_deviceModel) { + $this->setDeviceModel(); + } + return $this->_deviceModel; + } + + /** + * Set current device model + * + * @throws Mage_Core_Exception + * @param Mage_XmlConnect_Model_Device_Abstract|null $deviceModel + * @return $this + */ + public function setDeviceModel($deviceModel = null) + { + if ($deviceModel instanceof Mage_XmlConnect_Model_Device_Abstract) { + $this->_deviceModel = $deviceModel; + } elseif ($this->getType()) { + $this->_deviceModel = Mage::getModel('xmlconnect/device_' . $this->getType(), $this); + } else { + Mage::throwException(Mage::helper('xmlconnect')->__('Device doesn\'t recognized')); + } + return $this; + } + + /** + * Get current image limit model + * + * @return Mage_XmlConnect_Model_ImageLimits + */ + public function getImageLimitsModel() + { + if ($this->_imageLimitsModel === null) { + $this->setImageLimitsModel(); + } + return $this->_imageLimitsModel; + } + + /** + * Set current image limit model + * + * @param null|Mage_XmlConnect_Model_ImageLimits $imageLimitsModel + * @return $this + */ + public function setImageLimitsModel($imageLimitsModel = null) + { + if (null === $imageLimitsModel) { + $this->_imageLimitsModel = Mage::getModel('xmlconnect/imageLimits', $this); + } else { + $this->_imageLimitsModel = $imageLimitsModel; + } + return $this; + } + + /** + * Get image action model + * + * @return Mage_XmlConnect_Model_ImageAction + */ + public function getImageActionModel() + { + if (null === $this->_imageActionModel) { + $this->_imageActionModel = Mage::getModel('xmlconnect/imageAction', $this); + } + return $this->_imageActionModel; + } + + /** + * Set image action model + * + * @param Mage_XmlConnect_Model_ImageAction $imageActionModel + * @return $this + */ + public function setImageActionModel($imageActionModel) + { + $this->_imageActionModel = $imageActionModel; + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Configuration.php b/app/code/core/Mage/XmlConnect/Model/Configuration.php new file mode 100644 index 00000000000..28aaf14919f --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Configuration.php @@ -0,0 +1,271 @@ + + */ +class Mage_XmlConnect_Model_Configuration extends Mage_Core_Model_Abstract +{ + /** + * Admin application config flag for is active param + */ + const CONFIG_PATH_AA_SETTINGS = 'xmlconnect/admin_app/settings'; + + /** + * Core config data collection + * + * @var Mage_Core_Model_Resource_Config_Data_Collection + */ + protected $_configDataCollection; + + /** + * XmlConnect data collection + * + * @var Mage_XmlConnect_Model_Resource_ConfigData_Collection + */ + protected $_configConnectDataCollection; + + /** + * Core config model + * + * @var Mage_Core_Model_Config + */ + protected $_configDataModel; + + /** + * Admin application settings + * + * @var array + */ + protected $_adminApplicationSettings; + + /** + * Application model + * + * @var Mage_XmlConnect_Model_Application + */ + protected $_applicationModel; + + /** + * Get is active admin application flag + * + * @return bool + */ + public function isActiveAdminApp() + { + $isActiveSetting = $this->_getAdminApplicationSettings( + self::CONFIG_PATH_AA_SETTINGS . '/is_active' + ); + return $isActiveSetting ? (bool)$isActiveSetting['value'] : false; + } + + /** + * Save is active admin application param + * + * @param int $isActive + * @return $this + */ + public function saveIsActiveAdminApp($isActive) + { + $this->_getConfigDataModel()->saveConfig( + self::CONFIG_PATH_AA_SETTINGS . '/is_active', (int)$isActive + ); + return $this; + } + + /** + * Get admin application settings data + * + * @param null|string $path to config node + * @return array + */ + protected function _getAdminApplicationSettings($path = null) + { + if (null === $this->_adminApplicationSettings) { + $adminApplicationSettings = $this->_getConfigDataCollection() + ->addPathFilter(self::CONFIG_PATH_AA_SETTINGS) + ->getData(); + + foreach ($adminApplicationSettings as $setting) { + $this->_adminApplicationSettings[$setting['path']] = $setting; + } + } + + if ($path !== null && isset($this->_adminApplicationSettings[$path])) { + return $this->_adminApplicationSettings[$path]; + } else { + return $this->_adminApplicationSettings; + } + } + + /** + * Get core config data collection + * + * @return Mage_Core_Model_Resource_Config_Data_Collection + */ + protected function _getConfigDataCollection() + { + if (null === $this->_configDataCollection) { + $this->_configDataCollection = Mage::getModel('core/resource_config_data_collection'); + } else { + $this->_configDataCollection->clear()->getSelect()->reset(); + } + return $this->_configDataCollection; + } + + /** + * Get core config data model + * + * @return Mage_Core_Model_Config + */ + protected function _getConfigDataModel() + { + if (null === $this->_configDataModel) { + $this->_configDataModel = Mage::getModel('core/config'); + } + return $this->_configDataModel; + } + + /** + * Get device static pages + * + * @return array + */ + public function getDeviceStaticPages() + { + return $this->_getConfigDataByCategory(Mage_XmlConnect_Model_Application::STATIC_PAGE_CATEGORY, true); + } + + /** + * Get previous localization hash from storage + * + * @return string|null + */ + public function getPreviousLocalizationHash() + { + $localizationHashSetting = $this->_getAdminApplicationSettings( + self::CONFIG_PATH_AA_SETTINGS . '/localization_hash' + ); + return $localizationHashSetting ? $localizationHashSetting['value'] : null; + + } + + /** + * Save localization hash in configuration storage + * + * @param string $hash + * @return $this + */ + public function setPreviousLocalizationHash($hash) + { + $this->_getConfigDataModel()->saveConfig( + self::CONFIG_PATH_AA_SETTINGS . '/localization_hash', $hash + ); + return $this; + } + + /** + * Get xmlconnect saved config data by category + * + * @param string $category + * @param bool $unSerialize + * @return array + */ + protected function _getConfigDataByCategory($category = null, $unSerialize = false) + { + $configuration = $this->_getConnectConfigDataCollection()->addArrayFilter(array( + 'application_id' => $this->getApplicationModel()->getId(), + 'category' => $category, + ))->toOptionArray(); + if (!empty($configuration)) { + return $this->_formatConfigData($configuration[$category], $unSerialize, $category); + } else { + return array(); + } + } + + /** + * Format config data + * + * @param array $configuration + * @param bool $unSerialize + * @return array + */ + protected function _formatConfigData($configuration, $unSerialize = false) + { + $result = array(); + foreach ($configuration as $node => $values) { + if ($unSerialize) { + $values = unserialize($values); + } + $result[$node] = $values; + } + return $result; + } + + /** + * Get xmlconnect config data collection + * + * @return Mage_Core_Model_Resource_Config_Data_Collection + */ + protected function _getConnectConfigDataCollection() + { + if (null === $this->_configConnectDataCollection) { + $this->_configConnectDataCollection = Mage::getModel('xmlconnect/resource_configData_collection'); + } else { + $this->_configConnectDataCollection->clear()->getSelect()->reset(Zend_Db_Select::WHERE); + } + return $this->_configConnectDataCollection; + } + + /** + * Get application model + * + * @return Mage_XmlConnect_Model_Application + */ + public function getApplicationModel() + { + if (null === $this->_applicationModel) { + $this->setApplicationModel(); + } + return $this->_applicationModel; + } + + /** + * Set application model + * + * @return $this + */ + public function setApplicationModel() + { + $this->_applicationModel = Mage::helper('xmlconnect')->getApplication(); + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Queue.php b/app/code/core/Mage/XmlConnect/Model/Queue.php new file mode 100644 index 00000000000..e931fda3011 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Queue.php @@ -0,0 +1,328 @@ + + */ +class Mage_XmlConnect_Model_Queue extends Mage_Core_Model_Template +{ + /** + * Status in queue identifier + */ + const STATUS_IN_QUEUE = 0; + + /** + * Status cenceled identifier + */ + const STATUS_CANCELED = 1; + + /** + * Status completed identifier + */ + const STATUS_COMPLETED = 2; + + /** + * Status deleted identifier + */ + const STATUS_DELETED = 3; + + /** + * Airmail message type + */ + const MESSAGE_TYPE_AIRMAIL = 'airmail'; + + /** + * Push notification message type + */ + const MESSAGE_TYPE_PUSH = 'push'; + + /** + * Notification type config path + */ + const XML_PATH_NOTIFICATION_TYPE = 'xmlconnect/devices/%s/notification_type'; + + /** + * Count of message in queue for cron + * config path + */ + const XML_PATH_CRON_MESSAGES_COUNT = 'xmlconnect/mobile_application/cron_send_messages_count'; + + /** + * Current application type + * + * @var null|string + */ + protected $_appType; + + /** + * Application code + * + * @var string + */ + protected $_appCode; + + /** + * Initialize queue message + * + * @return null + */ + protected function _construct() + { + $this->_init('xmlconnect/queue'); + } + + /** + * Load object data + * + * @param int $id + * @param string $field + * @return $this + */ + public function load($id, $field = null) + { + parent::load($id, $field); + + if (!$this->getTemplateId() && Mage::app()->getRequest()->getParam('template_id', false)) { + $this->setTemplateId(Mage::app()->getRequest()->getParam('template_id')); + } + + if ($this->getTemplateId()) { + $template = Mage::getModel('xmlconnect/template')->load($this->getTemplateId()); + $this->setName($template->getName()); + $this->setApplicationId($template->getApplicationId()); + } + return $this; + } + + /** + * Get template type + * + * @return int + */ + public function getType() + { + return self::TYPE_HTML; + } + + /** + * Getter for application type + * @return string + */ + public function getApplicationType() + { + if (empty($this->_appType) && $this->getAppCode()) { + $app = Mage::getModel('xmlconnect/application')->loadByCode($this->getAppCode()); + $this->_appType = $app->getId() ? $app->getType() : null; + } + + return $this->_appType; + } + + /** + * Getter for application name + * + * @return string + */ + public function getAppName() + { + if ($this->getApplicationName()) { + return $this->getApplicationName(); + } else { + return Mage::helper('xmlconnect')->getApplicationName($this->getAppCode()); + } + } + + /** + * Getter for template name + * + * @return string + */ + public function getTplName() + { + if ($this->getTemplateName()) { + return $this->getTemplateName(); + } else { + return Mage::helper('xmlconnect')->getTemplateName($this->getTemplateId()); + } + } + + /** + * Retrieve processed template + * + * @param array $variables + * @return string + */ + public function getProcessedTemplate(array $variables = array()) + { + /* @var $processor Mage_Widget_Model_Template_Filter */ + $processor = Mage::getModel('widget/template_filter'); + + $variables['this'] = $this; + + if (Mage::app()->isSingleStoreMode()) { + $processor->setStoreId(Mage::app()->getStore()); + } else { + $processor->setStoreId(1); + } + + $htmlDescription = <<%s: +EOT; + + switch ($this->getData('type')) { + case self::MESSAGE_TYPE_AIRMAIL: + $html = sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Push title')) + . $this->getPushTitle() + . sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Message title')) + . $this->getMessageTitle() + . sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Message content')) + . $processor->filter($this->getContent()); + break; + case self::MESSAGE_TYPE_PUSH: + default: + $html = sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Push title')) + . $this->getPushTitle(); + break; + } + return $html; + } + + /** + * Reset all model data + * + * @return $this + */ + public function reset() + { + $this->setData(array()); + $this->setOrigData(); + + return $this; + } + + + /** + * Get JSON-encoded params for broadcast AirMail + * Format of JSON data: + * { + * "push": { + * "aps": { + * "alert": "New message!" + * } + * }, + * "title": "Message title", + * "message": "Your full message here.", + * "extra": { + * "some_key": "some_value" + * } + * } + * + * @return string + */ + public function getAirmailBroadcastParams() + { + $notificationType = Mage::getStoreConfig( + sprintf(self::XML_PATH_NOTIFICATION_TYPE, $this->getApplicationType()) + ); + + $payload = array( + 'push' => array($notificationType => array('alert' => $this->getPushTitle())), + 'title' => $this->getMessageTitle(), + 'message' => $this->getContent(), + ); + return Mage::helper('core')->jsonEncode($payload); + } + + /** + * Get JSON-encoded params for broadcast Push Notification + * Format of JSON data: + * { + * "aps": { + * "badge": 15, + * "alert": "Hello from Urban Airship!", + * "sound": "cat.caf" + * }, + * "exclude_tokens": [ + * "device token you want to skip", + * "another device token you want to skip" + * ] + * } + * + * @return string + */ + public function getPushBroadcastParams() + { + $notificationType = Mage::getStoreConfig( + sprintf(self::XML_PATH_NOTIFICATION_TYPE, $this->getApplicationType()) + ); + + $payload = array( + $notificationType => array( +// 'badge' => 'auto', + 'alert' => $this->getPushTitle(), + 'sound' => 'default' + ) + ); + return Mage::helper('core')->jsonEncode($payload); + } + + /** + * Save object data + * + * @return Mage_Core_Model_Abstract + */ + public function save() + { + if (!$this->getIsSent() && $this->getStatus() == self::STATUS_IN_QUEUE) { + try { + Mage::dispatchEvent('before_save_message_queue', array('queueMessage' => $this)); + } catch (Exception $e) { + Mage::logException($e); + } + } + return parent::save(); + } + + /** + * Get application code + * + * @return string + */ + public function getAppCode() + { + if (null === $this->_appCode) { + if ($this->getApplicationId()) { + $application = Mage::getModel('xmlconnect/application')->load($this->getApplicationId()); + $this->_appCode = $application->getCode(); + } + } + return $this->_appCode; + } +}