diff --git a/RELEASE_NOTES.txt b/RELEASE_NOTES.txt index de3ea51e0f..ec77a8a0b3 100644 --- a/RELEASE_NOTES.txt +++ b/RELEASE_NOTES.txt @@ -1,3 +1,228 @@ +==== 1.6.1.0-alpha1 ==== + +=== Major Highlights === +Added two-step password reset flow + +=== Improvements === +Added support for using Shift-Click to select a range of grid rows when clicking check boxes +Added ability to register during checkout when using PayPal Express +Updated PayflowLink HSS user interface in checkout +"Add to Wishlist", "Add to Compare" were added on the Product Details Page for configurable, bundled and downloadable products + +=== Changes === +TheFind integration was removed +Google Optimizer was removed (it will be supported as a core extension) +Improved how discounts are applied to sub products + +=== Fixes === +Fixed When using direct Export, the _super_product_sku and _super_product_option on the configurable product does not match +Fixed Composite product price in grid is displayed incorrectly with some currencies due to JS regexp problem +Fixed No error message on Payflow link iframe +Fixed Flex uploader elements overlaps hovering menu items in backend +Fixed Unable to upload images in Magento installed on local server +Fixed Configurable Products - Use Default (attribute name) does not work correctly on IE9 +Fixed Capture failed when Verification Authorization Amount is set to Zero +Fixed Attribute is sorted like a string even when Input Validation for Store Owner is an Integer Number +Fixed Void and Cancel Order doesn't work (PayflowLink HSS) +Fixed Grand Total (Excl Tax) with negative value displays in the printed Credit Memo +Fixed Resource model of Media module is wrongly declared +Fixed Constraint violation with core_cache_tag table +Fixed Misprint in \downloader\lib\Mage\Connect\Validator.php +Fixed XMLRPC API attribute status changing +Fixed Typo in Mage_Rss_Block_Catalog_Category::_toHtml() method +Fixed Incorrect tax summary for partial credit memos/invoices +Fixed SSL is not used for links in email templates when admin area is configured to use HTTPS +Fixed Incorrect style on product page +Fixed Error is displayed by editing product or by creating product on back-end in IE8 +Fixed Catalog price rules for composite products changes +Fixed Moving modules to the correct place +Fixed Wishlist shows items per store scope, not website +Fixed Products in Wishlist disappears, when Store View is changed +Fixed Wrong Comments History in notification of order creation/cancellation +Fixed In AJAX popup fields "From" and "To" have behavior as mandatory fields +Fixed Filter by Allow Countries not working for Customer Address Form in the Backend +Fixed Product price lower than 0 (after catalog price rule applying) +Fixed Google Checkout throws error if Zip Range is used for Tax Rate +- changed part of XML request to Google responsible for postal codes +- made changes to correctly fetch tax rules for postal code ranges +Fixed Website config object is not being cached +Fixed Select groups in grid view doesn't work under IE7 +Fixed No products name in Popular tags report file .csv +Fixed Qty Increments should work when it was defined in the default scope configuration +Fixed Products in catalog displays as "out of stock" +Fixed "Get help for this page" in each tab under System->Configuration links to the same help page +Fixed Unable to translate submenu +Fixed Redirect to main page of front-end during deleting Product Tax Class which is used in Tax Rule +Fixed Redirect to base URL should consider full request URI string +Fixed Incorrect transparency of PNG image in indexed non-alpha mode +Fixed Problem of generation URL between different domains +Fixed There are no server side validation of first character of Attribute Code (it should be letter) +Fixed Edit Order without creating new one functionality saves invalid changes in non-default customer address attributes +Fixed Frontend: If second customer logs in and does not select the "Remember Me" then the previous long-term cookie does not removes +Fixed Admin can Reorder order with status On Hold +Fixed Frontend: After new customer registration with "Remember Me" and pressing "Logout" the long-term cookie session doesn't apply if in configuration on backend ""Remember Me" Default Value" - No +Fixed Tax not displaying on PayPal side for Express orders +Fixed Wishlist: Not configured grouped product has unneeded link "Show Details" +Fixed Removed the ability to work with customise admin url through the parameter base_url +Fixed Roles not displaying selected resources +Fixed Unable to use Import when compiler is enabled +Fixed Missing Translation Capability in Transactional Email Variable +Fixed productConfigure is undefined error is occurred during creation Order in Backend in IE8 browser +Fixed Zend Full Page Cache. Lifetime of the cookie is not equal to specified on "Cookie Lifetime" field +Fixed Incorrect price values for Bundle Product +Fixed Link does not pass validation if ends with .html +Fixed Incorrect Customs Value in Create Packages in case when price value contains decimals +Fixed Incorrect reports with updated_at filter +Fixed paypal_payment_transaction_clean job takes credentials form default config instead of website for Payflow Link +Fixed Wrong schedule time setup for paypal_payment_transaction_clean job for Payflow Link +Fixed Backend Error message "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'qwe' for key 2" appears after saving new Email Template with existing name +Fixed Rule Conditions logic +Fixed Error appears after Customer Group saving with name length more than 32 +Fixed Category product index run time +Fixed Sidebar cart is missing composite product options on category page +Fixed Missed validation for space character at the begin of unique fields +- improved validation of Attribute Set Name and validation of unique fields in Mage_Core_Model_Resource_Db_Abstract class +Fixed Ability to input uppercase, space, specials symbols in Order Status Code +Fixed Filter by Allow Countries not working for Customer Address Form in the Backend +Fixed No ability to create Shipping Label with "plus-four codes" Zip Code (in case with USPS Domestic) +Fixed Changing language twice -> Error 404 +Fixed The sort order in products page doesn't work +Fixed When a grouped product with configured price=0 is added to the wishlist and shared, adding the product to the cart leads to 404 error +Fixed Media Saves Incorrect Cached Config +- added options that disallow saving cache +Fixed Bundle Product items shows randomly instead of according to option +Fixed Unable to place order with Payflow Link if store credit or reward point applied +Fixed Ajax loader does not appears after click on Verify Card on Payflow Link +Fixed "Google Checkout - Carrier" in Magento backend as shipping method rather than the actual shipping method chosen +Fixed JavaScript error appears in checkout because of PSC after press 'Proceed to Checkout' +Fixed Admin user interface: mistakes in labels names +Fixed Problems with grid sorting on edit customer backend page +Fixed It is possible to change the price of the Bundle product from fixed to the dynamic at my store +Fixed Set special price via Catalog Product API is not working +Fixed Price is wrong calculated for bundle product with a zero price for its items on product details page +- subitem price calculation were fixed +Fixed Layout issue appears in IE9 on the grids (example Customers) +Fixed Impossible to press 'Continue' button to place in onepage +Fixed "Add to Wishlist", "Add to Compare" aren't presented for Configurable, bundle, downloadable, simple products on Product Details Page +Fixed Register during checkout with PayPal Express Checkout +Fixed Extension Packager does not read recursive directory if include expression use file mask +Fixed Newsletter Subscription Confirmation Message +Fixed Discount is wrong calculated for Shopping Cart Price Rules when some of them created with Coupon and another without Coupon +Fixed Subtotal (Incl.Tax) on invoices must not include tax applied to shipping amount +- shippingTax amount were excluded from subTotal value +Fixed "Maximum shipping amount allowed to refund" message shows amount excl. tax if Display Shipping Amount set to Including Tax +- adjusted function to include tax into allowed amount for shipping refund +Fixed Display Out of Stock Products must not be considered during admin order creation +Fixed Check box is not working correctly under "prices" of the Bundle products. +Fixed CSS class missing +Fixed Frontend: JavaScript error appears if user registered on Checkout Page +Fixed Website config object is not being cached +- added functionality for memcache backend to split down data that is larger than slab size into chunks +Fixed Removed the ability to work with base_url +Fixed Custom design should be updated via import functionality +Fixed JS error during onepage checkout +Fixed Unable to translate "First name" and "Last name" fields on "Create an Account" page +Fixed After upgrading dashboard "Top 5 Search Terms" grid doesn't show search terms + + + +==== 1.6.x-devel-119961 ==== + +=== Fixes === +Fixed Wrong Comments History in notification of order creation/cancellation +Fixed In AJAX popup fields "From" and "To" have behavior as mandatory fields +Fixed Filter by Allow Countries not working for Customer Address Form in the Backend +Fixed Product price lower than 0 (after catalog price rule applying) +Fixed Google Checkout throws error if Zip Range is used for Tax Rate +- changed part of XML request to Google responsible for postal codes +- made changes to correctly fetch tax rules for postal code ranges +Fixed Website config object is not being cached +Fixed Select groups in grid view doesn't work under IE7 +Fixed No products name in Popular tags report file .csv +Fixed Qty Increments should work when it was defined in the default scope configuration +Fixed Products in catalog displays as "out of stock" +Fixed "Get help for this page" in each tab under System->Configuration links to the same help page +Fixed Unable to translate submenu +Fixed Redirect to main page of front-end during deleting Product Tax Class which is used in Tax Rule +Fixed Redirect to base URL should consider full request URI string + + + +==== 1.6.x-devel-119217 ==== + +=== Fixes === +Fixed Incorrect transparency of PNG image in indexed non-alpha mode +Fixed Problem of generation URL between different domains +Fixed There are no server side validation of first character of Attribute Code (it should be letter) +Fixed Edit Order without creating new one functionality saves invalid changes in non-default customer address attributes +Fixed Frontend: If second customer logs in and does not select the "Remember Me" then the previous long-term cookie does not removes +Fixed Admin can Reorder order with status On Hold +Fixed Frontend: After new customer registration with "Remember Me" and pressing "Logout" the long-term cookie session doesn't apply if in configuration on backend ""Remember Me" Default Value" - No +Fixed Tax not displaying on PayPal side for Express orders +Fixed Wishlist: Not configured grouped product has unneeded link "Show Details" +Fixed Removed the ability to work with customise admin url through the parameter base_url +Fixed Roles not displaying selected resources +Fixed Unable to use Import when compiler is enabled +Fixed Missing Translation Capability in Transactional Email Variable +Fixed productConfigure is undefined error is occurred during creation Order in Backend in IE8 browser +Fixed Zend Full Page Cache. Lifetime of the cookie is not equal to specified on "Cookie Lifetime" field +Fixed Incorrect price values for Bundle Product +Fixed Link does not pass validation if ends with .html +Fixed Incorrect Customs Value in Create Packages in case when price value contains decimals +Fixed Incorrect reports with updated_at filter +Fixed paypal_payment_transaction_clean job takes credentials form default config instead of website for Payflow Link +Fixed Wrong schedule time setup for paypal_payment_transaction_clean job for Payflow Link +Fixed Backend Error message "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'qwe' for key 2" appears after saving new Email Template with existing name +Fixed Rule Conditions logic +Fixed Error appears after Customer Group saving with name length more than 32 +Fixed Category product index run time +Fixed Sidebar cart is missing composite product options on category page +Fixed Missed validation for space character at the begin of unique fields +- improved validation of Attribute Set Name and validation of unique fields in Mage_Core_Model_Resource_Db_Abstract class +Fixed Ability to input uppercase, space, specials symbols in Order Status Code +Fixed Filter by Allow Countries not working for Customer Address Form in the Backend +Fixed No ability to create Shipping Label with "plus-four codes" Zip Code (in case with USPS Domestic) +Fixed Changing language twice -> Error 404 +Fixed The sort order in products page doesn't work +Fixed When a grouped product with configured price=0 is added to the wishlist and shared, adding the product to the cart leads to 404 error +Fixed Media Saves Incorrect Cached Config +- added options that disallow saving cache +Fixed Bundle Product items shows randomly instead of according to option +Fixed Unable to place order with Payflow Link if store credit or reward point applied +Fixed Ajax loader does not appears after click on Verify Card on Payflow Link +Fixed "Google Checkout - Carrier" in Magento backend as shipping method rather than the actual shipping method chosen +Fixed JavaScript error appears in checkout because of PSC after press 'Proceed to Checkout' +Fixed Admin user interface: mistakes in labels names +Fixed Problems with grid sorting on edit customer backend page +Fixed It is possible to change the price of the Bundle product from fixed to the dynamic at my store +Fixed Set special price via Catalog Product API is not working +Fixed Price is wrong calculated for bundle product with a zero price for its items on product details page +- subitem price calculation were fixed +Fixed Layout issue appears in IE9 on the grids (example Customers) +Fixed Impossible to press 'Continue' button to place in onepage +Fixed "Add to Wishlist", "Add to Compare" aren't presented for Configurable, bundle, downloadable, simple products on Product Details Page +Fixed Register during checkout with PayPal Express Checkout +Fixed Extension Packager does not read recursive directory if include expression use file mask +Fixed Newsletter Subscription Confirmation Message +Fixed Discount is wrong calculated for Shopping Cart Price Rules when some of them created with Coupon and another without Coupon +Fixed Subtotal (Incl.Tax) on invoices must not include tax applied to shipping amount +- shippingTax amount were excluded from subTotal value +Fixed "Maximum shipping amount allowed to refund" message shows amount excl. tax if Display Shipping Amount set to Including Tax +- adjusted function to include tax into allowed amount for shipping refund +Fixed Display Out of Stock Products must not be considered during admin order creation +Fixed Check box is not working correctly under "prices" of the Bundle products. +Fixed CSS class missing +Fixed Frontend: JavaScript error appears if user registered on Checkout Page +Fixed Website config object is not being cached +- added functionality for memcache backend to split down data that is larger than slab size into chunks +Fixed Removed the ability to work with base_url +Fixed Custom design should be updated via import functionality +Fixed JS error during onepage checkout +Fixed Unable to translate "First name" and "Last name" fields on "Create an Account" page +Fixed After upgrading dashboard "Top 5 Search Terms" grid doesn't show search terms + + + ==== 1.6.0.0 ==== === Major Highlights === diff --git a/app/Mage.php b/app/Mage.php index 3760a1ce98..85baa7b0b3 100644 --- a/app/Mage.php +++ b/app/Mage.php @@ -152,10 +152,10 @@ public static function getVersionInfo() return array( 'major' => '1', 'minor' => '6', - 'revision' => '0', + 'revision' => '1', 'patch' => '0', - 'stability' => '', - 'number' => '', + 'stability' => 'alpha', + 'number' => '1', ); } diff --git a/app/code/community/Find/Feed/Block/Adminhtml/Edit/Codes/Edit/Form.php b/app/code/community/Find/Feed/Block/Adminhtml/Edit/Codes/Edit/Form.php deleted file mode 100644 index 473ba001ac..0000000000 --- a/app/code/community/Find/Feed/Block/Adminhtml/Edit/Codes/Edit/Form.php +++ /dev/null @@ -1,124 +0,0 @@ - - */ -class Find_Feed_Block_Adminhtml_Edit_Codes_Edit_Form extends Mage_Adminhtml_Block_Widget_Form -{ - /** - * Import codes list - * - * @return array - */ - protected function _getImportCodeList() - { - $attributes = Mage::getConfig()->getNode(Find_Feed_Model_Import::XML_NODE_FIND_FEED_ATTRIBUTES)->children(); - $result = array(); - foreach ($attributes as $node) { - $label = trim((string)$node->label); - if ($label) { - $result[$label] = $label; - } - } - - return $result; - } - - /** - * Magento entity type list for eav attributes - * - * @return array - */ - protected function _getCatalogEntityType() - { - return Mage::getSingleton('eav/config')->getEntityType('catalog_product')->getId(); - } - - - /** - * Magento eav attributes list - * - * @return array - */ - protected function _getEavAttributeList() - { - $result = array(); - $collection = Mage::getResourceModel('catalog/product_attribute_collection'); - foreach ($collection as $model) { - $result[$model->getAttributeCode()] = $model->getAttributeCode(); - } - return $result; - } - - /** - * Prepare form - * - * @return Varien_Object - */ - protected function _prepareForm() - { - $form = new Varien_Data_Form(array( - 'id' => 'import_item_form', - 'method' => 'post' - )); - - $fieldset = $form->addFieldset('generate_fieldset', array( - 'legend' => Mage::helper('find_feed')->__('Item params') - )); - $fieldset->addField('import_code', 'select', array( - 'label' => Mage::helper('find_feed')->__('Import code'), - 'name' => 'import_code', - 'required' => true, - 'options' => $this->_getImportCodeList() - )); - $fieldset->addField('eav_code', 'select', array( - 'label' => Mage::helper('find_feed')->__('Eav code'), - 'name' => 'eav_code', - 'required' => true, - 'options' => $this->_getEavAttributeList() - )); - - $source = Mage::getModel('eav/entity_attribute_source_boolean'); - $isImportedOptions = $source->getOptionArray(); - - $fieldset->addField('is_imported', 'select', array( - 'label' => Mage::helper('find_feed')->__('Is imported'), - 'name' => 'is_imported', - 'value' => 1, - 'options' => $isImportedOptions - )); - $form->setUseContainer(true); - - $this->setForm($form); - return parent::_prepareForm(); - } -} diff --git a/app/code/community/Find/Feed/Block/Adminhtml/List/Codes.php b/app/code/community/Find/Feed/Block/Adminhtml/List/Codes.php deleted file mode 100644 index b75aa6ced5..0000000000 --- a/app/code/community/Find/Feed/Block/Adminhtml/List/Codes.php +++ /dev/null @@ -1,53 +0,0 @@ - - */ -class Find_Feed_Block_Adminhtml_List_Codes extends Mage_Adminhtml_Block_Widget_Grid_Container -{ - /** - * Initialize grid container settings - * - */ - public function __construct() - { - $this->_blockGroup = 'find_feed'; - $this->_controller = 'adminhtml_list_codes'; - $this->_headerText = Mage::helper('find_feed')->__('Attributes map'); - $this->_addButtonLabel = Mage::helper('find_feed')->__('Add new'); - - parent::__construct(); - - $url = $this->getUrl('*/codes_grid/editForm'); - $this->_updateButton('add', 'onclick', 'openNewImportWindow(\''.$url.'\');'); - } -} diff --git a/app/code/community/Find/Feed/Block/Adminhtml/List/Codes/Grid.php b/app/code/community/Find/Feed/Block/Adminhtml/List/Codes/Grid.php deleted file mode 100644 index 9b07c41ef5..0000000000 --- a/app/code/community/Find/Feed/Block/Adminhtml/List/Codes/Grid.php +++ /dev/null @@ -1,131 +0,0 @@ - - */ -class Find_Feed_Block_Adminhtml_List_Codes_Grid extends Mage_Adminhtml_Block_Widget_Grid -{ - /** - * Initialize grid settings - * - */ - protected function _construct() - { - parent::_construct(); - - $this->setId('find_feed_list_codes'); - $this->setUseAjax(true); - } - - /** - * Prepare codes collection - * - * @return Find_Feed_Block_Adminhtml_List_Codes_Grid - */ - protected function _prepareCollection() - { - $collection = Mage::getResourceModel('find_feed/codes_collection'); - $this->setCollection($collection); - return parent::_prepareCollection(); - } - - /** - * Configuration of grid - * - * @return $this - */ - protected function _prepareColumns() - { - $this->addColumn('import_code', array( - 'header'=> Mage::helper('find_feed')->__('Feed code'), - 'width' => '80px', - 'type' => 'text', - 'index' => 'import_code' - )); - - $this->addColumn('eav_code', array( - 'header'=> Mage::helper('find_feed')->__('Eav code'), - 'width' => '80px', - 'type' => 'text', - 'index' => 'eav_code' - )); - - $source = Mage::getModel('eav/entity_attribute_source_boolean'); - $isImportedOptions = $source->getOptionArray(); - - $this->addColumn('is_imported', array( - 'header' => Mage::helper('find_feed')->__('In feed'), - 'width' => '100px', - 'index' => 'is_imported', - 'type' => 'options', - 'options' => $isImportedOptions - )); - return parent::_prepareColumns(); - } - - /** - * Prepare massaction - * - * @return $this - */ - protected function _prepareMassaction() - { - $this->setMassactionIdField('code_id'); - $this->getMassactionBlock()->setFormFieldName('code_id'); - - $this->getMassactionBlock()->addItem('enable', array( - 'label' => Mage::helper('find_feed')->__('Import'), - 'url' => $this->getUrl('*/codes_grid/massEnable'), - 'selected' => true, - )); - $this->getMassactionBlock()->addItem('disable', array( - 'label' => Mage::helper('find_feed')->__('Not import'), - 'url' => $this->getUrl('*/codes_grid/massDisable'), - )); - $this->getMassactionBlock()->addItem('delete', array( - 'label' => Mage::helper('find_feed')->__('Delete'), - 'url' => $this->getUrl('*/codes_grid/delete'), - )); - - return $this; - } - - /** - * Return Grid URL for AJAX query - * - * @return string - */ - public function getGridUrl() - { - return $this->getUrl('*/codes_grid/grid', array('_current'=>true)); - } -} diff --git a/app/code/community/Find/Feed/Block/Adminhtml/List/Items.php b/app/code/community/Find/Feed/Block/Adminhtml/List/Items.php deleted file mode 100644 index d295a4a735..0000000000 --- a/app/code/community/Find/Feed/Block/Adminhtml/List/Items.php +++ /dev/null @@ -1,51 +0,0 @@ - - */ -class Find_Feed_Block_Adminhtml_List_Items extends Mage_Adminhtml_Block_Widget_Grid_Container -{ - /** - * Initialize grid container settings - * - */ - public function __construct() - { - $this->_blockGroup = 'find_feed'; - $this->_controller = 'adminhtml_list_items'; - $this->_headerText = Mage::helper('find_feed')->__('Product import'); - - parent::__construct(); - - $this->_removeButton('add'); - } -} diff --git a/app/code/community/Find/Feed/Block/Adminhtml/List/Items/Grid.php b/app/code/community/Find/Feed/Block/Adminhtml/List/Items/Grid.php deleted file mode 100644 index bdea413002..0000000000 --- a/app/code/community/Find/Feed/Block/Adminhtml/List/Items/Grid.php +++ /dev/null @@ -1,183 +0,0 @@ - - */ -class Find_Feed_Block_Adminhtml_List_Items_Grid extends Mage_Adminhtml_Block_Widget_Grid -{ - /** - * Initialize grid settings - * - */ - protected function _construct() - { - parent::_construct(); - - $this->setId('find_feed_list_items'); - $this->setDefaultSort('id'); - $this->setUseAjax(true); - } - - /** - * Return Current work store - * - * @return Mage_Core_Model_Store - */ - protected function _getStore() - { - return Mage::app()->getStore(); - } - - /** - * Prepare product collection - * - * @return Find_Feed_Block_Adminhtml_List_Items_Grid - */ - protected function _prepareCollection() - { - $collection = Mage::getModel('catalog/product')->getCollection() - ->setStore($this->_getStore()) - ->addAttributeToSelect('name') - ->addAttributeToSelect('sku') - ->addAttributeToSelect('price') - ->addAttributeToSelect('attribute_set_id') - ->addAttributeToSelect('is_imported'); - $this->setCollection($collection); - - return parent::_prepareCollection(); - } - - /** - * Prepare grid columns - * - * @return Find_Feed_Block_Adminhtml_List_Items_Grid - */ - protected function _prepareColumns() - { - $this->addColumn('id', array( - 'header' => Mage::helper('find_feed')->__('ID'), - 'sortable' => true, - 'width' => '60px', - 'index' => 'entity_id' - )); - - $this->addColumn('name', array( - 'header' => Mage::helper('find_feed')->__('Product Name'), - 'index' => 'name', - 'column_css_class' => 'name' - )); - - $this->addColumn('type', array( - 'header' => Mage::helper('find_feed')->__('Type'), - 'width' => '60px', - 'index' => 'type_id', - 'type' => 'options', - 'options' => Mage::getSingleton('catalog/product_type')->getOptionArray(), - )); - - $entityTypeId = Mage::helper('find_feed')->getProductEntityType(); - $sets = Mage::getResourceModel('eav/entity_attribute_set_collection') - ->setEntityTypeFilter($entityTypeId) - ->load() - ->toOptionHash(); - - $this->addColumn('set_name', array( - 'header' => Mage::helper('find_feed')->__('Attrib. Set Name'), - 'width' => '100px', - 'index' => 'attribute_set_id', - 'type' => 'options', - 'options' => $sets, - )); - - $this->addColumn('sku', array( - 'header' => Mage::helper('find_feed')->__('SKU'), - 'width' => '80px', - 'index' => 'sku', - 'column_css_class' => 'sku' - )); - - $this->addColumn('price', array( - 'header' => Mage::helper('find_feed')->__('Price'), - 'align' => 'center', - 'type' => 'currency', - 'currency_code' => $this->_getStore()->getCurrentCurrencyCode(), - 'rate' => $this->_getStore()->getBaseCurrency()->getRate($this->_getStore()->getCurrentCurrencyCode()), - 'index' => 'price' - )); - - $source = Mage::getModel('eav/entity_attribute_source_boolean'); - $isImportedOptions = $source->getOptionArray(); - - $this->addColumn('is_imported', array( - 'header' => Mage::helper('find_feed')->__('In feed'), - 'width' => '100px', - 'index' => 'is_imported', - 'type' => 'options', - 'options' => $isImportedOptions - )); - - return parent::_prepareColumns(); - } - - /** - * Prepare massaction - * - * @return Find_Feed_Block_Adminhtml_List_Items_Grid - */ - protected function _prepareMassaction() - { - $this->setMassactionIdField('entity_id'); - $this->getMassactionBlock()->setFormFieldName('item_id'); - - $this->getMassactionBlock()->addItem('enable', array( - 'label' => Mage::helper('find_feed')->__('Publish'), - 'url' => $this->getUrl('*/items_grid/massEnable'), - 'selected' => true, - )); - $this->getMassactionBlock()->addItem('disable', array( - 'label' => Mage::helper('find_feed')->__('Not publish'), - 'url' => $this->getUrl('*/items_grid/massDisable'), - )); - - return $this; - } - - /** - * Return Grid URL for AJAX query - * - * @return string - */ - public function getGridUrl() - { - return $this->getUrl('*/*/grid', array('_current'=>true)); - } -} diff --git a/app/code/community/Find/Feed/Helper/Data.php b/app/code/community/Find/Feed/Helper/Data.php deleted file mode 100755 index 52ceaac3ff..0000000000 --- a/app/code/community/Find/Feed/Helper/Data.php +++ /dev/null @@ -1,69 +0,0 @@ -getNode(Find_Feed_Model_Import::XML_NODE_FIND_FEED_ATTRIBUTES); - $attributeRequired = array(); - foreach ($attributeConfig->children() as $ac) { - if ((int)$ac->required) { - $attributeRequired[] = (string)$ac->label; - } - } - - foreach ($attributeRequired as $value) { - if (!isset($attributes[$value])) { - return false; - } - } - return true; - } - - /** - * Product entity type - * - * @return int - */ - public function getProductEntityType() - { - return Mage::getSingleton('eav/config')->getEntityType('catalog_product')->getId(); - } -} diff --git a/app/code/community/Find/Feed/Model/Adminhtml/System/Source/Cron/Frequency.php b/app/code/community/Find/Feed/Model/Adminhtml/System/Source/Cron/Frequency.php deleted file mode 100644 index 442298e460..0000000000 --- a/app/code/community/Find/Feed/Model/Adminhtml/System/Source/Cron/Frequency.php +++ /dev/null @@ -1,63 +0,0 @@ - 'Daily', - 'value' => self::DAILY), - array( - 'label' => 'Weekly', - 'value' => self::WEEKLY), - array( - 'label' => 'Monthly', - 'value' => self::MONTHLY), - array( - 'label' => 'Every minute', - 'value' => self::EVERY_MINUTE) - ); - } -} diff --git a/app/code/community/Find/Feed/Model/Import.php b/app/code/community/Find/Feed/Model/Import.php deleted file mode 100755 index c97ca991a3..0000000000 --- a/app/code/community/Find/Feed/Model/Import.php +++ /dev/null @@ -1,271 +0,0 @@ -processImport(); - } - - /** - * TheFind feed process import - */ - public function processImport() - { - $file = $this->_createFile(); - if ($file) { - $this->_deleteFtpFiles(); - $this->_sendFile($file); - if (!$this->_deleteFile($file)) { - Mage::throwException(Mage::helper('find_feed')->__("FTP: Can't delete files")); - } - } - } - - /** - * Create temp csv file and write export - * - * @return mixed - */ - protected function _createFile() - { - $dir = $this->_getTmpDir(); - $fileName = Mage::getStoreConfig(self::XML_PATH_SETTINGS_FINDFEED_FILENAME); - if (!$dir || !$fileName) { - return false; - } - - if (!($attributes = $this->_getImportAttributes()) || count($attributes) <= 0) { - return false; - } - - $headers = array_keys($attributes); - - $file = new Varien_Io_File; - $file->checkAndCreateFolder($dir); - $file->cd($dir); - $file->streamOpen($fileName, 'w+'); - $file->streamLock(); - $file->streamWriteCsv($headers, self::SEPARATOR, self::ENCLOSURE); - - $productCollectionPrototype = Mage::getResourceModel('catalog/product_collection'); - $productCollectionPrototype->setPageSize(self::COLLECTION_PAGE_SIZE); - $pageNumbers = $productCollectionPrototype->getLastPageNumber(); - unset($productCollectionPrototype); - - for ($i = 1; $i <= $pageNumbers; $i++) { - $productCollection = Mage::getResourceModel('catalog/product_collection'); - $productCollection->addAttributeToSelect($attributes); - $productCollection->addAttributeToFilter('is_imported', 1); - $productCollection->setPageSize(self::COLLECTION_PAGE_SIZE); - $productCollection->setCurPage($i)->load(); - foreach ($productCollection as $product) { - $attributesRow = array(); - foreach ($attributes as $key => $value) { - if ($this->_checkAttributeSource($product, $value)) { - if (is_array($product->getAttributeText($value))) { - $attributesRow[$key] = implode(', ', $product->getAttributeText($value)); - } else { - $attributesRow[$key] = $product->getAttributeText($value); - } - } else { - $attributesRow[$key] = $product->getData($value); - } - } - $file->streamWriteCsv($attributesRow, self::SEPARATOR, self::ENCLOSURE); - } - unset($productCollection); - } - - $file->streamUnlock(); - $file->streamClose(); - - if ($file->fileExists($fileName)) { - return $fileName; - } - return false; - } - - /** - * Check attribute source - * - * @param Mage_Catalog_Model_Product $product - * @param string $value - * @return bool - */ - protected function _checkAttributeSource($product, $value) - { - if (!array_key_exists($value, $this->_attributeSources)) { - $this->_attributeSources[$value] = $product->getResource()->getAttribute($value)->usesSource(); - } - return $this->_attributeSources[$value]; - } - - /** - * List import codes (attribute map) model - * - * @return mixed - */ - protected function _getImportAttributes() - { - $attributes = Mage::getResourceModel('find_feed/codes_collection') - ->getImportAttributes(); - - if (!Mage::helper('find_feed')->checkRequired($attributes)) { - return false; - } - return $attributes; - } - - /** - * Send file to remote ftp server - * - * @param string $fileName - */ - protected function _sendFile($fileName) - { - $dir = $this->_getTmpDir(); - $ftpServer = Mage::getStoreConfig(self::XML_PATH_SETTINGS_FTP_SERVER); - $ftpUserName = Mage::getStoreConfig(self::XML_PATH_SETTINGS_FTP_USER); - $ftpPass = Mage::getStoreConfig(self::XML_PATH_SETTINGS_FTP_PASSWORD); - $ftpPath = trim(Mage::getStoreConfig(self::XML_PATH_SETTINGS_FTP_PATH), '/'); - if ($ftpPath) { - $ftpPath = $ftpPath.'/'; - } - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, 'ftp://'.$ftpUserName.':'.$ftpPass.'@'.$ftpServer.'/'.$ftpPath.$fileName); - curl_setopt($ch, CURLOPT_UPLOAD, 1); - curl_setopt($ch, CURLOPT_INFILE, fopen($dir.$fileName, 'r')); - curl_setopt($ch, CURLOPT_INFILESIZE, filesize($dir.$fileName)); - curl_exec($ch); - curl_close($ch); - } - - /** - * Delete all files in current feed ftp directory - * - * @return bool - */ - protected function _deleteFtpFiles() - { - if (is_callable('ftp_connect')) { - $ftpServer = Mage::getStoreConfig(self::XML_PATH_SETTINGS_FTP_SERVER); - $ftpUserName = Mage::getStoreConfig(self::XML_PATH_SETTINGS_FTP_USER); - $ftpPass = Mage::getStoreConfig(self::XML_PATH_SETTINGS_FTP_PASSWORD); - $ftpPath = trim(Mage::getStoreConfig(self::XML_PATH_SETTINGS_FTP_PATH), '/'); - if ($ftpPath) { - $ftpPath = $ftpPath.'/'; - } - - try { - $connId = ftp_connect($ftpServer); - - $loginResult = ftp_login($connId, $ftpUserName, $ftpPass); - if (!$loginResult) { - return false; - } - ftp_pasv($connId, true); - - $ftpDir = $ftpPath?$ftpPath:'.'; - $nlist = ftp_nlist($connId, $ftpDir); - if ($nlist === false) { - return false; - } - foreach ($nlist as $file) { - if (!preg_match('/\.[xX][mM][lL]$/', $file)) { - ftp_delete($connId, $file); - } - } - - ftp_close($connId); - } catch (Exception $e) { - Mage::log($e->getMessage()); - return false; - } - return true; - } else { - return false; - } - } - - /** - * Current tmp directory - * - * @return string - */ - protected function _getTmpDir() - { - return Mage::getBaseDir('var') . DS . 'export' . DS . 'find_feed' . DS; - } - - /** - * Delete tmp file - * - * @param string $fileName - * @return true - */ - protected function _deleteFile($fileName) - { - $dir = $this->_getTmpDir(); - $file = new Varien_Io_File; - if ($file->fileExists($dir . $fileName, true)) { - $file->cd($dir); - $file->rm($fileName); - } - return true; - } -} diff --git a/app/code/community/Find/Feed/Model/Mysql4/Codes.php b/app/code/community/Find/Feed/Model/Mysql4/Codes.php deleted file mode 100644 index c9eaff6f78..0000000000 --- a/app/code/community/Find/Feed/Model/Mysql4/Codes.php +++ /dev/null @@ -1,35 +0,0 @@ -getStore(); - $website = $observer->getWebsite(); - $groups['settings']['fields']['cron_schedule']['value'] = $this->_getSchedule(); - - Mage::getModel('adminhtml/config_data') - ->setSection('feed') - ->setWebsite($website) - ->setStore($store) - ->setGroups($groups) - ->save(); - } - - /** - * Transform system settings option to cron schedule string - * - * @return string - */ - protected function _getSchedule() - { - $data = Mage::app()->getRequest()->getPost('groups'); - - $frequency = !empty($data['settings']['fields']['cron_frequency']['value'])? - $data['settings']['fields']['cron_frequency']['value']: - 0; - $hours = !empty($data['settings']['fields']['cron_hours']['value'])? - $data['settings']['fields']['cron_hours']['value']: - 0; - - $schedule = "0 $hours "; - - switch ($frequency) { - case Find_Feed_Model_Adminhtml_System_Source_Cron_Frequency::DAILY: - $schedule .= "* * *"; - break; - case Find_Feed_Model_Adminhtml_System_Source_Cron_Frequency::WEEKLY: - $schedule .= "* * 1"; - break; - case Find_Feed_Model_Adminhtml_System_Source_Cron_Frequency::MONTHLY: - $schedule .= "1 * *"; - break; - case Find_Feed_Model_Adminhtml_System_Source_Cron_Frequency::EVERY_MINUTE: - $schedule = "0-59 * * * *"; - break; - default: - $schedule .= "* */1 *"; - break; - } - - return $schedule; - } -} diff --git a/app/code/community/Find/Feed/controllers/Adminhtml/Codes/GridController.php b/app/code/community/Find/Feed/controllers/Adminhtml/Codes/GridController.php deleted file mode 100644 index 5d323df366..0000000000 --- a/app/code/community/Find/Feed/controllers/Adminhtml/Codes/GridController.php +++ /dev/null @@ -1,161 +0,0 @@ -loadLayout(); - $this->renderLayout(); - } - - /** - * Grid action - * - */ - public function gridAction() - { - $this->loadLayout(); - $this->getResponse()->setBody($this->getLayout()->createBlock('find_feed/adminhtml_list_codes_grid')->toHtml()); - } - - /** - * Grid edit form action - * - */ - public function editFormAction() - { - $this->loadLayout(); - $this->getResponse()->setBody($this->getLayout()->createBlock('find_feed/adminhtml_edit_codes')->toHtml()); - } - - /** - * Save grid edit form action - * - */ - public function saveFormAction() - { - $codeId = $this->getRequest()->getParam('code_id'); - $response = new Varien_Object(); - try { - $model = Mage::getModel('find_feed/codes'); - if ($codeId) { - $model->load($codeId); - } - $model->setImportCode($this->getRequest()->getParam('import_code')); - $model->setEavCode($this->getRequest()->getParam('eav_code')); - $model->setIsImported(intval($this->getRequest()->getParam('is_imported'))); - $model->save(); - $response->setError(0); - } catch(Exception $e) { - $response->setError(1); - $response->setMessage('Save error'); - } - $this->getResponse()->setBody($response->toJson()); - } - - /** - * Codes (attribute map) list for mass action - * - * @return array - */ - protected function _getMassActionCodes() - { - $idList = $this->getRequest()->getParam('code_id'); - if (!empty($idList)) { - $codes = array(); - foreach ($idList as $id) { - $model = Mage::getModel('find_feed/codes'); - if ($model->load($id)) { - array_push($codes, $model); - } - } - return $codes; - } else { - return array(); - } - } - - /** - * Set imported codes (attribute map) mass action - */ - public function massEnableAction() - { - $updatedCodes = 0; - foreach ($this->_getMassActionCodes() as $code) { - $code->setIsImported(1); - $code->save(); - $updatedCodes++; - } - if ($updatedCodes > 0) { - $this->_getSession()->addSuccess(Mage::helper('find_feed')->__("%s codes imported", $updatedCodes)); - } - $this->_redirect('*/*/index'); - } - - /** - * Set not imported codes (attribute map) mass action - */ - public function massDisableAction() - { - $updatedCodes = 0; - foreach ($this->_getMassActionCodes() as $code) { - $code->setIsImported(0); - $code->save(); - $updatedCodes++; - } - if ($updatedCodes > 0) { - $this->_getSession()->addSuccess(Mage::helper('find_feed')->__("%s codes not imported", $updatedCodes)); - } - $this->_redirect('*/*/index'); - } - - /** - * Delete codes (attribute map) mass action - */ - public function deleteAction() - { - $updatedCodes = 0; - foreach ($this->_getMassActionCodes() as $code) { - $code->delete(); - $updatedCodes++; - } - if ($updatedCodes > 0) { - $this->_getSession()->addSuccess(Mage::helper('find_feed')->__("%s codes deleted", $updatedCodes)); - } - $this->_redirect('*/*/index'); - } -} diff --git a/app/code/community/Find/Feed/controllers/Adminhtml/Items/GridController.php b/app/code/community/Find/Feed/controllers/Adminhtml/Items/GridController.php deleted file mode 100644 index 19272957fd..0000000000 --- a/app/code/community/Find/Feed/controllers/Adminhtml/Items/GridController.php +++ /dev/null @@ -1,115 +0,0 @@ -loadLayout(); - $this->renderLayout(); - } - - /** - * Grid action - */ - public function gridAction() - { - $this->loadLayout(); - $this->getResponse()->setBody($this->getLayout()->createBlock('find_feed/adminhtml_list_items_grid')->toHtml()); - } - - /** - * Product list for mass action - * - * @return array - */ - protected function _getMassActionProducts() - { - $idList = $this->getRequest()->getParam('item_id'); - if (!empty($idList)) { - $products = array(); - foreach ($idList as $id) { - $model = Mage::getModel('catalog/product'); - if ($model->load($id)) { - array_push($products, $model); - } - } - return $products; - } else { - return array(); - } - } - - /** - * Add product to feed mass action - */ - public function massEnableAction() - { - $idList = $this->getRequest()->getParam('item_id'); - $updateAction = Mage::getModel('catalog/product_action'); - $attrData = array( - 'is_imported' => 1 - ); - $updatedProducts = count($idList); - if ($updatedProducts) { - try { - $updateAction->updateAttributes($idList, $attrData, Mage::app()->getStore()->getId()); - Mage::getModel('find_feed/import')->processImport(); - $this->_getSession()->addSuccess(Mage::helper('find_feed')->__("%s product in feed.", $updatedProducts)); - } catch (Exception $e) { - $this->_getSession()->addError(Mage::helper('find_feed')->__("Unable to process an import. ") . $e->getMessage()); - } - } - $this->_redirect('*/*/index'); - } - - /** - * Not add product to feed mass action - */ - public function massDisableAction() - { - $updatedProducts = 0; - foreach ($this->_getMassActionProducts() as $product) { - $product->setIsImported(0); - $product->save(); - $updatedProducts++; - } - if ($updatedProducts) { - Mage::getModel('find_feed/import')->processImport(); - $this->_getSession()->addSuccess(Mage::helper('find_feed')->__("%s product not in feed.", $updatedProducts)); - } - $this->_redirect('*/*/index'); - } -} diff --git a/app/code/community/Find/Feed/etc/adminhtml.xml b/app/code/community/Find/Feed/etc/adminhtml.xml deleted file mode 100644 index e83e3adc23..0000000000 --- a/app/code/community/Find/Feed/etc/adminhtml.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - TheFind feed - 5 - - - Manage attributes - adminhtml/codes_grid/index - 5 - - - Manage items - adminhtml/items_grid/index - 10 - - - - - - - diff --git a/app/code/community/Find/Feed/etc/config.xml b/app/code/community/Find/Feed/etc/config.xml deleted file mode 100755 index 7c7452a187..0000000000 --- a/app/code/community/Find/Feed/etc/config.xml +++ /dev/null @@ -1,481 +0,0 @@ - - - - - - 1.6.0.0 - - - - - - Find_Feed_Model - find_feed_resource - - - Find_Feed_Model_Resource - find_feed_mysql4 - - - find_feed_import_codes
-
-
-
-
- - - - Find_Feed - Find_Feed_Model_Resource_Setup - - - - - Find_Feed_Block - - - - Find_Feed_Helper - - -
- - - - - - find_feed/observer - saveSystemConfig - - - - - - - - - - - - - - Feed - - - - - - - - - - - - - - - feed/settings/cron_schedule - - - find_feed/import::dispatch - - - - - - - - - - Find_Feed_Adminhtml - - - - - - - - - - find - - - - - - - - - feed.xml - - - - - - - <required>1</required> - <label>Title</label> - - - 1 - - - - 1 - - - - 1 - - - - 1 - - - - 0 - - - - 0 - UPC-EAN - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - - 0 - - - -
diff --git a/app/code/community/Find/Feed/etc/system.xml b/app/code/community/Find/Feed/etc/system.xml deleted file mode 100755 index 46a8d5dc09..0000000000 --- a/app/code/community/Find/Feed/etc/system.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - 300 - - - - - - find - 100 - 1 - 1 - 1 - - - - text - 200 - 1 - 1 - 1 - - - - - - - text - 10 - 1 - 1 - 1 - - - - text - 15 - 1 - 1 - 1 - - - - text - 20 - 1 - 1 - 1 - here to get started.]]> - - - - password - 30 - 1 - 1 - 1 - - - - text - 30 - 1 - 1 - 1 - - - 40 - - select - adminhtml/system_config_source_yesno - 1 - 1 - 1 - - - - select - find_feed/adminhtml_system_source_cron_frequency - 60 - 1 - 1 - 1 - - - - select - find_feed/adminhtml_system_source_cron_hours - 70 - 1 - 1 - 1 - - - - - - - diff --git a/app/code/community/Find/Feed/sql/find_feed_setup/install-1.6.0.0.php b/app/code/community/Find/Feed/sql/find_feed_setup/install-1.6.0.0.php deleted file mode 100644 index 04cd448c99..0000000000 --- a/app/code/community/Find/Feed/sql/find_feed_setup/install-1.6.0.0.php +++ /dev/null @@ -1,74 +0,0 @@ -startSetup(); -/** - * Create table 'find_feed/feed_import_codes' - */ -$table = $installer->getConnection() - ->newTable($installer->getTable('find_feed/feed_import_codes')) - ->addColumn('code_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array( - 'identity' => true, - 'unsigned' => true, - 'nullable' => false, - 'primary' => true, - ), 'Code id') - ->addColumn('import_code', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array( - 'nullable' => false, - ), 'Import type') - ->addColumn('eav_code', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array( - 'nullable' => false, - ), 'EAV code') - ->addColumn('is_imported', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array( - 'nullable' => false, - ), 'Is imported') - ->setComment('Find feed import codes'); -$installer->getConnection()->createTable($table); - -$this->addAttribute('catalog_product', 'is_imported', array( - 'group' => 'General', - 'type' => 'int', - 'input' => 'select', - 'label' => 'In feed', - 'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL, - 'visible' => 1, - 'required' => 0, - 'visible_on_front' => 0, - 'is_html_allowed_on_front' => 0, - 'is_configurable' => 0, - 'source' => 'eav/entity_attribute_source_boolean', - 'searchable' => 0, - 'filterable' => 0, - 'comparable' => 0, - 'unique' => false, - 'user_defined' => false, - 'is_user_defined' => false, - 'used_in_product_listing' => true -)); - -$installer->endSetup(); diff --git a/app/code/community/Find/Feed/sql/find_feed_setup/mysql4-install-0.0.1.php b/app/code/community/Find/Feed/sql/find_feed_setup/mysql4-install-0.0.1.php deleted file mode 100755 index 7545aab007..0000000000 --- a/app/code/community/Find/Feed/sql/find_feed_setup/mysql4-install-0.0.1.php +++ /dev/null @@ -1,41 +0,0 @@ -startSetup(); - -$this->run(" - -CREATE TABLE {$this->getTable('find_feed_import_codes')} ( - `code_id` int(10) unsigned NOT NULL auto_increment, - `import_code` varchar(255) NOT NULL, - `eav_code` varchar(255) NOT NULL, - `is_imported` int(10) unsigned NOT NULL, - PRIMARY KEY (`code_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -"); - -$this->endSetup(); diff --git a/app/code/community/Find/Feed/sql/find_feed_setup/mysql4-upgrade-0.0.1-0.0.2.php b/app/code/community/Find/Feed/sql/find_feed_setup/mysql4-upgrade-0.0.1-0.0.2.php deleted file mode 100644 index a7f84e24c5..0000000000 --- a/app/code/community/Find/Feed/sql/find_feed_setup/mysql4-upgrade-0.0.1-0.0.2.php +++ /dev/null @@ -1,50 +0,0 @@ -startSetup(); - -$this->addAttribute('catalog_product', 'is_imported', array( - 'group' => 'General', - 'type' => 'int', - 'input' => 'select', - 'label' => 'In feed', - 'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL, - 'visible' => 1, - 'required' => 0, - 'visible_on_front' => 0, - 'is_html_allowed_on_front' => 0, - 'is_configurable' => 0, - 'source' => 'eav/entity_attribute_source_boolean', - 'searchable' => 0, - 'filterable' => 0, - 'comparable' => 0, - 'unique' => false, - 'user_defined' => false, - 'is_user_defined' => false, - 'used_in_product_listing' => true -)); - -$this->endSetup(); diff --git a/app/code/community/Find/Feed/Block/Adminhtml/Edit/Codes.php b/app/code/core/Mage/Admin/Helper/Data.php similarity index 55% rename from app/code/community/Find/Feed/Block/Adminhtml/Edit/Codes.php rename to app/code/core/Mage/Admin/Helper/Data.php index e150b1538f..cc480c9385 100644 --- a/app/code/community/Find/Feed/Block/Adminhtml/Edit/Codes.php +++ b/app/code/core/Mage/Admin/Helper/Data.php @@ -18,47 +18,44 @@ * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * - * @category - * @package _storage + * @category Mage + * @package Mage_Admin * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ - /** - * Attribute map edit codes form container block + * Admin Data Helper * - * @category Find - * @package Find_Feed + * @category Mage + * @package Mage_Admin * @author Magento Core Team */ -class Find_Feed_Block_Adminhtml_Edit_Codes extends Mage_Adminhtml_Block_Widget_Form_Container +class Mage_Admin_Helper_Data extends Mage_Core_Helper_Abstract { /** - * Initialize form container + * Configuration path to expiration period of reset password link + */ + const XML_PATH_ADMIN_RESET_PASSWORD_LINK_EXPIRATION_PERIOD + = 'default/admin/emails/password_reset_link_expiration_period'; + + /** + * Generate unique token for reset password confirmation link * + * @return string */ - public function __construct() + public function generateResetPasswordLinkToken() { - $this->_blockGroup = 'find_feed'; - $this->_controller = 'adminhtml_edit_codes'; - - parent::__construct(); - - $this->_removeButton('back'); - $url = $this->getUrl('*/codes_grid/saveForm'); - $this->_updateButton('save', 'onclick', 'saveNewImportItem(\''.$url.'\')'); - $this->_updateButton('reset', 'label', 'Close'); - $this->_updateButton('reset', 'onclick', 'closeNewImportItem()'); + return Mage::helper('core')->uniqHash(); } /** - * Return Form Header text + * Retrieve customer reset password link expiration period in days * - * @return string + * @return int */ - public function getHeaderText() + public function getResetPasswordLinkExpirationPeriod() { - return Mage::helper('find_feed')->__('Import attribute map'); + return (int) Mage::getConfig()->getNode(self::XML_PATH_ADMIN_RESET_PASSWORD_LINK_EXPIRATION_PERIOD); } } diff --git a/app/code/core/Mage/Admin/Model/Observer.php b/app/code/core/Mage/Admin/Model/Observer.php index ebc30aa242..c685beb3c0 100644 --- a/app/code/core/Mage/Admin/Model/Observer.php +++ b/app/code/core/Mage/Admin/Model/Observer.php @@ -27,23 +27,35 @@ /** * Admin observer model * - * @category Mage - * @package Mage_Admin + * @category Mage + * @package Mage_Admin * @author Magento Core Team */ class Mage_Admin_Model_Observer { - public function actionPreDispatchAdmin($event) + /** + * Handler for controller_action_predispatch event + * + * @param Varien_Event_Observer $observer + * @return boolean + */ + public function actionPreDispatchAdmin($observer) { - $session = Mage::getSingleton('admin/session'); - /* @var $session Mage_Admin_Model_Session */ + $session = Mage::getSingleton('admin/session'); + /** @var $session Mage_Admin_Model_Session */ $request = Mage::app()->getRequest(); $user = $session->getUser(); - if ($request->getActionName() == 'forgotpassword' || $request->getActionName() == 'logout') { + $requestedActionName = $request->getActionName(); + $openActions = array( + 'forgotpassword', + 'resetpassword', + 'resetpasswordpost', + 'logout' + ); + if (in_array($requestedActionName, $openActions)) { $request->setDispatched(true); - } - else { + } else { if($user) { $user->reload(); } @@ -61,8 +73,7 @@ public function actionPreDispatchAdmin($event) ->setControllerName('index') ->setActionName('deniedIframe') ->setDispatched(false); - } - elseif($request->getParam('isAjax')) { + } elseif($request->getParam('isAjax')) { $request->setParam('forwarded', true) ->setControllerName('index') ->setActionName('deniedJson') diff --git a/app/code/core/Mage/Admin/Model/User.php b/app/code/core/Mage/Admin/Model/User.php index d2721714c1..f9b37bebcd 100644 --- a/app/code/core/Mage/Admin/Model/User.php +++ b/app/code/core/Mage/Admin/Model/User.php @@ -60,22 +60,41 @@ */ class Mage_Admin_Model_User extends Mage_Core_Model_Abstract { + /** + * Configuration pathes for email templates and identities + */ const XML_PATH_FORGOT_EMAIL_TEMPLATE = 'admin/emails/forgot_email_template'; const XML_PATH_FORGOT_EMAIL_IDENTITY = 'admin/emails/forgot_email_identity'; const XML_PATH_STARTUP_PAGE = 'admin/startup/page'; + + /** + * Minimum length of admin password + */ const MIN_PASSWORD_LENGTH = 7; + /** + * Model event prefix + * + * @var string + */ protected $_eventPrefix = 'admin_user'; /** + * Admin role + * * @var Mage_Admin_Model_Roles */ protected $_role; + /** + * Available resources flag + * + * @var boolean + */ protected $_hasAvailableResources = true; /** - * Varien constructor + * Initialize user model */ protected function _construct() { @@ -105,13 +124,15 @@ protected function _beforeSave() $data['username'] = $this->getUsername(); } - if ($this->getNewPassword()) { // change password + if ($this->getNewPassword()) { + // Change password $data['password'] = $this->_getEncodedPassword($this->getNewPassword()); - } elseif ($this->getPassword() && $this->getPassword() != $this->getOrigData('password')) { // new user password + } elseif ($this->getPassword() && $this->getPassword() != $this->getOrigData('password')) { + // New user password $data['password'] = $this->_getEncodedPassword($this->getPassword()); } - if ( !is_null($this->getIsActive()) ) { + if (!is_null($this->getIsActive())) { $data['is_active'] = intval($this->getIsActive()); } @@ -146,6 +167,11 @@ public function saveRelations() return $this; } + /** + * Retrieve user roles + * + * @return array + */ public function getRoles() { return $this->_getResource()->getRoles($this); @@ -168,30 +194,55 @@ public function getRole() return $this->_role; } + /** + * Unassign user from his current role + * + * @return Mage_Admin_Model_User + */ public function deleteFromRole() { $this->_getResource()->deleteFromRole($this); return $this; } + /** + * Check if such combination role/user exists + * + * @return boolean + */ public function roleUserExists() { $result = $this->_getResource()->roleUserExists($this); - return ( is_array($result) && count($result) > 0 ) ? true : false; + return (is_array($result) && count($result) > 0) ? true : false; } + /** + * Assign user to role + * + * @return Mage_Admin_Model_User + */ public function add() { $this->_getResource()->add($this); return $this; } + /** + * Check if user exists based on its id, username and email + * + * @return boolean + */ public function userExists() { $result = $this->_getResource()->userExists($this); - return ( is_array($result) && count($result) > 0 ) ? true : false; + return (is_array($result) && count($result) > 0) ? true : false; } + /** + * Retrieve admin user collection + * + * @return Mage_Admin_Model_Resource_User_Collection + */ public function getCollection() { return Mage::getResourceModel('admin/user_collection'); } @@ -200,32 +251,54 @@ public function getCollection() { * Send email with new user password * * @return Mage_Admin_Model_User + * @deprecated deprecated since version 1.6.1.0 */ public function sendNewPasswordEmail() { - $translate = Mage::getSingleton('core/translate'); - /* @var $translate Mage_Core_Model_Translate */ - $translate->setTranslateInline(false); - - Mage::getModel('core/email_template') - ->setDesignConfig(array('area' => 'adminhtml', 'store' => $this->getStoreId())) - ->sendTransactional( - Mage::getStoreConfig(self::XML_PATH_FORGOT_EMAIL_TEMPLATE), - Mage::getStoreConfig(self::XML_PATH_FORGOT_EMAIL_IDENTITY), - $this->getEmail(), - $this->getName(), - array('user' => $this, 'password' => $this->getPlainPassword())); + return $this; + } - $translate->setTranslateInline(true); + /** + * Send email with reset password confirmation link + * + * @return Mage_Admin_Model_User + */ + public function sendPasswordResetConfirmationEmail() + { + /** @var $mailer Mage_Core_Model_Email_Template_Mailer */ + $mailer = Mage::getModel('core/email_template_mailer'); + $emailInfo = Mage::getModel('core/email_info'); + $emailInfo->addTo($this->getEmail(), $this->getName()); + $mailer->addEmailInfo($emailInfo); + + // Set all required params and send emails + $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_FORGOT_EMAIL_IDENTITY)); + $mailer->setStoreId(0); + $mailer->setTemplateId(Mage::getStoreConfig(self::XML_PATH_FORGOT_EMAIL_TEMPLATE)); + $mailer->setTemplateParams(array( + 'user' => $this + )); + $mailer->send(); return $this; } + /** + * Retrieve user name + * + * @param string $separator + * @return string + */ public function getName($separator = ' ') { return $this->getFirstname() . $separator . $this->getLastname(); } + /** + * Retrieve user identifier + * + * @return mixed + */ public function getId() { return $this->getUserId(); @@ -301,6 +374,11 @@ public function login($username, $password) return $this; } + /** + * Reload current user + * + * @return Mage_Admin_Model_User + */ public function reload() { $id = $this->getId(); @@ -309,20 +387,38 @@ public function reload() return $this; } + /** + * Load user by its username + * + * @param string $username + * @return Mage_Admin_Model_User + */ public function loadByUsername($username) { $this->setData($this->getResource()->loadByUsername($username)); return $this; } + /** + * Check if user is assigned to any role + * + * @param int|Mage_Core_Admin_Model_User $user + * @return null|boolean|array + */ public function hasAssigned2Role($user) { return $this->getResource()->hasAssigned2Role($user); } - protected function _getEncodedPassword($pwd) + /** + * Retrieve encoded password + * + * @param string $password + * @return string + */ + protected function _getEncodedPassword($password) { - return Mage::helper('core')->getHash($pwd, 2); + return Mage::helper('core')->getHash($password, 2); } /** @@ -425,7 +521,9 @@ public function validate() $errors[] = Mage::helper('adminhtml')->__('Password must be at least of %d characters.', self::MIN_PASSWORD_LENGTH); } - if (!preg_match('/[a-z]/iu', $this->getNewPassword()) || !preg_match('/[0-9]/u', $this->getNewPassword())) { + if (!preg_match('/[a-z]/iu', $this->getNewPassword()) + || !preg_match('/[0-9]/u', $this->getNewPassword()) + ) { $errors[] = Mage::helper('adminhtml')->__('Password must include both numeric and alphabetic characters.'); } @@ -444,4 +542,55 @@ public function validate() return $errors; } + /** + * Change reset password link token + * + * Stores new reset password link token and its creation time + * + * @param string $newResetPasswordLinkToken + * @return Mage_Admin_Model_User + * @throws Mage_Core_Exception + */ + public function changeResetPasswordLinkToken($newResetPasswordLinkToken) { + if (!is_string($newResetPasswordLinkToken) || empty($newResetPasswordLinkToken)) { + throw Mage::exception('Mage_Core', Mage::helper('adminhtml')->__('Invalid password reset token.')); + } + $this->setRpToken($newResetPasswordLinkToken); + $currentDate = Varien_Date::now(true); + $this->setRpTokenCreatedAt($currentDate); + + return $this; + } + + /** + * Check if current reset password link token is expired + * + * @return boolean + */ + public function isResetPasswordLinkTokenExpired() + { + $resetPasswordLinkToken = $this->getRpToken(); + $resetPasswordLinkTokenCreatedAt = $this->getRpTokenCreatedAt(); + + if (empty($resetPasswordLinkToken) || empty($resetPasswordLinkTokenCreatedAt)) { + return true; + } + + $tokenExpirationPeriod = Mage::helper('admin')->getResetPasswordLinkExpirationPeriod(); + + $currentDate = Varien_Date::now(true); + $currentTimestamp = Varien_Date::toTimestamp($currentDate); + $tokenTimestamp = Varien_Date::toTimestamp($resetPasswordLinkTokenCreatedAt); + if ($tokenTimestamp > $currentTimestamp) { + return true; + } + + $dayDifference = floor(($currentTimestamp - $tokenTimestamp) / (24 * 60 * 60)); + if ($dayDifference >= $tokenExpirationPeriod) { + return true; + } + + return false; + } + } diff --git a/app/code/core/Mage/Admin/etc/config.xml b/app/code/core/Mage/Admin/etc/config.xml index b4ce4f3093..8446743297 100644 --- a/app/code/core/Mage/Admin/etc/config.xml +++ b/app/code/core/Mage/Admin/etc/config.xml @@ -28,7 +28,7 @@ - 1.6.0.0 + 1.6.1.0 @@ -56,6 +56,11 @@ + + + Mage_Admin_Helper + + @@ -74,6 +79,7 @@ admin_emails_forgot_email_template general + 3 diff --git a/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/mysql4-install-0.1.0.php b/app/code/core/Mage/Admin/sql/admin_setup/mysql4-upgrade-1.6.0.0-1.6.1.0.php similarity index 56% rename from app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/mysql4-install-0.1.0.php rename to app/code/core/Mage/Admin/sql/admin_setup/mysql4-upgrade-1.6.0.0-1.6.1.0.php index 38da846c8a..8a48a5be82 100644 --- a/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/mysql4-install-0.1.0.php +++ b/app/code/core/Mage/Admin/sql/admin_setup/mysql4-upgrade-1.6.0.0-1.6.1.0.php @@ -19,32 +19,30 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Admin * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ +/** @var $installer Mage_Core_Model_Resource_Setup */ $installer = $this; -/* @var $installer Mage_Core_Model_Resource_Setup */ - $installer->startSetup(); -$installer->run(" - -DROP TABLE IF EXISTS {$this->getTable('googleoptimizer/code')}; -CREATE TABLE {$this->getTable('googleoptimizer/code')} ( - `code_id` int(10) unsigned NOT NULL auto_increment, - `entity_id` int(10) unsigned NOT NULL, - `entity_type` varchar(50) NOT NULL default '', - `store_id` smallint(5) unsigned NOT NULL, - `control_script` text, - `tracking_script` text, - `conversion_script` text, - PRIMARY KEY (`code_id`), - KEY `GOOGLEOPTIMIZER_CODE_STORE` (`store_id`), - CONSTRAINT `FK_GOOGLEOPTIMIZER_CODE_STORE` FOREIGN KEY (`store_id`) REFERENCES `{$this->getTable('core/store')}` (`store_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8; +// Add reset password link token column +$installer->getConnection()->addColumn($installer->getTable('admin/user'), 'rp_token', array( + 'type' => Varien_Db_Ddl_Table::TYPE_TEXT, + 'length' => 256, + 'nullable' => true, + 'default' => null, + 'comment' => 'Reset Password Link Token' +)); - "); +// Add reset password link token creation date column +$installer->getConnection()->addColumn($installer->getTable('admin/user'), 'rp_token_created_at', array( + 'type' => Varien_Db_Ddl_Table::TYPE_TIMESTAMP, + 'nullable' => true, + 'default' => null, + 'comment' => 'Reset Password Link Token Creation Date' +)); $installer->endSetup(); diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit.php index 69e4f777a1..1eb19e6042 100644 --- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit.php +++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit.php @@ -42,16 +42,4 @@ public function __construct() parent::__construct(); $this->setTemplate('catalog/category/edit.phtml'); } - - protected function _prepareLayout() - { - $category = Mage::registry('current_category'); - if (Mage::app()->getConfig()->getModuleConfig('Mage_GoogleOptimizer')->is('active', true) - && Mage::helper('googleoptimizer')->isOptimizerActive($category->getStoreId())) { - $this->setChild('googleoptimizer_js', - $this->getLayout()->createBlock('googleoptimizer/js')->setTemplate('googleoptimizer/js.phtml') - ); - } - return parent::_prepareLayout(); - } } diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tabs.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tabs.php index 8417c19290..33c03fd777 100644 --- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tabs.php +++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tabs.php @@ -147,7 +147,10 @@ protected function _prepareLayout() $this->addTab('products', array( 'label' => Mage::helper('catalog')->__('Category Products'), - 'content' => $this->getLayout()->createBlock('adminhtml/catalog_category_tab_product', 'category.product.grid')->toHtml(), + 'content' => $this->getLayout()->createBlock( + 'adminhtml/catalog_category_tab_product', + 'category.product.grid' + )->toHtml(), )); // dispatch event add custom tabs @@ -155,17 +158,6 @@ protected function _prepareLayout() 'tabs' => $this )); - /** - * @todo Adding tab in observer - */ - if (Mage::app()->getConfig()->getModuleConfig('Mage_GoogleOptimizer')->is('active', true) - && Mage::helper('googleoptimizer')->isOptimizerActive($this->getCategory()->getStoreId())) { - $this->addTab('googleoptimizer', array( - 'label' => Mage::helper('googleoptimizer')->__('Category View Optimization'), - 'content' => $this->getLayout()->createBlock('googleoptimizer/adminhtml_catalog_category_edit_tab_googleoptimizer')->toHtml(), - )); - } - /*$this->addTab('features', array( 'label' => Mage::helper('catalog')->__('Feature Products'), 'content' => 'Feature Products' diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Group/Edit/Form.php b/app/code/core/Mage/Adminhtml/Block/Customer/Group/Edit/Form.php index d442aa3b36..5466380aec 100644 --- a/app/code/core/Mage/Adminhtml/Block/Customer/Group/Edit/Form.php +++ b/app/code/core/Mage/Adminhtml/Block/Customer/Group/Edit/Form.php @@ -44,12 +44,16 @@ protected function _prepareLayout() $fieldset = $form->addFieldset('base_fieldset', array('legend'=>Mage::helper('customer')->__('Group Information'))); + $validateClass = sprintf('required-entry validate-length maximum-length-%d', + Mage_Customer_Model_Group::GROUP_CODE_MAX_LENGTH); $name = $fieldset->addField('customer_group_code', 'text', array( 'name' => 'code', 'label' => Mage::helper('customer')->__('Group Name'), 'title' => Mage::helper('customer')->__('Group Name'), - 'class' => 'required-entry', + 'note' => Mage::helper('customer')->__('Maximum length must be less then %s symbols', + Mage_Customer_Model_Group::GROUP_CODE_MAX_LENGTH), + 'class' => $validateClass, 'required' => true, ) ); diff --git a/app/code/core/Mage/Adminhtml/Block/Page/Menu.php b/app/code/core/Mage/Adminhtml/Block/Page/Menu.php index f92f9af252..3b2d86e386 100644 --- a/app/code/core/Mage/Adminhtml/Block/Page/Menu.php +++ b/app/code/core/Mage/Adminhtml/Block/Page/Menu.php @@ -27,6 +27,9 @@ /** * Adminhtml menu block * + * @method Mage_Adminhtml_Block_Page_Menu setAdditionalCacheKeyInfo(array $cacheKeyInfo) + * @method array getAdditionalCacheKeyInfo() + * * @category Mage * @package Mage_Adminhtml * @author Magento Core Team @@ -71,12 +74,18 @@ public function getCacheLifetime() */ public function getCacheKeyInfo() { - return array( + $cacheKeyInfo = array( 'admin_top_nav', $this->getActive(), Mage::getSingleton('admin/session')->getUser()->getId(), Mage::app()->getLocale()->getLocaleCode() ); + // Add additional key parameters if needed + $additionalCacheKeyInfo = $this->getAdditionalCacheKeyInfo(); + if (is_array($additionalCacheKeyInfo) && !empty($additionalCacheKeyInfo)) { + $cacheKeyInfo = array_merge($cacheKeyInfo, $additionalCacheKeyInfo); + } + return $cacheKeyInfo; } /** diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Mysql4/Code/Collection.php b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Js.php similarity index 82% rename from app/code/core/Mage/GoogleOptimizer/Model/Mysql4/Code/Collection.php rename to app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Js.php index 75447ad631..34cee5950f 100644 --- a/app/code/core/Mage/GoogleOptimizer/Model/Mysql4/Code/Collection.php +++ b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Js.php @@ -19,19 +19,18 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Adminhtml * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ - /** - * Google Optimizer collection + * description * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Adminhtml * @author Magento Core Team */ -class Mage_GoogleOptimizer_Model_Mysql4_Code_Collection extends Mage_GoogleOptimizer_Model_Resource_Code_Collection +class Mage_Adminhtml_Block_Promo_Catalog_Edit_Js extends Mage_Adminhtml_Block_Template { } diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Tab/Actions.php b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Tab/Actions.php index 964eed53ba..ec29c1ca1c 100644 --- a/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Tab/Actions.php +++ b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Tab/Actions.php @@ -28,8 +28,7 @@ * description * * @category Mage - * @category Mage - * @package Mage_Adminhtml + * @package Mage_Adminhtml * @author Magento Core Team */ class Mage_Adminhtml_Block_Promo_Catalog_Edit_Tab_Actions @@ -80,38 +79,69 @@ protected function _prepareForm() { $model = Mage::registry('current_promo_catalog_rule'); - //$form = new Varien_Data_Form(array('id' => 'edit_form1', 'action' => $this->getData('action'), 'method' => 'post')); $form = new Varien_Data_Form(); $form->setHtmlIdPrefix('rule_'); - $fieldset = $form->addFieldset('action_fieldset', array('legend'=>Mage::helper('salesrule')->__('Update Prices Using the Following Information'))); + $fieldset = $form->addFieldset('action_fieldset', array( + 'legend' => Mage::helper('catalogrule')->__('Update Prices Using the Following Information') + ) + ); $fieldset->addField('simple_action', 'select', array( - 'label' => Mage::helper('salesrule')->__('Apply'), + 'label' => Mage::helper('catalogrule')->__('Apply'), 'name' => 'simple_action', - 'options' => array( - 'by_percent' => Mage::helper('salesrule')->__('By Percentage of the Original Price'), - 'by_fixed' => Mage::helper('salesrule')->__('By Fixed Amount'), - 'to_percent' => Mage::helper('salesrule')->__('To Percentage of the Original Price'), - 'to_fixed' => Mage::helper('salesrule')->__('To Fixed Amount'), + 'options' => array( + 'by_percent' => Mage::helper('catalogrule')->__('By Percentage of the Original Price'), + 'by_fixed' => Mage::helper('catalogrule')->__('By Fixed Amount'), + 'to_percent' => Mage::helper('catalogrule')->__('To Percentage of the Original Price'), + 'to_fixed' => Mage::helper('catalogrule')->__('To Fixed Amount'), ), )); $fieldset->addField('discount_amount', 'text', array( - 'name' => 'discount_amount', - 'required' => true, - 'class' => 'validate-not-negative-number', - 'label' => Mage::helper('salesrule')->__('Discount Amount'), + 'name' => 'discount_amount', + 'required' => true, + 'class' => 'validate-not-negative-number', + 'label' => Mage::helper('catalogrule')->__('Discount Amount'), + )); + + $fieldset->addField('sub_is_enable', 'select', array( + 'name' => 'sub_is_enable', + 'label' => Mage::helper('catalogrule')->__('Enable Discount to Subproducts'), + 'title' => Mage::helper('catalogrule')->__('Enable Discount to Subproducts'), + 'onchange' => 'hideShowSubproductOptions(this);', + 'values' => array( + 0 => Mage::helper('catalogrule')->__('No'), + 1 => Mage::helper('catalogrule')->__('Yes') + ) + )); + + $fieldset->addField('sub_simple_action', 'select', array( + 'label' => Mage::helper('catalogrule')->__('Apply'), + 'name' => 'sub_simple_action', + 'options' => array( + 'by_percent' => Mage::helper('catalogrule')->__('By Percentage of the Original Price'), + 'by_fixed' => Mage::helper('catalogrule')->__('By Fixed Amount'), + 'to_percent' => Mage::helper('catalogrule')->__('To Percentage of the Original Price'), + 'to_fixed' => Mage::helper('catalogrule')->__('To Fixed Amount'), + ), + )); + + $fieldset->addField('sub_discount_amount', 'text', array( + 'name' => 'sub_discount_amount', + 'required' => true, + 'class' => 'validate-not-negative-number', + 'label' => Mage::helper('catalogrule')->__('Discount Amount'), )); $fieldset->addField('stop_rules_processing', 'select', array( - 'label' => Mage::helper('salesrule')->__('Stop Further Rules Processing'), - 'title' => Mage::helper('salesrule')->__('Stop Further Rules Processing'), + 'label' => Mage::helper('catalogrule')->__('Stop Further Rules Processing'), + 'title' => Mage::helper('catalogrule')->__('Stop Further Rules Processing'), 'name' => 'stop_rules_processing', - 'options' => array( - '1' => Mage::helper('salesrule')->__('Yes'), - '0' => Mage::helper('salesrule')->__('No'), + 'options' => array( + '1' => Mage::helper('catalogrule')->__('Yes'), + '0' => Mage::helper('catalogrule')->__('No'), ), )); diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular/Detail/Grid.php b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular/Detail/Grid.php index 66de6ca950..5067ac356c 100644 --- a/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular/Detail/Grid.php +++ b/app/code/core/Mage/Adminhtml/Block/Report/Tag/Popular/Detail/Grid.php @@ -40,24 +40,30 @@ public function __construct() $this->setId('tag_grid'); } + /** + * Prepare collection for grid + * + * @return Mage_Adminhtml_Block_Report_Tag_Popular_Detail_Grid + */ protected function _prepareCollection() { - - $collection = Mage::getResourceModel('reports/tag_customer_collection') - ->addStatusFilter(Mage::getModel('tag/tag')->getApprovedStatus()) + /* @var $collection Mage_Reports_Model_Resource_Tag_Customer_Collection */ + $collection = Mage::getResourceModel('reports/tag_customer_collection'); + $collection->addStatusFilter(Mage::getModel('tag/tag')->getApprovedStatus()) ->addTagFilter($this->getRequest()->getParam('id')) - ->addDescOrder(); + ->addDescOrder() + ->addProductName(); $this->setCollection($collection); return parent::_prepareCollection(); } - protected function _afterLoadCollection() - { - $this->getCollection()->addProductName(); - } - + /** + * Form columns for the grid + * + * @return Mage_Adminhtml_Block_Report_Tag_Popular_Detail_Grid + */ protected function _prepareColumns() { 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 15b3ad601c..5b29721c3d 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 @@ -141,7 +141,8 @@ protected function _addAttributesToForm($attributes, Varien_Data_Form_Abstract $ $renderers = $this->_getAdditionalFormElementRenderers(); foreach ($attributes as $attribute) { - /* @var $attribute Mage_Customer_Model_Attribute */ + /** @var $attribute Mage_Customer_Model_Attribute */ + $attribute->setStoreId(Mage::getSingleton('adminhtml/session_quote')->getStoreId()); $inputType = $attribute->getFrontend()->getInputType(); if ($inputType) { 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 0f09b3f239..6848bb0e48 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 @@ -233,9 +233,6 @@ protected function _prepareVisibleFields(Varien_Data_Form_Element_Fieldset $fiel 'label' => Mage::helper('sales')->__('Message'), 'rows' => '5', 'cols' => '20', - 'onchange' => 'giftMessagesController.toogleRequired(\'' . $this->_getFieldId('message') - . '\', [\'' . $this->_getFieldId('sender') - . '\', \'' . $this->_getFieldId('recipient') . '\']);' ) ); return $this; 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 181c4600bc..df9604407d 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 @@ -87,14 +87,20 @@ protected function _addColumnFilterToCollection($column) return $this; } + /** + * Prepare collection to be displayed in the grid + * + * @return Mage_Adminhtml_Block_Sales_Order_Create_Search_Grid + */ protected function _prepareCollection() { $attributes = Mage::getSingleton('catalog/config')->getProductAttributes(); - $collection = Mage::getModel('catalog/product')->getCollection() + /* @var $collection Mage_Catalog_Model_Resource_Product_Collection */ + $collection = Mage::getModel('catalog/product')->getCollection(); + $collection ->setStore($this->getStore()) ->addAttributeToSelect($attributes) ->addAttributeToSelect('sku') - ->addMinimalPrice() ->addStoreFilter() ->addAttributeToFilter('type_id', array_keys( Mage::getConfig()->getNode('adminhtml/sales/order/create/available_product_types')->asArray() diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Creditmemo/View.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Creditmemo/View.php index 579ac45f0e..56314c13c0 100644 --- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Creditmemo/View.php +++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Creditmemo/View.php @@ -188,7 +188,7 @@ public function getEmailUrl() public function getPrintUrl() { return $this->getUrl('*/*/print', array( - 'invoice_id' => $this->getCreditmemo()->getId() + 'creditmemo_id' => $this->getCreditmemo()->getId() )); } @@ -201,10 +201,18 @@ public function updateBackButtonUrl($flag) { if ($flag) { if ($this->getCreditmemo()->getBackUrl()) { - return $this->_updateButton('back', 'onclick', 'setLocation(\'' . $this->getCreditmemo()->getBackUrl() . '\')'); + return $this->_updateButton( + 'back', + 'onclick', + 'setLocation(\'' . $this->getCreditmemo()->getBackUrl() . '\')' + ); } - return $this->_updateButton('back', 'onclick', 'setLocation(\'' . $this->getUrl('*/sales_creditmemo/') . '\')'); + return $this->_updateButton( + 'back', + 'onclick', + 'setLocation(\'' . $this->getUrl('*/sales_creditmemo/') . '\')' + ); } return $this; } diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/New/Form.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/New/Form.php index 8ff7e3432c..075dc18602 100644 --- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/New/Form.php +++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/New/Form.php @@ -61,7 +61,7 @@ protected function _prepareForm() array( 'name' => 'status', 'label' => Mage::helper('sales')->__('Status Code'), - 'class' => 'required-entry', + 'class' => 'required-entry validate-code', 'required' => true, ) ); 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 e36cbafcf2..e75da090c0 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 @@ -42,33 +42,17 @@ public function getFullTaxInfo() { /** @var $source Mage_Sales_Model_Order */ $source = $this->getOrder(); - $info = array(); - if ($source instanceof Mage_Sales_Model_Order) { - - $rates = Mage::getModel('sales/order_tax')->getCollection()->loadByOrder($source)->toArray(); - $info = Mage::getSingleton('tax/calculation')->reproduceProcess($rates['items']); - /** - * Set right tax amount from invoice - * (In $info tax invalid when invoice is partial) - */ - /** @var $blockInvoice Mage_Adminhtml_Block_Sales_Order_Invoice_Totals */ -// $blockInvoice = $this->getLayout()->getBlock('tax'); - /** @var $invoice Mage_Sales_Model_Order_Invoice */ -// $invoice = $blockInvoice->getSource(); -// $items = $invoice->getItemsCollection(); - $i = 0; - /** @var $item Mage_Sales_Model_Order_Invoice_Item */ -// foreach ($items as $item) { -// $info[$i]['hidden'] = $item->getHiddenTaxAmount(); -// $info[$i]['amount'] = $item->getTaxAmount(); -// $info[$i]['base_amount'] = $item->getBaseTaxAmount(); -// $info[$i]['base_real_amount'] = $item->getBaseTaxAmount(); -// $i++; -// } + $taxClassAmount = array(); + if ($source instanceof Mage_Sales_Model_Order) { + $taxClassAmount = Mage::helper('tax')->getCalculatedTaxes($source); + if (empty($taxClassAmount)) { + $rates = Mage::getModel('sales/order_tax')->getCollection()->loadByOrder($source)->toArray(); + $taxClassAmount = Mage::getSingleton('tax/calculation')->reproduceProcess($rates['items']); + } } - return $info; + return $taxClassAmount; } /** 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 3a923bca61..13296a7c69 100644 --- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php +++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php @@ -58,7 +58,12 @@ public function __construct() )); // see if order has non-editable products as items $nonEditableTypes = array_keys($this->getOrder()->getResource()->aggregateProductsByTypes( - $order->getId(), array_keys(Mage::getConfig()->getNode('adminhtml/sales/order/create/available_product_types')->asArray()), false + $order->getId(), + array_keys(Mage::getConfig() + ->getNode('adminhtml/sales/order/create/available_product_types') + ->asArray() + ), + false )); if ($nonEditableTypes) { $this->_updateButton('order_edit', 'onclick', @@ -161,7 +166,10 @@ public function __construct() )); } - if ($this->_isAllowedAction('reorder') && $this->helper('sales/reorder')->canReorder($order)) { + if ($this->_isAllowedAction('reorder') + && $this->helper('sales/reorder')->isAllowed($order->getStore()) + && $order->canReorder() + ) { $this->_addButton('order_reorder', array( 'label' => Mage::helper('sales')->__('Reorder'), 'onclick' => 'setLocation(\'' . $this->getReorderUrl() . '\')', 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 17475ec70d..2d62888132 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 @@ -220,4 +220,15 @@ public function isHidden() { return false; } + + /** + * Customer Notification Applicable check method + * + * @param array $history + * @return boolean + */ + public function isCustomerNotificationNotApplicable($historyItem) + { + return $historyItem['notified'] == Mage_Sales_Model_Order_Status_History::CUSTOMER_NOTIFICATION_NOT_APPLICABLE; + } } diff --git a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Preview.php b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Preview.php index 9497ad88e2..7048b3d6f2 100644 --- a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Preview.php +++ b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Preview.php @@ -44,6 +44,9 @@ protected function _toHtml() $template->setTemplateText($this->getRequest()->getParam('text')); $template->setTemplateStyles($this->getRequest()->getParam('styles')); } + $template->setTemplateText( + $this->escapeHtml($template->getTemplateText()) + ); Varien_Profiler::start("email_template_proccessing"); $vars = array(); diff --git a/app/code/core/Mage/Adminhtml/Controller/Sales/Creditmemo.php b/app/code/core/Mage/Adminhtml/Controller/Sales/Creditmemo.php index 85a7bd6365..1f0fb53b67 100644 --- a/app/code/core/Mage/Adminhtml/Controller/Sales/Creditmemo.php +++ b/app/code/core/Mage/Adminhtml/Controller/Sales/Creditmemo.php @@ -122,7 +122,7 @@ public function pdfcreditmemosAction(){ public function printAction() { /** @see Mage_Adminhtml_Sales_Order_InvoiceController */ - if ($creditmemoId = $this->getRequest()->getParam('invoice_id')) { // invoice_id?! + if ($creditmemoId = $this->getRequest()->getParam('creditmemo_id')) { if ($creditmemo = Mage::getModel('sales/order_creditmemo')->load($creditmemoId)) { $pdf = Mage::getModel('sales/order_pdf_creditmemo')->getPdf(array($creditmemo)); $this->_prepareDownloadResponse('creditmemo'.Mage::getSingleton('core/date')->date('Y-m-d_H-i-s'). diff --git a/app/code/core/Mage/Adminhtml/Helper/Data.php b/app/code/core/Mage/Adminhtml/Helper/Data.php index 7116343c7a..0db41a94c6 100644 --- a/app/code/core/Mage/Adminhtml/Helper/Data.php +++ b/app/code/core/Mage/Adminhtml/Helper/Data.php @@ -35,7 +35,8 @@ class Mage_Adminhtml_Helper_Data extends Mage_Core_Helper_Abstract { const XML_PATH_ADMINHTML_ROUTER_FRONTNAME = 'admin/routers/adminhtml/args/frontName'; const XML_PATH_USE_CUSTOM_ADMIN_URL = 'default/admin/url/use_custom'; - const XML_PATH_CUSTOM_ADMIN_URL = 'default/admin/url/custom'; + const XML_PATH_USE_CUSTOM_ADMIN_PATH = 'default/admin/url/use_custom_path'; + const XML_PATH_CUSTOM_ADMIN_PATH = 'default/admin/url/custom_path'; protected $_pageHelpUrl; 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 0ca65bdd10..57a4a5fee5 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 @@ -26,7 +26,7 @@ /** - * Adminhtml backend model for "Use Secure URLs in Admin" option + * Adminhtml backend model for "Custom Admin URL" option * * @category Mage * @package Mage_Adminhtml @@ -34,22 +34,71 @@ */ class Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom extends Mage_Core_Model_Config_Data { - const CONFIG_SCOPE = 'default'; + const CONFIG_SCOPE = 'stores'; const CONFIG_SCOPE_ID = 0; - const XML_PATH_UNSECURE_BASE_LINK_URL = 'web/unsecure/base_link_url'; - const XML_PATH_SECURE_BASE_LINK_URL = 'web/secure/base_link_url'; + const XML_PATH_UNSECURE_BASE_URL = 'web/unsecure/base_url'; + const XML_PATH_SECURE_BASE_URL = 'web/secure/base_url'; + const XML_PATH_UNSECURE_BASE_LINK_URL = 'web/unsecure/base_link_url'; + const XML_PATH_SECURE_BASE_LINK_URL = 'web/secure/base_link_url'; /** - * Check whether redirect should be set + * Validate value before save * * @return Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom */ protected function _beforeSave() { - if ($this->getOldValue() != $this->getValue()) { - Mage::register('custom_admin_url_redirect', true, true); + $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 + * + * @return Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom + */ + public function _afterSave() + { + $useCustomUrl = $this->getData('groups/url/fields/use_custom/value'); + $value = $this->getValue(); + + if ($useCustomUrl == 1 && empty($value)) { + return $this; + } + + if ($useCustomUrl == 1) { + Mage::getConfig()->saveConfig( + self::XML_PATH_SECURE_BASE_URL, + $value, + self::CONFIG_SCOPE, + self::CONFIG_SCOPE_ID + ); + Mage::getConfig()->saveConfig( + self::XML_PATH_UNSECURE_BASE_URL, + $value, + self::CONFIG_SCOPE, + self::CONFIG_SCOPE_ID + ); + } else { + Mage::getConfig()->deleteConfig( + self::XML_PATH_SECURE_BASE_URL, + self::CONFIG_SCOPE, + self::CONFIG_SCOPE_ID + ); + Mage::getConfig()->deleteConfig( + self::XML_PATH_UNSECURE_BASE_URL, + self::CONFIG_SCOPE, + self::CONFIG_SCOPE_ID + ); + } + return $this; } } diff --git a/app/code/core/Mage/GoogleOptimizer/controllers/IndexController.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custompath.php similarity index 64% rename from app/code/core/Mage/GoogleOptimizer/controllers/IndexController.php rename to app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custompath.php index 4367077769..5c02fa82b4 100644 --- a/app/code/core/Mage/GoogleOptimizer/controllers/IndexController.php +++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custompath.php @@ -19,23 +19,31 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Adminhtml * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -require_once 'Mage/GoogleOptimizer/controllers/Adminhtml/Googleoptimizer/IndexController.php'; /** - * GoogleOptimizer Front Controller + * Adminhtml backend model for "Custom Admin Path" option * * @category Mage - * @package Mage_GoogleOptimizer - * @name Mage_GoogleOptimizer_IndexController + * @package Mage_Adminhtml * @author Magento Core Team - * @deprecated after 1.4.2.0 Mage_GoogleOptimizer_Adminhtml_Googleoptimizer_IndexController is used -*/ -class Mage_GoogleOptimizer_IndexController extends Mage_GoogleOptimizer_Adminhtml_Googleoptimizer_IndexController + */ +class Mage_Adminhtml_Model_System_Config_Backend_Admin_Custompath extends Mage_Core_Model_Config_Data { - + /** + * Check whether redirect should be set + * + * @return Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom + */ + protected function _beforeSave() + { + if ($this->getOldValue() != $this->getValue()) { + Mage::register('custom_admin_path_redirect', true, true); + } + return $this; + } } diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Observer.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Observer.php index 0afcb934c8..e1d497bc27 100644 --- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Observer.php +++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Observer.php @@ -33,7 +33,7 @@ class Mage_Adminhtml_Model_System_Config_Backend_Admin_Observer */ public function afterCustomUrlChanged($observer) { - if (is_null(Mage::registry('custom_admin_url_redirect'))) { + if (is_null(Mage::registry('custom_admin_path_redirect'))) { return; } @@ -42,8 +42,8 @@ public function afterCustomUrlChanged($observer) $adminSession->unsetAll(); $adminSession->getCookie()->delete($adminSession->getSessionName()); - $route = ((bool)(string)Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_USE_CUSTOM_ADMIN_URL)) - ? Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_CUSTOM_ADMIN_URL) + $route = ((bool)(string)Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_USE_CUSTOM_ADMIN_PATH)) + ? Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_CUSTOM_ADMIN_PATH) : Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_ADMINHTML_ROUTER_FRONTNAME); Mage::app()->getResponse() diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Form/Renderer/Googleoptimizer/Import.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Password/Link/Expirationperiod.php similarity index 61% rename from app/code/core/Mage/Adminhtml/Block/Catalog/Form/Renderer/Googleoptimizer/Import.php rename to app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Password/Link/Expirationperiod.php index de9353aa16..28ccc7562b 100644 --- a/app/code/core/Mage/Adminhtml/Block/Catalog/Form/Renderer/Googleoptimizer/Import.php +++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Password/Link/Expirationperiod.php @@ -25,37 +25,28 @@ */ /** - * GoogleOptimizer import controls renderer + * Admin Reset Password Link Expiration period backend model * * @category Mage * @package Mage_Adminhtml * @author Magento Core Team */ -class Mage_Adminhtml_Block_Catalog_Form_Renderer_Googleoptimizer_Import extends Mage_Adminhtml_Block_Widget_Form_Renderer_Fieldset_Element +class Mage_Adminhtml_Model_System_Config_Backend_Admin_Password_Link_Expirationperiod + extends Mage_Core_Model_Config_Data { - public function __construct() + /** + * Validate expiration period value before saving + * + * @return Mage_Adminhtml_Model_System_Config_Backend_Admin_Password_Link_Expirationperiod + */ + protected function _beforeSave() { - $this->setTemplate('catalog/form/renderer/googleoptimizer/import.phtml'); - } - - public function render(Varien_Data_Form_Element_Abstract $element) - { - $this->setElement($element); - return $this->toHtml(); - } - - public function setElement(Varien_Data_Form_Element_Abstract $element) - { - $this->_element = $element; + parent::_beforeSave(); + $resetPasswordLinkExpirationPeriod = (int) $this->getValue(); + if ($resetPasswordLinkExpirationPeriod < 0) { + $resetPasswordLinkExpirationPeriod = (int) $this->getOldValue(); + } + $this->setValue((string) $resetPasswordLinkExpirationPeriod); return $this; } - - public function getElement() - { - return $this->_element; - } - - protected function _prepareLayout() - { - } } diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustom.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustom.php index 2c482a4d22..5650064ce1 100644 --- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustom.php +++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustom.php @@ -26,7 +26,7 @@ /** - * Adminhtml backend model for "Use Secure URLs in Admin" option + * Adminhtml backend model for "Use Custom Admin URL" option * * @category Mage * @package Mage_Adminhtml @@ -35,7 +35,7 @@ class Mage_Adminhtml_Model_System_Config_Backend_Admin_Usecustom extends Mage_Core_Model_Config_Data { /** - * Validate custom url and check whether redirect should be set + * Validate custom url * * @return Mage_Adminhtml_Model_System_Config_Backend_Admin_Usecustom */ @@ -49,10 +49,6 @@ protected function _beforeSave() } } - if ($this->getOldValue() != $value) { - Mage::register('custom_admin_url_redirect', true, true); - } - return $this; } } diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Code/Product.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustompath.php similarity index 64% rename from app/code/core/Mage/GoogleOptimizer/Block/Code/Product.php rename to app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustompath.php index 5ba6892fa3..5b5040bd18 100644 --- a/app/code/core/Mage/GoogleOptimizer/Block/Code/Product.php +++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustompath.php @@ -19,34 +19,32 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Adminhtml * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** - * Google Optmizer Product Block + * Adminhtml backend model for "Use Custom Admin Path" option * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Adminhtml * @author Magento Core Team */ -class Mage_GoogleOptimizer_Block_Code_Product extends Mage_GoogleOptimizer_Block_Code +class Mage_Adminhtml_Model_System_Config_Backend_Admin_Usecustompath extends Mage_Core_Model_Config_Data { - protected function _initGoogleOptimizerModel() + /** + * Check whether redirect should be set + * + * @return Mage_Adminhtml_Model_System_Config_Backend_Admin_Usecustompath + */ + protected function _beforeSave() { - $this->_setGoogleOptimizerModel($this->getGoogleOptimizer()); - return parent::_initGoogleOptimizerModel(); - } + if ($this->getOldValue() != $this->getValue()) { + Mage::register('custom_admin_path_redirect', true, true); + } - public function getProduct() - { - return Mage::registry('current_product'); - } - - public function getGoogleOptimizer() - { - return $this->getProduct()->getGoogleOptimizerScripts(); + return $this; } } diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Customer/Password/Link/Expirationperiod.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Customer/Password/Link/Expirationperiod.php new file mode 100644 index 0000000000..90dbb07a12 --- /dev/null +++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Customer/Password/Link/Expirationperiod.php @@ -0,0 +1,53 @@ + + */ +class Mage_Adminhtml_Model_System_Config_Backend_Customer_Password_Link_Expirationperiod + extends Mage_Core_Model_Config_Data +{ + /** + * Validate expiration period value before saving + * + * @return Mage_Adminhtml_Model_System_Config_Backend_Customer_Password_Link_Expirationperiod + */ + protected function _beforeSave() + { + parent::_beforeSave(); + $resetPasswordLinkExpirationPeriod = (int) $this->getValue(); + if ($resetPasswordLinkExpirationPeriod < 0) { + $resetPasswordLinkExpirationPeriod = (int) $this->getOldValue(); + } + $this->setValue((string) $resetPasswordLinkExpirationPeriod); + return $this; + } +} diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php index 56808bd599..75e8838062 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php @@ -46,6 +46,12 @@ public function uploadAction() Mage::getSingleton('catalog/product_media_config')->getBaseTmpMediaPath() ); + /** + * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS + */ + $result['tmp_name'] = str_replace(DS, "/", $result['tmp_name']); + $result['path'] = str_replace(DS, "/", $result['path']); + $result['url'] = Mage::getSingleton('catalog/product_media_config')->getTmpMediaUrl($result['file']); $result['file'] = $result['file'] . '.tmp'; $result['cookie'] = array( diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/ReviewController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/ReviewController.php index bd205549b1..c09c0eab86 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/ReviewController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/ReviewController.php @@ -122,9 +122,9 @@ public function saveAction() { if (($data = $this->getRequest()->getPost()) && ($reviewId = $this->getRequest()->getParam('id'))) { $review = Mage::getModel('review/review')->load($reviewId); - + $session = Mage::getSingleton('adminhtml/session'); if (! $review->getId()) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('catalog')->__('The review was removed by another user or does not exist.')); + $session->addError(Mage::helper('catalog')->__('The review was removed by another user or does not exist.')); } else { try { $review->addData($data)->save(); @@ -152,45 +152,52 @@ public function saveAction() $review->aggregate(); - Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('catalog')->__('The review has been saved.')); + $session->addSuccess(Mage::helper('catalog')->__('The review has been saved.')); + } catch (Mage_Core_Exception $e) { + $session->addError($e->getMessage()); } catch (Exception $e){ - Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); + $session->addException($e, Mage::helper('catalog')->__('An error occurred while saving this review.')); } } return $this->getResponse()->setRedirect($this->getUrl($this->getRequest()->getParam('ret') == 'pending' ? '*/*/pending' : '*/*/')); } - $this->_redirectReferer(); + $this->_redirect('*/*/'); } public function deleteAction() { - $reviewId = $this->getRequest()->getParam('id', false); + $reviewId = $this->getRequest()->getParam('id', false); + $session = Mage::getSingleton('adminhtml/session'); try { Mage::getModel('review/review')->setId($reviewId) ->aggregate() ->delete(); - Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('catalog')->__('The review has been deleted')); + $session->addSuccess(Mage::helper('catalog')->__('The review has been deleted')); if( $this->getRequest()->getParam('ret') == 'pending' ) { $this->getResponse()->setRedirect($this->getUrl('*/*/pending')); } else { $this->getResponse()->setRedirect($this->getUrl('*/*/')); } return; + } catch (Mage_Core_Exception $e) { + $session->addError($e->getMessage()); } catch (Exception $e){ - Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); + $session->addException($e, Mage::helper('catalog')->__('An error occurred while deleting this review.')); } - $this->_redirectReferer(); + $this->_redirect('*/*/edit/',array('id'=>$reviewId)); } public function massDeleteAction() { $reviewsIds = $this->getRequest()->getParam('reviews'); + $session = Mage::getSingleton('adminhtml/session'); + if(!is_array($reviewsIds)) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select review(s).')); + $session->addError(Mage::helper('adminhtml')->__('Please select review(s).')); } else { try { foreach ($reviewsIds as $reviewId) { @@ -200,8 +207,10 @@ public function massDeleteAction() Mage::getSingleton('adminhtml/session')->addSuccess( Mage::helper('adminhtml')->__('Total of %d record(s) have been deleted.', count($reviewsIds)) ); - } catch (Exception $e) { - Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); + } catch (Mage_Core_Exception $e) { + $session->addError($e->getMessage()); + } catch (Exception $e){ + $session->addException($e, Mage::helper('adminhtml')->__('An error occurred while deleting record(s).')); } } @@ -211,10 +220,11 @@ public function massDeleteAction() public function massUpdateStatusAction() { $reviewsIds = $this->getRequest()->getParam('reviews'); + $session = Mage::getSingleton('adminhtml/session'); + if(!is_array($reviewsIds)) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select review(s).')); + $session->addError(Mage::helper('adminhtml')->__('Please select review(s).')); } else { - $session = Mage::getSingleton('adminhtml/session'); /* @var $session Mage_Adminhtml_Model_Session */ try { $status = $this->getRequest()->getParam('status'); @@ -227,12 +237,10 @@ public function massUpdateStatusAction() $session->addSuccess( Mage::helper('adminhtml')->__('Total of %d record(s) have been updated.', count($reviewsIds)) ); - } - catch (Mage_Core_Exception $e) { - $session->addException($e->getMessage()); - } - catch (Exception $e) { - $session->addError(Mage::helper('adminhtml')->__('An error occurred while updating the selected review(s).')); + } catch (Mage_Core_Exception $e) { + $session->addError($e->getMessage()); + } catch (Exception $e) { + $session->addException($e, Mage::helper('adminhtml')->__('An error occurred while updating the selected review(s).')); } } @@ -242,8 +250,10 @@ public function massUpdateStatusAction() public function massVisibleInAction() { $reviewsIds = $this->getRequest()->getParam('reviews'); + $session = Mage::getSingleton('adminhtml/session'); + if(!is_array($reviewsIds)) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select review(s).')); + $session->addError(Mage::helper('adminhtml')->__('Please select review(s).')); } else { $session = Mage::getSingleton('adminhtml/session'); /* @var $session Mage_Adminhtml_Model_Session */ @@ -257,12 +267,10 @@ public function massVisibleInAction() $session->addSuccess( Mage::helper('adminhtml')->__('Total of %d record(s) have been updated.', count($reviewsIds)) ); - } - catch (Mage_Core_Exception $e) { - $session->addException($e->getMessage()); - } - catch (Exception $e) { - $session->addError(Mage::helper('adminhtml')->__('An error occurred while updating the selected review(s).')); + } catch (Mage_Core_Exception $e) { + $session->addError($e->getMessage()); + } catch (Exception $e) { + $session->addException($e, Mage::helper('adminhtml')->__('An error occurred while updating the selected review(s).')); } } @@ -299,7 +307,9 @@ public function jsonProductInfoAction() public function postAction() { - $productId = $this->getRequest()->getParam('product_id', false); + $productId = $this->getRequest()->getParam('product_id', false); + $session = Mage::getSingleton('adminhtml/session'); + if ($data = $this->getRequest()->getPost()) { if(isset($data['select_stores'])) { $data['stores'] = $data['select_stores']; @@ -328,7 +338,7 @@ public function postAction() $review->aggregate(); - Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('catalog')->__('The review has been saved.')); + $session->addSuccess(Mage::helper('catalog')->__('The review has been saved.')); if( $this->getRequest()->getParam('ret') == 'pending' ) { $this->getResponse()->setRedirect($this->getUrl('*/*/pending')); } else { @@ -336,9 +346,10 @@ public function postAction() } return; - } catch (Exception $e){ - die($e->getMessage()); - Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); + } catch (Mage_Core_Exception $e) { + $session->addError($e->getMessage()); + } catch (Exception $e) { + $session->addException($e, Mage::helper('adminhtml')->__('An error occurred while saving review.')); } } $this->getResponse()->setRedirect($this->getUrl('*/*/')); @@ -347,7 +358,9 @@ public function postAction() public function ratingItemsAction() { - $this->getResponse()->setBody($this->getLayout()->createBlock('adminhtml/review_rating_detailed')->setIndependentMode()->toHtml()); + $this->getResponse()->setBody( + $this->getLayout()->createBlock('adminhtml/review_rating_detailed')->setIndependentMode()->toHtml() + ); } protected function _isAllowed() diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/SetController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/SetController.php index 7512df45ef..c1882abe82 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/SetController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/SetController.php @@ -123,7 +123,7 @@ public function saveAction() if ($isNewSet) { //filter html tags $name = $helper->stripTags($this->getRequest()->getParam('attribute_set_name')); - $model->setAttributeSetName($name); + $model->setAttributeSetName(trim($name)); } else { if ($attributeSetId) { $model->load($attributeSetId); diff --git a/app/code/core/Mage/Adminhtml/controllers/IndexController.php b/app/code/core/Mage/Adminhtml/controllers/IndexController.php index 70cc2344a4..20960f7537 100644 --- a/app/code/core/Mage/Adminhtml/controllers/IndexController.php +++ b/app/code/core/Mage/Adminhtml/controllers/IndexController.php @@ -24,14 +24,26 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ - +/** + * Index admin controller + * + * @category Mage + * @package Mage_Adminhtml + * @author Magento Core Team + */ class Mage_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action { - protected function _outTemplate($tplName, $data=array()) + /** + * Render specified template + * + * @param string $tplName + * @param array $data parameters required by template + */ + protected function _outTemplate($tplName, $data = array()) { $this->_initLayoutMessages('adminhtml/session'); $block = $this->getLayout()->createBlock('adminhtml/template')->setTemplate("$tplName.phtml"); - foreach ($data as $index=>$value) { + foreach ($data as $index => $value) { $block->assign($index, $value); } $html = $block->toHtml(); @@ -54,6 +66,9 @@ public function indexAction() $this->_redirect($url); } + /** + * Administrator login action + */ public function loginAction() { if (Mage::getSingleton('admin/session')->isLoggedIn()) { @@ -63,7 +78,7 @@ public function loginAction() $loginData = $this->getRequest()->getParam('login'); $data = array(); - if( is_array($loginData) && array_key_exists('username', $loginData) ) { + if(is_array($loginData) && array_key_exists('username', $loginData)) { $data['username'] = $loginData['username']; } else { $data['username'] = null; @@ -72,6 +87,9 @@ public function loginAction() $this->_outTemplate('login', $data); } + /** + * Administrator logout action + */ public function logoutAction() { /** @var $adminSession Mage_Admin_Model_Session */ @@ -85,28 +103,27 @@ public function logoutAction() /** * Global Search Action - * */ public function globalSearchAction() { $searchModules = Mage::getConfig()->getNode("adminhtml/global_search"); $items = array(); - if ( !Mage::getSingleton('admin/session')->isAllowed('admin/global_search') ) { + if (!Mage::getSingleton('admin/session')->isAllowed('admin/global_search')) { $items[] = array( - 'id' => 'error', - 'type' => Mage::helper('adminhtml')->__('Error'), - 'name' => Mage::helper('adminhtml')->__('Access Denied'), - 'description' => Mage::helper('adminhtml')->__('You have not enough permissions to use this functionality.') + 'id' => 'error', + 'type' => Mage::helper('adminhtml')->__('Error'), + 'name' => Mage::helper('adminhtml')->__('Access Denied'), + 'description' => Mage::helper('adminhtml')->__('You have not enough permissions to use this functionality.') ); $totalCount = 1; } else { if (empty($searchModules)) { $items[] = array( - 'id' => 'error', - 'type' => Mage::helper('adminhtml')->__('Error'), - 'name' => Mage::helper('adminhtml')->__('No search modules were registered'), - 'description' => Mage::helper('adminhtml')->__('Please make sure that all global admin search modules are installed and activated.') + 'id' => 'error', + 'type' => Mage::helper('adminhtml')->__('Error'), + 'name' => Mage::helper('adminhtml')->__('No search modules were registered'), + 'description' => Mage::helper('adminhtml')->__('Please make sure that all global admin search modules are installed and activated.') ); $totalCount = 1; } else { @@ -126,10 +143,10 @@ public function globalSearchAction() } $searchInstance = new $className(); $results = $searchInstance->setStart($start) - ->setLimit($limit) - ->setQuery($query) - ->load() - ->getResults(); + ->setLimit($limit) + ->setQuery($query) + ->load() + ->getResults(); $items = array_merge_recursive($items, $results); } $totalCount = sizeof($items); @@ -143,16 +160,25 @@ public function globalSearchAction() $this->getResponse()->setBody($block->toHtml()); } + /** + * Example action + */ public function exampleAction() { $this->_outTemplate('example'); } + /** + * Test action + */ public function testAction() { echo $this->getLayout()->createBlock('core/profiler')->toHtml(); } + /** + * Change locale action + */ public function changeLocaleAction() { $locale = $this->getRequest()->getParam('locale'); @@ -162,38 +188,52 @@ public function changeLocaleAction() $this->_redirectReferer(); } + /** + * Denied JSON action + */ public function deniedJsonAction() { $this->getResponse()->setBody($this->_getDeniedJson()); } + /** + * Retrieve response for deniedJsonAction() + */ protected function _getDeniedJson() { - return Mage::helper('core')->jsonEncode( - array( - 'ajaxExpired' => 1, - 'ajaxRedirect' => $this->getUrl('*/index/login') - ) - ); + return Mage::helper('core')->jsonEncode(array( + 'ajaxExpired' => 1, + 'ajaxRedirect' => $this->getUrl('*/index/login') + )); } + /** + * Denied IFrame action + */ public function deniedIframeAction() { $this->getResponse()->setBody($this->_getDeniedIframe()); } + /** + * Retrieve response for deniedIframeAction() + */ protected function _getDeniedIframe() { - return ''; + return ''; } + /** + * Forgot administrator password action + */ public function forgotpasswordAction() { $email = $this->getRequest()->getParam('email'); $params = $this->getRequest()->getParams(); if (!empty($email) && !empty($params)) { $collection = Mage::getResourceModel('admin/user_collection'); - /* @var $collection Mage_Admin_Model_Mysql4_User_Collection */ + /** @var $collection Mage_Admin_Model_Mysql4_User_Collection */ $collection->addFieldToFilter('email', $email); $collection->load(false); @@ -201,31 +241,150 @@ public function forgotpasswordAction() foreach ($collection as $item) { $user = Mage::getModel('admin/user')->load($item->getId()); if ($user->getId()) { - $pass = Mage::helper('core')->getRandomString(7); - $user->setPassword($pass); + $newResetPasswordLinkToken = Mage::helper('admin')->generateResetPasswordLinkToken(); + $user->changeResetPasswordLinkToken($newResetPasswordLinkToken); $user->save(); - $user->setPlainPassword($pass); - $user->sendNewPasswordEmail(); - Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('A new password was sent to your email address. Please check your email and click Back to Login.')); - $email = ''; + $user->sendPasswordResetConfirmationEmail(); } break; } - } else { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Cannot find the email address.')); } + $this->_getSession() + ->addSuccess(Mage::helper('adminhtml')->__('If there is an account associated with %s you will receive an email with a link to reset your password.', Mage::helper('adminhtml')->htmlEscape($email))); } elseif (!empty($params)) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('The email address is empty.')); + $this->_getSession()->addError(Mage::helper('adminhtml')->__('The email address is empty.')); } - $data = array( 'email' => $email ); $this->_outTemplate('forgotpassword', $data); } + /** + * Display reset forgotten password form + * + * User is redirected on this action when he clicks on the corresponding link in password reset confirmation email + */ + public function resetPasswordAction() + { + $resetPasswordLinkToken = (string) $this->getRequest()->getQuery('token'); + $userId = (int) $this->getRequest()->getQuery('id'); + try { + $this->_validateResetPasswordLinkToken($userId, $resetPasswordLinkToken); + $data = array( + 'userId' => $userId, + 'resetPasswordLinkToken' => $resetPasswordLinkToken + ); + $this->_outTemplate('resetforgottenpassword', $data); + } catch (Exception $exception) { + $this->_getSession()->addError(Mage::helper('adminhtml')->__('Your password reset link has expired.')); + $this->_redirect('*/*/'); + } + } + + /** + * Reset forgotten password + * + * Used to handle data recieved from reset forgotten password form + */ + public function resetPasswordPostAction() + { + $resetPasswordLinkToken = (string) $this->getRequest()->getQuery('token'); + $userId = (int) $this->getRequest()->getQuery('id'); + $password = (string) $this->getRequest()->getPost('password'); + $passwordConfirmation = (string) $this->getRequest()->getPost('confirmation'); + + try { + $this->_validateResetPasswordLinkToken($userId, $resetPasswordLinkToken); + } catch (Exception $exception) { + $this->_getSession()->addError(Mage::helper('adminhtml')->__('Your password reset link has expired.')); + $this->_redirect('*/*/'); + return; + } + + $errorMessages = array(); + if (iconv_strlen($password) <= 0) { + array_push($errorMessages, Mage::helper('adminhtml')->__('New password field cannot be empty.')); + } + /** @var $user Mage_Admin_Model_User */ + $user = Mage::getModel('admin/user')->load($userId); + + $user->setNewPassword($password); + $user->setPasswordConfirmation($passwordConfirmation); + $validationErrorMessages = $user->validate(); + if (is_array($validationErrorMessages)) { + $errorMessages = array_merge($errorMessages, $validationErrorMessages); + } + + if (!empty($errorMessages)) { + foreach ($errorMessages as $errorMessage) { + $this->_getSession()->addError($errorMessage); + } + $data = array( + 'userId' => $userId, + 'resetPasswordLinkToken' => $resetPasswordLinkToken + ); + $this->_outTemplate('resetforgottenpassword', $data); + return; + } + + try { + // Empty current reset password token i.e. invalidate it + $user->setRpToken(null); + $user->setRpTokenCreatedAt(null); + $user->setPasswordConfirmation(null); + // Force password change + $user->setForceNewPassword(true); + $user->save(); + $this->_getSession()->addSuccess(Mage::helper('adminhtml')->__('Your password has been updated.')); + $this->_redirect('*/*/login'); + } catch (Exception $exception) { + $this->_getSession()->addException($exception, $this->__('Cannot save a new password.')); + $data = array( + 'userId' => $userId, + 'resetPasswordLinkToken' => $resetPasswordLinkToken + ); + $this->_outTemplate('resetforgottenpassword', $data); + return; + } + } + + /** + * Check if password reset token is valid + * + * @param int $userId + * @param string $resetPasswordLinkToken + * @throws Mage_Core_Exception + */ + protected function _validateResetPasswordLinkToken($userId, $resetPasswordLinkToken) + { + if (!is_int($userId) + || !is_string($resetPasswordLinkToken) + || empty($resetPasswordLinkToken) + || empty($userId) + || $userId < 0 + ) { + throw Mage::exception('Mage_Core', Mage::helper('adminhtml')->__('Invalid password reset token.')); + } + + /** @var $user Mage_Admin_Model_User */ + $user = Mage::getModel('admin/user')->load($userId); + if (!$user || !$user->getId()) { + throw Mage::exception('Mage_Core', Mage::helper('adminhtml')->__('Wrong account specified.')); + } + $userToken = $user->getRpToken(); + if (strcmp($userToken, $resetPasswordLinkToken) != 0 || $user->isResetPasswordLinkTokenExpired()) { + throw Mage::exception('Mage_Core', Mage::helper('adminhtml')->__('Your password reset link has expired.')); + } + } + + /** + * Check if user has permissions to access this controller + * + * @return boolean + */ protected function _isAllowed() { return true; diff --git a/app/code/core/Mage/Adminhtml/controllers/NotificationController.php b/app/code/core/Mage/Adminhtml/controllers/NotificationController.php index 2431e0046c..2f8c5d41e6 100644 --- a/app/code/core/Mage/Adminhtml/controllers/NotificationController.php +++ b/app/code/core/Mage/Adminhtml/controllers/NotificationController.php @@ -62,11 +62,9 @@ public function markAsReadAction() $model->setIsRead(1) ->save(); $session->addSuccess(Mage::helper('adminnotification')->__('The message has been marked as read.')); - } - catch (Mage_Core_Exception $e) { + } catch (Mage_Core_Exception $e) { $session->addError($e->getMessage()); - } - catch (Exception $e) { + } catch (Exception $e) { $session->addException($e, Mage::helper('adminnotification')->__('An error occurred while marking notification as read.')); } @@ -82,8 +80,7 @@ public function massMarkAsReadAction() $ids = $this->getRequest()->getParam('notification'); if (!is_array($ids)) { $session->addError(Mage::helper('adminnotification')->__('Please select messages.')); - } - else { + } else { try { foreach ($ids as $id) { $model = Mage::getModel('adminnotification/inbox') @@ -98,8 +95,7 @@ public function massMarkAsReadAction() ); } catch (Mage_Core_Exception $e) { $session->addError($e->getMessage()); - } - catch (Exception $e) { + } catch (Exception $e) { $session->addException($e, Mage::helper('adminnotification')->__('An error occurred while marking the messages as read.')); } } @@ -122,15 +118,13 @@ public function removeAction() $model->setIsRemove(1) ->save(); $session->addSuccess(Mage::helper('adminnotification')->__('The message has been removed.')); - } - catch (Mage_Core_Exception $e) { + } catch (Mage_Core_Exception $e) { $session->addError($e->getMessage()); - } - catch (Exception $e) { + } catch (Exception $e) { $session->addException($e, Mage::helper('adminnotification')->__('An error occurred while removing the message.')); } - $this->_redirectReferer(); + $this->_redirect('*/*/'); return; } $this->_redirect('*/*/'); @@ -142,8 +136,7 @@ public function massRemoveAction() $ids = $this->getRequest()->getParam('notification'); if (!is_array($ids)) { $session->addError(Mage::helper('adminnotification')->__('Please select messages.')); - } - else { + } else { try { foreach ($ids as $id) { $model = Mage::getModel('adminnotification/inbox') @@ -158,8 +151,7 @@ public function massRemoveAction() ); } catch (Mage_Core_Exception $e) { $session->addError($e->getMessage()); - } - catch (Exception $e) { + } catch (Exception $e) { $session->addException($e, Mage::helper('adminnotification')->__('An error occurred while removing messages.')); } } diff --git a/app/code/core/Mage/Adminhtml/controllers/Report/SalesController.php b/app/code/core/Mage/Adminhtml/controllers/Report/SalesController.php index c621024ea8..8a5b56332a 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Report/SalesController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Report/SalesController.php @@ -458,7 +458,7 @@ protected function _isAllowed() return $this->_getSession()->isAllowed('report/salesroot/shipping'); break; case 'bestsellers': - return $this->_getSession()->isAllowed('report/products/ordered'); + return $this->_getSession()->isAllowed('report/products/bestsellers'); break; default: return $this->_getSession()->isAllowed('report/salesroot'); 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 260d798075..34c5955838 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreditmemoController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreditmemoController.php @@ -333,7 +333,8 @@ public function saveAction() */ public function cancelAction() { - if ($creditmemo = $this->_initCreditmemo()) { + $creditmemo = $this->_initCreditmemo(); + if ($creditmemo) { try { $creditmemo->cancel(); $this->_saveCreditmemo($creditmemo); @@ -354,7 +355,8 @@ public function cancelAction() */ public function voidAction() { - if ($invoice = $this->_initCreditmemo()) { + $creditmemo = $this->_initCreditmemo(); + if ($creditmemo) { try { $creditmemo->void(); $this->_saveCreditmemo($creditmemo); @@ -442,4 +444,13 @@ 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 4529ac6a8a..5296e92272 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/InvoiceController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/InvoiceController.php @@ -480,4 +480,13 @@ protected function _needToAddDummyForShipment($item, $qtys) { } } + /** + * Create pdf for current invoice + */ + public function printAction() + { + $this->_initInvoice(); + parent::printAction(); + } + } 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 26d5d47872..4e24919bc3 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/StatusController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/StatusController.php @@ -64,8 +64,7 @@ protected function _initStatus() public function indexAction() { $this->_title($this->__('Sales'))->_title($this->__('Order Statuses')); - $this->loadLayout() - ->renderLayout(); + $this->loadLayout()->_setActiveMenu('system')->renderLayout(); } /** diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Recurring/ProfileController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Recurring/ProfileController.php index d3b34ddc89..9a34591f47 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Sales/Recurring/ProfileController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Recurring/ProfileController.php @@ -159,6 +159,35 @@ public function updateProfileAction() } } + /** + * Cutomer billing agreements ajax action + * + */ + public function customerGridAction() + { + $this->_initCustomer(); + $this->loadLayout(false) + ->renderLayout(); + } + + /** + * Initialize customer by ID specified in request + * + * @return Mage_Adminhtml_Sales_Billing_AgreementController + */ + protected function _initCustomer() + { + $customerId = (int) $this->getRequest()->getParam('id'); + $customer = Mage::getModel('customer/customer'); + + if ($customerId) { + $customer->load($customerId); + } + + Mage::register('current_customer', $customer); + return $this; + } + /** * Load/set profile * diff --git a/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php b/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php index b34beba4cc..5068421254 100644 --- a/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php +++ b/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php @@ -24,9 +24,8 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ - /** - * config controller + * Configuration controller * * @category Mage * @package Mage_Adminhtml @@ -59,7 +58,7 @@ public function preDispatch() } /** - * Enter description here... + * Index action * */ public function indexAction() @@ -68,7 +67,7 @@ public function indexAction() } /** - * Enter description here... + * Edit configuration section * */ public function editAction() @@ -91,8 +90,10 @@ public function editAction() $this->loadLayout(); $this->_setActiveMenu('system/config'); + $this->getLayout()->getBlock('menu')->setAdditionalCacheKeyInfo(array($current)); - $this->_addBreadcrumb(Mage::helper('adminhtml')->__('System'), Mage::helper('adminhtml')->__('System'), $this->getUrl('*/system')); + $this->_addBreadcrumb(Mage::helper('adminhtml')->__('System'), Mage::helper('adminhtml')->__('System'), + $this->getUrl('*/system')); $this->getLayout()->getBlock('left') ->append($this->getLayout()->createBlock('adminhtml/system_config_tabs')->initTabs()); @@ -100,16 +101,22 @@ public function editAction() if ($this->_isSectionAllowedFlag) { $this->_addContent($this->getLayout()->createBlock('adminhtml/system_config_edit')->initForm()); - $this->_addJs($this->getLayout()->createBlock('adminhtml/template')->setTemplate('system/shipping/ups.phtml')); - $this->_addJs($this->getLayout()->createBlock('adminhtml/template')->setTemplate('system/config/js.phtml')); - $this->_addJs($this->getLayout()->createBlock('adminhtml/template')->setTemplate('system/shipping/applicable_country.phtml')); + $this->_addJs($this->getLayout() + ->createBlock('adminhtml/template') + ->setTemplate('system/shipping/ups.phtml')); + $this->_addJs($this->getLayout() + ->createBlock('adminhtml/template') + ->setTemplate('system/config/js.phtml')); + $this->_addJs($this->getLayout() + ->createBlock('adminhtml/template') + ->setTemplate('system/shipping/applicable_country.phtml')); $this->renderLayout(); } } /** - * Enter description here... + * Save configuration * */ public function saveAction() @@ -168,7 +175,9 @@ public function saveAction() } } catch (Exception $e) { - $session->addException($e, Mage::helper('adminhtml')->__('An error occurred while saving this configuration:').' '.$e->getMessage()); + $session->addException($e, + Mage::helper('adminhtml')->__('An error occurred while saving this configuration:') . ' ' + . $e->getMessage()); } $this->_saveState($this->getRequest()->getPost('config_state')); @@ -188,20 +197,19 @@ protected function _saveSection () } /** - * Description goes here... + * Advanced save procedure */ - protected function _saveAdvanced () + protected function _saveAdvanced() { Mage::app()->cleanCache( array( 'layout', Mage_Core_Model_Layout_Update::LAYOUT_GENERAL_CACHE_TAG - ) - ); + )); } /** - * action for ajax saving of fieldset state + * Save fieldset state through AJAX * */ public function stateAction() @@ -282,7 +290,7 @@ protected function _isSectionAllowed($section) } /** - * saving state of config field sets + * Save state of configuration field sets * * @param array $configState * @return bool diff --git a/app/code/core/Mage/Adminhtml/controllers/Tax/Class/CustomerController.php b/app/code/core/Mage/Adminhtml/controllers/Tax/Class/CustomerController.php index 13d2317560..6ea3ff3f67 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Tax/Class/CustomerController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Tax/Class/CustomerController.php @@ -45,7 +45,11 @@ public function indexAction() ->_title($this->__('Customer Tax Classes')); $this->_initAction() - ->_addContent($this->getLayout()->createBlock('adminhtml/tax_class')->setClassType(Mage_Tax_Model_Class::TAX_CLASS_TYPE_CUSTOMER)) + ->_addContent( + $this->getLayout() + ->createBlock('adminhtml/tax_class') + ->setClassType(Mage_Tax_Model_Class::TAX_CLASS_TYPE_CUSTOMER) + ) ->renderLayout(); } @@ -89,8 +93,16 @@ public function editAction() Mage::register('tax_class', $model); $this->_initAction() - ->_addBreadcrumb($classId ? Mage::helper('tax')->__('Edit Class') : Mage::helper('tax')->__('New Class'), $classId ? Mage::helper('tax')->__('Edit Class') : Mage::helper('tax')->__('New Class')) - ->_addContent($this->getLayout()->createBlock('adminhtml/tax_class_edit')->setData('action', $this->getUrl('*/tax_class/save'))->setClassType(Mage_Tax_Model_Class::TAX_CLASS_TYPE_CUSTOMER)) + ->_addBreadcrumb( + $classId ? Mage::helper('tax')->__('Edit Class') : Mage::helper('tax')->__('New Class'), + $classId ? Mage::helper('tax')->__('Edit Class') : Mage::helper('tax')->__('New Class') + ) + ->_addContent( + $this->getLayout() + ->createBlock('adminhtml/tax_class_edit') + ->setData('action', $this->getUrl('*/tax_class/save')) + ->setClassType(Mage_Tax_Model_Class::TAX_CLASS_TYPE_CUSTOMER) + ) ->renderLayout(); } @@ -101,6 +113,7 @@ public function editAction() public function deleteAction() { $classId = $this->getRequest()->getParam('id'); + $session = Mage::getSingleton('adminhtml/session'); $classModel = Mage::getModel('tax/class') ->load($classId); @@ -115,8 +128,8 @@ public function deleteAction() ->setClassTypeFilter(Mage_Tax_Model_Class::TAX_CLASS_TYPE_CUSTOMER, $classId); if ($ruleCollection->getSize() > 0) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('You cannot delete this tax class as it is used in Tax Rules. You have to delete the rules it is used in first.')); - $this->_redirectReferer(); + $session->addError(Mage::helper('tax')->__('You cannot delete this tax class as it is used in Tax Rules. You have to delete the rules it is used in first.')); + $this->_redirect('*/*/edit/',array('id'=>$classId)); return; } @@ -126,26 +139,24 @@ public function deleteAction() $groupCount = $customerGroupCollection->getSize(); if ($groupCount > 0) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('You cannot delete this tax class as it is used for %d customer groups.', $groupCount)); - $this->_redirectReferer(); + $session->addError(Mage::helper('tax')->__('You cannot delete this tax class as it is used for %d customer groups.', $groupCount)); + $this->_redirect('*/*/edit/',array('id'=>$classId)); return; } try { $classModel->delete(); - Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('tax')->__('The tax class has been deleted.')); + $session->addSuccess(Mage::helper('tax')->__('The tax class has been deleted.')); $this->getResponse()->setRedirect($this->getUrl("*/*/")); return ; - } - catch (Mage_Core_Exception $e) { - Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); - } - catch (Exception $e) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('An error occurred while deleting this tax class.')); + } catch (Mage_Core_Exception $e) { + $session->addError($e->getMessage()); + } catch (Exception $e) { + $session->addException($e, Mage::helper('tax')->__('An error occurred while deleting this tax class.')); } - $this->_redirectReferer(); + $this->_redirect('*/*/edit/',array('id'=>$classId)); } /** diff --git a/app/code/core/Mage/Adminhtml/controllers/Tax/Class/ProductController.php b/app/code/core/Mage/Adminhtml/controllers/Tax/Class/ProductController.php index 8825c8c6f4..3e54230c77 100644 --- a/app/code/core/Mage/Adminhtml/controllers/Tax/Class/ProductController.php +++ b/app/code/core/Mage/Adminhtml/controllers/Tax/Class/ProductController.php @@ -112,11 +112,12 @@ public function editAction() public function deleteAction() { $classId = $this->getRequest()->getParam('id'); + $session = Mage::getSingleton('adminhtml/session'); $classModel = Mage::getModel('tax/class') ->load($classId); if (!$classModel->getId() || $classModel->getClassType() != Mage_Tax_Model_Class::TAX_CLASS_TYPE_PRODUCT) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('This class no longer exists')); + $session->addError(Mage::helper('tax')->__('This class no longer exists')); $this->_redirect('*/*/'); return; } @@ -126,8 +127,8 @@ public function deleteAction() ->setClassTypeFilter(Mage_Tax_Model_Class::TAX_CLASS_TYPE_PRODUCT, $classId); if ($ruleCollection->getSize() > 0) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('You cannot delete this tax class as it is used in Tax Rules. You have to delete the rules it is used in first.')); - $this->_redirectReferer(); + $session->addError(Mage::helper('tax')->__('You cannot delete this tax class as it is used in Tax Rules. You have to delete the rules it is used in first.')); + $this->_redirect('*/*/edit/', array('id' => $classId)); return; } @@ -137,26 +138,24 @@ public function deleteAction() $productCount = $productCollection->getSize(); if ($productCount > 0) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('You cannot delete this tax class as it is used for %d products.', $productCount)); - $this->_redirectReferer(); + $session->addError(Mage::helper('tax')->__('You cannot delete this tax class as it is used for %d products.', $productCount)); + $this->_redirect('*/*/edit/', array('id' => $classId)); return; } try { $classModel->delete(); - Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('tax')->__('The tax class has been deleted.')); + $session->addSuccess(Mage::helper('tax')->__('The tax class has been deleted.')); $this->getResponse()->setRedirect($this->getUrl("*/*/")); return; - } - catch (Mage_Core_Exception $e) { - Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); - } - catch (Exception $e) { - Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('An error occurred while deleting this tax class.')); + } catch (Mage_Core_Exception $e) { + $session->addError($e->getMessage()); + } catch (Exception $e) { + $session->addException($e, Mage::helper('tax')->__('An error occurred while deleting this tax class.')); } - $this->_redirectReferer(); + $this->_redirect('*/*/edit/', array('id' => $classId)); } /** diff --git a/app/code/core/Mage/Adminhtml/controllers/UrlrewriteController.php b/app/code/core/Mage/Adminhtml/controllers/UrlrewriteController.php index 7ce26034e6..cd4714c918 100644 --- a/app/code/core/Mage/Adminhtml/controllers/UrlrewriteController.php +++ b/app/code/core/Mage/Adminhtml/controllers/UrlrewriteController.php @@ -121,6 +121,7 @@ public function saveAction() $this->_initRegistry(); if ($data = $this->getRequest()->getPost()) { + $session = Mage::getSingleton('adminhtml/session'); try { // set basic urlrewrite data $model = Mage::registry('current_urlrewrite'); @@ -162,7 +163,8 @@ public function saveAction() $rewrite = Mage::getResourceModel('catalog/url') ->getRewriteByIdPath($idPath, $model->getStoreId()); if (!$rewrite) { - Mage::throwException('Chosen product does not associated with the chosen store or category.'); + $exceptionTxt = 'Chosen product does not associated with the chosen store or category.'; + Mage::throwException($exceptionTxt); } if($rewrite->getId() && $rewrite->getId() != $model->getId()) { $model->setIdPath($idPath); @@ -179,17 +181,15 @@ public function saveAction() // save and redirect $model->save(); - Mage::getSingleton('adminhtml/session')->addSuccess( - Mage::helper('adminhtml')->__('The URL Rewrite has been saved.') - ); + $session->addSuccess(Mage::helper('adminhtml')->__('The URL Rewrite has been saved.')); $this->_redirect('*/*/'); return; - } - catch (Exception $e) { - Mage::getSingleton('adminhtml/session') - ->addError($e->getMessage()) - ->setUrlrewriteData($data) - ; + } catch (Mage_Core_Exception $e) { + $session->addError($e->getMessage()) + ->setUrlrewriteData($data); + } catch (Exception $e) { + $session->addException($e, Mage::helper('adminhtml')->__('An error occurred while saving URL Rewrite.')) + ->setUrlrewriteData($data); // return intentionally omitted } } @@ -210,10 +210,10 @@ public function deleteAction() Mage::getSingleton('adminhtml/session')->addSuccess( Mage::helper('adminhtml')->__('The URL Rewrite has been deleted.') ); - } - catch (Exception $e) { - Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); - $this->_redirectReferer(); + } catch (Exception $e) { + Mage::getSingleton('adminhtml/session') + ->addException($e, Mage::helper('adminhtml')->__('An error occurred while deleting URL Rewrite.')); + $this->_redirect('*/*/edit/', array('id'=>Mage::registry('current_urlrewrite')->getId())); return; } } diff --git a/app/code/core/Mage/Adminhtml/etc/config.xml b/app/code/core/Mage/Adminhtml/etc/config.xml index 7e4806dbfa..569b189ee5 100644 --- a/app/code/core/Mage/Adminhtml/etc/config.xml +++ b/app/code/core/Mage/Adminhtml/etc/config.xml @@ -50,8 +50,8 @@ @@ -412,6 +417,8 @@ support customer_password_forgot_email_template + customer_password_remind_email_template + 3
2 diff --git a/app/code/core/Mage/Customer/etc/system.xml b/app/code/core/Mage/Customer/etc/system.xml index 107894e14a..66746b7e46 100644 --- a/app/code/core/Mage/Customer/etc/system.xml +++ b/app/code/core/Mage/Customer/etc/system.xml @@ -170,24 +170,42 @@ 1 1 - - + + select - adminhtml/system_config_source_email_identity - 1 + adminhtml/system_config_source_email_template + 10 1 1 1 - - - + + + select adminhtml/system_config_source_email_template - 1 + 20 1 1 1 - + + + + select + adminhtml/system_config_source_email_identity + 30 + 1 + 1 + 1 + + + + text + adminhtml/system_config_backend_customer_password_link_expirationperiod + 40 + 1 + 0 + 0 +
@@ -315,7 +333,7 @@ 1 - + textarea 1 1 @@ -323,7 +341,7 @@ 1 - + textarea 2 1 @@ -331,7 +349,7 @@ 1 - + textarea 3 1 @@ -339,7 +357,7 @@ 1 - + textarea 4 1 @@ -347,7 +365,7 @@ 1 - + textarea 5 1 diff --git a/app/code/core/Mage/Customer/sql/customer_setup/install-1.6.0.0.php b/app/code/core/Mage/Customer/sql/customer_setup/install-1.6.0.0.php index 036b2f9b74..e4153f7f23 100644 --- a/app/code/core/Mage/Customer/sql/customer_setup/install-1.6.0.0.php +++ b/app/code/core/Mage/Customer/sql/customer_setup/install-1.6.0.0.php @@ -166,10 +166,16 @@ ), 'Entity Id') ->addColumn('value', Varien_Db_Ddl_Table::TYPE_DATETIME, null, array( 'nullable' => false, - 'default' => '0000-00-00 00:00:00' + 'default' => $installer->getConnection()->getSuggestedZeroDate() ), 'Value') - ->addIndex($installer->getIdxName('customer_address_entity_datetime', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), - array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) + ->addIndex( + $installer->getIdxName( + 'customer_address_entity_datetime', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), + array('entity_id', 'attribute_id'), + array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_address_entity_datetime', array('entity_type_id')), array('entity_type_id')) ->addIndex($installer->getIdxName('customer_address_entity_datetime', array('attribute_id')), @@ -178,13 +184,21 @@ array('entity_id')) ->addIndex($installer->getIdxName('customer_address_entity_datetime', array('entity_id', 'attribute_id', 'value')), array('entity_id', 'attribute_id', 'value')) - ->addForeignKey($installer->getFkName('customer_address_entity_datetime', 'attribute_id', 'eav/attribute', 'attribute_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_datetime', 'attribute_id', 'eav/attribute', 'attribute_id'), 'attribute_id', $installer->getTable('eav/attribute'), 'attribute_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_datetime', 'entity_id', 'customer/address_entity', 'entity_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_datetime', 'entity_id', 'customer/address_entity', 'entity_id'), 'entity_id', $installer->getTable('customer/address_entity'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_datetime', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), + ->addForeignKey( + $installer->getFkName( + 'customer_address_entity_datetime', + 'entity_type_id', + 'eav/entity_type', + 'entity_type_id' + ), 'entity_type_id', $installer->getTable('eav/entity_type'), 'entity_type_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->setComment('Customer Address Entity Datetime'); @@ -219,7 +233,12 @@ 'nullable' => false, 'default' => '0.0000', ), 'Value') - ->addIndex($installer->getIdxName('customer_address_entity_decimal', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), + ->addIndex( + $installer->getIdxName( + 'customer_address_entity_decimal', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_address_entity_decimal', array('entity_type_id')), array('entity_type_id')) @@ -229,13 +248,16 @@ array('entity_id')) ->addIndex($installer->getIdxName('customer_address_entity_decimal', array('entity_id', 'attribute_id', 'value')), array('entity_id', 'attribute_id', 'value')) - ->addForeignKey($installer->getFkName('customer_address_entity_decimal', 'attribute_id', 'eav/attribute', 'attribute_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_decimal', 'attribute_id', 'eav/attribute', 'attribute_id'), 'attribute_id', $installer->getTable('eav/attribute'), 'attribute_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_decimal', 'entity_id', 'customer/address_entity', 'entity_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_decimal', 'entity_id', 'customer/address_entity', 'entity_id'), 'entity_id', $installer->getTable('customer/address_entity'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_decimal', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_decimal', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), 'entity_type_id', $installer->getTable('eav/entity_type'), 'entity_type_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->setComment('Customer Address Entity Decimal'); @@ -270,7 +292,12 @@ 'nullable' => false, 'default' => '0', ), 'Value') - ->addIndex($installer->getIdxName('customer_address_entity_int', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), + ->addIndex( + $installer->getIdxName( + 'customer_address_entity_int', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_address_entity_int', array('entity_type_id')), array('entity_type_id')) @@ -280,13 +307,16 @@ array('entity_id')) ->addIndex($installer->getIdxName('customer_address_entity_int', array('entity_id', 'attribute_id', 'value')), array('entity_id', 'attribute_id', 'value')) - ->addForeignKey($installer->getFkName('customer_address_entity_int', 'attribute_id', 'eav/attribute', 'attribute_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_int', 'attribute_id', 'eav/attribute', 'attribute_id'), 'attribute_id', $installer->getTable('eav/attribute'), 'attribute_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_int', 'entity_id', 'customer/address_entity', 'entity_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_int', 'entity_id', 'customer/address_entity', 'entity_id'), 'entity_id', $installer->getTable('customer/address_entity'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_int', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_int', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), 'entity_type_id', $installer->getTable('eav/entity_type'), 'entity_type_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->setComment('Customer Address Entity Int'); @@ -320,7 +350,12 @@ ->addColumn('value', Varien_Db_Ddl_Table::TYPE_TEXT, '64k', array( 'nullable' => false, ), 'Value') - ->addIndex($installer->getIdxName('customer_address_entity_text', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), + ->addIndex( + $installer->getIdxName( + 'customer_address_entity_text', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_address_entity_text', array('entity_type_id')), array('entity_type_id')) @@ -328,13 +363,16 @@ array('attribute_id')) ->addIndex($installer->getIdxName('customer_address_entity_text', array('entity_id')), array('entity_id')) - ->addForeignKey($installer->getFkName('customer_address_entity_text', 'attribute_id', 'eav/attribute', 'attribute_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_text', 'attribute_id', 'eav/attribute', 'attribute_id'), 'attribute_id', $installer->getTable('eav/attribute'), 'attribute_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_text', 'entity_id', 'customer/address_entity', 'entity_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_text', 'entity_id', 'customer/address_entity', 'entity_id'), 'entity_id', $installer->getTable('customer/address_entity'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_text', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_text', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), 'entity_type_id', $installer->getTable('eav/entity_type'), 'entity_type_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->setComment('Customer Address Entity Text'); @@ -367,7 +405,12 @@ ), 'Entity Id') ->addColumn('value', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array( ), 'Value') - ->addIndex($installer->getIdxName('customer_address_entity_varchar', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), + ->addIndex( + $installer->getIdxName( + 'customer_address_entity_varchar', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_address_entity_varchar', array('entity_type_id')), array('entity_type_id')) @@ -377,13 +420,16 @@ array('entity_id')) ->addIndex($installer->getIdxName('customer_address_entity_varchar', array('entity_id', 'attribute_id', 'value')), array('entity_id', 'attribute_id', 'value')) - ->addForeignKey($installer->getFkName('customer_address_entity_varchar', 'attribute_id', 'eav/attribute', 'attribute_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_varchar', 'attribute_id', 'eav/attribute', 'attribute_id'), 'attribute_id', $installer->getTable('eav/attribute'), 'attribute_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_varchar', 'entity_id', 'customer/address_entity', 'entity_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_varchar', 'entity_id', 'customer/address_entity', 'entity_id'), 'entity_id', $installer->getTable('customer/address_entity'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_address_entity_varchar', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), + ->addForeignKey( + $installer->getFkName('customer_address_entity_varchar', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), 'entity_type_id', $installer->getTable('eav/entity_type'), 'entity_type_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->setComment('Customer Address Entity Varchar'); @@ -416,9 +462,14 @@ ), 'Entity Id') ->addColumn('value', Varien_Db_Ddl_Table::TYPE_DATETIME, null, array( 'nullable' => false, - 'default' => '0000-00-00 00:00:00' + 'default' => $installer->getConnection()->getSuggestedZeroDate() ), 'Value') - ->addIndex($installer->getIdxName('customer_entity_datetime', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), + ->addIndex( + $installer->getIdxName( + 'customer_entity_datetime', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_entity_datetime', array('entity_type_id')), array('entity_type_id')) @@ -434,7 +485,8 @@ ->addForeignKey($installer->getFkName('customer_entity_datetime', 'entity_id', 'customer/entity', 'entity_id'), 'entity_id', $installer->getTable('customer/entity'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_entity_datetime', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), + ->addForeignKey( + $installer->getFkName('customer_entity_datetime', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), 'entity_type_id', $installer->getTable('eav/entity_type'), 'entity_type_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->setComment('Customer Entity Datetime'); @@ -469,7 +521,12 @@ 'nullable' => false, 'default' => '0.0000', ), 'Value') - ->addIndex($installer->getIdxName('customer_entity_decimal', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), + ->addIndex( + $installer->getIdxName( + 'customer_entity_decimal', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_entity_decimal', array('entity_type_id')), array('entity_type_id')) @@ -485,7 +542,8 @@ ->addForeignKey($installer->getFkName('customer_entity_decimal', 'entity_id', 'customer/entity', 'entity_id'), 'entity_id', $installer->getTable('customer/entity'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_entity_decimal', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), + ->addForeignKey( + $installer->getFkName('customer_entity_decimal', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), 'entity_type_id', $installer->getTable('eav/entity_type'), 'entity_type_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->setComment('Customer Entity Decimal'); @@ -520,7 +578,12 @@ 'nullable' => false, 'default' => '0', ), 'Value') - ->addIndex($installer->getIdxName('customer_entity_int', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), + ->addIndex( + $installer->getIdxName( + 'customer_entity_int', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_entity_int', array('entity_type_id')), array('entity_type_id')) @@ -570,7 +633,12 @@ ->addColumn('value', Varien_Db_Ddl_Table::TYPE_TEXT, '64k', array( 'nullable' => false, ), 'Value') - ->addIndex($installer->getIdxName('customer_entity_text', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), + ->addIndex( + $installer->getIdxName( + 'customer_entity_text', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_entity_text', array('entity_type_id')), array('entity_type_id')) @@ -584,7 +652,8 @@ ->addForeignKey($installer->getFkName('customer_entity_text', 'entity_id', 'customer/entity', 'entity_id'), 'entity_id', $installer->getTable('customer/entity'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_entity_text', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), + ->addForeignKey( + $installer->getFkName('customer_entity_text', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), 'entity_type_id', $installer->getTable('eav/entity_type'), 'entity_type_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->setComment('Customer Entity Text'); @@ -617,7 +686,12 @@ ), 'Entity Id') ->addColumn('value', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array( ), 'Value') - ->addIndex($installer->getIdxName('customer_entity_varchar', array('entity_id', 'attribute_id'), Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE), + ->addIndex( + $installer->getIdxName( + 'customer_entity_varchar', + array('entity_id', 'attribute_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), array('entity_id', 'attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) ->addIndex($installer->getIdxName('customer_entity_varchar', array('entity_type_id')), array('entity_type_id')) @@ -633,7 +707,8 @@ ->addForeignKey($installer->getFkName('customer_entity_varchar', 'entity_id', 'customer/entity', 'entity_id'), 'entity_id', $installer->getTable('customer/entity'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->addForeignKey($installer->getFkName('customer_entity_varchar', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), + ->addForeignKey( + $installer->getFkName('customer_entity_varchar', 'entity_type_id', 'eav/entity_type', 'entity_type_id'), 'entity_type_id', $installer->getTable('eav/entity_type'), 'entity_type_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->setComment('Customer Entity Varchar'); @@ -754,7 +829,8 @@ ), 'Multiline Count') ->addIndex($installer->getIdxName('customer/eav_attribute_website', array('website_id')), array('website_id')) - ->addForeignKey($installer->getFkName('customer/eav_attribute_website', 'attribute_id', 'eav/attribute', 'attribute_id'), + ->addForeignKey( + $installer->getFkName('customer/eav_attribute_website', 'attribute_id', 'eav/attribute', 'attribute_id'), 'attribute_id', $installer->getTable('eav/attribute'), 'attribute_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) ->addForeignKey($installer->getFkName('customer/eav_attribute_website', 'website_id', 'core/website', 'website_id'), diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Code/Category.php b/app/code/core/Mage/Customer/sql/customer_setup/mysql4-upgrade-1.6.0.0-1.6.1.0.php similarity index 57% rename from app/code/core/Mage/GoogleOptimizer/Block/Code/Category.php rename to app/code/core/Mage/Customer/sql/customer_setup/mysql4-upgrade-1.6.0.0-1.6.1.0.php index d9a6c54ab5..df8407c5cb 100644 --- a/app/code/core/Mage/GoogleOptimizer/Block/Code/Category.php +++ b/app/code/core/Mage/Customer/sql/customer_setup/mysql4-upgrade-1.6.0.0-1.6.1.0.php @@ -19,34 +19,30 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Customer * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ +/* @var $installer Mage_Customer_Model_Entity_Setup */ +$installer = $this; +$installer->startSetup(); -/** - * Google Optimizer Category Block - * - * @category Mage - * @package Mage_GoogleOptimizer - * @author Magento Core Team - */ -class Mage_GoogleOptimizer_Block_Code_Category extends Mage_GoogleOptimizer_Block_Code -{ - protected function _initGoogleOptimizerModel() - { - $this->_setGoogleOptimizerModel($this->getGoogleOptimizer()); - return parent::_initGoogleOptimizerModel(); - } +// Add reset password link token attribute +$installer->addAttribute('customer', 'rp_token', array( + 'type' => 'varchar', + 'input' => 'hidden', + 'visible' => false, + 'required' => false +)); - public function getCategory() - { - return Mage::registry('current_category'); - } +// Add reset password link token creation date attribute +$installer->addAttribute('customer', 'rp_token_created_at', array( + 'type' => 'datetime', + 'input' => 'date', + 'validate_rules' => 'a:1:{s:16:"input_validation";s:4:"date";}', + 'visible' => false, + 'required' => false +)); - public function getGoogleOptimizer() - { - return $this->getCategory()->getGoogleOptimizerScripts(); - } -} +$installer->endSetup(); 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 0bccc427f5..bd16bce324 100755 --- a/app/code/core/Mage/Directory/Model/Resource/Country/Collection.php +++ b/app/code/core/Mage/Directory/Model/Resource/Country/Collection.php @@ -46,11 +46,12 @@ protected function _construct() /** * Load allowed countries for current store * + * @param mixed $store * @return Mage_Directory_Model_Resource_Country_Collection */ - public function loadByStore() + public function loadByStore($store = null) { - $allowCountries = explode(',', (string)Mage::getStoreConfig('general/country/allow')); + $allowCountries = explode(',', (string)Mage::getStoreConfig('general/country/allow', $store)); if (!empty($allowCountries)) { $this->addFieldToFilter("country_id", array('in' => $allowCountries)); } 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 e5e93ffac5..9a26339915 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 @@ -32,7 +32,8 @@ * @package Mage_Eav * @author Magento Core Team */ -abstract class Mage_Eav_Model_Entity_Attribute_Frontend_Abstract implements Mage_Eav_Model_Entity_Attribute_Frontend_Interface +abstract class Mage_Eav_Model_Entity_Attribute_Frontend_Abstract + implements Mage_Eav_Model_Entity_Attribute_Frontend_Interface { /** @@ -139,13 +140,58 @@ public function isVisible() */ public function getClass() { - $out = $this->getAttribute()->getFrontendClass(); + $out = array(); + $out[] = $this->getAttribute()->getFrontendClass(); if ($this->getAttribute()->getIsRequired()) { - $out .= ' required-entry'; + $out[] = 'required-entry'; + } + + $inputRuleClass = $this->_getInputValidateClass(); + if ($inputRuleClass) { + $out[] = $inputRuleClass; + } + if (!empty($out)) { + $out = implode(' ', $out); + } else { + $out = ''; } 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: + $class = false; + break; + } + } + return $class; + } + /** * Reireive config field * 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 8022ec9869..d9bf3099dd 100644 --- a/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php +++ b/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php @@ -104,6 +104,15 @@ abstract class Mage_Eav_Model_Entity_Collection_Abstract extends Varien_Data_Col */ protected $_useAnalyticFunction = false; + /** + * Cast map for attribute order + * + * @var array + */ + protected $_castToIntMap = array( + 'validate-digits' + ); + /** * Collection constructor * @@ -356,21 +365,50 @@ public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC) $attrInstance = $this->getEntity()->getAttribute($attribute); $entityField = 'e.' . $attribute; } + if ($attrInstance) { if ($attrInstance->getBackend()->isStatic()) { - $this->getSelect()->order($entityField . ' ' . $dir); + $orderExpr = $entityField; } else { $this->_addAttributeJoin($attribute, 'left'); if (isset($this->_joinAttributes[$attribute])||isset($this->_joinFields[$attribute])) { - $this->getSelect()->order($attribute . ' ' . $dir); + $orderExpr = $attribute; } else { - $this->getSelect()->order($this->_getAttributeTableAlias($attribute) . '.value ' . $dir); + $orderExpr = $this->_getAttributeTableAlias($attribute).'.value'; } } + + if (in_array($attrInstance->getFrontendClass(), $this->_castToIntMap)) { + $orderExpr = Mage::getResourceHelper('eav')->getCastToIntExpression( + $this->_prepareOrderExpression($orderExpr) + ); + } + + $orderExpr .= ' ' . $dir; + $this->getSelect()->order($orderExpr); } 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 * @@ -1057,7 +1095,11 @@ public function _loadAttributes($printQuery = false, $logQuery = false) $selects = array(); foreach ($tableAttributes as $table=>$attributes) { $select = $this->_getLoadAttributesSelect($table, $attributes); - $selects[$attributeTypes[$table]][] = $this->_addLoadAttributesSelectValues($select, $table, $attributeTypes[$table]); + $selects[$attributeTypes[$table]][] = $this->_addLoadAttributesSelectValues( + $select, + $table, + $attributeTypes[$table] + ); } $selectGroups = Mage::getResourceHelper('eav')->getLoadAttributesSelectGroups($selects); foreach ($selectGroups as $selects) { @@ -1333,7 +1375,10 @@ protected function _getAttributeConditionSql($attribute, $condition, $joinType = } if ($entity->isAttributeStatic($attribute)) { - $conditionSql = $this->_getConditionSql($this->getConnection()->quoteIdentifier('e.' . $attribute), $condition); + $conditionSql = $this->_getConditionSql( + $this->getConnection()->quoteIdentifier('e.' . $attribute), + $condition + ); } else { $this->_addAttributeJoin($attribute, $joinType); if (isset($this->_joinAttributes[$attribute]['condition_alias'])) { 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 00df9979bb..4995d47869 100755 --- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set.php +++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Set.php @@ -89,8 +89,8 @@ public function validate($object, $attributeSetName) { $adapter = $this->_getReadAdapter(); - $bind = array( - 'attribute_set_name' => $attributeSetName, + $bind = array( + 'attribute_set_name' => trim($attributeSetName), 'entity_type_id' => $object->getEntityTypeId() ); $select = $adapter->select() diff --git a/app/code/core/Mage/Eav/Model/Resource/Helper/Mysql4.php b/app/code/core/Mage/Eav/Model/Resource/Helper/Mysql4.php index 0279bbeb80..a652c6839a 100644 --- a/app/code/core/Mage/Eav/Model/Resource/Helper/Mysql4.php +++ b/app/code/core/Mage/Eav/Model/Resource/Helper/Mysql4.php @@ -114,4 +114,15 @@ public function getLoadAttributesSelectGroups($selects) } return array($mainGroup); } + + /** + * Retrieve 'cast to int' expression + * + * @param string|Zend_Db_Expr $expression + * @return Zend_Db_Expr + */ + public function getCastToIntExpression($expression) + { + return new Zend_Db_Expr("CAST($expression AS SIGNED)"); + } } diff --git a/app/code/core/Mage/Eav/sql/eav_setup/install-1.6.0.0.php b/app/code/core/Mage/Eav/sql/eav_setup/install-1.6.0.0.php index 5fcfced0f1..92965fb496 100644 --- a/app/code/core/Mage/Eav/sql/eav_setup/install-1.6.0.0.php +++ b/app/code/core/Mage/Eav/sql/eav_setup/install-1.6.0.0.php @@ -190,7 +190,7 @@ ), 'Entity Id') ->addColumn('value', Varien_Db_Ddl_Table::TYPE_DATETIME, null, array( 'nullable' => false, - 'default' => '0000-00-00 00:00:00' + 'default' => $installer->getConnection()->getSuggestedZeroDate() ), 'Attribute Value') ->addIndex($installer->getIdxName(array('eav/entity_value_prefix', 'datetime'), array('entity_type_id')), array('entity_type_id')) diff --git a/app/code/core/Mage/GoogleBase/sql/googlebase_setup/mysql4-upgrade-1.5.9.9-1.6.0.0.php b/app/code/core/Mage/GoogleBase/sql/googlebase_setup/mysql4-upgrade-1.5.9.9-1.6.0.0.php index 39b7bfadf1..a36142bbe9 100644 --- a/app/code/core/Mage/GoogleBase/sql/googlebase_setup/mysql4-upgrade-1.5.9.9-1.6.0.0.php +++ b/app/code/core/Mage/GoogleBase/sql/googlebase_setup/mysql4-upgrade-1.5.9.9-1.6.0.0.php @@ -33,7 +33,7 @@ */ $installer->getConnection()->dropForeignKey( $installer->getTable('googlebase/attributes'), - 'FK_GOOGLEBASE_ATTRIBUTES_ATTRIBUTE_ID' + 'GOOGLEBASE_ATTRIBUTES_ATTRIBUTE_ID' ); $installer->getConnection()->dropForeignKey( @@ -43,17 +43,17 @@ $installer->getConnection()->dropForeignKey( $installer->getTable('googlebase/items'), - 'FK_GOOGLEBASE_ITEMS_PRODUCT_ID' + 'GOOGLEBASE_ITEMS_PRODUCT_ID' ); $installer->getConnection()->dropForeignKey( $installer->getTable('googlebase/items'), - 'FK_GOOGLEBASE_ITEMS_STORE_ID' + 'GOOGLEBASE_ITEMS_STORE_ID' ); $installer->getConnection()->dropForeignKey( $installer->getTable('googlebase/types'), - 'FK_GOOGLEBASE_TYPES_ATTRIBUTE_SET_ID' + 'GOOGLEBASE_TYPES_ATTRIBUTE_SET_ID' ); diff --git a/app/code/core/Mage/GoogleCheckout/Helper/Data.php b/app/code/core/Mage/GoogleCheckout/Helper/Data.php index 9627d57c4c..674a4c2933 100644 --- a/app/code/core/Mage/GoogleCheckout/Helper/Data.php +++ b/app/code/core/Mage/GoogleCheckout/Helper/Data.php @@ -81,4 +81,112 @@ public function isShippingCarrierActive($storeId) { return (true == Mage::getStoreConfig(self::XML_PATH_SHIPPING_CARRIER_ACTIVE, $storeId)); } + + /** + * Convert Magento zip range to array of Google Checkout zip-patterns + * (e.g., 12000-13999 -> [12*, 13*]) + * + * @param string $zipRange + * @return array + */ + public function zipRangeToZipPattern($zipRange) + { + $zipLength = 5; + $zipPattern = array(); + + if (!preg_match("/^(.+)-(.+)$/", $zipRange, $zipParts)) { + return array($zipRange); + } + + if ($zipParts[1] == $zipParts[2]) { + return array($zipParts[1]); + } + + if ($zipParts[1] > $zipParts[2]) { + list($zipParts[2], $zipParts[1]) = array($zipParts[1], $zipParts[2]); + } + + $from = str_split($zipParts[1]); + $to = str_split($zipParts[2]); + + $startZip = ''; + $diffPosition = null; + for ($pos = 0; $pos < $zipLength; $pos++) { + if ($from[$pos] == $to[$pos]) { + $startZip .= $from[$pos]; + } else { + $diffPosition = $pos; + break; + } + } + + /* + * calculate zip-patterns + */ + if (min(array_slice($to, $diffPosition)) == 9 && max(array_slice($from, $diffPosition)) == 0) { + // particular case like 11000-11999 -> 11* + return array($startZip . '*'); + } else { + // calculate approximate zip-patterns + $start = $from[$diffPosition]; + $finish = $to[$diffPosition]; + if ($diffPosition < $zipLength - 1) { + $start++; + $finish--; + } + $end = $diffPosition < $zipLength - 1 ? '*' : ''; + for ($digit = $start; $digit <= $finish; $digit++) { + $zipPattern[] = $startZip . $digit . $end; + } + } + + if ($diffPosition == $zipLength - 1) { + return $zipPattern; + } + + $nextAsteriskFrom = true; + $nextAsteriskTo = true; + for ($pos = $zipLength - 1; $pos > $diffPosition; $pos--) { + // calculate zip-patterns based on $from value + if ($from[$pos] == 0 && $nextAsteriskFrom) { + $nextAsteriskFrom = true; + } else { + $subZip = ''; + for ($k = $diffPosition; $k < $pos; $k++) { + $subZip .= $from[$k]; + } + $delta = $nextAsteriskFrom ? 0 : 1; + $end = $pos < $zipLength - 1 ? '*' : ''; + for ($i = $from[$pos] + $delta; $i <= 9; $i++) { + $zipPattern[] = $startZip . $subZip . $i . $end; + } + $nextAsteriskFrom = false; + } + + // calculate zip-patterns based on $to value + if ($to[$pos] == 9 && $nextAsteriskTo) { + $nextAsteriskTo = true; + } else { + $subZip = ''; + for ($k = $diffPosition; $k < $pos; $k++) { + $subZip .= $to[$k]; + } + $delta = $nextAsteriskTo ? 0 : 1; + $end = $pos < $zipLength - 1 ? '*' : ''; + for ($i = 0; $i <= $to[$pos] - $delta; $i++) { + $zipPattern[] = $startZip . $subZip . $i . $end; + } + $nextAsteriskTo = false; + } + } + + if ($nextAsteriskFrom) { + $zipPattern[] = $startZip . $from[$diffPosition] . '*'; + } + if ($nextAsteriskTo) { + $zipPattern[] = $startZip . $to[$diffPosition] . '*'; + } + + return $zipPattern; + } } diff --git a/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php b/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php index d41983ce0e..66d65568e0 100644 --- a/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php +++ b/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php @@ -675,6 +675,7 @@ protected function _importGoogleTotals($qAddress) if ($method) { Mage::getSingleton('tax/config')->setShippingPriceIncludeTax(false); $rate = $this->_createShippingRate($method) + ->setMethodTitle($shipping['shipping-name']['VALUE']) ->setPrice($shipping['shipping-cost']['VALUE']); $qAddress->addShippingRate($rate) ->setShippingMethod($method) diff --git a/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Checkout.php b/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Checkout.php index ec1219699b..97b0ad3b88 100644 --- a/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Checkout.php +++ b/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Checkout.php @@ -743,17 +743,21 @@ protected function _getTaxTableXml($rules, $type) foreach ($taxRates as $rate) { $xml .= << - + EOT; if ($rate['country'] === Mage_Usa_Model_Shipping_Carrier_Abstract::USA_COUNTRY_ID) { if (!empty($rate['postcode']) && $rate['postcode'] !== '*') { - $xml .= << - {$rate['postcode']} - + $rate['postcode'] = Mage::helper('googlecheckout') + ->zipRangeToZipPattern($rate['postcode']); + foreach ($rate['postcode'] as $postcode) { + $xml .= << + $postcode + EOT; + } } else if (!empty($rate['state'])) { $xml .= << @@ -788,7 +792,7 @@ protected function _getTaxTableXml($rules, $type) } } $xml .= << + {$rate['value']} EOT; if ($shippingTaxed) { diff --git a/app/code/core/Mage/GoogleCheckout/etc/config.xml b/app/code/core/Mage/GoogleCheckout/etc/config.xml index 8a1e8cccfd..9a6b7902d3 100644 --- a/app/code/core/Mage/GoogleCheckout/etc/config.xml +++ b/app/code/core/Mage/GoogleCheckout/etc/config.xml @@ -28,7 +28,7 @@ - 1.6.0.0 + 1.6.0.1 diff --git a/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/install-1.6.0.0.php b/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/install-1.6.0.0.php index a77e92cf42..cecca2cde2 100644 --- a/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/install-1.6.0.0.php +++ b/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/install-1.6.0.0.php @@ -59,7 +59,7 @@ 'type' => 'int', 'backend' => '', 'frontend' => '', - 'label' => 'Is product available for purchase with Google Checkout', + 'label' => 'Is Product Available for Purchase with Google Checkout', 'input' => 'select', 'class' => '', 'source' => 'eav/entity_attribute_source_boolean', diff --git a/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/mysql4-upgrade-0.7.1-0.7.2.php b/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/mysql4-upgrade-0.7.1-0.7.2.php index 249bdcf190..1c0425edd8 100644 --- a/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/mysql4-upgrade-0.7.1-0.7.2.php +++ b/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/mysql4-upgrade-0.7.1-0.7.2.php @@ -31,7 +31,7 @@ $installer->updateAttribute('catalog_product', 'disable_googlecheckout', array( 'attribute_code' => 'enable_googlecheckout', - 'frontend_label' => 'Is product available for purchase with Google Checkout', + 'frontend_label' => 'Is Product Available for Purchase with Google Checkout', )); $attribute = $installer->getAttribute('catalog_product', 'enable_googlecheckout'); diff --git a/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/mysql4-upgrade-0.1.1-0.1.2.php b/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/mysql4-upgrade-1.6.0.0-1.6.0.1.php similarity index 77% rename from app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/mysql4-upgrade-0.1.1-0.1.2.php rename to app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/mysql4-upgrade-1.6.0.0-1.6.0.1.php index e3e2f0e648..4799c84e4b 100644 --- a/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/mysql4-upgrade-0.1.1-0.1.2.php +++ b/app/code/core/Mage/GoogleCheckout/sql/googlecheckout_setup/mysql4-upgrade-1.6.0.0-1.6.0.1.php @@ -19,16 +19,17 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_GoogleCheckout * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ +/* @var $installer Mage_GoogleCheckout_Model_Resource_Setup */ $installer = $this; -/* @var $installer Mage_Core_Model_Resource_Setup */ -$installer->startSetup(); - -$installer->getConnection()->addColumn($installer->getTable('googleoptimizer/code'), 'additional_data', "text"); - -$installer->endSetup(); +$installer->updateAttribute( + Mage_Catalog_Model_Product::ENTITY, + 'enable_googlecheckout', + 'frontend_label', + 'Is Product Available for Purchase with Google Checkout' +); diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Catalog/Category/Edit/Tab/Googleoptimizer.php b/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Catalog/Category/Edit/Tab/Googleoptimizer.php deleted file mode 100644 index 18e5dc1213..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Catalog/Category/Edit/Tab/Googleoptimizer.php +++ /dev/null @@ -1,195 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Block_Adminhtml_Catalog_Category_Edit_Tab_Googleoptimizer extends Mage_Adminhtml_Block_Catalog_Form -{ - public function __construct() - { - parent::__construct(); - $this->setShowGlobalIcon(true); - } - - public function getCategory() - { - if (!$this->_category) { - $this->_category = Mage::registry('current_category'); - } - return $this->_category; - } - - public function getGoogleOptimizer() - { - return $this->getCategory()->getGoogleOptimizerScripts(); - } - - public function _prepareLayout() - { - $form = new Varien_Data_Form(); - - $fieldset = $form->addFieldset('base_fieldset', - array('legend' => Mage::helper('googleoptimizer')->__('Google Optimizer Scripts')) - ); - - if ($this->getCategory()->getStoreId() == '0') { - Mage::helper('googleoptimizer')->setStoreId(Mage::app()->getDefaultStoreView()); - } else { - Mage::helper('googleoptimizer')->setStoreId($this->getCategory()->getStoreId()); - } - - $disabledScriptsFields = false; - $values = array(); - if ($this->getGoogleOptimizer() && $this->getGoogleOptimizer()->getData()) { - $disabledScriptsFields = true; - $values = $this->getGoogleOptimizer()->getData(); - $checkedUseDefault = true; - if ($this->getGoogleOptimizer()->getStoreId() == $this->getCategory()->getStoreId()) { - $checkedUseDefault = false; - $disabledScriptsFields = false; - $fieldset->addField('code_id', 'hidden', array('name' => 'code_id')); - } - // show 'use default' checkbox if store different for default and product has scripts for default store - if ($this->getCategory()->getStoreId() != '0') { - $fieldset->addField('store_flag', 'checkbox', - array( - 'name' => 'store_flag', - 'value' => '1', - 'label' => Mage::helper('googleoptimizer')->__('Use Default'), - 'class' => 'checkbox', - 'required' => false, - 'onchange' => 'googleOptimizerScopeAction()', - ) - )->setIsChecked($checkedUseDefault); - } - } - - $fieldset->addField('conversion_page', 'select', - array( - 'name' => 'conversion_page', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Page'), - 'values'=> Mage::getModel('googleoptimizer/adminhtml_system_config_source_googleoptimizer_conversionpages')->toOptionArray(), - 'class' => 'select googleoptimizer validate-googleoptimizer', - 'required' => false, - 'onchange' => 'googleOptimizerConversionPageAction(this)' - ) - ); - //Mage::getStoreConfigFlag(Mage_Core_Model_Store::XML_PATH_STORE_IN_URL) - if ($this->getCategory()->getStoreId() == '0' && !Mage::app()->isSingleStoreMode()) { - $fieldset->addField('conversion_page_url', 'note', - array( - 'name' => 'conversion_page_url', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Page URL'), - 'text' => Mage::helper('googleoptimizer')->__('Please select store view to see the URL') - ) - ); - } else { - $fieldset->addField('conversion_page_url', 'text', - array( - 'name' => 'conversion_page_url', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Page URL'), - 'class' => 'input-text', - 'readonly' => 'readonly', - 'required' => false, - 'note' => Mage::helper('googleoptimizer')->__('Please copy and paste this value to experiment edit form') - ) - ); - } - - $fieldset->addField('export_controls', 'text', array('name' => 'export_controls')); - - $fieldset->addField('control_script', 'textarea', - array( - 'name' => 'control_script', - 'label' => Mage::helper('googleoptimizer')->__('Control Script'), - 'class' => 'textarea googleoptimizer validate-googleoptimizer', - 'required' => false, - ) - ); - - $fieldset->addField('tracking_script', 'textarea', - array( - 'name' => 'tracking_script', - 'label' => Mage::helper('googleoptimizer')->__('Tracking Script'), - 'class' => 'textarea googleoptimizer validate-googleoptimizer', - 'required' => false, - ) - ); - - $fieldset->addField('conversion_script', 'textarea', - array( - 'name' => 'conversion_script', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Script'), - 'class' => 'textarea googleoptimizer validate-googleoptimizer', - 'required' => false, - ) - ); - - if (Mage::helper('googleoptimizer')->getConversionPagesUrl() - && $this->getGoogleOptimizer() - && $this->getGoogleOptimizer()->getConversionPage()) - { - $form->getElement('conversion_page_url') - ->setValue(Mage::helper('googleoptimizer') - ->getConversionPagesUrl()->getData($this->getGoogleOptimizer()->getConversionPage()) - ); - } - - if ($disabledScriptsFields) { - foreach ($fieldset->getElements() as $element) { - if ($element->getType() == 'textarea' || $element->getType() == 'select') { - $element->setDisabled($disabledScriptsFields); - } - } - } - - $fakeEntityAttribute = Mage::getModel('catalog/resource_eav_attribute'); - - $readonly = $this->getCategory()->getOptimizationReadonly(); - foreach ($fieldset->getElements() as $element) { - $element->setDisabled($readonly); - if ($element->getId() != 'store_flag') { - $element->setEntityAttribute($fakeEntityAttribute); - } - } - - $form->getElement('export_controls')->setRenderer( - $this->getLayout()->createBlock('adminhtml/catalog_form_renderer_googleoptimizer_import') - ); - - $form->addValues($values); - $form->setFieldNameSuffix('googleoptimizer'); - $this->setForm($form); - - return parent::_prepareLayout(); - } - -} diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Catalog/Product/Edit/Tab/Googleoptimizer.php b/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Catalog/Product/Edit/Tab/Googleoptimizer.php deleted file mode 100644 index edefae1b19..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Catalog/Product/Edit/Tab/Googleoptimizer.php +++ /dev/null @@ -1,225 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Block_Adminhtml_Catalog_Product_Edit_Tab_Googleoptimizer - extends Mage_Adminhtml_Block_Catalog_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface -{ - - protected function _prepareForm() - { - $form = new Varien_Data_Form(); - - $fieldset = $form->addFieldset('googleoptimizer_fields', - array('legend' => Mage::helper('googleoptimizer')->__('Google Optimizer Scripts')) - ); - - if ($this->getProduct()->getStoreId() == '0') { - Mage::helper('googleoptimizer')->setStoreId(Mage::app()->getDefaultStoreView()); - } else { - Mage::helper('googleoptimizer')->setStoreId($this->getProduct()->getStoreId()); - } - - - $disabledScriptsFields = false; - $values = array(); - if ($this->getGoogleOptimizer() && $this->getGoogleOptimizer()->getData()) { - $disabledScriptsFields = true; - $values = $this->getGoogleOptimizer()->getData(); - $checkedUseDefault = true; - if ($this->getGoogleOptimizer()->getStoreId() == $this->getProduct()->getStoreId()) { - $checkedUseDefault = false; - $disabledScriptsFields = false; - $fieldset->addField('code_id', 'hidden', array('name' => 'code_id')); - } - - // show 'use default' checkbox if store different for default and product has scripts for default store - if ($this->getProduct()->getStoreId() != '0') { - $fieldset->addField('store_flag', 'checkbox', - array( - 'name' => 'store_flag', - 'value' => '1', - 'label' => Mage::helper('googleoptimizer')->__('Use Default Values'), - 'class' => 'checkbox', - 'required' => false, - 'onchange' => 'googleOptimizerScopeAction()', - ) - )->setIsChecked($checkedUseDefault); - } - } - - $fieldset->addField('conversion_page', 'select', - array( - 'name' => 'conversion_page', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Page'), - 'values'=> Mage::getModel('googleoptimizer/adminhtml_system_config_source_googleoptimizer_conversionpages')->toOptionArray(), - 'class' => 'select googleoptimizer validate-googleoptimizer', - 'required' => false, - 'onchange' => 'googleOptimizerConversionPageAction(this)' - ) - ); - - if ($this->getProduct()->getStoreId() == '0' && !Mage::app()->isSingleStoreMode()) { - $fieldset->addField('conversion_page_url', 'note', - array( - 'name' => 'conversion_page_url', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Page URL'), - 'text' => Mage::helper('googleoptimizer')->__('Please select store view to see the URL.') - ) - ); - } else { - $fieldset->addField('conversion_page_url', 'text', - array( - 'name' => 'conversion_page_url', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Page URL'), - 'class' => 'input-text', - 'readonly' => 'readonly', - 'required' => false, - 'note' => Mage::helper('googleoptimizer')->__('Please copy and paste this value to experiment edit form.') - ) - ); - } - - $fieldset->addField('export_controls', 'text', array('name' => 'export_controls')); - - $fieldset->addField('control_script', 'textarea', - array( - 'name' => 'control_script', - 'label' => Mage::helper('googleoptimizer')->__('Control Script'), - 'class' => 'textarea googleoptimizer validate-googleoptimizer', - 'required' => false, - ) - ); - $fieldset->addField('tracking_script', 'textarea', - array( - 'name' => 'tracking_script', - 'label' => Mage::helper('googleoptimizer')->__('Tracking Script'), - 'class' => 'textarea googleoptimizer validate-googleoptimizer', - 'required' => false, - ) - ); - $fieldset->addField('conversion_script', 'textarea', - array( - 'name' => 'conversion_script', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Script'), - 'class' => 'textarea googleoptimizer validate-googleoptimizer', - 'required' => false, - ) - ); - - $attributes = Mage::helper('googleoptimizer')->getProductAttributes($this->getProduct()); - $fieldset->addField('attributes', 'multiselect', - array( - 'name' => 'attributes', - 'label' => Mage::helper('googleoptimizer')->__('Attributes'), - 'class' => 'googleoptimizer validate-googleoptimizer validate-googleoptimizer-attributes', - 'values' => $attributes, - 'required' => false, - 'onchange' => 'googleOptimizerAttributesCheckAction(this)', - 'note' => Mage::helper('googleoptimizer')->__('The limit is 8 attributes only.') - ) - ); - - if (Mage::helper('googleoptimizer')->getConversionPagesUrl() - && $this->getGoogleOptimizer() - && $this->getGoogleOptimizer()->getConversionPage()) - { - $form->getElement('conversion_page_url') - ->setValue(Mage::helper('googleoptimizer') - ->getConversionPagesUrl()->getData($this->getGoogleOptimizer()->getConversionPage()) - ); - } - - if ($disabledScriptsFields) { - foreach ($fieldset->getElements() as $element) { - if ($element->getType() == 'textarea' || $element->getType() == 'select') { - $element->setDisabled($disabledScriptsFields); - } - } - $form->getElement('export_controls')->setDisabled($disabledScriptsFields); - } - - $fakeEntityAttribute = Mage::getModel('catalog/resource_eav_attribute'); - - foreach ($fieldset->getElements() as $element) { - if ($element->getId() != 'store_flag') { - $element->setEntityAttribute($fakeEntityAttribute); - } - } - - $form->getElement('export_controls')->setRenderer( - $this->getLayout()->createBlock('adminhtml/catalog_form_renderer_googleoptimizer_import') - ); - - $form->addValues($values); - $form->setFieldNameSuffix('googleoptimizer'); - $this->setForm($form); - - return parent::_prepareForm(); - } - - public function getProduct() - { - return Mage::registry('product'); - } - - public function getGoogleOptimizer() - { - return $this->getProduct()->getGoogleOptimizerScripts(); - } - - public function getTabLabel() - { - return Mage::helper('googleoptimizer')->__('Product View Optimization'); - } - - public function getTabTitle() - { - return Mage::helper('googleoptimizer')->__('Product View Optimization'); - } - - public function canShowTab() - { - if (Mage::helper('googleoptimizer')->isOptimizerActive($this->getProduct()->getStoreId()) - && $this->getProduct()->getAttributeSetId()) - { - return true; - } - return false; - } - - public function isHidden() - { - return false; - } - -} diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Cms/Page/Edit/Enable.php b/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Cms/Page/Edit/Enable.php deleted file mode 100644 index 2d91fbe7c8..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Cms/Page/Edit/Enable.php +++ /dev/null @@ -1,80 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Block_Adminhtml_Cms_Page_Edit_Enable extends Mage_Adminhtml_Block_Template -{ - /** - * Utility method to call method of specified block - * in case google optimizer enabled for cms in the system. - * Uses as parameters block name, method name and params for method. - * - * @param string $name - * @param string $method - * @param array $params - * @return Mage_GoogleOptimizer_Block_Adminhtml_Cms_Page_Edit_Enable - */ - public function ifGoogleOptimizerEnabled($name, $method, $params = array()) - { - if (Mage::helper('googleoptimizer')->isOptimizerActiveForCms()) { - $block = $this->getLayout()->getBlock($name); - if ($block) { - call_user_func_array(array($block, $method), $params); - } - } - - return $this; - } - - /** - * in case google optimizer enabled for cms in the system. - * Uses as parameters container name, block name, type and attributes - * - * @param string $container - * @param string $name - * @param string $type - * @param string $attributes - * @return Mage_GoogleOptimizer_Block_Adminhtml_Cms_Page_Edit_Enable - */ - public function ifGoogleOptimizerEnabledAppend($container, $name, $type, $attributes = array()) - { - if (Mage::helper('googleoptimizer')->isOptimizerActiveForCms()) { - $containerBlock = $this->getLayout()->getBlock($container); - if ($containerBlock) { - $block = $this->getLayout()->createBlock($type, $name, $attributes); - $containerBlock->append($block); - } - } - - return $this; - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Cms/Page/Edit/Renderer/Conversion.php b/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Cms/Page/Edit/Renderer/Conversion.php deleted file mode 100644 index ad67363f26..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Cms/Page/Edit/Renderer/Conversion.php +++ /dev/null @@ -1,78 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Block_Adminhtml_Cms_Page_Edit_Renderer_Conversion extends Mage_Adminhtml_Block_Widget_Form_Renderer_Fieldset_Element -{ - public function __construct() - { - $this->setTemplate('googleoptimizer/cms/edit/renderer/conversion.phtml'); - } - - public function render(Varien_Data_Form_Element_Abstract $element) - { - $this->_element = $element; - return $this->toHtml(); - } - - public function getElement() - { - return $this->_element; - } - - public function getStoreViews() - { - $storeViews = Mage::app()->getStores(); - return $storeViews; - } - - public function getJsonStoreViews() - { - $storeViews = array(); - foreach ($this->getStoreViews() as $_store) { - $storeViews[] = $_store->getCode(); - } - $storeViews = new Varien_Object($storeViews); - return $storeViews->toJson(); - } - - public function getJsonConversionPagesUrl() - { - $storeViewsUrls = array(); - foreach ($this->getStoreViews() as $_store) { - Mage::helper('googleoptimizer')->setStoreId($_store->getId()); - $storeViewsUrls[$_store->getCode()] = Mage::helper('googleoptimizer')->getConversionPagesUrl()->getData(); - } - $storeViewsUrls = new Varien_Object($storeViewsUrls); - return $storeViewsUrls->toJson(); - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Cms/Page/Edit/Tab/Googleoptimizer.php b/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Cms/Page/Edit/Tab/Googleoptimizer.php deleted file mode 100644 index 3243e9ddbc..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Block/Adminhtml/Cms/Page/Edit/Tab/Googleoptimizer.php +++ /dev/null @@ -1,247 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Block_Adminhtml_Cms_Page_Edit_Tab_Googleoptimizer - extends Mage_Adminhtml_Block_Widget_Form - implements Mage_Adminhtml_Block_Widget_Tab_Interface -{ - protected function _prepareForm() - { - $form = new Varien_Data_Form(); - - $fieldset = $form->addFieldset('googleoptimizer_fields', - array('legend'=>Mage::helper('googleoptimizer')->__('Google Optimizer Scripts')) - ); - - Mage::helper('googleoptimizer')->setStoreId(Mage::app()->getDefaultStoreView()); - - /* - * Checking if user have permissions to save information - */ - if ($this->_isAllowedAction('save')) { - $isElementDisabled = false; - } else { - $isElementDisabled = true; - } - - $fieldset->addField('conversion_page', 'select', - array( - 'name' => 'conversion_page', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Page'), - 'values'=> Mage::getModel('googleoptimizer/adminhtml_system_config_source_googleoptimizer_conversionpages')->toOptionArray(), - 'class' => 'select googleoptimizer validate-googleoptimizer', - 'required' => false, - 'onchange' => 'googleOptimizerConversionPageAction(this)', - 'disabled' => $isElementDisabled - ) - ); - - if (!Mage::app()->isSingleStoreMode()) { - $form->getElement('conversion_page')->setOnchange('googleOptimizerConversionCmsPageAction(this)'); - $fieldset->addField('conversion_page_url', 'note', - array( - 'name' => 'conversion_page_url', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Page URL'), - 'disabled' => $isElementDisabled - ) - )->setRenderer($this->getLayout()->createBlock('googleoptimizer/adminhtml_cms_page_edit_renderer_conversion')); - } else { - $fieldset->addField('conversion_page_url', 'text', - array( - 'name' => 'conversion_page_url', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Page URL'), - 'class' => 'input-text', - 'readonly' => 'readonly', - 'required' => false, - 'note' => Mage::helper('googleoptimizer')->__('Please copy and paste this value to experiment edit form.'), - 'disabled' => $isElementDisabled - ) - ); - } - - $fieldset->addField('export_controls', 'text', - array( - 'name' => 'export_controls', - 'disabled' => $isElementDisabled - ) - ); - - $pageTypes = array( - '' => Mage::helper('googleoptimizer')->__('-- Please Select --'), - 'original' => Mage::helper('googleoptimizer')->__('Original Page'), - 'variant' => Mage::helper('googleoptimizer')->__('Variant Page') - ); - - $fieldset->addField('page_type', 'select', - array( - 'name' => 'page_type', - 'label' => Mage::helper('googleoptimizer')->__('Page Type'), - 'values'=> $pageTypes, - 'class' => 'select googleoptimizer validate-googleoptimizer', - 'required' => false, - 'onchange' => 'googleOptimizerVariantPageAction(this)', - 'disabled' => $isElementDisabled - ) - ); - - $fieldset->addField('control_script', 'textarea', - array( - 'name' => 'control_script', - 'label' => Mage::helper('googleoptimizer')->__('Control Script'), - 'class' => 'textarea validate-googleoptimizer', - 'required' => false, - 'note' => '', - 'disabled' => $isElementDisabled - ) - ); - $fieldset->addField('tracking_script', 'textarea', - array( - 'name' => 'tracking_script', - 'label' => Mage::helper('googleoptimizer')->__('Tracking Script'), - 'class' => 'textarea validate-googleoptimizer', - 'required' => false, - 'note' => '', - 'disabled' => $isElementDisabled - ) - ); - $fieldset->addField('conversion_script', 'textarea', - array( - 'name' => 'conversion_script', - 'label' => Mage::helper('googleoptimizer')->__('Conversion Script'), - 'class' => 'textarea validate-googleoptimizer', - 'required' => false, - 'note' => '', - 'disabled' => $isElementDisabled - ) - ); - - if (Mage::helper('googleoptimizer')->getConversionPagesUrl() - && $this->getGoogleOptimizer() - && $this->getGoogleOptimizer()->getConversionPage()) - { - $form->getElement('conversion_page_url') - ->setValue(Mage::helper('googleoptimizer') - ->getConversionPagesUrl()->getData($this->getGoogleOptimizer()->getConversionPage()) - ); - } - - $renderer = $this->getLayout()->createBlock('adminhtml/catalog_form_renderer_googleoptimizer_import'); - $form->getElement('export_controls')->setRenderer($renderer); - - $values = array(); - if ($this->getGoogleOptimizer() && $this->getGoogleOptimizer()->getData()) { - $values = $this->getGoogleOptimizer()->getData(); - $fieldset->addField('code_id', 'hidden', array('name' => 'code_id')); - if ($this->getGoogleOptimizer()->getData('page_type') == Mage_GoogleOptimizer_Model_Code_Page::PAGE_TYPE_VARIANT) { - foreach ($fieldset->getElements() as $element) { - if (($element->getId() != 'tracking_script' && $element->getId() != 'page_type') - && ($element->getType() == 'textarea' || $element->getType() == 'select')) - { - $element->setDisabled(true); - } - } - } - } - - $form->addValues($values); - $form->setFieldNameSuffix('googleoptimizer'); - $this->setForm($form); - - return parent::_prepareForm(); - } - - public function getCmsPage() - { - return Mage::registry('cms_page'); - } - - public function getGoogleOptimizer() - { - if ($this->getCmsPage()->getGoogleoptimizer()) {//if data was set from session after exception - $googleOptimizer = new Varien_Object($this->getCmsPage()->getGoogleoptimizer()); - } else { - $googleOptimizer = $this->getCmsPage()->getGoogleOptimizerScripts(); - } - return $googleOptimizer; - } - - /** - * Prepare label for tab - * - * @return string - */ - public function getTabLabel() - { - return Mage::helper('googleoptimizer')->__('Page View Optimization'); - } - - /** - * Prepare title for tab - * - * @return string - */ - public function getTabTitle() - { - return Mage::helper('googleoptimizer')->__('Page View Optimization'); - } - - /** - * 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 true - */ - public function isHidden() - { - return false; - } - - /** Check permission for passed action - * - * @param string $action - * @return bool - */ - protected function _isAllowedAction($action) - { - return Mage::getSingleton('admin/session')->isAllowed('cms/page/' . $action); - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Code.php b/app/code/core/Mage/GoogleOptimizer/Block/Code.php deleted file mode 100644 index 956e05c02a..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Block/Code.php +++ /dev/null @@ -1,111 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Block_Code extends Mage_Core_Block_Template -{ - protected $_scriptType = null; - protected $_googleOptmizerModel = null; - protected $_avaibleScriptTypes = array('control_script', 'tracking_script', 'conversion_script'); - - /** - * override this method if need something special for type of script - * - * @return Mage_GoogleOptimizer_Block_Code - */ - protected function _initGoogleOptimizerModel() - { - return $this; - } - - /** - * Setting google optimizer model - * - * @param Varien_Object $model - * @return Mage_GoogleOptimizer_Block_Code - */ - protected function _setGoogleOptimizerModel($model) - { - $this->_googleOptmizerModel = $model; - return $this; - } - - /** - * Return google optimizer model - * - * @return Varien_Object - */ - protected function _getGoogleOptimizerModel() - { - return $this->_googleOptmizerModel; - } - - protected function _toHtml() - { - return parent::_toHtml() . $this->getScriptCode(); - } - - /** - * Return script by type $this->_scriptType - * - * @return string - */ - public function getScriptCode() - { - if (!Mage::helper('googleoptimizer')->isOptimizerActive()) { - return ''; - } - if (is_null($this->_scriptType)) { - return ''; - } - $this->_initGoogleOptimizerModel(); - if (!($this->_getGoogleOptimizerModel() instanceof Varien_Object)) { - return ''; - } - return $this->_getGoogleOptimizerModel()->getData($this->_scriptType); - } - - /** - * Check than set script type - * - * @param string $scriptType - * @return Mage_GoogleOptimizer_Block_Code - */ - public function setScriptType($scriptType) - { - if (in_array($scriptType, $this->_avaibleScriptTypes)) { - $this->_scriptType = $scriptType; - } - return $this; - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Code/Conversion.php b/app/code/core/Mage/GoogleOptimizer/Block/Code/Conversion.php deleted file mode 100644 index 062b6638f5..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Block/Code/Conversion.php +++ /dev/null @@ -1,71 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Block_Code_Conversion extends Mage_GoogleOptimizer_Block_Code -{ - protected $_pageType = null; - - protected function _initGoogleOptimizerModel() - { - $collection = Mage::getModel('googleoptimizer/code') - ->getCollection(); - - if ($this->getPageType()) { - $collection->addFieldToFilter('conversion_page', $this->getPageType()); - } - - $conversionCodes = array(); - foreach ($collection as $_item) { - $conversionCodes[] = $_item->getConversionScript(); - } - $this->_setGoogleOptimizerModel( - new Varien_Object(array( - 'conversion_script' => implode('', $conversionCodes) - )) - ); - return parent::_initGoogleOptimizerModel(); - } - - public function setPageType($pageType) - { - $this->_pageType = $pageType; - return $this; - } - - public function getPageType() - { - return $this->_pageType; - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Js.php b/app/code/core/Mage/GoogleOptimizer/Block/Js.php deleted file mode 100644 index 1bc465b35f..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Block/Js.php +++ /dev/null @@ -1,65 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Block_Js extends Mage_Adminhtml_Block_Template -{ - public function getJsonConversionPagesUrl() - { - return Mage::helper('googleoptimizer')->getConversionPagesUrl()->toJson(); - } - - public function getMaxCountOfAttributes() - { - return Mage_GoogleOptimizer_Model_Code_Product::DEFAULT_COUNT_OF_ATTRIBUTES; - } - - public function getExportUrl() - { - return $this->getUrl('*/googleoptimizer_index/codes'); - } - - public function getControlFieldKey () - { - return $this->getDataSetDefault('control_field_key', 'control_script'); - } - - public function getTrackingFieldKey () - { - return $this->getDataSetDefault('tracking_field_key', 'tracking_script'); - } - - public function getConversionFieldKey () - { - return $this->getDataSetDefault('conversion_field_key', 'conversion_script'); - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/Helper/Data.php b/app/code/core/Mage/GoogleOptimizer/Helper/Data.php deleted file mode 100644 index fb09056717..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Helper/Data.php +++ /dev/null @@ -1,237 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Helper_Data extends Mage_Core_Helper_Abstract -{ - const XML_PATH_ENABLED = 'google/optimizer/active'; - const XML_PATH_ALLOWED_ATTRIBUTES = 'admin/attributes'; - - const MAX_ATTRIBUTE_LENGTH_LIMIT = 25; - - protected $_storeId = null; - - protected $_activeForCmsFlag = null; - - public function setStoreId($storeId) - { - $this->_storeId = $storeId; - return $this; - } - - public function getStoreId() - { - return $this->_storeId; - } - - public function isOptimizerActive($store = null) - { - return Mage::getStoreConfig(self::XML_PATH_ENABLED, $store); - } - - /** - * Return is active google optimizer for cms. - * Return true if optimizer is enabled only for one store|website. - * - * @return boolean - */ - public function isOptimizerActiveForCms() - { - if (!is_null($this->_activeForCmsFlag)) { - return $this->_activeForCmsFlag; - } - $stores = array_merge( - array(0), - array_keys(Mage::getSingleton('adminhtml/system_store')->getStoreCollection()) - ); - foreach ($stores as $store) { - if ($this->isOptimizerActive($store)) { - $this->_activeForCmsFlag = true; - return $this->_activeForCmsFlag; - } - } - $this->_activeForCmsFlag = false; - return $this->_activeForCmsFlag; - } - - /** - * Prepare product attribute html output - * - * @param unknown_type $callObject - * @param unknown_type $attributeHtml - * @param unknown_type $params - * @return unknown - */ - public function productAttribute($callObject, $attributeHtml, $params) - { - $attributeName = $params['attribute']; - $product = $params['product']; - - if (!$this->isOptimizerActive($product->getStoreId()) - || !$product->getGoogleOptimizerScripts() - || !$product->getGoogleOptimizerScripts()->getControlScript()) { - return $attributeHtml; - } - if (in_array($attributeName, $product->getGoogleOptimizerScripts()->getAttributes())) { - $newAttributeName = 'product_'.$attributeName.'_'.$product->getId(); - if (strlen($newAttributeName) > self::MAX_ATTRIBUTE_LENGTH_LIMIT) { - $newAttributeName = 'product_'; - $newAttributeName .= substr($attributeName, 0, (self::MAX_ATTRIBUTE_LENGTH_LIMIT - strlen('product__'.$product->getId()))); - $newAttributeName .= '_'.$product->getId(); - } - $attributeHtml = '' . $attributeHtml . ''; - } - return $attributeHtml; - } - - /** - * Prepare category attribute html output - * - * @param unknown_type $callObject - * @param unknown_type $attributeHtml - * @param unknown_type $params - * @return unknown - */ - public function categoryAttribute($callObject, $attributeHtml, $params) - { - $attributeName = $params['attribute']; - $category = $params['category']; - - if (!$this->isOptimizerActive($category->getStoreId()) - || !$category->getGoogleOptimizerScripts() - || !$category->getGoogleOptimizerScripts()->getControlScript()) { - return $attributeHtml; - } - - $newAttributeName = 'category_'.$attributeName.'_'.$category->getId(); - if (strlen($newAttributeName) > self::MAX_ATTRIBUTE_LENGTH_LIMIT) { - $newAttributeName = 'category_'; - $newAttributeName .= substr($attributeName, 0, (self::MAX_ATTRIBUTE_LENGTH_LIMIT - strlen('category__' . $category->getId()))); - $newAttributeName .= '_' . $category->getId(); - } - - $attributeHtml = '' . $attributeHtml . ''; - return $attributeHtml; - } - - /** - * Return conversion pages from source model - * - * @return Varien_Object - */ - public function getConversionPagesUrl() - { - /** - * Example: - * - * array( - * 'checkout_cart' => 'http://base.url/...' - * ) - */ - $urls = array(); - $choices = Mage::getModel('googleoptimizer/adminhtml_system_config_source_googleoptimizer_conversionpages') - ->toOptionArray(); - $url = Mage::getModel('core/url'); - $session = Mage::getSingleton('core/session')->setSkipSessionIdFlag(true); - $store = Mage::app()->getStore($this->getStoreId()); - foreach ($choices as $choice) { - $route = ''; - switch ($choice['value']) { - case 'checkout_cart': - $route = 'checkout/cart'; - break; - case 'checkout_onepage': - $route = 'checkout/onepage'; - break; - case 'checkout_multishipping': - $route = 'checkout/multishipping'; - break; - case 'checkout_onepage_success': - $route = 'checkout/onepage/success/'; - break; - case 'checkout_multishipping_success': - $route = 'checkout/multishipping/success/'; - break; - case 'customer_account_create': - $route = 'customer/account/create/'; - break; - } - if ($route) { - $_query = array(); - $_path = Mage_Core_Model_Url::XML_PATH_UNSECURE_URL; - if (Mage::getConfig()->shouldUrlBeSecure('/' . $route)) { - $_path = Mage_Core_Model_Url::XML_PATH_SECURE_URL; - } - $storeBaseUrl = $store->getConfig($_path); - $websiteBaseUrl = $store->getWebsite()->getConfig($_path); - $defaultBaseUrl = Mage::app()->getStore(0)->getConfig($_path); - if ($storeBaseUrl == $websiteBaseUrl && !Mage::app()->isSingleStoreMode()) { - $_query = array('__store' => $store->getCode()); - } - $urls[$choice['value']] = $url->setStore($this->getStoreId())->getUrl($route, - array('_secure' => true, '_query' => $_query) - ); - } - } - $session->setSkipSessionIdFlag(false); - return new Varien_Object($urls); - } - - /** - * Create array of attributes for variation - * allowed by googleoptimizer config and user defined attributes - * - * @param Mage_Catalog_Model_Product $product - * @return array - */ - public function getProductAttributes(Varien_Object $product) - { - /** @var $product Mage_Catalog_Model_Product */ - $allowedAttributes = array_keys(Mage::getConfig()->getNode(self::XML_PATH_ALLOWED_ATTRIBUTES)->asArray()); - $productAttributes = $product->getAttributes(); - $optimizerAttributes = array(); - foreach ($productAttributes as $_attributeCode => $_attribute) { - if ($_attribute->getIsUserDefined() && $_attribute->getIsVisibleOnFront()) { - $optimizerAttributes[] = array( - 'label' => $_attribute->getFrontendLabel(), - 'value' => $_attributeCode - ); - } elseif (in_array($_attributeCode, $allowedAttributes)) { - $optimizerAttributes[] = array( - 'label' => $_attribute->getFrontendLabel(), - 'value' => $_attributeCode - ); - } - } - return $optimizerAttributes; - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Adminhtml/System/Config/Source/Googleoptimizer/Conversionpages.php b/app/code/core/Mage/GoogleOptimizer/Model/Adminhtml/System/Config/Source/Googleoptimizer/Conversionpages.php deleted file mode 100644 index dfa4e62616..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Model/Adminhtml/System/Config/Source/Googleoptimizer/Conversionpages.php +++ /dev/null @@ -1,52 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Model_Adminhtml_System_Config_Source_Googleoptimizer_Conversionpages -{ - - public function toOptionArray() - { - return array( - array('value' => '', 'label' => Mage::helper('googleoptimizer')->__('-- Please Select --')), - array('value' => 'other', 'label' => Mage::helper('googleoptimizer')->__('Other')), - array('value' => 'checkout_cart', 'label' => Mage::helper('googleoptimizer')->__('Shopping Cart')), - array('value' => 'checkout_onepage', 'label' => Mage::helper('googleoptimizer')->__('One Page Checkout')), - array('value' => 'checkout_multishipping', 'label' => Mage::helper('googleoptimizer')->__('Multi Address Checkout')), - array('value' => 'checkout_onepage_success', 'label' => Mage::helper('googleoptimizer')->__('Order Success (One Page Checkout)')), - array('value' => 'checkout_multishipping_success', 'label' => Mage::helper('googleoptimizer')->__('Order Success (Multi Address Checkout)')), - array('value' => 'customer_account_create', 'label' => Mage::helper('googleoptimizer')->__('Account Registration')), - ); - } - -} diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Code.php b/app/code/core/Mage/GoogleOptimizer/Model/Code.php deleted file mode 100644 index a00c09cc55..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Model/Code.php +++ /dev/null @@ -1,200 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Model_Code extends Mage_Core_Model_Abstract -{ - protected $_entity = null; - protected $_entityType = null; - protected $_validateEntryFlag = false; - protected $_scriptTypes = array('control', 'tracking', 'conversion'); - - protected function _construct() - { - parent::_construct(); - $this->_init('googleoptimizer/code'); - } - - /** - * Set entity - * - * @param Varien_Object $entity - * @return Mage_GoogleOptimizer_Model_Code - */ - public function setEntity(Varien_Object $entity) - { - $this->_entity = $entity; - return $this; - } - - /** - * Return entity - * - * @return unknown - */ - public function getEntity() - { - return $this->_entity; - } - - /** - * Return entity type (product|category|...etc) - * - * @return string - */ - public function getEntityType() - { - return $this->_entityType; - } - - /** - * Loading scripts and assigning scripts on entity - * - * @param Varien_Object $entity - * @return Mage_GoogleOptimizer_Model_Code - */ - public function loadScripts($storeId) - { - if (is_null($this->getEntity()) || is_null($this->getEntityType())) { - return $this; - } - - if (!$storeId) { - $storeId = Mage::app()->getStore()->getId(); - } - - $this->getResource()->loadByEntityType($this, $storeId); - $this->_afterLoad(); - return $this; - } - - /** - * Validate sctipts that assigned on entity - * - * @return bool - */ - protected function _validate() - { - $entryFlag = false; - $validationResult = false; - if ($control = $this->getControlScript()) { - $entryFlag = true; - } - if ($tracking = $this->getTrackingScript()) { - $entryFlag = true; - } - if ($conversion = $this->getConversionScript()) { - $entryFlag = true; - } - if ($conversionPage = $this->getConversionPage()) { - $entryFlag = true; - } - $this->_validateEntryFlag = $entryFlag; - if ($entryFlag && (!$control || !$tracking || !$conversion || !$conversionPage)) { - return false; - } - return true; - } - - /** - * Save scripts assigned on entity - * - * @param Varien_Object $entity - * @return Mage_GoogleOptimizer_Model_Code - */ - public function saveScripts($storeId) - { - if (is_null($this->getEntity()) || is_null($this->getEntityType())) { - return $this; - } - if (!$this->getEntity()->getGoogleOptimizerScripts()) { - return $this; - } - $script = $this->getEntity()->getGoogleOptimizerScripts(); - - $this->setData($script->getData()) - ->setEntityId($this->getEntity()->getId()) - ->setEntityType($this->getEntityType()); - - /** - * We can't modify store id if existing stcript - */ - if (!$script->getId()) { - $this->setStoreId($storeId); - } - - if (false === $this->_validate()) { - throw new Exception(Mage::helper('googleoptimizer')->__('All fields of script types have to be filled.')); - } - - // use default scripts, need to delete scripts for current store - if ($this->getStoreFlag()) { - $this->deleteScripts($storeId); - return $this; - } - - $this->save(); - return $this; - } - - /** - * Removing scripts assigned to entity - * - * @param integer $storeId - * @return Mage_GoogleOptimizer_Model_Code - */ - public function deleteScripts($storeId) - { - if (is_null($this->getEntity()) || is_null($this->getEntityType())) { - return $this; - } - $this->getResource()->deleteByEntityType($this, $storeId); - return $this; - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Code/Page.php b/app/code/core/Mage/GoogleOptimizer/Model/Code/Page.php deleted file mode 100644 index a9a1da973f..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Model/Code/Page.php +++ /dev/null @@ -1,71 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Model_Code_Page extends Mage_GoogleOptimizer_Model_Code -{ - const PAGE_TYPE_VARIANT = 'variant'; - protected $_entityType = 'page'; - - protected function _afterLoad() - { - if ($data = $this->getAdditionalData()) { - $data = unserialize($data); - if (isset($data['page_type'])) { - $this->setPageType($data['page_type']); - } - } - return parent::_afterLoad(); - } - - protected function _beforeSave() - { - - if ($pageType = $this->getData('page_type')) { - $this->setData('additional_data', serialize(array( - 'page_type' => $pageType)) - ); - } - parent::_beforeSave(); - } - - protected function _validate() - { - if ($this->getPageType() && $this->getPageType() == self::PAGE_TYPE_VARIANT) { - if ($this->getTrackingScript()) { - return true; - } - } - return parent::_validate(); - } - -} diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Code/Product.php b/app/code/core/Mage/GoogleOptimizer/Model/Code/Product.php deleted file mode 100644 index 05b5b67278..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Model/Code/Product.php +++ /dev/null @@ -1,100 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Model_Code_Product extends Mage_GoogleOptimizer_Model_Code -{ - const DEFAULT_COUNT_OF_ATTRIBUTES = 8; - protected $_entityType = 'product'; - - protected function _afterLoad() - { - if ($data = $this->getAdditionalData()) { - $data = unserialize($data); - if (isset($data['attributes'])) { - $this->setAttributes($data['attributes']); - } - } - return parent::_afterLoad(); - } - - protected function _beforeSave() - { - if (!($attributes = $this->getData('attributes'))) { - $attributes = array(); - } - $this->setData('additional_data', serialize(array( - 'attributes' => $attributes)) - ); - parent::_beforeSave(); - } - - protected function _validate() - { - $_validationResult = parent::_validate(); - if (!$_validationResult) { - return false; - } - $attributesFlag = false; - if ($attributes = $this->getAttributes()) { - $attributesCount = 0; - foreach ($attributes as $_attributeId => $_attributeValue) { - if ($_attributeValue != '') { - $attributesCount++; - } - } - if ($attributesCount && $attributesCount <= self::DEFAULT_COUNT_OF_ATTRIBUTES) { - $attributesFlag = true; - } - } - if ($this->_validateEntryFlag && !$attributesFlag) { - return false; - } - if (!$this->_validateEntryFlag && $attributesFlag) { - return false; - } - return true; - } - - /** - * Return empty array if attributes is not defined - * - * @return array - */ - public function getAttributes() - { - if ($attributes = $this->_getData('attributes')) { - return $attributes; - } - return array(); - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Observer.php b/app/code/core/Mage/GoogleOptimizer/Model/Observer.php deleted file mode 100644 index 711407e185..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Model/Observer.php +++ /dev/null @@ -1,284 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Model_Observer -{ - /** - * Loading product scripts after load product - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function appendToProductGoogleOptimizerScripts($observer) - { - $product = $observer->getEvent()->getProduct(); - - if (!Mage::helper('googleoptimizer')->isOptimizerActive($product->getStoreId())) { - return $this; - } - - $googleOptimizerModel = Mage::getModel('googleoptimizer/code_product') - ->setEntity($product) - ->loadScripts($product->getStoreId()); - if ($googleOptimizerModel->getId()) { - $product->setGoogleOptimizerScripts($googleOptimizerModel); - } - return $this; - } - - /** - * @deprecated please use prepareProductGoogleOptimizerScripts method instead - * - * @param Varien_Object $observer - */ - public function prepareGoogleOptimizerScripts($observer) - { - $this->prepareProductGoogleOptimizerScripts($observer); - } - - /** - * Prepare product scripts for saving - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function prepareProductGoogleOptimizerScripts($observer) - { - $product = $observer->getEvent()->getProduct(); - $request = $observer->getEvent()->getRequest(); - - if ($googleOptimizer = $request->getPost('googleoptimizer')) { - $product->setGoogleOptimizerScripts(new Varien_Object($googleOptimizer)); - } - return $this; - } - - /** - * Save product scripts after saving product - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function saveProductGoogleOptimizerScripts($observer) - { - $product = $observer->getEvent()->getProduct(); - - if ($product->getGoogleOptimizerScripts()) { - $googleOptimizer = Mage::getModel('googleoptimizer/code_product') - ->setEntity($product) - ->saveScripts($product->getStoreId()); - } - - return $this; - } - - /** - * Delete Produt scripts after deleting product - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function deleteProductGoogleOptimizerScripts($observer) - { - $product = $observer->getEvent()->getProduct(); - $googleOptimizer = Mage::getModel('googleoptimizer/code_product') - ->setEntity($product) - ->deleteScripts($product->getStoreId()); - return $this; - } - - /** - * Loading page scripts after load page - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function appendToPageGoogleOptimizerScripts($observer) - { - /** - * Check activity for frontend - */ - if (Mage::app()->getStore()->getId() && !Mage::helper('googleoptimizer')->isOptimizerActive()) { - return $this; - } - - $cmsPage = $observer->getEvent()->getObject(); - $googleOptimizerModel = Mage::getModel('googleoptimizer/code_page') - ->setEntity($cmsPage) - ->loadScripts(0); - - if ($googleOptimizerModel->getId()) { - $cmsPage->setGoogleOptimizerScripts($googleOptimizerModel); - } - return $this; - } - - /** - * Prepare page scripts for saving - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function preparePageGoogleOptimizerScripts($observer) - { - $cmsPage = $observer->getEvent()->getPage(); - $request = $observer->getEvent()->getRequest(); - - if ($googleOptimizer = $request->getPost('googleoptimizer')) { - $cmsPage->setGoogleOptimizerScripts(new Varien_Object($googleOptimizer)); - } - return $this; - } - - /** - * Save page scripts after saving page - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function savePageGoogleOptimizerScripts($observer) - { - $cmsPage = $observer->getEvent()->getObject(); - - if ($cmsPage->getGoogleOptimizerScripts()) { - $googleOptimizer = Mage::getModel('googleoptimizer/code_page') - ->setEntity($cmsPage) - ->saveScripts(0); - } - - return $this; - } - - /** - * Delete page scripts after deleting page - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function deletePageGoogleOptimizerScripts($observer) - { - $cmsPage = $observer->getEvent()->getObject(); - $googleOptimizer = Mage::getModel('googleoptimizer/code_page') - ->setEntity($cmsPage) - ->deleteScripts(0); - return $this; - } - - public function assignHandlers($observer) - { - $catalogHalper = $observer->getEvent()->getHelper(); - $helper = Mage::helper('googleoptimizer'); - $catalogHalper->addHandler('productAttribute', $helper) - ->addHandler('categoryAttribute', $helper); - return $this; - } - - /** - * Loading category scripts after load category - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function appendToCategoryGoogleOptimizerScripts($observer) - { - $category = $observer->getEvent()->getCategory(); - - if (!Mage::helper('googleoptimizer')->isOptimizerActive($category->getStoreId())) { - return $this; - } - - $googleOptimizerModel = Mage::getModel('googleoptimizer/code_category') - ->setEntity($category) - ->loadScripts($category->getStoreId()); - if ($googleOptimizerModel->getId()) { - $category->setGoogleOptimizerScripts($googleOptimizerModel); - } - return $this; - } - - /** - * Prepare category scripts for saving - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function prepareCategoryGoogleOptimizerScripts($observer) - { - $category = $observer->getEvent()->getCategory(); - $request = $observer->getEvent()->getRequest(); - - if ($googleOptimizer = $request->getPost('googleoptimizer')) { - $category->setGoogleOptimizerScripts(new Varien_Object($googleOptimizer)); - } - return $this; - } - - /** - * Save category scripts after saving category - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function saveCategoryGoogleOptimizerScripts($observer) - { - $category = $observer->getEvent()->getCategory(); - - if (!Mage::helper('googleoptimizer')->isOptimizerActive($category->getStoreId())) { - return $this; - } - - if ($category->getGoogleOptimizerScripts()) { - $googleOptimizer = Mage::getModel('googleoptimizer/code_category') - ->setEntity($category) - ->saveScripts($category->getStoreId()); - } - - return $this; - } - - /** - * Delete category scripts after deleting category - * - * @param Varien_Object $observer - * @return Mage_GoogleOptimizer_Model_Observer - */ - public function deleteCategoryGoogleOptimizerScripts($observer) - { - $category = $observer->getEvent()->getCategory(); - $googleOptimizer = Mage::getModel('googleoptimizer/code_category') - ->setEntity($category) - ->deleteScripts($category->getStoreId()); - return $this; - } - -} diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Resource/Code.php b/app/code/core/Mage/GoogleOptimizer/Model/Resource/Code.php deleted file mode 100755 index c05886519f..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/Model/Resource/Code.php +++ /dev/null @@ -1,139 +0,0 @@ - - */ -class Mage_GoogleOptimizer_Model_Resource_Code extends Mage_Core_Model_Resource_Db_Abstract -{ - /** - * Resource initialization - * - */ - protected function _construct() - { - $this->_init('googleoptimizer/code', 'code_id'); - } - - /** - * Load scripts by entity and store - * - * @param Mage_GoogleOptimizer_Model_Code $object - * @param integer $storeId - * @return Mage_GoogleOptimizer_Model_Resource_Code - */ - public function loadbyEntityType($object, $storeId) - { - $adapter = $this->_getReadAdapter(); - - $codeIdExpr = $adapter->getCheckSql( - 't_store.code_id IS NOT NULL', - 't_store.code_id', - 't_def.code_id'); - $storeIdExpr = $adapter->getCheckSql( - 't_store.store_id IS NOT NULL', - 't_store.store_id', - 't_def.store_id'); - $controlScriptExpr = $adapter->getCheckSql( - 't_store.control_script IS NOT NULL', - 't_store.control_script', - 't_def.control_script'); - $trackingScriptExpr = $adapter->getCheckSql( - 't_store.tracking_script IS NOT NULL', - 't_store.tracking_script', - 't_def.tracking_script'); - $conversionScriptExpr = $adapter->getCheckSql( - 't_store.conversion_script IS NOT NULL', - 't_store.conversion_script', - 't_def.conversion_script'); - $conversionPageExpr = $adapter->getCheckSql( - 't_store.conversion_page IS NOT NULL', - 't_store.conversion_page', - 't_def.conversion_page'); - $additionalDataExpr = $adapter->getCheckSql( - 't_store.additional_data IS NOT NULL', - 't_store.additional_data', - 't_def.additional_data'); - - $select = $adapter->select() - ->from( - array('t_def' => $this->getMainTable()), - array('entity_id', 'entity_type')) - ->joinLeft( - array('t_store' => $this->getMainTable()), - 't_store.entity_id = t_def.entity_id AND t_store.entity_type = t_def.entity_type AND ' - . $adapter->quoteInto('t_store.store_id = ?', $storeId), - array( - 'code_id' => $codeIdExpr, - 'store_id' => $storeIdExpr, - 'control_script' => $controlScriptExpr, - 'tracking_script' => $trackingScriptExpr, - 'conversion_script' => $conversionScriptExpr, - 'conversion_page' => $conversionPageExpr, - 'additional_data' => $additionalDataExpr)) - ->where('t_def.entity_id=?', $object->getEntity()->getId()) - ->where('t_def.entity_type=?', $object->getEntityType()) - ->where('t_def.store_id IN (0, ?)', $storeId) - ->order('t_def.store_id DESC') - ->limit(1); - $data = $adapter->fetchRow($select); - if ($data) { - $object->setData($data); - } - $this->_afterLoad($object); - return $this; - } - - /** - * Delete scripts by entity and store - * - * @param Mage_GoogleOptimizer_Model_Code $object - * @param integer $store_id - * @return Mage_GoogleOptimizer_Model_Resource_Code - */ - public function deleteByEntityType($object, $store_id) - { - $adapter = $this->_getWriteAdapter(); - - $entityIds = $object->getEntityIds(); - if (!empty($entityIds)) { - $where[$this->getMainTable() . '.entity_id IN (?)'] = $entityIds; - } else { - $where[$this->getMainTable() . '.entity_id=?'] = $object->getEntity()->getId(); - } - $where[$this->getMainTable() . '.entity_type=?'] = $object->getEntityType(); - $where[$this->getMainTable() . '.store_id=?'] = $store_id; - $adapter->delete($this->getMainTable(), $where); - - $this->_afterDelete($object); - return $this; - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/controllers/Adminhtml/Googleoptimizer/IndexController.php b/app/code/core/Mage/GoogleOptimizer/controllers/Adminhtml/Googleoptimizer/IndexController.php deleted file mode 100755 index 131607f4f0..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/controllers/Adminhtml/Googleoptimizer/IndexController.php +++ /dev/null @@ -1,57 +0,0 @@ - -*/ -class Mage_GoogleOptimizer_Adminhtml_Googleoptimizer_IndexController extends Mage_Adminhtml_Controller_Action -{ - /** - * Retrieve js scripts by parsing remote Google Optimizer page - */ - public function codesAction() - { - if ($this->getRequest()->getQuery('url')) { - $client = new Varien_Http_Client($this->getRequest()->getQuery('url')); - $response = $client->request(Varien_Http_Client::GET); - $result = array(); - if (preg_match_all('/]*id="([_a-zA-Z0-9]+)"[^>]*>([^<]+)<\/textarea>/', $response->getRawBody(), $matches)) { - $c = count($matches[1]); - for ($i = 0; $i < $c; $i++) { - $id = $matches[1][$i]; - $code = $matches[2][$i]; - $result[$id] = $code; - } - } - $this->getResponse()->setBody( Mage::helper('core')->jsonEncode($result) ); - } - } -} diff --git a/app/code/core/Mage/GoogleOptimizer/etc/config.xml b/app/code/core/Mage/GoogleOptimizer/etc/config.xml deleted file mode 100644 index 9fd6db9066..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/etc/config.xml +++ /dev/null @@ -1,262 +0,0 @@ - - - - - - 1.6.0.0 - - - - - - Mage_GoogleOptimizer_Model - googleoptimizer_resource - - - Mage_GoogleOptimizer_Model_Resource - googleoptimizer_mysql4 - - - googleoptimizer_code
-
-
-
-
- - - Mage_GoogleOptimizer_Helper - - - - - - Mage_GoogleOptimizer - - - - - - Mage_GoogleOptimizer_Block - - - - - - - googleoptimizer/observer - appendToPageGoogleOptimizerScripts - - - - -
- - - - - - - - - - - - Mage_GoogleOptimizer_Adminhtml - - - - - - - - - - - Mage_GoogleOptimizer.csv - - - - - - - - googleoptimizer.xml - - - - - - - - googleoptimizer/observer - appendToProductGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - appendToCategoryGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - assignHandlers - - - - - - - - - - - Mage_GoogleOptimizer.csv - - - - - - - - - googleoptimizer/observer - appendToProductGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - prepareProductGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - saveProductGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - deleteProductGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - appendToCategoryGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - prepareCategoryGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - saveCategoryGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - deleteCategoryGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - appendToPageGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - preparePageGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - savePageGoogleOptimizerScripts - - - - - - - googleoptimizer/observer - deletePageGoogleOptimizerScripts - - - - - - - - googleoptimizer.xml - - - - - - - - 0 - - - -
diff --git a/app/code/core/Mage/GoogleOptimizer/etc/system.xml b/app/code/core/Mage/GoogleOptimizer/etc/system.xml deleted file mode 100644 index 6912c44e36..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/etc/system.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - text - 20 - 1 - 1 - 1 - - - - select - adminhtml/system_config_source_yesno - 10 - 1 - 1 - 1 - - - - - - - diff --git a/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/install-1.6.0.0.php b/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/install-1.6.0.0.php deleted file mode 100644 index 39133c5a57..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/install-1.6.0.0.php +++ /dev/null @@ -1,78 +0,0 @@ - - */ -$installer = $this; -/* @var $installer Mage_Core_Model_Resource_Setup */ - -$installer->startSetup(); - -/** - * Create table 'googleoptimizer/code' - */ -$table = $installer->getConnection() - ->newTable($installer->getTable('googleoptimizer/code')) - ->addColumn('code_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array( - 'identity' => true, - 'unsigned' => true, - 'nullable' => false, - 'primary' => true, - ), 'Google optimizer code id') - ->addColumn('entity_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array( - 'unsigned' => true, - 'nullable' => false, - ), 'Optimized entity id product id or catalog id') - ->addColumn('entity_type', Varien_Db_Ddl_Table::TYPE_TEXT, 50, array( - ), 'Optimized entity type') - ->addColumn('store_id', Varien_Db_Ddl_Table::TYPE_SMALLINT, null, array( - 'unsigned' => true, - 'nullable' => false, - ), 'Store id') - ->addColumn('control_script', Varien_Db_Ddl_Table::TYPE_TEXT, '64k', array( - ), 'Google optimizer control script') - ->addColumn('tracking_script', Varien_Db_Ddl_Table::TYPE_TEXT, '64k', array( - ), 'Google optimizer tracking script') - ->addColumn('conversion_script', Varien_Db_Ddl_Table::TYPE_TEXT, '64k', array( - ), 'Google optimizer conversion script') - ->addColumn('conversion_page', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array( - ), 'Google optimizer conversion page') - ->addColumn('additional_data', Varien_Db_Ddl_Table::TYPE_TEXT, '64k', array( - ), 'Google optimizer additional data') - ->addIndex($installer->getIdxName('googleoptimizer/code', array('store_id')), - array('store_id')) - ->addForeignKey($installer->getFkName('googleoptimizer/code', 'store_id', 'core/store', 'store_id'), - 'store_id', $installer->getTable('core/store'), 'store_id', - Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE) - ->setComment('Googleoptimizer code'); -$installer->getConnection()->createTable($table); - -$installer->endSetup(); diff --git a/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/mysql4-upgrade-1.5.9.9-1.6.0.0.php b/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/mysql4-upgrade-1.5.9.9-1.6.0.0.php deleted file mode 100644 index 7eedc97647..0000000000 --- a/app/code/core/Mage/GoogleOptimizer/sql/googleoptimizer_setup/mysql4-upgrade-1.5.9.9-1.6.0.0.php +++ /dev/null @@ -1,134 +0,0 @@ -startSetup(); - -/** - * Drop foreign keys - */ -$installer->getConnection()->dropForeignKey( - $installer->getTable('googleoptimizer/code'), - 'FK_GOOGLEOPTIMIZER_CODE_STORE' -); - - -/** - * Drop indexes - */ -$installer->getConnection()->dropIndex( - $installer->getTable('googleoptimizer/code'), - 'GOOGLEOPTIMIZER_CODE_STORE' -); - - -/** - * Change columns - */ -$tables = array( - $installer->getTable('googleoptimizer/code') => array( - 'columns' => array( - 'code_id' => array( - 'type' => Varien_Db_Ddl_Table::TYPE_INTEGER, - 'identity' => true, - 'unsigned' => true, - 'nullable' => false, - 'primary' => true, - 'comment' => 'Google optimizer code id' - ), - 'entity_id' => array( - 'type' => Varien_Db_Ddl_Table::TYPE_INTEGER, - 'unsigned' => true, - 'nullable' => false, - 'comment' => 'Optimized entity id product id or catalog id' - ), - 'entity_type' => array( - 'type' => Varien_Db_Ddl_Table::TYPE_TEXT, - 'length' => 50, - 'comment' => 'Optimized entity type' - ), - 'store_id' => array( - 'type' => Varien_Db_Ddl_Table::TYPE_SMALLINT, - 'unsigned' => true, - 'nullable' => false, - 'comment' => 'Store id' - ), - 'control_script' => array( - 'type' => Varien_Db_Ddl_Table::TYPE_TEXT, - 'length' => '64K', - 'comment' => 'Google optimizer control script' - ), - 'tracking_script' => array( - 'type' => Varien_Db_Ddl_Table::TYPE_TEXT, - 'length' => '64K', - 'comment' => 'Google optimizer tracking script' - ), - 'conversion_script' => array( - 'type' => Varien_Db_Ddl_Table::TYPE_TEXT, - 'length' => '64K', - 'comment' => 'Google optimizer conversion script' - ), - 'conversion_page' => array( - 'type' => Varien_Db_Ddl_Table::TYPE_TEXT, - 'length' => 255, - 'comment' => 'Google optimizer conversion page' - ), - 'additional_data' => array( - 'type' => Varien_Db_Ddl_Table::TYPE_TEXT, - 'length' => '64K', - 'comment' => 'Google optimizer additional data' - ) - ), - 'comment' => 'Googleoptimizer code' - ) -); - -$installer->getConnection()->modifyTables($tables); - - -/** - * Add indexes - */ -$installer->getConnection()->addIndex( - $installer->getTable('googleoptimizer/code'), - $installer->getIdxName('googleoptimizer/code', array('store_id')), - array('store_id') -); - - -/** - * Add foreign keys - */ -$installer->getConnection()->addForeignKey( - $installer->getFkName('googleoptimizer/code', 'store_id', 'core/store', 'store_id'), - $installer->getTable('googleoptimizer/code'), - 'store_id', - $installer->getTable('core/store'), - 'store_id' -); - -$installer->endSetup(); 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 ac73c16d31..c0e13a4902 100644 --- a/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php +++ b/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php @@ -396,6 +396,8 @@ protected function _prepareLinks(array $productIds) /** * Prepare configurable product data * + * @deprecated since 1.6.1.0 + * @see Mage_Catalog_Model_Resource_Product_Type_Configurable::getConfigurableOptions() * @param array $productIds * @return array */ @@ -428,6 +430,8 @@ protected function _prepareConfigurableProductData(array $productIds) /** * Prepare configurable product price * + * @deprecated since 1.6.1.0 + * @see Mage_Catalog_Model_Resource_Product_Type_Configurable::getConfigurableOptions() * @param array $productIds * @return array */ @@ -556,9 +560,12 @@ public function export() $attrValue = $item->getData($attrCode); if (!empty($this->_attributeValues[$attrCode])) { - if ($this->_attributeTypes[$attrCode] == 'multiselect') { + if ($this->_attributeTypes[$attrCode] == 'multiselect') { $attrValue = explode(',', $attrValue); - $attrValue = array_intersect_key($this->_attributeValues[$attrCode], array_flip($attrValue)); + $attrValue = array_intersect_key( + $this->_attributeValues[$attrCode], + array_flip($attrValue) + ); $rowMultiselects[$itemId][$attrCode] = $attrValue; } else if (isset($this->_attributeValues[$attrCode][$attrValue])) { $attrValue = $this->_attributeValues[$attrCode][$attrValue]; @@ -617,29 +624,33 @@ public function export() Mage_Catalog_Model_Product_Link::LINK_TYPE_CROSSSELL => '_links_crosssell_', Mage_Catalog_Model_Product_Link::LINK_TYPE_GROUPED => '_associated_' ); - - // prepare configurable products data - $configurableData = $this->_prepareConfigurableProductData($productIds); - if ($configurableData) { - $configurablePrice = $this->_prepareConfigurableProductPrice($productIds); - foreach ($configurableData as $productId => &$rows) { - if (isset($configurablePrice[$productId])) { - $largest = max(count($rows), count($configurablePrice[$productId])); - - for ($i = 0; $i < $largest; $i++) { - if (!isset($configurableData[$productId][$i])) { - $configurableData[$productId][$i] = array(); - } - if (isset($configurablePrice[$productId][$i])) { - $configurableData[$productId][$i] = array_merge( - $configurableData[$productId][$i], - $configurablePrice[$productId][$i] - ); - } - } + $configurableProductsCollection = Mage::getResourceModel('catalog/product_collection'); + $configurableProductsCollection->addAttributeToFilter( + 'entity_id', + array( + 'in' => $productIds + ) + )->addAttributeToFilter( + 'type_id', + array( + 'eq' => Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE + ) + ); + $configurableData = array(); + while ($product = $configurableProductsCollection->fetchItem()) { + $productAttributesOptions = $product->getTypeInstance(true)->getConfigurableOptions($product); + + foreach ($productAttributesOptions as $productAttributeOption) { + $configurableData[$product->getId()] = array(); + foreach ($productAttributeOption as $optionValues) { + $configurableData[$product->getId()][] = array( + '_super_products_sku' => $optionValues['sku'], + '_super_attribute_code' => $optionValues['attribute_code'], + '_super_attribute_option' => $optionValues['option_title'], + '_super_attribute_price_corr' => $optionValues['pricing_value'] + ); } } - unset($configurablePrice); } // prepare custom options information @@ -683,7 +694,8 @@ public function export() } elseif ($option['title'] != $customOptions[0]['_custom_option_title']) { $row['_custom_option_title'] = $option['title']; } - if ($values = $option->getValues()) { + $values = $option->getValues(); + if ($values) { $firstValue = array_shift($values); $priceType = $firstValue['price_type'] == 'percent' ? '%' : ''; @@ -818,8 +830,8 @@ public function export() $dataRow = array_merge($dataRow, array_shift($configurableData[$productId])); } if(!empty($rowMultiselects[$productId])) { - foreach($rowMultiselects[$productId] as $attrKey=>$attrVal) { - if(!empty($rowMultiselects[$productId][$attrKey])) { + foreach ($rowMultiselects[$productId] as $attrKey => $attrVal) { + if (!empty($rowMultiselects[$productId][$attrKey])) { $dataRow[$attrKey] = array_shift($rowMultiselects[$productId][$attrKey]); } } @@ -853,8 +865,10 @@ public function export() if (!empty($configurableData[$productId])) { $additionalRowsCount = max($additionalRowsCount, count($configurableData[$productId])); } - foreach($rowMultiselects[$productId] as $attributes) { - $additionalRowsCount = max($additionalRowsCount, count($attributes)); + if (!empty($rowMultiselects[$productId])) { + foreach($rowMultiselects[$productId] as $attributes) { + $additionalRowsCount = max($additionalRowsCount, count($attributes)); + } } if ($additionalRowsCount) { diff --git a/app/code/core/Mage/ImportExport/Model/Import/Adapter.php b/app/code/core/Mage/ImportExport/Model/Import/Adapter.php index 76e7eb955e..0c5dbd26ac 100644 --- a/app/code/core/Mage/ImportExport/Model/Import/Adapter.php +++ b/app/code/core/Mage/ImportExport/Model/Import/Adapter.php @@ -48,14 +48,8 @@ public static function factory($type, $options = null) } $adapterClass = __CLASS__ . '_' . ucfirst(strtolower($type)); - if (!class_exists($adapterClass, false)) { - $adapterFile = str_replace('_', '/', $adapterClass) . '.php'; - if (!@include_once($adapterFile)) { - Mage::throwException("'{$type}' file extension is not supported"); - } - if (!class_exists($adapterClass, false)) { - Mage::throwException("Can not find adapter class {$adapterClass} in adapter file {$adapterFile}"); - } + if (!class_exists($adapterClass)) { + Mage::throwException("'{$type}' file extension is not supported"); } $adapter = new $adapterClass($options); 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 df63b295fb..50b37d1cd5 100644 --- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Abstract.php +++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Abstract.php @@ -574,7 +574,7 @@ public function isAttributeValid($attrCode, array $attrParams, array $rowData, $ if (!$valid) { $this->addRowError(Mage::helper('importexport')->__("Invalid value for '%s'"), $rowNum, $attrCode); - } elseif ($attrParams['is_unique']) { + } elseif (!empty($attrParams['is_unique'])) { if (isset($this->_uniqueAttributes[$attrCode][$rowData[$attrCode]])) { $this->addRowError(Mage::helper('importexport')->__("Duplicate Unique Attribute for '%s'"), $rowNum, $attrCode); return false; diff --git a/app/code/core/Mage/Media/etc/config.xml b/app/code/core/Mage/Media/etc/config.xml index 7115d4c05e..61dbb37838 100644 --- a/app/code/core/Mage/Media/etc/config.xml +++ b/app/code/core/Mage/Media/etc/config.xml @@ -38,8 +38,8 @@ media_resource - Mage_Media_Model_Resource - media_mysql4 + Mage_Media_Model_File + media_file
diff --git a/app/code/core/Mage/PageCache/Helper/Data.php b/app/code/core/Mage/PageCache/Helper/Data.php index 93a227313e..8499d63185 100644 --- a/app/code/core/Mage/PageCache/Helper/Data.php +++ b/app/code/core/Mage/PageCache/Helper/Data.php @@ -109,4 +109,14 @@ public function setNoCacheCookie() $cookie->set(self::NO_CACHE_COOKIE, 1, $lifetime); } } + + /** + * Returns a lifetime of cookie for external cache + * + * @return string Time in seconds + */ + public function getNoCacheCookieLifetime() + { + return Mage::getStoreConfig(self::XML_PATH_EXTERNAL_CACHE_LIFETIME); + } } diff --git a/app/code/core/Mage/Payment/Block/Form/Container.php b/app/code/core/Mage/Payment/Block/Form/Container.php index 7be7fb9668..a54b4d6972 100644 --- a/app/code/core/Mage/Payment/Block/Form/Container.php +++ b/app/code/core/Mage/Payment/Block/Form/Container.php @@ -116,7 +116,7 @@ public function getMethods() $quote = $this->getQuote(); $store = $quote ? $quote->getStoreId() : null; $methods = $this->helper('payment')->getStoreMethods($store, $quote); - $total = $quote->getGrandTotal(); + $total = $quote->getBaseSubtotal(); foreach ($methods as $key => $method) { if ($this->_canUseMethod($method) && ($total != 0 diff --git a/app/code/core/Mage/GoogleOptimizer/Block/Code/Page.php b/app/code/core/Mage/Paypal/Block/Hosted/Pro/Form.php similarity index 71% rename from app/code/core/Mage/GoogleOptimizer/Block/Code/Page.php rename to app/code/core/Mage/Paypal/Block/Hosted/Pro/Form.php index 5165a3f19c..73b7a778d2 100644 --- a/app/code/core/Mage/GoogleOptimizer/Block/Code/Page.php +++ b/app/code/core/Mage/Paypal/Block/Hosted/Pro/Form.php @@ -19,25 +19,28 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Paypal * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ - /** - * Google Optimizer Page Block + * Hosted Pro link form * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Paypal * @author Magento Core Team */ -class Mage_GoogleOptimizer_Block_Code_Page extends Mage_GoogleOptimizer_Block_Code +class Mage_Paypal_Block_Hosted_Pro_Form extends Mage_Payment_Block_Form { - protected function _initGoogleOptimizerModel() + /** + * Internal constructor + * Set info template for payment step + * + */ + protected function _construct() { - $cmsPage = Mage::getSingleton('cms/page'); - $this->_setGoogleOptimizerModel($cmsPage->getGoogleOptimizerScripts()); - return parent::_initGoogleOptimizerModel(); + parent::_construct(); + $this->setTemplate('paypal/hss/info.phtml'); } } diff --git a/app/code/community/Find/Feed/Model/Codes.php b/app/code/core/Mage/Paypal/Block/Hosted/Pro/Info.php similarity index 72% rename from app/code/community/Find/Feed/Model/Codes.php rename to app/code/core/Mage/Paypal/Block/Hosted/Pro/Info.php index 9a1229bff3..5b33cf228d 100644 --- a/app/code/community/Find/Feed/Model/Codes.php +++ b/app/code/core/Mage/Paypal/Block/Hosted/Pro/Info.php @@ -18,26 +18,28 @@ * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * - * @category - * @package _storage + * @category Mage + * @package Mage_Paypal * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** - * TheFind feed attribute map grid container + * Hosted Pro link infoblock * - * @category Find - * @package Find_Feed + * @category Mage + * @package Mage_Paypal + * @author Magento Core Team */ -class Find_Feed_Model_Codes extends Mage_Core_Model_Abstract +class Mage_Paypal_Block_Hosted_Pro_Info extends Mage_Paypal_Block_Payment_Info { /** - * Local constructor + * Don't show CC type * + * @return false */ - protected function _construct() + public function getCcTypeName() { - $this->_init('find_feed/codes'); + return false; } } 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 d68128c23a..09838bc757 100644 --- a/app/code/core/Mage/Paypal/Block/Payflow/Link/Form.php +++ b/app/code/core/Mage/Paypal/Block/Payflow/Link/Form.php @@ -25,7 +25,7 @@ */ /** - * Payflow link form + * Payflow link iframe block * * @category Mage * @package Mage_Paypal @@ -35,12 +35,22 @@ class Mage_Paypal_Block_Payflow_Link_Form extends Mage_Payment_Block_Form { /** * Internal constructor - * Set info template for payment step + * Set payment method code * - */ + */ protected function _construct() { parent::_construct(); - $this->setTemplate('paypal/hss/info.phtml'); + $this->setTemplate('paypal/payflowlink/iframe.phtml'); + } + + /** + * Get frame action URL + * + * @return string + */ + public function getFrameActionUrl() + { + return $this->getUrl('paypal/payflow/form', array('_secure' => true)); } } 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 b3db7669ee..62b2c55c63 100644 --- a/app/code/core/Mage/Paypal/Block/Payflow/Link/Iframe.php +++ b/app/code/core/Mage/Paypal/Block/Payflow/Link/Iframe.php @@ -31,19 +31,8 @@ * @package Mage_Paypal * @author Magento Core Team */ -class Mage_Paypal_Block_Payflow_Link_Iframe extends Mage_Paypal_Block_Iframe +class Mage_Paypal_Block_Payflow_Link_Iframe extends Mage_Payment_Block_Form { - /** - * Internal constructor - * Set payment method code - * - */ - protected function _construct() - { - parent::_construct(); - $this->_paymentMethodCode = Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK; - } - /** * Get frame action URL * @@ -61,7 +50,7 @@ public function getFrameActionUrl() */ public function getSecureToken() { - return $this->_getOrder() + return $this->_getSalesDocument() ->getPayment() ->getAdditionalInformation('secure_token'); } @@ -73,7 +62,7 @@ public function getSecureToken() */ public function getSecureTokenId() { - return $this->_getOrder() + return $this->_getSalesDocument() ->getPayment() ->getAdditionalInformation('secure_token_id'); } @@ -96,8 +85,18 @@ public function getTransactionUrl() public function isTestMode() { $mode = Mage::helper('payment') - ->getMethodInstance($this->_paymentMethodCode) + ->getMethodInstance(Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK) ->getConfigData('sandbox_flag'); return (bool) $mode; } + + /** + * Get sales document object + * + * @return Mage_Sales_Model_Order|Mage_Sales_Model_Quote + */ + protected function _getSalesDocument() + { + return Mage::getSingleton('checkout/session')->getQuote(); + } } diff --git a/app/code/community/Find/Feed/Model/Resource/Setup.php b/app/code/core/Mage/Paypal/Exception.php similarity index 81% rename from app/code/community/Find/Feed/Model/Resource/Setup.php rename to app/code/core/Mage/Paypal/Exception.php index 54cc85712e..de8ed4c19c 100644 --- a/app/code/community/Find/Feed/Model/Resource/Setup.php +++ b/app/code/core/Mage/Paypal/Exception.php @@ -18,19 +18,13 @@ * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * - * @category - * @package _storage + * @category Mage + * @package Mage_Paypal * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -/** - * Thefind feed module setup - * - * @category Find - * @package Find_Feed - */ -class Find_Feed_Model_Resource_Setup extends Mage_Catalog_Model_Resource_Setup +class Mage_Paypal_Exception extends Mage_Core_Exception { -} +} diff --git a/app/code/core/Mage/Paypal/Helper/Hss.php b/app/code/core/Mage/Paypal/Helper/Hss.php index 6ac58ab414..569f3af2fe 100644 --- a/app/code/core/Mage/Paypal/Helper/Hss.php +++ b/app/code/core/Mage/Paypal/Helper/Hss.php @@ -35,7 +35,6 @@ class Mage_Paypal_Helper_Hss extends Mage_Core_Helper_Abstract * @var array */ protected $_hssMethods = array( - Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK, Mage_Paypal_Model_Config::METHOD_HOSTEDPRO ); diff --git a/app/code/core/Mage/Paypal/Model/Api/Nvp.php b/app/code/core/Mage/Paypal/Model/Api/Nvp.php index efec35ae8e..ba318ebaa3 100644 --- a/app/code/core/Mage/Paypal/Model/Api/Nvp.php +++ b/app/code/core/Mage/Paypal/Model/Api/Nvp.php @@ -445,6 +445,7 @@ class Mage_Paypal_Model_Api_Nvp extends Mage_Paypal_Model_Api_Abstract 'amount' => 'L_SHIPPINGOPTIONAMOUNT%d', 'code' => 'L_SHIPPINGOPTIONNAME%d', 'name' => 'L_SHIPPINGOPTIONLABEL%d', + 'tax_amount' => 'L_TAXAMT%d', ); /** diff --git a/app/code/core/Mage/Paypal/Model/Config.php b/app/code/core/Mage/Paypal/Model/Config.php index b8d4bb1769..d813c0fe81 100644 --- a/app/code/core/Mage/Paypal/Model/Config.php +++ b/app/code/core/Mage/Paypal/Model/Config.php @@ -95,6 +95,14 @@ class Mage_Paypal_Model_Config const PAYMENT_ACTION_ORDER = 'Order'; const PAYMENT_ACTION_AUTH = 'Authorization'; + /** + * Authorization amounts for Account Verification + * @var int + */ + const AUTHORIZATION_AMOUNT_ZERO = 0; + const AUTHORIZATION_AMOUNT_ONE = 1; + const AUTHORIZATION_AMOUNT_FULL = 2; + /** * Fraud management actions * @var string @@ -853,6 +861,21 @@ public function getPaymentAction() } } + /** + * Returns array of possible Authorization Amounts for Account Verification + * + * @return array + */ + public function getAuthorizationAmounts() + { + $authorizationAmount = array( + self::AUTHORIZATION_AMOUNT_ZERO => Mage::helper('paypal')->__('$0 Auth'), + self::AUTHORIZATION_AMOUNT_ONE => Mage::helper('paypal')->__('$1 Auth'), + self::AUTHORIZATION_AMOUNT_FULL => Mage::helper('paypal')->__('Full Auth'), + ); + return $authorizationAmount; + } + /** * Express Checkout "solution types" source getter * "sole" = "Express Checkout for Auctions" - PayPal allows guest checkout diff --git a/app/code/core/Mage/Paypal/Model/Express/Checkout.php b/app/code/core/Mage/Paypal/Model/Express/Checkout.php index cfc426d787..44fcd7821b 100644 --- a/app/code/core/Mage/Paypal/Model/Express/Checkout.php +++ b/app/code/core/Mage/Paypal/Model/Express/Checkout.php @@ -87,6 +87,11 @@ class Mage_Paypal_Model_Express_Checkout protected $_pendingPaymentMessage = ''; protected $_checkoutRedirectUrl = ''; + /** + * @var Mage_Customer_Model_Session + */ + protected $_customerSession; + /** * Redirect urls supposed to be set to support giropay * @@ -145,6 +150,7 @@ public function __construct($params = array()) } else { throw new Exception('Config instance is required.'); } + $this->_customerSession = Mage::getSingleton('customer/session'); } /** @@ -340,6 +346,10 @@ public function start($returnUrl, $cancelUrl) /** * Update quote when returned from PayPal + * rewrite billing address by paypal + * save old billing address for new customer + * export shipping address in case address absence + * * @param string $token */ public function returnFromPaypal($token) @@ -347,10 +357,18 @@ public function returnFromPaypal($token) $this->_getApi(); $this->_api->setToken($token) ->callGetExpressCheckoutDetails(); + $quote = $this->_quote; // import billing address - $billingAddress = $this->_quote->getBillingAddress(); + $billingAddress = $quote->getBillingAddress(); $exportedBillingAddress = $this->_api->getExportedBillingAddress(); + $quote->setCustomerEmail($billingAddress->getEmail()); + $quote->setCustomerPrefix($billingAddress->getPrefix()); + $quote->setCustomerFirstname($billingAddress->getFirstname()); + $quote->setCustomerMiddlename($billingAddress->getMiddlename()); + $quote->setCustomerLastname($billingAddress->getLastname()); + $quote->setCustomerSuffix($billingAddress->getSuffix()); + $quote->setCustomerNote($exportedBillingAddress->getData('note')); foreach ($exportedBillingAddress->getExportedKeys() as $key) { if (!$billingAddress->getDataUsingMethod($key)) { $billingAddress->setDataUsingMethod($key, $exportedBillingAddress->getData($key)); @@ -359,14 +377,15 @@ public function returnFromPaypal($token) // import shipping address $exportedShippingAddress = $this->_api->getExportedShippingAddress(); - if (!$this->_quote->getIsVirtual()) { - $shippingAddress = $this->_quote->getShippingAddress(); + if (!$quote->getIsVirtual()) { + $shippingAddress = $quote->getShippingAddress(); if ($shippingAddress) { if ($exportedShippingAddress) { foreach ($exportedShippingAddress->getExportedKeys() as $key) { $shippingAddress->setDataUsingMethod($key, $exportedShippingAddress->getData($key)); } $shippingAddress->setCollectShippingRates(true); + $shippingAddress->setSameAsBilling(0); } // import shipping method @@ -377,7 +396,7 @@ public function returnFromPaypal($token) $shippingAddress->setShippingMethod($code)->setCollectShippingRates(true); } } - $this->_quote->getPayment()->setAdditionalInformation( + $quote->getPayment()->setAdditionalInformation( self::PAYMENT_INFO_TRANSPORT_SHIPPING_METHOD, $code ); @@ -386,13 +405,13 @@ public function returnFromPaypal($token) $this->_ignoreAddressValidation(); // import payment info - $payment = $this->_quote->getPayment(); + $payment = $quote->getPayment(); $payment->setMethod($this->_methodType); Mage::getSingleton('paypal/info')->importToPayment($this->_api, $payment); $payment->setAdditionalInformation(self::PAYMENT_INFO_TRANSPORT_PAYER_ID, $this->_api->getPayerId()) ->setAdditionalInformation(self::PAYMENT_INFO_TRANSPORT_TOKEN, $token) ; - $this->_quote->collectTotals()->save(); + $quote->collectTotals()->save(); } /** @@ -442,7 +461,7 @@ public function getShippingOptionsCallbackResponse(array $request) $quoteAddress->setDataUsingMethod($key, $address->getData($key)); } $quoteAddress->setCollectShippingRates(true)->collectTotals(); - $options = $this->_prepareShippingOptions($quoteAddress, false); + $options = $this->_prepareShippingOptions($quoteAddress, false, true); } $response = $this->_api->setShippingOptions($options)->formatShippingOptionsCallback(); @@ -484,10 +503,18 @@ public function place($token, $shippingMethodCode = null) $this->updateShippingMethod($shippingMethodCode); } - if (!$this->_quote->getCustomerId()) { - $this->_quote->setCustomerIsGuest(true) - ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID) - ->setCustomerEmail($this->_quote->getBillingAddress()->getEmail()); + $isNewCustomer = false; + switch ($this->_quote->getCheckoutMethod()) { + case Mage_Checkout_Model_Type_Onepage::METHOD_GUEST: + $this->_prepareGuestQuote(); + break; + case Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER: + $this->_prepareNewCustomerQuote(); + $isNewCustomer = true; + break; + default: + $this->_prepareCustomerQuote(); + break; } $this->_ignoreAddressValidation(); @@ -495,6 +522,15 @@ public function place($token, $shippingMethodCode = null) $service = Mage::getModel('sales/service_quote', $this->_quote); $service->submitAll(); $this->_quote->save(); + + if ($isNewCustomer) { + try { + $this->_involveNewCustomer(); + } catch (Exception $e) { + Mage::logException($e); + } + } + $this->_recurringPaymentProfiles = $service->getRecurringPaymentProfiles(); // TODO: send recurring profile emails @@ -624,8 +660,10 @@ protected function _getApi() * @param bool $mayReturnEmpty * @return array|false */ - protected function _prepareShippingOptions(Mage_Sales_Model_Quote_Address $address, $mayReturnEmpty = false) - { + protected function _prepareShippingOptions( + Mage_Sales_Model_Quote_Address $address, + $mayReturnEmpty = false, $calculateTax = false + ) { $options = array(); $i = 0; $iMin = false; $min = false; $userSelectedOption = null; @@ -636,18 +674,27 @@ protected function _prepareShippingOptions(Mage_Sales_Model_Quote_Address $addre continue; } $isDefault = $address->getShippingMethod() === $rate->getCode(); + $amountExclTax = Mage::helper('tax')->getShippingPrice($amount, false, $address); + $amountInclTax = Mage::helper('tax')->getShippingPrice($amount, true, $address); $options[$i] = new Varien_Object(array( 'is_default' => $isDefault, 'name' => trim("{$rate->getCarrierTitle()} - {$rate->getMethodTitle()}", ' -'), 'code' => $rate->getCode(), - 'amount' => $amount, + 'amount' => $amountExclTax, )); + if ($calculateTax) { + $options[$i]->setTaxAmount( + $amountInclTax - $amountExclTax + + $address->getTaxAmount() - $address->getShippingTaxAmount() + ); + } if ($isDefault) { $userSelectedOption = $options[$i]; } - if (false === $min || $amount < $min) { - $min = $amount; $iMin = $i; + if (false === $min || $amountInclTax < $min) { + $min = $amountInclTax; + $iMin = $i; } $i++; } @@ -660,6 +707,9 @@ protected function _prepareShippingOptions(Mage_Sales_Model_Quote_Address $addre 'code' => 'no_rate', 'amount' => 0.00, )); + if ($calculateTax) { + $options[$i]->setTaxAmount($address->getTaxAmount()); + } } elseif (is_null($userSelectedOption) && isset($options[$iMin])) { $options[$iMin]->setIsDefault(true); } @@ -719,4 +769,143 @@ protected function _matchShippingMethodCode(Mage_Sales_Model_Quote_Address $addr } return ''; } + + /** + * Prepare quote for guest checkout order submit + * + * @return Mage_Paypal_Model_Express_Checkout + */ + protected function _prepareGuestQuote() + { + $quote = $this->_quote; + $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 + * and restore magento customer data from quote + * + * @return Mage_Paypal_Model_Express_Checkout + */ + protected function _prepareNewCustomerQuote() + { + $quote = $this->_quote; + $billing = $quote->getBillingAddress(); + $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress(); + + $customer = $quote->getCustomer(); + /** @var $customer Mage_Customer_Model_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); + } elseif ($shipping) { + $customerBilling->setIsDefaultShipping(true); + } + /** + * @todo integration with dynamica attributes customer_dob, customer_taxvat, customer_gender + */ + if ($quote->getCustomerDob() && !$billing->getCustomerDob()) { + $billing->setCustomerDob($quote->getCustomerDob()); + } + + if ($quote->getCustomerTaxvat() && !$billing->getCustomerTaxvat()) { + $billing->setCustomerTaxvat($quote->getCustomerTaxvat()); + } + + if ($quote->getCustomerGender() && !$billing->getCustomerGender()) { + $billing->setCustomerGender($quote->getCustomerGender()); + } + + Mage::helper('core')->copyFieldset('checkout_onepage_billing', 'to_customer', $billing, $customer); + $customer->setEmail($quote->getCustomerEmail()); + $customer->setPrefix($quote->getCustomerPrefix()); + $customer->setFirstname($quote->getCustomerFirstname()); + $customer->setMiddlename($quote->getCustomerMiddlename()); + $customer->setLastname($quote->getCustomerLastname()); + $customer->setSuffix($quote->getCustomerSuffix()); + $customer->setPassword($customer->decryptPassword($quote->getPasswordHash())); + $customer->setPasswordHash($customer->hashPassword($customer->getPassword())); + $quote->setCustomer($customer) + ->setCustomerId(true); + + return $this; + } + + /** + * Prepare quote for customer order submit + * + * @return Mage_Paypal_Model_Express_Checkout + */ + protected function _prepareCustomerQuote() + { + $quote = $this->_quote; + $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->getCustomerId() && !$shipping->getSameAsBilling()) + || (!$shipping->getSameAsBilling() && $shipping->getSaveInAddressBook()))) { + $customerShipping = $shipping->exportCustomerAddress(); + $customer->addAddress($customerShipping); + $shipping->setCustomerAddress($customerShipping); + } + + if (isset($customerBilling) && !$customer->getDefaultBilling()) { + $customerBilling->setIsDefaultBilling(true); + } + if ($shipping && isset($customerBilling) && !$customer->getDefaultShipping() && $shipping->getSameAsBilling()) { + $customerBilling->setIsDefaultShipping(true); + } elseif ($shipping && isset($customerShipping) && !$customer->getDefaultShipping()) { + $customerShipping->setIsDefaultShipping(true); + } + $quote->setCustomer($customer); + + return $this; + } + + /** + * Involve new customer to system + * + * @return Mage_Paypal_Model_Express_Checkout + */ + protected function _involveNewCustomer() + { + $customer = $this->_quote->getCustomer(); + if ($customer->isConfirmationRequired()) { + $customer->sendNewAccountEmail('confirmation'); + $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(); + $this->getCustomerSession()->loginById($customer->getId()); + } + return $this; + } + + /** + * Get customer session object + * + * @return Mage_Customer_Model_Session + */ + public function getCustomerSession() + { + return $this->_customerSession; + } } diff --git a/app/code/core/Mage/Paypal/Model/Hostedpro.php b/app/code/core/Mage/Paypal/Model/Hostedpro.php index c9d60f0bd4..b1b7514460 100644 --- a/app/code/core/Mage/Paypal/Model/Hostedpro.php +++ b/app/code/core/Mage/Paypal/Model/Hostedpro.php @@ -60,8 +60,8 @@ class Mage_Paypal_Model_Hostedpro extends Mage_Paypal_Model_Direct */ protected $_code = Mage_Paypal_Model_Config::METHOD_HOSTEDPRO; - protected $_formBlockType = 'paypal/payflow_link_form'; - protected $_infoBlockType = 'paypal/payflow_link_info'; + protected $_formBlockType = 'paypal/hosted_pro_form'; + protected $_infoBlockType = 'paypal/hosted_pro_info'; /** * Availability options @@ -240,7 +240,7 @@ protected function _getUrl($path, $storeId, $secure = null) { $store = Mage::app()->getStore($storeId); return Mage::getUrl($path, array( - "_store" => $store, + "_store" => $store, "_secure" => is_null($secure) ? $store->isCurrentlySecure() : $secure )); } diff --git a/app/code/core/Mage/Paypal/Model/Observer.php b/app/code/core/Mage/Paypal/Model/Observer.php index e0e7fb526f..7b2a5bc7ea 100644 --- a/app/code/core/Mage/Paypal/Model/Observer.php +++ b/app/code/core/Mage/Paypal/Model/Observer.php @@ -54,6 +54,40 @@ public function fetchReports() } } + /** + * Clean unfinished transaction + * + * @return Mage_Paypal_Model_Observer + */ + public function cleanTransactions() + { + /** @var $date Mage_Core_Model_Date */ + $date = Mage::getModel('core/date'); + $createdBefore = strtotime('-1 hour', $date->timestamp()); + + /** @var $collection Mage_Paypal_Model_Resource_Payment_Transaction_Collection */ + $collection = Mage::getModel('paypal/payment_transaction')->getCollection(); + $collection->addCreatedBeforeFilter($date->gmtDate(null, $createdBefore)); + + /** @var $method Mage_Paypal_Model_Payflowlink */ + $method = Mage::helper('payment')->getMethodInstance(Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK); + + /** @var $item Mage_Paypal_Model_Payment_Transaction */ + foreach ($collection as $item) { + try { + $method->void(new Varien_Object(array( + 'transaction_id' => $item->getTxnId(), + 'store' => $item->getAdditionalInformation('store_id') + ))); + $item->delete(); + } catch (Mage_Paypal_Exception $e) { + $item->delete(); + } catch (Exception $e) { + Mage::logException($e); + } + } + } + /** * Save order into registry to use it in the overloaded controller. * @@ -64,7 +98,7 @@ public function saveOrderAfterSubmit(Varien_Event_Observer $observer) { /* @var $order Mage_Sales_Model_Order */ $order = $observer->getEvent()->getData('order'); - Mage::register('payflowlink_order', $order, true); + Mage::register('hss_order', $order, true); return $this; } @@ -78,7 +112,7 @@ public function saveOrderAfterSubmit(Varien_Event_Observer $observer) public function setResponseAfterSaveOrder(Varien_Event_Observer $observer) { /* @var $order Mage_Sales_Model_Order */ - $order = Mage::registry('payflowlink_order'); + $order = Mage::registry('hss_order'); if ($order && $order->getId()) { $payment = $order->getPayment(); diff --git a/app/code/core/Mage/Paypal/Model/Payflowlink.php b/app/code/core/Mage/Paypal/Model/Payflowlink.php index cec352841d..fe6180483b 100644 --- a/app/code/core/Mage/Paypal/Model/Payflowlink.php +++ b/app/code/core/Mage/Paypal/Model/Payflowlink.php @@ -47,7 +47,6 @@ class Mage_Paypal_Model_Payflowlink extends Mage_Paypal_Model_Payflowpro */ protected $_canUseInternal = false; protected $_canUseForMultishipping = false; - protected $_isInitializeNeeded = true; /** * Request & response model @@ -67,6 +66,12 @@ class Mage_Paypal_Model_Payflowlink extends Mage_Paypal_Model_Payflowpro */ const RESPONSE_ERROR_MSG = 'Payment error. %s was not found.'; + /** + * Quote Changed Error message + * @var string + */ + const SHOPPING_CART_CHANGED_ERROR_MSG = 'Shopping cart contents has been changed.'; + /** * Key for storing secure hash in additional information of payment model * @@ -108,29 +113,173 @@ public function isAvailable($quote = null) */ public function initialize($paymentAction, $stateObject) { - switch ($paymentAction) { - case Mage_Paypal_Model_Config::PAYMENT_ACTION_AUTH: - case Mage_Paypal_Model_Config::PAYMENT_ACTION_SALE: - $payment = $this->getInfoInstance(); - $order = $payment->getOrder(); - $order->setCanSendNewEmailFlag(false); - $payment->setAmountAuthorized($order->getTotalDue()); - $payment->setBaseAmountAuthorized($order->getBaseTotalDue()); - $this->_generateSecureSilentPostHash($payment); - $request = $this->_buildTokenRequest($payment); - $response = $this->_postRequest($request); - $this->_processTokenErrors($response, $payment); - - $order = $payment->getOrder(); - $order->setCanSendNewEmailFlag(false); - - $stateObject->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT); - $stateObject->setStatus('pending_payment'); - $stateObject->setIsNotified(false); + $payment = $this->getInfoInstance(); + + $salesDocument = $payment->getOrder(); + if (!$salesDocument) { + $salesDocument = $payment->getQuote(); + $amount = $salesDocument->getBaseGrandTotal(); + } else { + $amount = $salesDocument->getBaseTotalDue(); + } + //create reference transaction if Verification Authorization Amount set to $0 or $1 + $authorizationAmount = $this->getConfigData('authorization_amount', $salesDocument->getStoreId()); + switch ($authorizationAmount) { + case Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_FULL: + $this->_initialize($payment, $amount); + break; + case Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_ONE: + $this->_initialize($payment, 1); break; - default: + case Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_ZERO: + try { + $this->_initialize($payment, 0); + } catch (Mage_Paypal_Exception $e) { + $authorizationAmount = Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_ONE; + $this->_initialize($payment, 1); + } break; } + $payment->setAdditionalInformation('authorization_amount', $authorizationAmount); + + return $this; + } + + /** + * Initialize request + * + * @param Varien_Object $payment + * @param $amount + * @return Mage_Paypal_Model_Payflowlink + */ + protected function _initialize(Varien_Object $payment, $amount) + { + $this->_generateSecureSilentPostHash($payment); + $request = $this->_buildTokenRequest($payment, $amount); + $response = $this->_postRequest($request); + $this->_processTokenErrors($response, $payment); + return $this; + } + + /** + * Authorize payment + * + * @param Mage_Sales_Model_Order_Payment | Mage_Sales_Model_Quote_Payment $payment + * @param mixed $amount + * @return Mage_Paypal_Model_Payflowlink + */ + public function authorize(Varien_Object $payment, $amount) + { + $txnId = $payment->getAdditionalInformation('authorization_id'); + /** @var $transaction Mage_Paypal_Model_Payment_Transaction */ + $transaction = Mage::getModel('paypal/payment_transaction'); + $transaction->loadByTxnId($txnId); + + $payment->setTransactionId($txnId)->setIsTransactionClosed(0); + if ($payment->getAdditionalInformation('paypal_fraud_filters') !== null) { + $payment->setIsTransactionPending(true); + $payment->setIsFraudDetected(true); + } + + $this->_authorize($payment, $amount, $transaction, $txnId); + if ($payment->getAdditionalInformation('authorization_amount') != + Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_FULL + ) { + $payment->setParentTransactionId($txnId); + parent::authorize($payment, $amount); + if ($payment->getTransactionId()) { + $payment->setAdditionalInformation('authorization_id', $payment->getTransactionId()); + } + + } + + $transaction->delete(); + return $this; + } + + /** + * Additional authorization logic for Account Verification + * + * @param Varien_Object $payment + * @param mixed $amount + * @param Mage_Paypal_Model_Payment_Transaction $transaction + * @param string $txnId + * @return Mage_Paypal_Model_Payflowlink + */ + protected function _authorize(Varien_Object $payment, $amount, $transaction, $txnId) + { + $authorizationAmount = $payment->getAdditionalInformation('authorization_amount'); + if ($authorizationAmount == Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_ONE) { + $payment->setParentTransactionId($txnId); + $this->void($payment); + } elseif ($authorizationAmount == Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_FULL) { + $this->_checkTransaction($transaction, $amount); + } + return $this; + } + + /** + * Capture payment + * + * @param Mage_Sales_Model_Order_Payment | Mage_Sales_Model_Quote_Payment $payment + * @param mixed $amount + * @return Mage_Paypal_Model_Payflowlink + */ + public function capture(Varien_Object $payment, $amount) + { + $removePaypalTransaction = false; + /** @var $transaction Mage_Paypal_Model_Payment_Transaction */ + $transaction = Mage::getModel('paypal/payment_transaction'); + $txnId = $payment->getAdditionalInformation('authorization_id'); + $transaction->loadByTxnId($txnId); + if ($transaction->getId()) { + $removePaypalTransaction = true; + $payment->setTransactionId($txnId); + $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH); + $this->_authorize($payment, $amount, $transaction, $txnId); + $payment->setReferenceTransactionId($payment->getAdditionalInformation('authorization_id')); + } + + $payment->setParentTransactionId($txnId); + + $payment->setAmountOrdered(round($amount,2)); + parent::capture($payment, $amount); + + if ($removePaypalTransaction) { + $transaction->delete(); + } + + return $this; + } + + /** + * Void payment + * + * @param Varien_Object $payment + * @return Mage_Paypal_Model_Payflowlink + */ + public function void(Varien_Object $payment) + { + /** @var $payment Mage_Sales_Model_Quote_Payment */ + if ($payment instanceof Mage_Sales_Model_Order_Payment) { + parent::void($payment); + return $this; + } elseif ($payment instanceof Mage_Sales_Model_Quote_Payment) { + $this->setStore($payment->getQuote()->getStoreId()); + } else { + if ($payment->getStore()) { + $this->setStore($payment->getStore()); + } + } + + $request = $this->_buildBasicRequest($payment); + $request->setTrxtype(self::TRXTYPE_DELAYED_VOID); + + $request->setOrigid($payment->getTransactionId()); + $response = $this->_postRequest($request); + $this->_processErrors($response); + + return $this; } /** @@ -176,62 +325,49 @@ public function process($responseData) $this->setResponseData($responseData); - if ($order = $this->_getOrderFromResponse()) { - $this->_processOrder($order); + $document = $this->_getDocumentFromResponse(); + if ($document) { + $this->_process($document); } } /** - * Operate with order using information from silent post + * Operate with order or quote using information from silent post * - * @param Mage_Sales_Model_Order $order + * @param Varien_Object $document */ - protected function _processOrder(Mage_Sales_Model_Order $order) + protected function _process(Varien_Object $document) { $response = $this->getResponse(); - $payment = $order->getPayment(); - $payment->setTransactionId($response->getPnref()) - ->setIsTransactionClosed(0); - $canSendNewOrderEmail = true; + $payment = $document->getPayment(); if ($response->getResult() == self::RESPONSE_CODE_FRAUDSERVICE_FILTER || - $response->getResult() == self::RESPONSE_CODE_DECLINED_BY_FILTER) { - $canSendNewOrderEmail = false; - $fraudMessage = $this->_getFraudMessage() ? - $response->getFraudMessage() : $response->getRespmsg(); - $payment->setIsTransactionPending(true) - ->setIsFraudDetected(true) - ->setAdditionalInformation('paypal_fraud_filters', $fraudMessage); + $response->getResult() == self::RESPONSE_CODE_DECLINED_BY_FILTER + ) { + $fraudMessage = $this->_getFraudMessage() ? $response->getFraudMessage() : $response->getRespmsg(); + $payment->setAdditionalInformation('paypal_fraud_filters', $fraudMessage); } if ($response->getAvsdata() && strstr(substr($response->getAvsdata(), 0, 2), 'N')) { $payment->setAdditionalInformation('paypal_avs_code', substr($response->getAvsdata(), 0, 2)); } + if ($response->getCvv2match() && $response->getCvv2match() != 'Y') { $payment->setAdditionalInformation('paypal_cvv2_match', $response->getCvv2match()); } - switch ($response->getType()){ - case self::TRXTYPE_AUTH_ONLY: - $payment->registerAuthorizationNotification($payment->getBaseAmountAuthorized()); - break; - case self::TRXTYPE_SALE: - $payment->registerCaptureNotification($payment->getBaseAmountAuthorized()); - break; - } - $order->save(); + $payment->setAdditionalInformation('authorization_id', $response->getPnref()); - try { - if ($canSendNewOrderEmail) { - $order->sendNewOrderEmail(); - } - Mage::getModel('sales/quote') - ->load($order->getQuoteId()) - ->setIsActive(false) - ->save(); - } catch (Exception $e) { - Mage::throwException(Mage::helper('paypal')->__('Can not send new order email.')); - } + /** @var $transaction Mage_Paypal_Model_Payment_Transaction */ + $transaction = Mage::getModel('paypal/payment_transaction'); + $transaction->setTxnId($response->getPnref()); + + $transaction->setAdditionalInformation('amt', $response->getAmt()); + $transaction->setAdditionalInformation('store_id', $document->getStoreId()); + + $document->setIsChanged(1); + $document->save(); + $transaction->save(); } /** @@ -250,47 +386,58 @@ protected function _getFraudMessage() return false; } + /** + * Check Transaction + * + * @param Mage_Paypal_Model_Payment_Transaction $transaction + * @param mixed $amount + * @return Mage_Paypal_Model_Payflowlink + */ + protected function _checkTransaction($transaction, $amount) + { + if (!$transaction->getId()) { + Mage::throwException(Mage::helper('paypal')->__(self::SHOPPING_CART_CHANGED_ERROR_MSG)); + } + + $authorizedAmt = $transaction->getAdditionalInformation('amt'); + + if (!$authorizedAmt || $amount > $authorizedAmt) { + Mage::throwException(Mage::helper('paypal')->__(self::SHOPPING_CART_CHANGED_ERROR_MSG)); + } + return $this; + } + /** * Check response from Payflow gateway. * - * @return Mage_Sales_Model_Order in case of validation passed + * @return Mage_Sales_Model_Abstract in case of validation passed * @throws Mage_Core_Exception in other cases */ - protected function _getOrderFromResponse() + protected function _getDocumentFromResponse() { $response = $this->getResponse(); - $order = Mage::getModel('sales/order') - ->loadByIncrementId($response->getInvnum()); + $salesDocument = Mage::getModel('sales/quote')->load($response->getPonum()); + $salesDocument->getPayment()->setMethod(Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK); - if ($this->_getSecureSilentPostHash($order->getPayment()) != $response->getUser2() - || $this->_code != $order->getPayment()->getMethodInstance()->getCode()) { + if ($this->_getSecureSilentPostHash($salesDocument->getPayment()) != $response->getUser2() + || $this->_code != $salesDocument->getPayment()->getMethodInstance()->getCode()) { return false; } if ($response->getResult() != self::RESPONSE_CODE_FRAUDSERVICE_FILTER && $response->getResult() != self::RESPONSE_CODE_DECLINED_BY_FILTER && - $response->getResult() != self::RESPONSE_CODE_APPROVED) { - if ($order->getState() != Mage_Sales_Model_Order::STATE_CANCELED) { - $order->registerCancellation($response->getRespmsg())->save(); - } + $response->getResult() != self::RESPONSE_CODE_APPROVED + ) { Mage::throwException($response->getRespmsg()); } - $amountCompared = ($response->getAmt() == - $order->getPayment()->getBaseAmountAuthorized()) ? true : false; - if (!$order->getId() || - $order->getState() != Mage_Sales_Model_Order::STATE_PENDING_PAYMENT || - !$amountCompared) { - Mage::throwException($this->_formatStr(self::RESPONSE_ERROR_MSG, 'Order')); - } - - $fetchData = $this->fetchTransactionInfo($order->getPayment(), $response->getPnref()); - if (!isset($fetchData['custref']) || $fetchData['custref'] != $order->getIncrementId()) { - Mage::throwException($this->_formatStr(self::RESPONSE_ERROR_MSG, 'Transaction')); + $fetchData = $this->fetchTransactionInfo($salesDocument->getPayment(), $response->getPnref()); + if (!isset($fetchData['custref']) || $fetchData['custref'] != $salesDocument->getReservedOrderId()) { + Mage::throwException($this->_formatStr(self::RESPONSE_ERROR_MSG, 'Transaction error')); } - return $order; + return $salesDocument; } /** @@ -299,27 +446,42 @@ protected function _getOrderFromResponse() * @param Mage_Sales_Model_Order_Payment $payment * @return Varien_Object */ - protected function _buildTokenRequest(Varien_Object $payment) + protected function _buildTokenRequest(Varien_Object $payment, $amount) { + $orderId = null; + $fullAmount = $payment->getAdditionalInformation('authorization_amount'); + + $salesDocument = $payment->getOrder(); + if (!$salesDocument) { + $salesDocument = $payment->getQuote(); + if (!$salesDocument->getReservedOrderId()) { + $salesDocument->reserveOrderId(); + } + $orderId = $salesDocument->getReservedOrderId(); + } else { + $orderId = $salesDocument->getIncrementId(); + } + $request = $this->_buildBasicRequest($payment); + if (empty($salesDocument)) { + return $request; + } + $request->setCreatesecuretoken('Y') ->setSecuretokenid($this->_generateSecureTokenId()) ->setTrxtype($this->_getTrxTokenType()) - ->setAmt($this->_formatStr('%.2F', $payment->getOrder()->getBaseTotalDue())) - ->setCurrency($payment->getOrder()->getBaseCurrencyCode()) - ->setInvnum($payment->getOrder()->getIncrementId()) - ->setCustref($payment->getOrder()->getIncrementId()) - ->setPonum($payment->getOrder()->getId()) - ->setSubtotal($payment->getOrder()->getBaseSubtotal()) - ->setTaxamt($this->_formatStr('%.2F', $payment->getOrder()->getBaseTaxAmount())) - ->setFreightamt($this->_formatStr('%.2F', $payment->getOrder()->getBaseShippingAmount())); - - $order = $payment->getOrder(); - if (empty($order)) { - return $request; + ->setAmt($this->_formatStr('%.2F', $amount)) + ->setCurrency($salesDocument->getBaseCurrencyCode()) + ->setInvnum($orderId) + ->setCustref($orderId) + ->setPonum($salesDocument->getId()); + if ($fullAmount != Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_FULL) { + $request->setSubtotal($this->_formatStr('%.2F', $salesDocument->getBaseSubtotal())) + ->setTaxamt($this->_formatStr('%.2F', $salesDocument->getBaseTaxAmount())) + ->setFreightamt($this->_formatStr('%.2F', $salesDocument->getBaseShippingAmount())); } - $billing = $order->getBillingAddress(); + $billing = $salesDocument->getBillingAddress(); if (!empty($billing)) { $request->setFirstname($billing->getFirstname()) ->setLastname($billing->getLastname()) @@ -328,9 +490,9 @@ protected function _buildTokenRequest(Varien_Object $payment) ->setState($billing->getRegionCode()) ->setZip($billing->getPostcode()) ->setCountry($billing->getCountry()) - ->setEmail($payment->getOrder()->getCustomerEmail()); + ->setEmail($salesDocument->getCustomerEmail()); } - $shipping = $order->getShippingAddress(); + $shipping = $salesDocument->getShippingAddress(); if (!empty($shipping)) { $this->_applyCountryWorkarounds($shipping); $request->setShiptofirstname($shipping->getFirstname()) @@ -342,7 +504,7 @@ protected function _buildTokenRequest(Varien_Object $payment) ->setShiptocountry($shipping->getCountry()); } //pass store Id to request - $request->setUser1($order->getStoreId()) + $request->setUser1($salesDocument->getStoreId()) ->setUser2($this->_getSecureSilentPostHash($payment)); return $request; @@ -380,6 +542,25 @@ protected function _buildBasicRequest(Varien_Object $payment) ->setPwd($this->getConfigData('pwd', $this->_getStoreId())) ->setVerbosity($this->getConfigData('verbosity', $this->_getStoreId())) ->setTender(self::TENDER_CC); + if ($payment->getAmountOrdered() > 0) { + $request->setAmt(round($payment->getAmountOrdered(),2)); + } + return $request; + } + + /** + * Return request object with information for 'authorization' or 'sale' action + * + * @param Mage_Sales_Model_Order_Payment $payment + * @param float $amount + * @return Varien_Object + */ + protected function _buildPlaceRequest(Varien_Object $payment, $amount) + { + $request = $this->_buildBasicRequest($payment); + $request->setAmt(round($amount,2)); + $request->setCurrency($payment->getOrder()->getBaseCurrencyCode()); + return $request; } @@ -390,12 +571,7 @@ protected function _buildBasicRequest(Varien_Object $payment) */ protected function _getTrxTokenType() { - switch ($this->getConfigData('payment_action')) { - case Mage_Paypal_Model_Config::PAYMENT_ACTION_AUTH: - return self::TRXTYPE_AUTH_ONLY; - case Mage_Paypal_Model_Config::PAYMENT_ACTION_SALE: - return self::TRXTYPE_SALE; - } + return self::TRXTYPE_AUTH_ONLY; } /** @@ -430,7 +606,9 @@ protected function _formatStr($format, $string) */ protected function _processTokenErrors($response, $payment) { - if (!$response->getSecuretoken() && + if ($response->getResult() == self::RESPONSE_CODE_INVALID_AMOUNT) { + throw new Mage_Paypal_Exception(Mage::helper('paypal')->__('Invalid Amount')); + } elseif (!$response->getSecuretoken() && $response->getResult() != self::RESPONSE_CODE_APPROVED && $response->getResult() != self::RESPONSE_CODE_FRAUDSERVICE_FILTER) { Mage::throwException($response->getRespmsg()); @@ -463,4 +641,23 @@ protected function _generateSecureSilentPostHash($payment) $payment->setAdditionalInformation($this->_secureSilentPostHashKey, $secureHash); return $secureHash; } + + /** + * Set reference transaction data into request + * + * @param Varien_Object $payment + * @param Varien_Object $request + * @return Mage_Paypal_Model_Payflowlink + */ + protected function _setReferenceTransaction(Varien_Object $payment, $request) + { + if ($payment->getParentTransactionId()) { + $request->setOrigid($payment->getParentTransactionId()); + + $request->unsAcct(); + $request->unsExpdate(); + $request->unsCvv2(); + } + return $this; + } } diff --git a/app/code/core/Mage/Paypal/Model/Payflowpro.php b/app/code/core/Mage/Paypal/Model/Payflowpro.php index de8ca11df9..d101ea435d 100644 --- a/app/code/core/Mage/Paypal/Model/Payflowpro.php +++ b/app/code/core/Mage/Paypal/Model/Payflowpro.php @@ -60,11 +60,13 @@ class Mage_Paypal_Model_Payflowpro extends Mage_Payment_Model_Method_Cc * Response codes */ const RESPONSE_CODE_APPROVED = 0; + const RESPONSE_CODE_INVALID_AMOUNT = 4; const RESPONSE_CODE_FRAUDSERVICE_FILTER = 126; const RESPONSE_CODE_DECLINED = 12; const RESPONSE_CODE_DECLINED_BY_FILTER = 125; const RESPONSE_CODE_DECLINED_BY_MERCHANT = 128; const RESPONSE_CODE_CAPTURE_ERROR = 111; + const RESPONSE_CODE_VOID_ERROR = 108; /** * Payment method code @@ -154,6 +156,7 @@ public function authorize(Varien_Object $payment, $amount) { $request = $this->_buildPlaceRequest($payment, $amount); $request->setTrxtype(self::TRXTYPE_AUTH_ONLY); + $this->_setReferenceTransaction($payment, $request); $response = $this->_postRequest($request); $this->_processErrors($response); @@ -178,7 +181,11 @@ public function authorize(Varien_Object $payment, $amount) */ public function capture(Varien_Object $payment, $amount) { - if ($payment->getParentTransactionId()) { + if ($payment->getReferenceTransactionId()) { + $request = $this->_buildPlaceRequest($payment, $amount); + $request->setTrxtype(self::TRXTYPE_SALE); + $request->setOrigid($payment->getReferenceTransactionId()); + } elseif ($payment->getParentTransactionId()) { $request = $this->_buildBasicRequest($payment); $request->setTrxtype(self::TRXTYPE_DELAYED_CAPTURE); $request->setOrigid($payment->getParentTransactionId()); @@ -473,7 +480,9 @@ protected function _generateRequestId() */ protected function _processErrors(Varien_Object $response) { - if ($response->getResultCode() != self::RESPONSE_CODE_APPROVED + if ($response->getResultCode() == self::RESPONSE_CODE_VOID_ERROR) { + throw new Mage_Paypal_Exception(Mage::helper('paypal')->__('You cannot void a verification transaction')); + } elseif ($response->getResultCode() != self::RESPONSE_CODE_APPROVED && $response->getResultCode() != self::RESPONSE_CODE_FRAUDSERVICE_FILTER) { Mage::throwException($response->getRespmsg()); } @@ -492,4 +501,16 @@ protected function _applyCountryWorkarounds(Varien_Object $address) $address->setRegionCode('PR'); } } + + /** + * Set reference transaction data into request + * + * @param Varien_Object $payment + * @param Varien_Object $request + * @return Mage_Paypal_Model_Payflowpro + */ + protected function _setReferenceTransaction(Varien_Object $payment, $request) + { + return $this; + } } diff --git a/app/code/core/Mage/Paypal/Model/Payment/Transaction.php b/app/code/core/Mage/Paypal/Model/Payment/Transaction.php new file mode 100644 index 0000000000..df0df23d5c --- /dev/null +++ b/app/code/core/Mage/Paypal/Model/Payment/Transaction.php @@ -0,0 +1,242 @@ + + */ +class Mage_Paypal_Model_Payment_Transaction extends Mage_Core_Model_Abstract +{ + /** + * Whether to throw exceptions on different operations + * + * @var bool + */ + protected $_isFailsafe = false; + + /** + * Event object prefix + * + * @see Mage_Core_Model_Absctract::$_eventPrefix + * @var string + */ + protected $_eventPrefix = 'paypal_payment_transaction'; + + /** + * Event object prefix + * + * @see Mage_Core_Model_Absctract::$_eventObject + * @var string + */ + protected $_eventObject = 'paypal_payment_transaction'; + + /** + * Order website id + * + * @var int + */ + protected $_orderWebsiteId = null; + + /** + * Initialize resource model + */ + protected function _construct() + { + $this->_init('paypal/payment_transaction'); + return parent::_construct(); + } + + /** + * Transaction ID setter + * @param string $txnId + * @return Mage_Paypal_Model_Payment_Transaction + */ + public function setTxnId($txnId) + { + $this->_verifyTxnId($txnId); + return $this->setData('txn_id', $txnId); + } + + /** + * Check object before loading by by specified transaction ID + * @param $txnId + * @return Mage_Paypal_Model_Payment_Transaction + */ + protected function _beforeLoadByTxnId($txnId) + { + Mage::dispatchEvent( + $this->_eventPrefix . '_load_by_txn_id_before', + $this->_getEventData() + array('txn_id' => $txnId) + ); + return $this; + } + + /** + * Load self by specified transaction ID. Requires the valid payment object to be set + * @param string $txnId + * @return Mage_Paypal_Model_Payment_Transaction + */ + public function loadByTxnId($txnId) + { + $this->_beforeLoadByTxnId($txnId); + $this->getResource()->loadObjectByTxnId( + $this, $txnId + ); + $this->_afterLoadByTxnId(); + return $this; + } + + /** + * Check object after loading by by specified transaction ID + * @param $txnId + * @return Mage_Paypal_Model_Payment_Transaction + */ + 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 + * Doesn't allow to set arrays + * + * @param string $key + * @param mixed $value + * @return Mage_Paypal_Model_Order_Payment_Transaction + * @throws Mage_Core_Exception + */ + public function setAdditionalInformation($key, $value) + { + if (is_object($value)) { + Mage::throwException(Mage::helper('paypal')->__('Payment transactions disallow storing objects.')); + } + $info = $this->_getData('additional_information'); + if (!$info) { + $info = array(); + } + $info[$key] = $value; + return $this->setData('additional_information', $info); + } + + /** + * Getter for entire additional_information value or one of its element by key + * @param string $key + * @return array|null|mixed + */ + public function getAdditionalInformation($key = null) + { + $info = $this->_getData('additional_information'); + if (!$info) { + $info = array(); + } + if ($key) { + return (isset($info[$key]) ? $info[$key] : null); + } + return $info; + } + + /** + * Unsetter for entire additional_information value or one of its element by key + * @param string $key + * @return Mage_Paypal_Model_Payment_Transaction + */ + public function unsAdditionalInformation($key = null) + { + if ($key) { + $info = $this->_getData('additional_information'); + if (is_array($info)) { + unset($info[$key]); + } + } else { + $info = array(); + } + return $this->setData('additional_information', $info); + } + + /** + * Setter/Getter whether transaction is supposed to prevent exceptions on saving + * + * @param bool $failsafe + */ + public function isFailsafe($setFailsafe = null) + { + if (null === $setFailsafe) { + return $this->_isFailsafe; + } + $this->_isFailsafe = (bool)$setFailsafe; + return $this; + } + + /** + * Verify data required for saving + * @return Mage_Paypal_Model_Payment_Transaction + * @throws Mage_Core_Exception + */ + protected function _beforeSave() + { + if (!$this->getId()) { + $this->setCreatedAt(Mage::getModel('core/date')->gmtDate()); + } + return parent::_beforeSave(); + } + + /** + * Check whether specified transaction ID is valid + * @param string $txnId + * @throws Mage_Core_Exception + */ + protected function _verifyTxnId($txnId) + { + if (null !== $txnId && 0 == strlen($txnId)) { + Mage::throwException(Mage::helper('paypal')->__('Transaction ID must not be empty.')); + } + } + + /** + * Make sure this object is a valid transaction + * TODO for more restriction we can check for data consistency + * @throws Mage_Core_Exception + */ + protected function _verifyThisTransactionExists() + { + if (!$this->getId()) { + Mage::throwException(Mage::helper('paypal')->__('This operation requires an existing transaction 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 new file mode 100644 index 0000000000..cddaf8bcd3 --- /dev/null +++ b/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction.php @@ -0,0 +1,123 @@ + + */ +class Mage_Paypal_Model_Resource_Payment_Transaction extends Mage_Core_Model_Resource_Db_Abstract +{ + /** + * Serializeable field: additional_information + * + * @var array + */ + protected $_serializableFields = array( + 'additional_information' => array(null, array()) + ); + + /** + * Initialize main table and the primary key field name + * + */ + protected function _construct() + { + $this->_init('paypal/payment_transaction', 'transaction_id'); + } + + /** + * Load the transaction object by specified txn_id + * + * @param Mage_Paypal_Model_Payment_Transaction $transaction + * @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 + * + * @throws Mage_Core_Exception + * + * @param Mage_Core_Model_Abstract $transaction + * @return Mage_Paypal_Model_Resource_Payment_Transaction + */ + protected function _beforeSave(Mage_Core_Model_Abstract $transaction) + { + $txnId = $transaction->getData('txn_id'); + $idFieldName = $this->getIdFieldName(); + + // make sure unique key won't cause trouble + if ($transaction->isFailsafe()) { + $autoincrementId = (int)$this->_lookupByTxnId($txnId, $idFieldName); + if ($autoincrementId) { + $transaction->setData($idFieldName, $autoincrementId)->isObjectNew(false); + } + } + + return parent::_beforeSave($transaction); + } + + /** + * Load cell/row by specified unique key parts + * + * @param string $txnId + * @param mixed (array|string|object) $columns + * @param bool $isRow + * @return mixed (array|string) + */ + private function _lookupByTxnId($txnId, $columns, $isRow = false) + { + $select = $this->_getLoadByUniqueKeySelect($txnId, $columns); + if ($isRow) { + return $this->_getWriteAdapter()->fetchRow($select); + } + return $this->_getWriteAdapter()->fetchOne($select); + } + + /** + * Get select object for loading transaction by the unique key of order_id, payment_id, txn_id + * + * @param string $txnId + * @param string|array|Zend_Db_Expr $columns + * @return Varien_Db_Select + */ + private function _getLoadByUniqueKeySelect($txnId, $columns = '*') + { + return $this->_getWriteAdapter()->select() + ->from($this->getMainTable(), $columns) + ->where('txn_id = ?', $txnId); + } +} 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 new file mode 100644 index 0000000000..53adcfde91 --- /dev/null +++ b/app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction/Collection.php @@ -0,0 +1,96 @@ + + */ +class Mage_Paypal_Model_Resource_Payment_Transaction_Collection + extends Mage_Core_Model_Resource_Db_Collection_Abstract +{ + /** + * Created Before filter + * + * @var string + */ + protected $_createdBefore = ""; + /** + * Initialize collection items factory class + */ + protected function _construct() + { + $this->_init('paypal/payment_transaction'); + parent::_construct(); + } + + /** + * CreatedAt filter setter + * + * @param string $date + * @return Mage_Sales_Model_Resource_Order_Payment_Transaction_Collection + */ + public function addCreatedBeforeFilter($date) + { + $this->_createdBefore = $date; + return $this; + } + + /** + * Prepare filters + * + * @return Mage_Paypal_Model_Resource_Payment_Transaction_Collection + */ + protected function _beforeLoad() + { + parent::_beforeLoad(); + + if ($this->isLoaded()) { + return $this; + } + + // filters + if ($this->_createdBefore) { + $this->getSelect()->where('main_table.created_at < ?', $this->_createdBefore); + } + return $this; + } + + /** + * Unserialize additional_information in each item + * + * @return Mage_Paypal_Model_Resource_Payment_Transaction_Collection + */ + protected function _afterLoad() + { + foreach ($this->_items as $item) { + $this->getResource()->unserializeFields($item); + } + return parent::_afterLoad(); + } +} diff --git a/app/code/community/Find/Feed/Model/Adminhtml/System/Source/Cron/Hours.php b/app/code/core/Mage/Paypal/Model/System/Config/Source/AuthorizationAmounts.php similarity index 72% rename from app/code/community/Find/Feed/Model/Adminhtml/System/Source/Cron/Hours.php rename to app/code/core/Mage/Paypal/Model/System/Config/Source/AuthorizationAmounts.php index 6c238cc2ea..3160a23606 100644 --- a/app/code/community/Find/Feed/Model/Adminhtml/System/Source/Cron/Hours.php +++ b/app/code/core/Mage/Paypal/Model/System/Config/Source/AuthorizationAmounts.php @@ -18,33 +18,26 @@ * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * - * @category - * @package _storage + * @category Mage + * @package Mage_Paypal * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ - /** - * Source for cron hours - * - * @category Find - * @package Find_Feed + * Source model for available Authorization Amounts for Account Verification */ -class Find_Feed_Model_Adminhtml_System_Source_Cron_Hours +class Mage_Paypal_Model_System_Config_Source_AuthorizationAmounts { - /** - * Fetch options array - * + * Options getter + * * @return array */ public function toOptionArray() { - $hours = array(); - for ($i = 1; $i <= 24; $i++) { - $hours[] = array('label' => $i, 'value' => $i); - } - return $hours; + /** @var $configModel Mage_Paypal_Model_Config */ + $configModel = Mage::getModel('paypal/config'); + return $configModel->getAuthorizationAmounts(); } } diff --git a/app/code/core/Mage/Paypal/controllers/HostedproController.php b/app/code/core/Mage/Paypal/controllers/HostedproController.php index da175a0774..1de750d28d 100644 --- a/app/code/core/Mage/Paypal/controllers/HostedproController.php +++ b/app/code/core/Mage/Paypal/controllers/HostedproController.php @@ -107,7 +107,7 @@ protected function _getCheckout() /** * Get iframe block * - * @return Mage_Paypal_Block_Payflow_Link_Iframe + * @return Mage_Paypal_Block_Hosted_Pro_Iframe */ protected function _getIframeBlock() { diff --git a/app/code/core/Mage/Paypal/controllers/PayflowController.php b/app/code/core/Mage/Paypal/controllers/PayflowController.php index c6aa62155f..f9b6459a22 100644 --- a/app/code/core/Mage/Paypal/controllers/PayflowController.php +++ b/app/code/core/Mage/Paypal/controllers/PayflowController.php @@ -41,7 +41,7 @@ public function cancelPaymentAction() $gotoSection = $this->_cancelPayment(); $redirectBlock = $this->_getIframeBlock() ->setGotoSection($gotoSection) - ->setTemplate('paypal/hss/redirect.phtml'); + ->setTemplate('paypal/payflowlink/redirect.phtml'); $this->getResponse()->setBody($redirectBlock->toHtml()); } @@ -51,28 +51,20 @@ public function cancelPaymentAction() public function returnUrlAction() { $redirectBlock = $this->_getIframeBlock() - ->setTemplate('paypal/hss/redirect.phtml'); + ->setTemplate('paypal/payflowlink/redirect.phtml'); $session = $this->_getCheckout(); - if ($session->getLastRealOrderId()) { - $order = Mage::getModel('sales/order')->loadByIncrementId($session->getLastRealOrderId()); - - if ($order && $order->getIncrementId() == $session->getLastRealOrderId()) { - $allowedOrderStates = array( - Mage_Sales_Model_Order::STATE_PROCESSING, - Mage_Sales_Model_Order::STATE_COMPLETE - ); - if (in_array($order->getState(), $allowedOrderStates)) { - $session->unsLastRealOrderId(); - $redirectBlock->setGotoSuccessPage(true); - } else { - $gotoSection = $this->_cancelPayment(strval($this->getRequest()->getParam('RESPMSG'))); - $redirectBlock->setGotoSection($gotoSection); - $redirectBlock->setErrorMsg($this->__('Payment has been declined. Please try again.')); - } - } + $quote = $session->getQuote(); + /** @var $payment Mage_Sales_Model_Quote_Payment */ + $payment = $quote->getPayment(); + $gotoSection = 'payment'; + if ($payment->getAdditionalInformation('authorization_id')) { + $gotoSection = 'review'; + } else { + $gotoSection = 'payment'; + $redirectBlock->setErrorMsg($this->__('Payment has been declined. Please try again.')); } - + $redirectBlock->setGotoSection($gotoSection); $this->getResponse()->setBody($redirectBlock->toHtml()); } @@ -117,6 +109,28 @@ protected function _cancelPayment($errorMsg = '') */ public function formAction() { + $quote = $this->_getCheckout()->getQuote(); + $payment = $quote->getPayment(); + + try { + $method = Mage::helper('payment')->getMethodInstance(Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK); + $method->setData('info_instance', $payment); + $method->initialize($method->getConfigData('payment_action'), new Varien_Object()); + + $quote->save(); + } catch (Mage_Core_Exception $e) { + $this->loadLayout('paypal_payflow_link_iframe'); + + $block = $this->getLayout()->getBlock('payflow.link.info'); + $block->setErrorMessage($e->getMessage()); + + $this->getResponse()->setBody( + $block->toHtml() + ); + return; + } catch (Exception $e) { + Mage::logException($e); + } $this->getResponse() ->setBody($this->_getIframeBlock()->toHtml()); } diff --git a/app/code/core/Mage/Paypal/etc/config.xml b/app/code/core/Mage/Paypal/etc/config.xml index c4c0962c25..86a5feb541 100644 --- a/app/code/core/Mage/Paypal/etc/config.xml +++ b/app/code/core/Mage/Paypal/etc/config.xml @@ -28,7 +28,7 @@ - 1.6.0.0 + 1.6.0.1 @@ -53,6 +53,9 @@ paypal_cert
+ + paypal_payment_transaction
+
@@ -136,18 +139,18 @@ - + paypal/observer saveOrderAfterSubmit - + - + paypal/observer setResponseAfterSaveOrder - + @@ -260,7 +263,7 @@ paypal/hostedpro Payment by cards or by PayPal account - Authorization + Authorization paypal @@ -272,6 +275,14 @@ paypal/observer::fetchReports + + + */15 * * * * + + + paypal/observer::cleanTransactions + + diff --git a/app/code/core/Mage/Paypal/etc/system.xml b/app/code/core/Mage/Paypal/etc/system.xml index 6e43dc8ecf..76121ec119 100644 --- a/app/code/core/Mage/Paypal/etc/system.xml +++ b/app/code/core/Mage/Paypal/etc/system.xml @@ -1572,6 +1572,16 @@ 1 1 + + + Learn More]]> + payment/payflow_link/authorization_amount + select + paypal/system_config_source_authorizationAmounts + 15 + 1 + 1 + payment/payflow_link/allowspecific @@ -1615,22 +1625,23 @@ 1 1 - - + + + payment/payflow_link/vendor text - payment/payflow_link/user 45 1 1 - - - - payment/payflow_link/vendor + + + + If you do not have multiple users set up on your account, please re-enter your Vendor/Merchant Login here. text + payment/payflow_link/user 50 1 1 - + payment/payflow_link/pwd diff --git a/app/code/core/Mage/Paypal/sql/paypal_setup/upgrade-1.6.0.0-1.6.0.1.php b/app/code/core/Mage/Paypal/sql/paypal_setup/upgrade-1.6.0.0-1.6.0.1.php new file mode 100644 index 0000000000..3c633eb734 --- /dev/null +++ b/app/code/core/Mage/Paypal/sql/paypal_setup/upgrade-1.6.0.0-1.6.0.1.php @@ -0,0 +1,55 @@ +getConnection() + ->newTable($installer->getTable('paypal/payment_transaction')) + ->addColumn('transaction_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array( + 'identity' => true, + 'unsigned' => true, + 'nullable' => false, + 'primary' => true, + ), 'Entity Id') + ->addColumn('txn_id', Varien_Db_Ddl_Table::TYPE_TEXT, 100, array( + ), 'Txn Id') + ->addColumn('additional_information', Varien_Db_Ddl_Table::TYPE_BLOB, '64K', array( + ), 'Additional Information') + ->addColumn('created_at', Varien_Db_Ddl_Table::TYPE_TIMESTAMP, null, array( + ), 'Created At') + ->addIndex( + $installer->getIdxName( + 'paypal/payment_transaction', + array('txn_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), + array('txn_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)) + ->setComment('PayPal Payflow Link Payment Transaction'); +$installer->getConnection()->createTable($table); diff --git a/app/code/core/Mage/Poll/Block/ActivePoll.php b/app/code/core/Mage/Poll/Block/ActivePoll.php index eabc9db237..8643b8708d 100755 --- a/app/code/core/Mage/Poll/Block/ActivePoll.php +++ b/app/code/core/Mage/Poll/Block/ActivePoll.php @@ -112,7 +112,7 @@ public function getActivePollsIds() return $this->_pollModel ->setExcludeFilter($this->getVotedPollsIds()) ->setStoreFilter(Mage::app()->getStore()->getId()) - ->getCollection()->getAllIds(); + ->getAllIds(); } /** @@ -209,7 +209,7 @@ protected function _toHtml() $this->assign($data); Mage::getSingleton('core/session')->setJustVotedPoll(false); - + if ($this->_pollModel->isVoted($pollId) === true) { $this->setTemplate($this->_templates['results']); } else { diff --git a/app/code/core/Mage/Poll/Model/Poll.php b/app/code/core/Mage/Poll/Model/Poll.php index a940af8514..0ed6d6c17b 100644 --- a/app/code/core/Mage/Poll/Model/Poll.php +++ b/app/code/core/Mage/Poll/Model/Poll.php @@ -155,6 +155,16 @@ public function getRandomId() return $this->_getResource()->getRandomId($this); } + /** + * Get all ids for not closed polls + * + * @return array + */ + public function getAllIds() + { + return $this->_getResource()->getAllIds($this); + } + /** * Add vote to poll * diff --git a/app/code/core/Mage/Poll/Model/Resource/Poll.php b/app/code/core/Mage/Poll/Model/Resource/Poll.php index 8eb0e26af7..a8de3f194d 100755 --- a/app/code/core/Mage/Poll/Model/Resource/Poll.php +++ b/app/code/core/Mage/Poll/Model/Resource/Poll.php @@ -58,35 +58,57 @@ protected function _initUniqueFields() } /** - * Get random identifier not closed poll + * Get select object for not closed poll ids * * @param Mage_Poll_Model_Poll $object - * @return int + * @return */ - public function getRandomId($object) + protected function _getSelectIds($object) { $read = $this->_getReadAdapter(); - $select = $read->select(); + $select = $read->select() + ->from(array('main_table'=>$this->getMainTable()), $this->getIdFieldName()) + ->where('closed = ?', 0); - if ($object->getExcludeFilter()) { - $select->where('main_table.poll_id NOT IN(?)', $object->getExcludeFilter()); + $excludeIds = $object->getExcludeFilter(); + if ($excludeIds) { + $select->where('main_table.poll_id NOT IN(?)', $excludeIds); } - $select->from(array('main_table'=>$this->getMainTable()), $this->getIdFieldName()) - ->where('closed = :is_closed') - ->orderRand() - ->limit(1); - $bind = array(':is_closed' => 0); - if (($storeId = $object->getStoreFilter())) { + $storeId = $object->getStoreFilter(); + if ($storeId) { $select->join( array('store' => $this->getTable('poll/poll_store')), - 'main_table.poll_id=store.poll_id AND store.store_id = :store_id', + 'main_table.poll_id=store.poll_id AND store.store_id = ' . $read->quote($storeId), array() ); - $bind[':store_id'] = $storeId; } - return $read->fetchOne($select, $bind); + return $select; + } + + /** + * Get random identifier not closed poll + * + * @param Mage_Poll_Model_Poll $object + * @return int + */ + public function getRandomId($object) + { + $select = $this->_getSelectIds($object)->orderRand()->limit(1); + return $this->_getReadAdapter()->fetchOne($select); + } + + /** + * Get all ids for not closed polls + * + * @param Mage_Poll_Model_Poll $object + * @return array + */ + public function getAllIds($object) + { + $select = $this->_getSelectIds($object); + return $this->_getReadAdapter()->fetchCol($select); } /** diff --git a/app/code/core/Mage/Reports/etc/adminhtml.xml b/app/code/core/Mage/Reports/etc/adminhtml.xml index 5f87b73fc2..305f07debd 100644 --- a/app/code/core/Mage/Reports/etc/adminhtml.xml +++ b/app/code/core/Mage/Reports/etc/adminhtml.xml @@ -181,9 +181,9 @@ Products - + Bestsellers - + Products Ordered diff --git a/app/code/core/Mage/Rss/Block/Catalog/Category.php b/app/code/core/Mage/Rss/Block/Catalog/Category.php index d281d7b171..3d123c2a9e 100644 --- a/app/code/core/Mage/Rss/Block/Catalog/Category.php +++ b/app/code/core/Mage/Rss/Block/Catalog/Category.php @@ -77,7 +77,7 @@ protected function _toHtml() ; $productCollection = Mage::getModel('catalog/product')->getCollection(); - $currentyCateogry = $layer->setCurrentCategory($category); + $currentCategory = $layer->setCurrentCategory($category); $layer->prepareProductCollection($productCollection); $productCollection->addCountToCategories($_collection); @@ -85,7 +85,7 @@ protected function _toHtml() /* only load latest 50 products */ - $_productCollection = $currentyCateogry + $_productCollection = $currentCategory ->getProductCollection() ->addAttributeToSort('updated_at','desc') ->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds()) diff --git a/app/code/core/Mage/Rule/Model/Condition/Abstract.php b/app/code/core/Mage/Rule/Model/Condition/Abstract.php index 35e8bb8294..5646cc912e 100644 --- a/app/code/core/Mage/Rule/Model/Condition/Abstract.php +++ b/app/code/core/Mage/Rule/Model/Condition/Abstract.php @@ -52,6 +52,12 @@ abstract class Mage_Rule_Model_Condition_Abstract */ protected $_defaultOperatorInputByType = null; + /** + * List of input types for values which should be array + * @var array + */ + protected $_arrayInputTypes = array(); + public function __construct() { parent::__construct(); @@ -83,6 +89,7 @@ public function getDefaultOperatorInputByType() 'multiselect' => array('{}', '!{}', '()', '!()'), 'grid' => array('()', '!()'), ); + $this->_arrayInputTypes = array('multiselect', 'grid'); } return $this->_defaultOperatorInputByType; } @@ -210,11 +217,7 @@ public function getInputType() public function getOperatorSelectOptions() { - if ($this->getAttribute() === 'category_ids') { - $type = 'multiselect'; - } else { - $type = $this->getInputType(); - } + $type = $this->getInputType(); $opt = array(); $operatorByType = $this->getOperatorByInputType(); foreach ($this->getOperatorOption() as $k => $v) { @@ -252,17 +255,34 @@ public function getValueSelectOptions() return $opt; } + /** + * Retrieve parsed value + * + * @return array|string|int|float + */ public function getValueParsed() { - $value = $this->getData('value'); - - $op = $this->getOperator(); - if (($op === '{}' || $op === '!{}' || $op === '()' || $op === '!()') && is_scalar($value)) { - $value = preg_split('#\s*[,;]\s*#', $value, null, PREG_SPLIT_NO_EMPTY); - $this->setValue($value); + if (!$this->hasValueParsed()) { + $value = $this->getData('value'); + if ($this->isArrayOperatorType() && is_string($value)) { + $value = preg_split('#\s*[,;]\s*#', $value, null, PREG_SPLIT_NO_EMPTY); + } + $this->setValueParsed($value); } + return $this->getData('value_parsed'); + } - return $value; + /** + * Check if value should be array + * + * Depends on operator input type + * + * @return bool + */ + public function isArrayOperatorType() + { + $op = $this->getOperator(); + return $op === '()' || $op === '!()' || in_array($this->getInputType(), $this->_arrayInputTypes); } public function getValue() @@ -513,16 +533,10 @@ public function validateAttribute($validatedValue) /** * Comparison operator */ - $op = $this->getOperator(); + $op = $this->getOperatorForValidate(); // if operator requires array and it is not, or on opposite, return false - if (( - ($op == '()' || $op == '!()' || $op == '{}' || $op == '!{}') - && !is_array($value) - ) || ( - !($op == '()' || $op == '!()' || $op == '{}' || $op == '!{}' || $op == '==' || $op == '!=') - && is_array($value) - )) { + if ($this->isArrayOperatorType() xor is_array($value)) { return false; } @@ -539,24 +553,24 @@ public function validateAttribute($validatedValue) } } else { if (is_array($validatedValue)) { - $result = in_array($value, $validatedValue); + $result = count($validatedValue) == 1 && array_shift($validatedValue) == $value; } else { - $result = $validatedValue == $value; + $result = $this->_compareValues($validatedValue, $value); } } break; case '<=': case '>': - if (is_array($validatedValue) || is_null($validatedValue)) { - $result = false; + if (!is_scalar($validatedValue)) { + return false; } else { $result = $validatedValue <= $value; } break; case '>=': case '<': - if (is_array($validatedValue) || is_null($validatedValue)) { - $result = false; + if (!is_scalar($validatedValue)) { + return false; } else { $result = $validatedValue >= $value; } @@ -579,9 +593,9 @@ public function validateAttribute($validatedValue) } } else { if (is_array($validatedValue)) { - $result = false; + $result = in_array($value, $validatedValue); } else { - $result = stripos((string)$validatedValue, (string)$value) !== false; + $result = $this->_compareValues($value, $validatedValue, false); } } break; @@ -590,7 +604,13 @@ public function validateAttribute($validatedValue) if (is_array($validatedValue)) { $result = count(array_intersect($validatedValue, (array)$value))>0; } else { - $result = in_array($validatedValue, (array)$value); + $value = (array)$value; + foreach ($value as $item) { + if ($this->_compareValues($validatedValue, $item)) { + $result = true; + break; + } + } } break; } @@ -602,8 +622,38 @@ public function validateAttribute($validatedValue) return $result; } + /** + * Case and type insensitive comparison of values + * + * @param string|int|float $validatedValue + * @param string|int|float $value + * @return bool + */ + protected function _compareValues($validatedValue, $value, $strict = true) + { + if ($strict && is_numeric($validatedValue) && is_numeric($value)) { + return $validatedValue == $value; + } else { + $validatePattern = preg_quote($validatedValue, '~'); + if ($strict) { + $validatePattern = '^' . $validatePattern . '$'; + } + return (bool)preg_match('~' . $validatePattern . '~iu', $value); + } + } + 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/Sales/Block/Adminhtml/Customer/Edit/Tab/Agreement.php b/app/code/core/Mage/Sales/Block/Adminhtml/Customer/Edit/Tab/Agreement.php index 57e80d86e6..d420dac074 100644 --- a/app/code/core/Mage/Sales/Block/Adminhtml/Customer/Edit/Tab/Agreement.php +++ b/app/code/core/Mage/Sales/Block/Adminhtml/Customer/Edit/Tab/Agreement.php @@ -44,9 +44,9 @@ class Mage_Sales_Block_Adminhtml_Customer_Edit_Tab_Agreement * Disable filters and paging * */ - public function _construct() + public function __construct() { - parent::_construct(); + parent::__construct(); $this->setId('customer_edit_tab_agreements'); } 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 3baa754df9..1a89433237 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 @@ -37,9 +37,9 @@ class Mage_Sales_Block_Adminhtml_Customer_Edit_Tab_Recurring_Profile * Disable filters and paging * */ - public function _construct() + public function __construct() { - parent::_construct(); + parent::__construct(); $this->setId('customer_edit_tab_recurring_profile'); } @@ -109,4 +109,14 @@ public function getAfter() { return 'orders'; } + + /** + * Return grid url + * + * @return string + */ + public function getGridUrl() + { + return $this->getUrl('*/sales_recurring_profile/customerGrid', array('_current' => true)); + } } diff --git a/app/code/core/Mage/Sales/Model/Convert/Quote.php b/app/code/core/Mage/Sales/Model/Convert/Quote.php index e44df96448..c21886522e 100644 --- a/app/code/core/Mage/Sales/Model/Convert/Quote.php +++ b/app/code/core/Mage/Sales/Model/Convert/Quote.php @@ -132,7 +132,8 @@ public function itemToOrderItem(Mage_Sales_Model_Quote_Item_Abstract $item) ->setProductType($item->getProductType()) ->setQtyBackordered($item->getBackorders()) ->setProduct($item->getProduct()) - ->setBaseOriginalPrice($item->getBaseOriginalPrice()); + ->setBaseOriginalPrice($item->getBaseOriginalPrice()) + ; $options = $item->getProductOrderOptions(); if (!$options) { diff --git a/app/code/core/Mage/Sales/Model/Order.php b/app/code/core/Mage/Sales/Model/Order.php index 7d522cfb66..95dd618a8e 100644 --- a/app/code/core/Mage/Sales/Model/Order.php +++ b/app/code/core/Mage/Sales/Model/Order.php @@ -635,8 +635,9 @@ public function canCreditmemo() /** * We can have problem with float in php (on some server $a=762.73;$b=762.73; $a-$b!=0) * for this we have additional diapason for 0 + * TotalPaid - contains amount, that were not rounded. */ - if (abs($this->getTotalPaid() - $this->getTotalRefunded()) < .0001) { + if (abs($this->getStore()->roundPrice($this->getTotalPaid()) - $this->getTotalRefunded()) < .0001) { return false; } diff --git a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Total/Shipping.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Total/Shipping.php index 28a0b9a8c8..927b9e0415 100644 --- a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Total/Shipping.php +++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Total/Shipping.php @@ -33,6 +33,12 @@ */ class Mage_Sales_Model_Order_Creditmemo_Total_Shipping extends Mage_Sales_Model_Order_Creditmemo_Total_Abstract { + /** + * Collects information about shipping charges + * + * @param Mage_Sales_Model_Order_Creditmemo $creditmemo Credit Memo object + * @return Mage_Sales_Model_Order_Creditmemo_Total_Shipping + */ public function collect(Mage_Sales_Model_Order_Creditmemo $creditmemo) { $order = $creditmemo->getOrder(); @@ -46,6 +52,12 @@ public function collect(Mage_Sales_Model_Order_Creditmemo $creditmemo) $isShippingInclTax = Mage::getSingleton('tax/config')->displaySalesShippingInclTax($order->getStoreId()); + if ($baseShipping != 0) { + $baseAllowedTaxAmount = $order->getBaseShippingTaxAmount() - $order->getBaseShippingTaxRefunded(); + $baseShippingInclTax = Mage::app()->getStore()->roundPrice($baseAllowedAmount + $baseAllowedTaxAmount); + } + $baseAllowedAmount = $baseShippingInclTax - $order->getBaseShippingRefunded(); + /** * Check if shipping amount was specified (from invoice or another source). * Using has magic method to allow setting 0 as shipping amount. @@ -88,10 +100,7 @@ public function collect(Mage_Sales_Model_Order_Creditmemo $creditmemo) } else { if ($baseShipping != 0) { $allowedTaxAmount = $order->getShippingTaxAmount() - $order->getShippingTaxRefunded(); - $baseAllowedTaxAmount = $order->getBaseShippingTaxAmount() - $order->getBaseShippingTaxRefunded(); - $shippingInclTax = Mage::app()->getStore()->roundPrice($allowedAmount + $allowedTaxAmount); - $baseShippingInclTax = Mage::app()->getStore()->roundPrice($baseAllowedAmount + $baseAllowedTaxAmount); } $shipping = $allowedAmount; $baseShipping = $baseAllowedAmount; diff --git a/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Subtotal.php b/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Subtotal.php index 9a9a9330e8..0ed5d0affa 100644 --- a/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Subtotal.php +++ b/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Subtotal.php @@ -58,9 +58,9 @@ public function collect(Mage_Sales_Model_Order_Invoice $invoice) $allowedSubtotal = $order->getSubtotal() - $order->getSubtotalInvoiced(); $baseAllowedSubtotal = $order->getBaseSubtotal() -$order->getBaseSubtotalInvoiced(); $allowedSubtotalInclTax = $allowedSubtotal + $order->getHiddenTaxAmount() - + $order->getTaxAmount() - $order->getTaxInvoiced(); + + $order->getTaxAmount() - $order->getTaxInvoiced() - $order->getShippingTaxAmount(); $baseAllowedSubtotalInclTax = $baseAllowedSubtotal + $order->getBaseHiddenTaxAmount() - + $order->getBaseTaxAmount() - $order->getBaseTaxInvoiced(); + + $order->getBaseTaxAmount() - $order->getBaseTaxInvoiced() - $order->getBaseShippingTaxAmount(); if ($invoice->isLast()) { $subtotal = $allowedSubtotal; 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 7406bb5510..c0b09b9111 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 @@ -66,32 +66,44 @@ public function getTotalsForDisplay() */ public function getFullTaxInfo() { - $rates = Mage::getResourceModel('sales/order_tax_collection')->loadByOrder($this->getOrder())->toArray(); - $fullInfo = Mage::getSingleton('tax/calculation')->reproduceProcess($rates['items']); - $fontSize = $this->getFontSize() ? $this->getFontSize() : 7; - $tax_info = array(); + $taxClassAmount = Mage::helper('tax')->getCalculatedTaxes($this->getOrder()); + $fontSize = $this->getFontSize() ? $this->getFontSize() : 7; - if ($fullInfo) { - foreach ($fullInfo as $info) { - if (isset($info['hidden']) && $info['hidden']) { - continue; - } + if (!empty($taxClassAmount)) { + foreach ($taxClassAmount as &$tax) { + $percent = $tax['percent'] ? ' (' . $tax['percent']. '%)' : ''; + $tax['amount'] = $this->getAmountPrefix().$this->getOrder()->formatPriceTxt($tax['tax_amount']); + $tax['label'] = Mage::helper('tax')->__($tax['title']) . $percent . ':'; + $tax['font_size'] = $fontSize; + } + } else { + $rates = Mage::getResourceModel('sales/order_tax_collection')->loadByOrder($this->getOrder())->toArray(); + $fullInfo = Mage::getSingleton('tax/calculation')->reproduceProcess($rates['items']); + $tax_info = array(); - $_amount = $info['amount']; + if ($fullInfo) { + foreach ($fullInfo as $info) { + if (isset($info['hidden']) && $info['hidden']) { + continue; + } - foreach ($info['rates'] as $rate) { - $percent = $rate['percent'] ? ' (' . $rate['percent']. '%)' : ''; + $_amount = $info['amount']; - $tax_info[] = array( - 'amount' => $this->getAmountPrefix().$this->getOrder()->formatPriceTxt($_amount), - 'label' => Mage::helper('tax')->__($rate['title']) . $percent . ':', - 'font_size' => $fontSize - ); - } - } - } + foreach ($info['rates'] as $rate) { + $percent = $rate['percent'] ? ' (' . $rate['percent']. '%)' : ''; - return $tax_info; + $tax_info[] = array( + 'amount' => $this->getAmountPrefix() . $this->getOrder()->formatPriceTxt($_amount), + 'label' => Mage::helper('tax')->__($rate['title']) . $percent . ':', + 'font_size' => $fontSize + ); + } + } + } + $taxClassAmount = $tax_info; + } + + return $taxClassAmount; } /** 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 0da95d358d..01720951eb 100755 --- a/app/code/core/Mage/Sales/Model/Resource/Report/Order.php +++ b/app/code/core/Mage/Sales/Model/Resource/Report/Order.php @@ -44,7 +44,7 @@ protected function _construct() } /** - * Aggregate Orders data by order created at + * Aggregate Orders data * * @param mixed $from * @param mixed $to @@ -52,193 +52,10 @@ protected function _construct() */ public function aggregate($from = null, $to = null) { - // convert input dates to UTC to be comparable with DATETIME fields in DB - $from = $this->_dateToUtc($from); - $to = $this->_dateToUtc($to); + Mage::getResourceModel('sales/report_order_createdat')->aggregate($from, $to); + Mage::getResourceModel('sales/report_order_updatedat')->aggregate($from, $to); + $this->_setFlagData(Mage_Reports_Model_Flag::REPORT_ORDER_FLAG_CODE); - $this->_checkDates($from, $to); - $adapter = $this->_getWriteAdapter(); - - $adapter->beginTransaction(); - - try { - if ($from !== null || $to !== null) { - $subSelect = $this->_getTableDateRangeSelect( - $this->getTable('sales/order'), - 'created_at', 'updated_at', $from, $to - ); - } else { - $subSelect = null; - } - $this->_clearTableByDateRange($this->getMainTable(), $from, $to, $subSelect); - - $periodExpr = $adapter->getDatePartSql( - $this->getStoreTZOffsetQuery(array('o' => $this->getTable('sales/order')), 'o.created_at', $from, $to) - ); - // Columns list - $columns = array( - // convert dates from UTC to current admin timezone - 'period' => $periodExpr, - 'store_id' => 'o.store_id', - 'order_status' => 'o.status', - 'orders_count' => new Zend_Db_Expr('COUNT(o.entity_id)'), - 'total_qty_ordered' => new Zend_Db_Expr('SUM(oi.total_qty_ordered)'), - 'total_qty_invoiced' => new Zend_Db_Expr('SUM(oi.total_qty_invoiced)'), - 'total_income_amount' => new Zend_Db_Expr( - sprintf('SUM((%s - %s) * %s)', - $adapter->getIfNullSql('o.base_grand_total', 0), - $adapter->getIfNullSql('o.base_total_canceled',0), - $adapter->getIfNullSql('o.base_to_global_rate',0) - ) - ), - 'total_revenue_amount' => new Zend_Db_Expr( - sprintf('SUM((%s - %s - %s - (%s - %s - %s)) * %s)', - $adapter->getIfNullSql('o.base_total_invoiced', 0), - $adapter->getIfNullSql('o.base_tax_invoiced', 0), - $adapter->getIfNullSql('o.base_shipping_invoiced', 0), - $adapter->getIfNullSql('o.base_total_refunded', 0), - $adapter->getIfNullSql('o.base_tax_refunded', 0), - $adapter->getIfNullSql('o.base_shipping_refunded', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_profit_amount' => new Zend_Db_Expr( - sprintf('SUM((%s - %s - %s - %s - %s) * %s)', - $adapter->getIfNullSql('o.base_total_paid', 0), - $adapter->getIfNullSql('o.base_total_refunded', 0), - $adapter->getIfNullSql('o.base_tax_invoiced', 0), - $adapter->getIfNullSql('o.base_shipping_invoiced', 0), - $adapter->getIfNullSql('o.base_total_invoiced_cost', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_invoiced_amount' => new Zend_Db_Expr( - sprintf('SUM(%s * %s)', - $adapter->getIfNullSql('o.base_total_invoiced', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_canceled_amount' => new Zend_Db_Expr( - sprintf('SUM(%s * %s)', - $adapter->getIfNullSql('o.base_total_canceled', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_paid_amount' => new Zend_Db_Expr( - sprintf('SUM(%s * %s)', - $adapter->getIfNullSql('o.base_total_paid', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_refunded_amount' => new Zend_Db_Expr( - sprintf('SUM(%s * %s)', - $adapter->getIfNullSql('o.base_total_refunded', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_tax_amount' => new Zend_Db_Expr( - sprintf('SUM((%s - %s) * %s)', - $adapter->getIfNullSql('o.base_tax_amount', 0), - $adapter->getIfNullSql('o.base_tax_canceled', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_tax_amount_actual' => new Zend_Db_Expr( - sprintf('SUM((%s -%s) * %s)', - $adapter->getIfNullSql('o.base_tax_invoiced', 0), - $adapter->getIfNullSql('o.base_tax_refunded', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_shipping_amount' => new Zend_Db_Expr( - sprintf('SUM((%s - %s) * %s)', - $adapter->getIfNullSql('o.base_shipping_amount', 0), - $adapter->getIfNullSql('o.base_shipping_canceled', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_shipping_amount_actual' => new Zend_Db_Expr( - sprintf('SUM((%s - %s) * %s)', - $adapter->getIfNullSql('o.base_shipping_invoiced', 0), - $adapter->getIfNullSql('o.base_shipping_refunded', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_discount_amount' => new Zend_Db_Expr( - sprintf('SUM((ABS(%s) - %s) * %s)', - $adapter->getIfNullSql('o.base_discount_amount', 0), - $adapter->getIfNullSql('o.base_discount_canceled', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ), - 'total_discount_amount_actual' => new Zend_Db_Expr( - sprintf('SUM((%s - %s) * %s)', - $adapter->getIfNullSql('o.base_discount_invoiced', 0), - $adapter->getIfNullSql('o.base_discount_refunded', 0), - $adapter->getIfNullSql('o.base_to_global_rate', 0) - ) - ) - ); - - $select = $adapter->select(); - $selectOrderItem = $adapter->select(); - - $qtyCanceledExpr = $adapter->getIfNullSql('qty_canceled', 0); - $cols = array( - 'order_id' => 'order_id', - 'total_qty_ordered' => new Zend_Db_expr("SUM(qty_ordered - {$qtyCanceledExpr})"), - 'total_qty_invoiced' => new Zend_Db_expr('SUM(qty_invoiced)'), - ); - $selectOrderItem->from($this->getTable('sales/order_item'), $cols) - ->where('parent_item_id IS NULL') - ->group('order_id'); - - $select->from(array('o' => $this->getTable('sales/order')), $columns) - ->join(array('oi' => $selectOrderItem), 'oi.order_id = o.entity_id', array()) - ->where('o.state NOT IN (?)', array( - Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, - Mage_Sales_Model_Order::STATE_NEW - )); - - if ($subSelect !== null) { - $select->having($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); - } - - $select->group(array( - $periodExpr, - 'o.store_id', - 'o.status', - )); - - $adapter->query($select->insertFromSelect($this->getMainTable(), array_keys($columns))); - - // setup all columns to select SUM() except period, store_id and order_status - foreach ($columns as $k => $v) { - $columns[$k] = new Zend_Db_expr('SUM(' . $k . ')'); - } - $columns['period'] = 'period'; - $columns['store_id'] = new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID); - $columns['order_status'] = 'order_status'; - - $select->reset(); - $select->from($this->getMainTable(), $columns) - ->where('store_id <> 0'); - - if ($subSelect !== null) { - $select->where($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); - } - - $select->group(array( - 'period', - 'order_status' - )); - $adapter->query($select->insertFromSelect($this->getMainTable(), array_keys($columns))); - $this->_setFlagData(Mage_Reports_Model_Flag::REPORT_ORDER_FLAG_CODE); - $adapter->commit(); - } catch (Exception $e) { - $adapter->rollBack(); - throw $e; - } return $this; } } diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Collection.php index 49a4d65339..8ec0b8c7e7 100755 --- a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Collection.php +++ b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Collection.php @@ -41,6 +41,13 @@ class Mage_Sales_Model_Resource_Report_Order_Collection extends Mage_Sales_Model */ protected $_periodFormat; + /** + * Aggregated Data Table + * + * @var string + */ + protected $_aggregationTable = 'sales/order_aggregated_created'; + /** * Selected columns * @@ -56,7 +63,7 @@ public function __construct() { parent::_construct(); $this->setModel('adminhtml/report_item'); - $this->_resource = Mage::getResourceModel('sales/report')->init('sales/order_aggregated_created'); + $this->_resource = Mage::getResourceModel('sales/report')->init($this->_aggregationTable); $this->setConnection($this->getResource()->getReadConnection()); } 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 new file mode 100644 index 0000000000..69deb503f7 --- /dev/null +++ b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Createdat.php @@ -0,0 +1,260 @@ + + */ +class Mage_Sales_Model_Resource_Report_Order_Createdat extends Mage_Sales_Model_Resource_Report_Abstract +{ + /** + * Model initialization + * + */ + protected function _construct() + { + $this->_init('sales/order_aggregated_created', 'id'); + } + + /** + * Aggregate Orders data by order created at + * + * @param mixed $from + * @param mixed $to + * @return Mage_Sales_Model_Resource_Report_Order_Createdat + */ + public function aggregate($from = null, $to = null) + { + return $this->_aggregateByField('created_at', $from, $to); + } + + /** + * Aggregate Orders data by custom field + * + * @throws Exception + * @param string $aggregationField + * @param mixed $from + * @param mixed $to + * @return Mage_Sales_Model_Resource_Report_Order_Createdat + */ + protected function _aggregateByField($aggregationField, $from, $to) + { + // convert input dates to UTC to be comparable with DATETIME fields in DB + $from = $this->_dateToUtc($from); + $to = $this->_dateToUtc($to); + + $this->_checkDates($from, $to); + $adapter = $this->_getWriteAdapter(); + + $adapter->beginTransaction(); + try { + + if ($from !== null || $to !== null) { + $subSelect = $this->_getTableDateRangeSelect( + $this->getTable('sales/order'), + 'created_at', 'updated_at', $from, $to + ); + } else { + $subSelect = null; + } + $this->_clearTableByDateRange($this->getMainTable(), $from, $to, $subSelect); + + $periodExpr = $adapter->getDatePartSql($this->getStoreTZOffsetQuery( + array('o' => $this->getTable('sales/order')), + 'o.' . $aggregationField, + $from, $to + )); + // Columns list + $columns = array( + // convert dates from UTC to current admin timezone + 'period' => $periodExpr, + 'store_id' => 'o.store_id', + 'order_status' => 'o.status', + 'orders_count' => new Zend_Db_Expr('COUNT(o.entity_id)'), + 'total_qty_ordered' => new Zend_Db_Expr('SUM(oi.total_qty_ordered)'), + 'total_qty_invoiced' => new Zend_Db_Expr('SUM(oi.total_qty_invoiced)'), + 'total_income_amount' => new Zend_Db_Expr( + sprintf('SUM((%s - %s) * %s)', + $adapter->getIfNullSql('o.base_grand_total', 0), + $adapter->getIfNullSql('o.base_total_canceled',0), + $adapter->getIfNullSql('o.base_to_global_rate',0) + ) + ), + 'total_revenue_amount' => new Zend_Db_Expr( + sprintf('SUM((%s - %s - %s - (%s - %s - %s)) * %s)', + $adapter->getIfNullSql('o.base_total_invoiced', 0), + $adapter->getIfNullSql('o.base_tax_invoiced', 0), + $adapter->getIfNullSql('o.base_shipping_invoiced', 0), + $adapter->getIfNullSql('o.base_total_refunded', 0), + $adapter->getIfNullSql('o.base_tax_refunded', 0), + $adapter->getIfNullSql('o.base_shipping_refunded', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_profit_amount' => new Zend_Db_Expr( + sprintf('SUM((%s - %s - %s - %s - %s) * %s)', + $adapter->getIfNullSql('o.base_total_paid', 0), + $adapter->getIfNullSql('o.base_total_refunded', 0), + $adapter->getIfNullSql('o.base_tax_invoiced', 0), + $adapter->getIfNullSql('o.base_shipping_invoiced', 0), + $adapter->getIfNullSql('o.base_total_invoiced_cost', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_invoiced_amount' => new Zend_Db_Expr( + sprintf('SUM(%s * %s)', + $adapter->getIfNullSql('o.base_total_invoiced', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_canceled_amount' => new Zend_Db_Expr( + sprintf('SUM(%s * %s)', + $adapter->getIfNullSql('o.base_total_canceled', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_paid_amount' => new Zend_Db_Expr( + sprintf('SUM(%s * %s)', + $adapter->getIfNullSql('o.base_total_paid', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_refunded_amount' => new Zend_Db_Expr( + sprintf('SUM(%s * %s)', + $adapter->getIfNullSql('o.base_total_refunded', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_tax_amount' => new Zend_Db_Expr( + sprintf('SUM((%s - %s) * %s)', + $adapter->getIfNullSql('o.base_tax_amount', 0), + $adapter->getIfNullSql('o.base_tax_canceled', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_tax_amount_actual' => new Zend_Db_Expr( + sprintf('SUM((%s -%s) * %s)', + $adapter->getIfNullSql('o.base_tax_invoiced', 0), + $adapter->getIfNullSql('o.base_tax_refunded', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_shipping_amount' => new Zend_Db_Expr( + sprintf('SUM((%s - %s) * %s)', + $adapter->getIfNullSql('o.base_shipping_amount', 0), + $adapter->getIfNullSql('o.base_shipping_canceled', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_shipping_amount_actual' => new Zend_Db_Expr( + sprintf('SUM((%s - %s) * %s)', + $adapter->getIfNullSql('o.base_shipping_invoiced', 0), + $adapter->getIfNullSql('o.base_shipping_refunded', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_discount_amount' => new Zend_Db_Expr( + sprintf('SUM((ABS(%s) - %s) * %s)', + $adapter->getIfNullSql('o.base_discount_amount', 0), + $adapter->getIfNullSql('o.base_discount_canceled', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ), + 'total_discount_amount_actual' => new Zend_Db_Expr( + sprintf('SUM((%s - %s) * %s)', + $adapter->getIfNullSql('o.base_discount_invoiced', 0), + $adapter->getIfNullSql('o.base_discount_refunded', 0), + $adapter->getIfNullSql('o.base_to_global_rate', 0) + ) + ) + ); + + $select = $adapter->select(); + $selectOrderItem = $adapter->select(); + + $qtyCanceledExpr = $adapter->getIfNullSql('qty_canceled', 0); + $cols = array( + 'order_id' => 'order_id', + 'total_qty_ordered' => new Zend_Db_expr("SUM(qty_ordered - {$qtyCanceledExpr})"), + 'total_qty_invoiced' => new Zend_Db_expr('SUM(qty_invoiced)'), + ); + $selectOrderItem->from($this->getTable('sales/order_item'), $cols) + ->where('parent_item_id IS NULL') + ->group('order_id'); + + $select->from(array('o' => $this->getTable('sales/order')), $columns) + ->join(array('oi' => $selectOrderItem), 'oi.order_id = o.entity_id', array()) + ->where('o.state NOT IN (?)', array( + Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, + Mage_Sales_Model_Order::STATE_NEW + )); + + if ($subSelect !== null) { + $select->having($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); + } + + $select->group(array( + $periodExpr, + 'o.store_id', + 'o.status', + )); + + $adapter->query($select->insertFromSelect($this->getMainTable(), array_keys($columns))); + + // setup all columns to select SUM() except period, store_id and order_status + foreach ($columns as $k => $v) { + $columns[$k] = new Zend_Db_expr('SUM(' . $k . ')'); + } + $columns['period'] = 'period'; + $columns['store_id'] = new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID); + $columns['order_status'] = 'order_status'; + + $select->reset(); + $select->from($this->getMainTable(), $columns) + ->where('store_id <> 0'); + + if ($subSelect !== null) { + $select->where($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); + } + + $select->group(array( + 'period', + 'order_status' + )); + $adapter->query($select->insertFromSelect($this->getMainTable(), array_keys($columns))); + $adapter->commit(); + } catch (Exception $e) { + $adapter->rollBack(); + throw $e; + } + + return $this; + } +} 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 new file mode 100644 index 0000000000..65b56a7206 --- /dev/null +++ b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Updatedat.php @@ -0,0 +1,57 @@ + + */ +class Mage_Sales_Model_Resource_Report_Order_Updatedat extends Mage_Sales_Model_Resource_Report_Order_Createdat +{ + /** + * Model initialization + * + */ + protected function _construct() + { + $this->_init('sales/order_aggregated_updated', 'id'); + } + + /** + * Aggregate Orders data by order updated at + * + * @param mixed $from + * @param mixed $to + * @return Mage_Sales_Model_Resource_Report_Order_Updatedat + */ + public function aggregate($from = null, $to = null) + { + return $this->_aggregateByField('updated_at', $from, $to); + } +} diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Updatedat/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Updatedat/Collection.php index 6e7c732ef6..98e63cca62 100755 --- a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Updatedat/Collection.php +++ b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Updatedat/Collection.php @@ -33,261 +33,12 @@ * @author Magento Core Team */ class Mage_Sales_Model_Resource_Report_Order_Updatedat_Collection - extends Mage_Sales_Model_Resource_Report_Collection_Abstract + extends Mage_Sales_Model_Resource_Report_Order_Collection { /** - * Period format + * Aggregated Data Table * * @var string */ - protected $_periodFormat; - - /** - * Is inited - * - * @var bool - */ - protected $_inited = false; - - /** - * Selected columns - * - * @var array - */ - protected $_selectedColumns = array(); - - /** - * Initialize custom resource model - * - */ - public function __construct() - { - parent::_construct(); - $this->setModel('adminhtml/report_item'); - $this->_resource = Mage::getResourceModel('sales/report')->init('sales/order', 'entity_id'); - $this->setConnection($this->getResource()->getReadConnection()); - } - - /** - * Apply stores filter - * - * @return Mage_Sales_Model_Resource_Report_Order_Updatedat_Collection - */ - protected function _applyStoresFilter() - { - $nullCheck = false; - $storeIds = $this->_storesIds; - - if (!is_array($storeIds)) { - $storeIds = array($storeIds); - } - - $storeIds = array_unique($storeIds); - - if ($index = array_search(null, $storeIds)) { - unset($storeIds[$index]); - $nullCheck = true; - } - - if ($nullCheck) { - $this->getSelect()->where('store_id IN(?) OR store_id IS NULL', $storeIds); - } elseif ($storeIds[0] != '') { - $this->getSelect()->where('store_id IN(?)', $storeIds); - } - - return $this; - } - - /** - * Apply order status filter - * - * @return Mage_Sales_Model_Resource_Report_Order_Updatedat_Collection - */ - protected function _applyOrderStatusFilter() - { - if (is_null($this->_orderStatus)) { - return $this; - } - $orderStatus = $this->_orderStatus; - if (!is_array($orderStatus)) { - $orderStatus = array($orderStatus); - } - $this->getSelect()->where('status IN(?)', $orderStatus); - return $this; - } - - /** - * Retrieve array of columns to select - * - * @return array - */ - protected function _getSelectedColumns() - { - $adapter = $this->getConnection(); - $ifnullBaseTotalCanceled = $adapter->getIfNullSql('e.base_total_canceled', 0); - $totalIncomeAmount = "SUM((e.base_grand_total - {$ifnullBaseTotalCanceled}) * e.base_to_global_rate)"; - - $ifnullBaseTotalRefunded = $adapter->getIfNullSql('e.base_total_refunded', 0); - $ifnullBaseTaxInvoiced = $adapter->getIfNullSql('e.base_tax_invoiced', 0); - $ifnullBaseShippingInvoiced = $adapter->getIfNullSql('e.base_shipping_invoiced', 0); - $ifnullBaseTotalInvoiced = $adapter->getIfNullSql('e.base_total_invoiced', 0); - $ifnullBaseTaxRefunded = $adapter->getIfNullSql('e.base_tax_refunded', 0); - $ifnullBaseShippingRefunded = $adapter->getIfNullSql('e.base_shipping_refunded', 0); - - $totalRevenueAmount = new Zend_Db_Expr( - sprintf('SUM((%s - %s - %s - (%s - %s - %s)) * e.base_to_global_rate)', - $ifnullBaseTotalInvoiced, - $ifnullBaseTaxInvoiced, - $ifnullBaseShippingInvoiced, - $ifnullBaseTotalRefunded, - $ifnullBaseTaxRefunded, - $ifnullBaseShippingRefunded - ) - ); - - $ifnullBaseTotalInvoicedCost = $adapter->getIfNullSql('e.base_total_invoiced_cost', 0); - $totalProfitAmountSum = new Zend_Db_Expr( - sprintf('SUM((e.base_total_paid - %s - %s - %s - %s) * e.base_to_global_rate)', - $ifnullBaseTotalRefunded, - $ifnullBaseTaxInvoiced, - $ifnullBaseShippingInvoiced, - $ifnullBaseTotalInvoicedCost - ) - ); - - $ifnullBaseTaxCanceled = $adapter->getIfNullSql('e.base_tax_canceled', 0); - $sumTotalTaxAmount = new Zend_Db_Expr( - "SUM((e.base_tax_amount - {$ifnullBaseTaxCanceled}) * e.base_to_global_rate)" - ); - - $sumTotalTaxAmountActual = new Zend_Db_Expr( - "SUM((e.base_tax_invoiced - {$ifnullBaseTaxRefunded}) * e.base_to_global_rate)" - ); - - $ifnullBaseShippingCanceled = $adapter->getIfNullSql('e.base_shipping_canceled', 0); - $sumTotalShippingAmount = new Zend_Db_Expr( - "SUM((e.base_shipping_amount - {$ifnullBaseShippingCanceled}) * e.base_to_global_rate)" - ); - - $sumTotalShippingAmountActual = new Zend_Db_Expr( - "SUM((e.base_shipping_invoiced - {$ifnullBaseShippingRefunded}) * e.base_to_global_rate)" - ); - - $ifnullBaseDiscountCanceled = $adapter->getIfNullSql('e.base_discount_canceled', 0); - $sumTotalDiscountAmount = new Zend_Db_Expr( - "SUM((ABS(e.base_discount_amount) - {$ifnullBaseDiscountCanceled}) * e.base_to_global_rate)" - ); - - $ifnullBaseDiscountRefunded = $adapter->getIfNullSql('e.base_discount_refunded', 0); - $sumTotalDiscountAmountActual = new Zend_Db_Expr( - "SUM((e.base_discount_invoiced - {$ifnullBaseDiscountRefunded}) * e.base_to_global_rate)" - ); - - $this->_selectedColumns = array( - 'orders_count' => 'COUNT(e.entity_id)', - 'total_qty_ordered' => $adapter->getIfNullSql('SUM(oi.total_qty_ordered)', 0), - 'total_qty_invoiced' => $adapter->getIfNullSql('SUM(oi.total_qty_invoiced)', 0), - 'total_income_amount' => $adapter->getIfNullSql($totalIncomeAmount, 0), - 'total_revenue_amount' => $adapter->getIfNullSql($totalRevenueAmount, 0), - 'total_profit_amount' => $adapter->getIfNullSql($totalProfitAmountSum, 0), - 'total_invoiced_amount' => $adapter->getIfNullSql( - 'SUM(e.base_total_invoiced * e.base_to_global_rate)', 0), - 'total_canceled_amount' => $adapter->getIfNullSql( - 'SUM(e.base_total_canceled * e.base_to_global_rate)', 0), - 'total_paid_amount' => $adapter->getIfNullSql( - 'SUM(e.base_total_paid * e.base_to_global_rate)', 0), - 'total_refunded_amount' => $adapter->getIfNullSql( - 'SUM(e.base_total_refunded * e.base_to_global_rate)', 0), - 'total_tax_amount' => $adapter->getIfNullSql($sumTotalTaxAmount, 0), - 'total_tax_amount_actual' => $adapter->getIfNullSql($sumTotalTaxAmountActual, 0), - 'total_shipping_amount' => $adapter->getIfNullSql($sumTotalShippingAmount, 0), - 'total_shipping_amount_actual' => $adapter->getIfNullSql($sumTotalShippingAmountActual, 0), - 'total_discount_amount' => $adapter->getIfNullSql($sumTotalDiscountAmount, 0), - 'total_discount_amount_actual' => $adapter->getIfNullSql($sumTotalDiscountAmountActual, 0), - ); - - if (!$this->isTotals()) { - if ('month' == $this->_period) { - $this->_periodFormat = $adapter->getDateFormatSql('e.updated_at', '%Y-%m'); - } elseif ('year' == $this->_period) { - $this->_periodFormat = $adapter->getDateExtractSql('e.updated_at', - Varien_Db_Adapter_Interface::INTERVAL_YEAR); - } else { - $this->_periodFormat = $adapter->getDateFormatSql('e.updated_at', '%Y-%m-%d'); - } - $this->_selectedColumns['period'] = $this->_periodFormat; - } - return $this->_selectedColumns; - } - - /** - * Add selected data - * - * @return Mage_Sales_Model_Resource_Report_Order_Updatedat_Collection - */ - protected function _initSelect() - { - if ($this->_inited) { - return $this; - } - - $columns = $this->_getSelectedColumns(); - $adapter = $this->getConnection(); - $mainTable = $this->getResource()->getMainTable(); - $ifnullQtyCanceled = $adapter->getIfNullSql('qty_canceled', 0); - $selectOrderItem = $adapter->select() - ->from($this->getTable('sales/order_item'), array( - 'order_id' => 'order_id', - 'total_qty_ordered' => "SUM(qty_ordered - {$ifnullQtyCanceled})", - 'total_qty_invoiced' => 'SUM(qty_invoiced)', - )) - ->where('parent_item_id IS NULL') - ->group('order_id'); - - $select = $this->getSelect() - ->from(array('e' => $mainTable), $columns) - ->join(array('oi' => $selectOrderItem), 'oi.order_id = e.entity_id', array()) - ->where('e.state NOT IN (?)', array( - Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, - Mage_Sales_Model_Order::STATE_NEW - )); - - $this->_applyStoresFilter(); - $this->_applyOrderStatusFilter(); - - $dateUpdatedAt = $adapter->getDatePartSql('e.updated_at'); - if ($this->_to !== null) { - $dateTo = $adapter->formatDate($this->_to, false); - $select->where("{$dateUpdatedAt} <= {$dateTo}"); - } - - if ($this->_from !== null) { - $dateFrom = $adapter->formatDate($this->_from, false); - $select->where("{$dateUpdatedAt} >= {$dateFrom}"); - } - - if (!$this->isTotals()) { - $select->group($this->_periodFormat); - } - - $this->_inited = true; - return $this; - } - - /** - * Load - * - * @param boolean $printQuery - * @param boolean $logQuery - * @return Mage_Sales_Model_Resource_Report_Order_Updatedat_Collection - */ - public function load($printQuery = false, $logQuery = false) - { - if ($this->isLoaded()) { - return $this; - } - $this->_initSelect(); - $this->setApplyFilters(false); - return parent::load($printQuery, $logQuery); - } + protected $_aggregationTable = 'sales/order_aggregated_updated'; } diff --git a/app/code/core/Mage/Sales/controllers/DownloadController.php b/app/code/core/Mage/Sales/controllers/DownloadController.php index 0c92232d34..e99ac342b2 100644 --- a/app/code/core/Mage/Sales/controllers/DownloadController.php +++ b/app/code/core/Mage/Sales/controllers/DownloadController.php @@ -113,7 +113,20 @@ public function downloadProfileCustomOptionAction() $orderItemInfo = $recurringProfile->getData('order_item_info'); try { $request = unserialize($orderItemInfo['info_buyRequest']); - if (!isset($request['options'][$this->getRequest()->getParam('option_id')])) { + $optionId = $this->getRequest()->getParam('option_id'); + if (!isset($request['options'][$optionId])) { + $this->_forward('noRoute'); + return; + } + // Check if the product exists + $product = Mage::getModel('catalog/product')->load($request['product']); + if (!$product || !$product->getId()) { + $this->_forward('noRoute'); + return; + } + // Try to load the option + $option = $product->getOptionById($optionId); + if (!$option || !$option->getId() || $option->getType() != 'file') { $this->_forward('noRoute'); return; } @@ -121,9 +134,6 @@ public function downloadProfileCustomOptionAction() } catch (Exception $e) { $this->_forward('noRoute'); } - $info = array( - '' - ); } /** @@ -134,8 +144,9 @@ public function downloadCustomOptionAction() $quoteItemOptionId = $this->getRequest()->getParam('id'); $option = Mage::getModel('sales/quote_item_option')->load($quoteItemOptionId); - if (!$option->getId()) { + if (!$option->getId() || $option->getCode() == 'info_buyRequest') { $this->_forward('noRoute'); + return; } try { $info = unserialize($option->getValue()); diff --git a/app/code/core/Mage/Sales/etc/config.xml b/app/code/core/Mage/Sales/etc/config.xml index d367a4f770..cfb1f8d5cc 100644 --- a/app/code/core/Mage/Sales/etc/config.xml +++ b/app/code/core/Mage/Sales/etc/config.xml @@ -28,7 +28,7 @@ - 1.6.0.3 + 1.6.0.4 diff --git a/app/code/core/Mage/Sales/sql/sales_setup/upgrade-1.6.0.3-1.6.0.4.php b/app/code/core/Mage/Sales/sql/sales_setup/upgrade-1.6.0.3-1.6.0.4.php new file mode 100644 index 0000000000..b54a220986 --- /dev/null +++ b/app/code/core/Mage/Sales/sql/sales_setup/upgrade-1.6.0.3-1.6.0.4.php @@ -0,0 +1,37 @@ +getConnection(); +$connection->createTable($connection->createTableByDdl( + $installer->getTable('sales/order_aggregated_created'), + $installer->getTable('sales/order_aggregated_updated') +)); diff --git a/app/code/core/Mage/SalesRule/Helper/Data.php b/app/code/core/Mage/SalesRule/Helper/Data.php index 406247d6de..5a1c7541e6 100644 --- a/app/code/core/Mage/SalesRule/Helper/Data.php +++ b/app/code/core/Mage/SalesRule/Helper/Data.php @@ -30,7 +30,7 @@ class Mage_SalesRule_Helper_Data extends Mage_Core_Helper_Abstract { /** - * Set store and base price which will be used duering discount calculation to item object + * Set store and base price which will be used during discount calculation to item object * * @param Mage_Sales_Model_Quote_Item_Abstract $item * @param float $basePrice 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 0e8b4d9141..911c6a871a 100755 --- a/app/code/core/Mage/SalesRule/Model/Resource/Report/Collection.php +++ b/app/code/core/Mage/SalesRule/Model/Resource/Report/Collection.php @@ -41,6 +41,13 @@ class Mage_SalesRule_Model_Resource_Report_Collection extends Mage_Sales_Model_R */ protected $_periodFormat; + /** + * Aggregated Data Table + * + * @var string + */ + protected $_aggregationTable = 'salesrule/coupon_aggregated'; + /** * array of columns that should be aggregated * @@ -56,7 +63,7 @@ public function __construct() { parent::_construct(); $this->setModel('adminhtml/report_item'); - $this->_resource = Mage::getResourceModel('sales/report')->init('salesrule/coupon_aggregated'); + $this->_resource = Mage::getResourceModel('sales/report')->init($this->_aggregationTable); $this->setConnection($this->getResource()->getReadConnection()); } 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 6cf42e7eda..f769a42d09 100755 --- a/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule.php +++ b/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule.php @@ -52,140 +52,25 @@ protected function _construct() */ public function aggregate($from = null, $to = null) { - // convert input dates to UTC to be comparable with DATETIME fields in DB - $from = $this->_dateToUtc($from); - $to = $this->_dateToUtc($to); - - $this->_checkDates($from, $to); - $this->_aggregateByOrderCreatedAt($from, $to); + Mage::getResourceModel('salesrule/report_rule_createdat')->aggregate($from, $to); + Mage::getResourceModel('salesrule/report_rule_updatedat')->aggregate($from, $to); $this->_setFlagData(Mage_Reports_Model_Flag::REPORT_COUPONS_FLAG_CODE); + return $this; } /** * Aggregate coupons reports by order created at as range * + * @deprecated after 1.6.0.0-rc2 + * * @param mixed $from * @param mixed $to * @return Mage_SalesRule_Model_Resource_Report_Rule */ protected function _aggregateByOrderCreatedAt($from, $to) { - $table = $this->getTable('salesrule/coupon_aggregated'); - $sourceTable = $this->getTable('sales/order'); - $this->_getWriteAdapter()->beginTransaction(); - $adapter = $this->_getWriteAdapter(); - - try { - if ($from !== null || $to !== null) { - $subSelect = $this->_getTableDateRangeSelect($sourceTable, 'created_at', 'updated_at', $from, $to); - } else { - $subSelect = null; - } - - $this->_clearTableByDateRange($table, $from, $to, $subSelect); - - // convert dates from UTC to current admin timezone - $periodExpr = $adapter->getDatePartSql( - $this->getStoreTZOffsetQuery($sourceTable, 'created_at', $from, $to) - ); - - $columns = array( - 'period' => $periodExpr, - 'store_id' => 'store_id', - 'order_status' => 'status', - 'coupon_code' => 'coupon_code', - 'coupon_uses' => 'COUNT(entity_id)', - - 'subtotal_amount' => - $adapter->getIfNullSql('SUM((base_subtotal - ' . - $adapter->getIfNullSql('base_subtotal_canceled', 0).') * base_to_global_rate)', 0), - - 'discount_amount' => - $adapter->getIfNullSql('SUM((ABS(base_discount_amount) - ' . - $adapter->getIfNullSql('base_discount_canceled', 0).') * base_to_global_rate)', 0), - - 'total_amount' => - $adapter->getIfNullSql('SUM((base_subtotal - ' . - $adapter->getIfNullSql('base_subtotal_canceled', 0) . ' - '. - $adapter->getIfNullSql('ABS(base_discount_amount) - ' . - $adapter->getIfNullSql('base_discount_canceled', 0), 0). ') - * base_to_global_rate)', 0), - - 'subtotal_amount_actual' => - $adapter->getIfNullSql('SUM((base_subtotal_invoiced - ' . - $adapter->getIfNullSql('base_subtotal_refunded', 0). ') * base_to_global_rate)', 0), - - 'discount_amount_actual' => - $adapter->getIfNullSql('SUM((base_discount_invoiced - ' . - $adapter->getIfNullSql('base_discount_refunded', 0) . ') - * base_to_global_rate)', 0), - - 'total_amount_actual' => - $adapter->getIfNullSql('SUM((base_subtotal_invoiced - ' . - $adapter->getIfNullSql('base_subtotal_refunded', 0) . ' - ' . - $adapter->getIfNullSql('base_discount_invoiced - ' . - $adapter->getIfNullSql('base_discount_refunded', 0), 0) . - ') * base_to_global_rate)', 0), - ); - - $select = $this->_getWriteAdapter()->select(); - $select->from(array('source_table' => $sourceTable), $columns) - ->where('coupon_code IS NOT NULL'); - - if ($subSelect !== null) { - $select->having($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); - } - - $select->group(array( - $periodExpr, - 'store_id', - 'status', - 'coupon_code' - )); - - $select->having('COUNT(entity_id) > 0'); - $select->insertFromSelect($table, array_keys($columns)); - - $this->_getWriteAdapter()->query($select->insertFromSelect($table, array_keys($columns))); - - $select->reset(); - - $columns = array( - 'period' => 'period', - 'store_id' => new Zend_Db_Expr('0'), - 'order_status' => 'order_status', - 'coupon_code' => 'coupon_code', - 'coupon_uses' => 'SUM(coupon_uses)', - 'subtotal_amount' => 'SUM(subtotal_amount)', - 'discount_amount' => 'SUM(discount_amount)', - 'total_amount' => 'SUM(total_amount)', - 'subtotal_amount_actual' => 'SUM(subtotal_amount_actual)', - 'discount_amount_actual' => 'SUM(discount_amount_actual)', - 'total_amount_actual' => 'SUM(total_amount_actual)', - ); - - $select - ->from($table, $columns) - ->where('store_id <> 0'); - - if ($subSelect !== null) { - $select->where($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); - } - - $select->group(array( - 'period', - 'order_status', - 'coupon_code' - )); - - $this->_getWriteAdapter()->query($select->insertFromSelect($table, array_keys($columns))); - } catch (Exception $e) { - $this->_getWriteAdapter()->rollBack(); - throw $e; - } - - $this->_getWriteAdapter()->commit(); + Mage::getResourceModel('salesrule/report_rule_createdat')->aggregate($from, $to); return $this; } } 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 new file mode 100644 index 0000000000..0a7b620426 --- /dev/null +++ b/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Createdat.php @@ -0,0 +1,186 @@ + + */ +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 + * + * @param mixed $from + * @param mixed $to + * @return Mage_SalesRule_Model_Resource_Report_Rule_Createdat + */ + public function aggregate($from = null, $to = null) + { + return $this->_aggregateByOrder('created_at', $from, $to); + } + + /** + * Aggregate coupons reports by orders + * + * @throws Exception + * @param string $aggregationField + * @param mixed $from + * @param mixed $to + * @return Mage_SalesRule_Model_Resource_Report_Rule_Createdat + */ + protected function _aggregateByOrder($aggregationField, $from, $to) + { + $table = $this->getMainTable(); + $sourceTable = $this->getTable('sales/order'); + $adapter = $this->_getWriteAdapter(); + $adapter->beginTransaction(); + + try { + if ($from !== null || $to !== null) { + $subSelect = $this->_getTableDateRangeSelect($sourceTable, 'created_at', 'updated_at', $from, $to); + } else { + $subSelect = null; + } + + $this->_clearTableByDateRange($table, $from, $to, $subSelect); + + // convert dates from UTC to current admin timezone + $periodExpr = $adapter->getDatePartSql( + $this->getStoreTZOffsetQuery($sourceTable, $aggregationField, $from, $to) + ); + + $columns = array( + 'period' => $periodExpr, + 'store_id' => 'store_id', + 'order_status' => 'status', + 'coupon_code' => 'coupon_code', + 'coupon_uses' => 'COUNT(entity_id)', + + 'subtotal_amount' => + $adapter->getIfNullSql('SUM((base_subtotal - ' . + $adapter->getIfNullSql('base_subtotal_canceled', 0).') * base_to_global_rate)', 0), + + 'discount_amount' => + $adapter->getIfNullSql('SUM((ABS(base_discount_amount) - ' . + $adapter->getIfNullSql('base_discount_canceled', 0).') * base_to_global_rate)', 0), + + 'total_amount' => + $adapter->getIfNullSql('SUM((base_subtotal - ' . + $adapter->getIfNullSql('base_subtotal_canceled', 0) . ' - '. + $adapter->getIfNullSql('ABS(base_discount_amount) - ' . + $adapter->getIfNullSql('base_discount_canceled', 0), 0). ') + * base_to_global_rate)', 0), + + 'subtotal_amount_actual' => + $adapter->getIfNullSql('SUM((base_subtotal_invoiced - ' . + $adapter->getIfNullSql('base_subtotal_refunded', 0). ') * base_to_global_rate)', 0), + + 'discount_amount_actual' => + $adapter->getIfNullSql('SUM((base_discount_invoiced - ' . + $adapter->getIfNullSql('base_discount_refunded', 0) . ') + * base_to_global_rate)', 0), + + 'total_amount_actual' => + $adapter->getIfNullSql('SUM((base_subtotal_invoiced - ' . + $adapter->getIfNullSql('base_subtotal_refunded', 0) . ' - ' . + $adapter->getIfNullSql('base_discount_invoiced - ' . + $adapter->getIfNullSql('base_discount_refunded', 0), 0) . + ') * base_to_global_rate)', 0), + ); + + $select = $adapter->select(); + $select->from(array('source_table' => $sourceTable), $columns) + ->where('coupon_code IS NOT NULL'); + + if ($subSelect !== null) { + $select->having($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); + } + + $select->group(array( + $periodExpr, + 'store_id', + 'status', + 'coupon_code' + )); + + $select->having('COUNT(entity_id) > 0'); + $select->insertFromSelect($table, array_keys($columns)); + + $adapter->query($select->insertFromSelect($table, array_keys($columns))); + + $select->reset(); + + $columns = array( + 'period' => 'period', + 'store_id' => new Zend_Db_Expr('0'), + 'order_status' => 'order_status', + 'coupon_code' => 'coupon_code', + 'coupon_uses' => 'SUM(coupon_uses)', + 'subtotal_amount' => 'SUM(subtotal_amount)', + 'discount_amount' => 'SUM(discount_amount)', + 'total_amount' => 'SUM(total_amount)', + 'subtotal_amount_actual' => 'SUM(subtotal_amount_actual)', + 'discount_amount_actual' => 'SUM(discount_amount_actual)', + 'total_amount_actual' => 'SUM(total_amount_actual)', + ); + + $select + ->from($table, $columns) + ->where('store_id <> 0'); + + if ($subSelect !== null) { + $select->where($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); + } + + $select->group(array( + 'period', + 'order_status', + 'coupon_code' + )); + + $adapter->query($select->insertFromSelect($table, array_keys($columns))); + $adapter->commit(); + } catch (Exception $e) { + $adapter->rollBack(); + throw $e; + } + + return $this; + } +} 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 new file mode 100644 index 0000000000..b804c4d062 --- /dev/null +++ b/app/code/core/Mage/SalesRule/Model/Resource/Report/Rule/Updatedat.php @@ -0,0 +1,57 @@ + + */ +class Mage_SalesRule_Model_Resource_Report_Rule_Updatedat extends Mage_SalesRule_Model_Resource_Report_Rule_Createdat +{ + /** + * Resource Report Rule constructor + * + */ + protected function _construct() + { + $this->_init('salesrule/coupon_aggregated_updated', 'id'); + } + + /** + * Aggregate Coupons data by order updated at + * + * @param mixed $from + * @param mixed $to + * @return Mage_SalesRule_Model_Resource_Report_Rule_Updatedat + */ + public function aggregate($from = null, $to = null) + { + return $this->_aggregateByOrder('updated_at', $from, $to); + } +} diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Report/Updatedat/Collection.php b/app/code/core/Mage/SalesRule/Model/Resource/Report/Updatedat/Collection.php index 94f36a3518..ab55e46025 100755 --- a/app/code/core/Mage/SalesRule/Model/Resource/Report/Updatedat/Collection.php +++ b/app/code/core/Mage/SalesRule/Model/Resource/Report/Updatedat/Collection.php @@ -33,133 +33,12 @@ * @author Magento Core Team */ class Mage_SalesRule_Model_Resource_Report_Updatedat_Collection - extends Mage_Sales_Model_Resource_Report_Order_Updatedat_Collection + extends Mage_SalesRule_Model_Resource_Report_Collection { /** - * Selected columns array + * Aggregated Data Table * - * @var array + * @var string */ - protected $_selectedColumns = array(); - - /** - * Retrieve array of columns to select - * - * @return array - */ - - protected function _getSelectedColumns() - { - $adapter = $this->getConnection(); - - $this->_selectedColumns = array( - 'store_id' => 'MIN(e.store_id)', - 'order_status' => 'MIN(e.status)', - 'coupon_code' => 'MIN(e.coupon_code)', - 'coupon_uses' => 'COUNT(e.entity_id)', - - 'subtotal_amount' => - 'SUM((e.base_subtotal - '. - $adapter->getIfNullSql('e.base_subtotal_canceled', 0). - ') * e.base_to_global_rate)', - - 'discount_amount' => - 'SUM((ABS(e.base_discount_amount) - '. - $adapter->getIfNullSql('e.base_discount_canceled', 0). - ') * e.base_to_global_rate)', - - 'total_amount' => - 'SUM((e.base_subtotal - '. - $adapter->getIfNullSql('e.base_subtotal_canceled', 0) . ' - ' . - $adapter->getIfNullSql('ABS(e.base_discount_amount) - ' . - $adapter->getIfNullSql('e.base_discount_canceled', 0), 0) . - ') * e.base_to_global_rate)', - - 'subtotal_amount_actual' => - 'SUM((e.base_subtotal_invoiced - '. - $adapter->getIfNullSql('e.base_subtotal_refunded', 0). - ') * e.base_to_global_rate)', - - 'discount_amount_actual' => - 'SUM((e.base_discount_invoiced - '. - $adapter->getIfNullSql('e.base_discount_refunded', 0). - ') * e.base_to_global_rate)', - - 'total_amount_actual' => - 'SUM((e.base_subtotal_invoiced - '. - $adapter->getIfNullSql('e.base_subtotal_refunded', 0) . ' - '. - $adapter->getIfNullSql('e.base_discount_invoiced - '. - $adapter->getIfNullSql('e.base_discount_refunded', 0), 0). - ') * e.base_to_global_rate)', - ); - - if (!$this->isTotals()) { - - - if ('month' == $this->_period) { - $this->_periodFormat = $adapter->getDateFormatSql( - 'e.updated_at', - '%Y-%m' - ); - } elseif ('year' == $this->_period) { - $this->_periodFormat = $adapter->getDateExtractSql( - 'e.updated_at', - Varien_Db_Adapter_Interface::INTERVAL_YEAR - ); - } else { - $this->_periodFormat = $adapter->getDateFormatSql( - 'e.updated_at', - '%Y-%m-%d' - ); - } - $this->_selectedColumns['period'] = $this->_periodFormat; - } - - return $this->_selectedColumns; - } - - /** - * Add selected data - * - * @return Mage_SalesRule_Model_Resource_Report_Updatedat_Collection - */ - protected function _initSelect() - { - if ($this->_inited) { - return $this; - } - - $columns = $this->_getSelectedColumns(); - if ($this->isTotals() || $this->isSubTotals()) { - unset($columns['coupon_code']); - } - - $this->getSelect() - ->from(array('e' => $this->getResource()->getMainTable()), $columns) - ->where('e.coupon_code IS NOT NULL'); - - $this->_applyStoresFilter(); - $this->_applyOrderStatusFilter(); - - if ($this->_to !== null) { - $this->getSelect()->where('e.updated_at <= ?', $this->_to); - } - if ($this->_from !== null) { - $this->getSelect()->where('e.updated_at >= ?', $this->_from); - } - - if ($this->isSubTotals()) { - $this->getSelect()->group($this->_periodFormat); - } else if (!$this->isTotals()) { - $this->getSelect()->group(array( - $this->_periodFormat, - 'coupon_code' - )); - } - - $this->getSelect()->having('COUNT(e.entity_id) > 0'); - - $this->_inited = true; - return $this; - } + protected $_aggregationTable = 'salesrule/coupon_aggregated_updated'; } 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 7755c3606a..9260151da8 100755 --- a/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php +++ b/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php @@ -67,14 +67,16 @@ public function setValidationFilter($websiteId, $customerGroupId, $couponCode = ->addFieldToFilter('is_active', 1); if ($couponCode) { - $this->getSelect()->where('main_table.coupon_type <> ?', Mage_SalesRule_Model_Rule::COUPON_TYPE_NO_COUPON); $this->getSelect() - ->join( + ->joinLeft( array('rule_coupons' => $this->getTable('salesrule/coupon')), - 'main_table.rule_id = rule_coupons.rule_id '. - $this->getSelect()->getAdapter()->quoteInto('AND rule_coupons.code = ?', $couponCode), + 'main_table.rule_id = rule_coupons.rule_id ', array('code') ); + $this->getSelect()->where( + '(main_table.coupon_type = ? ', Mage_SalesRule_Model_Rule::COUPON_TYPE_NO_COUPON + ); + $this->getSelect()->orWhere('rule_coupons.code = ?)', $couponCode); } else { $this->addFieldToFilter('main_table.coupon_type', Mage_SalesRule_Model_Rule::COUPON_TYPE_NO_COUPON); } diff --git a/app/code/core/Mage/SalesRule/etc/config.xml b/app/code/core/Mage/SalesRule/etc/config.xml index 1c63b2fbf1..af4213d1d5 100644 --- a/app/code/core/Mage/SalesRule/etc/config.xml +++ b/app/code/core/Mage/SalesRule/etc/config.xml @@ -28,7 +28,7 @@ - 1.6.0.0 + 1.6.0.1 @@ -64,6 +64,9 @@ coupon_aggregated
+ + coupon_aggregated_updated
+
coupon_aggregated_order
diff --git a/app/code/core/Mage/SalesRule/sql/salesrule_setup/upgrade-1.6.0.0-1.6.0.1.php b/app/code/core/Mage/SalesRule/sql/salesrule_setup/upgrade-1.6.0.0-1.6.0.1.php new file mode 100644 index 0000000000..abaeaf830e --- /dev/null +++ b/app/code/core/Mage/SalesRule/sql/salesrule_setup/upgrade-1.6.0.0-1.6.0.1.php @@ -0,0 +1,34 @@ +getConnection(); +$connection->createTable($connection->createTableByDdl( + $installer->getTable('salesrule/coupon_aggregated'), + $installer->getTable('salesrule/coupon_aggregated_updated') +)); diff --git a/app/code/core/Mage/Tag/controllers/IndexController.php b/app/code/core/Mage/Tag/controllers/IndexController.php index 4e7cfff9d9..0233f0cbe4 100644 --- a/app/code/core/Mage/Tag/controllers/IndexController.php +++ b/app/code/core/Mage/Tag/controllers/IndexController.php @@ -112,9 +112,11 @@ protected function _extractTags($tagNamesInString) */ protected function _cleanTags(array $tagNamesArr) { + $helper = Mage::helper('core'); foreach( $tagNamesArr as $key => $tagName ) { $tagNamesArr[$key] = trim($tagNamesArr[$key], '\''); $tagNamesArr[$key] = trim($tagNamesArr[$key]); + $tagNamesArr[$key] = $helper->escapeHtml($tagNamesArr[$key]); if( $tagNamesArr[$key] == '' ) { unset($tagNamesArr[$key]); } diff --git a/app/code/core/Mage/Tax/Helper/Data.php b/app/code/core/Mage/Tax/Helper/Data.php index 6e20e4477d..836b3e891d 100644 --- a/app/code/core/Mage/Tax/Helper/Data.php +++ b/app/code/core/Mage/Tax/Helper/Data.php @@ -411,8 +411,9 @@ protected function _getAllRatesByProductClass($store=null) * @param bool $priceIncludesTax flag what price parameter contain tax * @return float */ - public function getPrice($product, $price, $includingTax = null, $shippingAddress = null, $billingAddress = null, $ctc = null, $store = null, $priceIncludesTax = null) - { + public function getPrice($product, $price, $includingTax = null, $shippingAddress = null, $billingAddress = null, + $ctc = null, $store = null, $priceIncludesTax = null + ) { if (!$price) { return $price; } @@ -430,13 +431,16 @@ public function getPrice($product, $price, $includingTax = null, $shippingAddres $taxClassId = $product->getTaxClassId(); if (is_null($percent)) { if ($taxClassId) { - $request = Mage::getSingleton('tax/calculation')->getRateRequest($shippingAddress, $billingAddress, $ctc, $store); - $percent = Mage::getSingleton('tax/calculation')->getRate($request->setProductClassId($taxClassId)); + $request = Mage::getSingleton('tax/calculation') + ->getRateRequest($shippingAddress, $billingAddress, $ctc, $store); + $percent = Mage::getSingleton('tax/calculation') + ->getRate($request->setProductClassId($taxClassId)); } } if ($taxClassId && $priceIncludesTax) { $request = Mage::getSingleton('tax/calculation')->getRateRequest(false, false, false, $store); - $includingPercent = Mage::getSingleton('tax/calculation')->getRate($request->setProductClassId($taxClassId)); + $includingPercent = Mage::getSingleton('tax/calculation') + ->getRate($request->setProductClassId($taxClassId)); } if ($percent === false || is_null($percent)) { @@ -683,7 +687,8 @@ public function getPriceTaxSql($priceField, $taxClassField) */ public function joinTaxClass($select, $storeId, $priceTable = 'main_table') { - $taxClassAttribute = Mage::getModel('eav/entity_attribute')->loadByCode(Mage_Catalog_Model_Product::ENTITY, 'tax_class_id'); + $taxClassAttribute = Mage::getModel('eav/entity_attribute') + ->loadByCode(Mage_Catalog_Model_Product::ENTITY, 'tax_class_id'); $joinConditionD = implode(' AND ',array( "tax_class_d.entity_id = {$priceTable}.entity_id", $select->getAdapter()->quoteInto('tax_class_d.attribute_id = ?', (int)$taxClassAttribute->getId()), @@ -774,5 +779,80 @@ public function getCalculationAgorithm($store=null) { return $this->_config->getAlgorithm($store); } -} + /** + * Get calculated taxes for each tax class + * + * @param Mage_Sales_Model_Order $source + * + * array( + * $index => array( + * 'tax_amount' => $taxAmount, + * 'base_tax_amount' => $baseTaxAmount, + * 'hidden_tax_amount' => $hiddenTaxAmount + * ) + * ) + * @return array + */ + public function getCalculatedTaxes($source) + { + if (Mage::registry('current_invoice')) { + $current = Mage::registry('current_invoice'); + } elseif (Mage::registry('current_creditmemo')) { + $current = Mage::registry('current_creditmemo'); + } else { + $current = $source; + } + + $taxClassAmount = array(); + if ($current && $source) { + $shippingTaxAmount = $current->getShippingTaxAmount(); + $baseShippingTaxAmount = $current->getBaseShippingTaxAmount(); + $shippingHiddenTaxAmount = $current->getShippingHiddenTaxAmount(); + + $i = 0; + foreach($current->getItemsCollection() as $item) { + $taxCollection = Mage::getResourceModel('tax/sales_order_tax_item') + ->getTaxItemsByItemId( + $item->getOrderItemId() ? $item->getOrderItemId() : $item->getItemId() + ); + + foreach ($taxCollection as $tax) { + $taxClassId = $tax['tax_id']; + $percent = $tax['percent']; + if (isset($taxClassAmount[$taxClassId])) { + $taxClassAmount[$taxClassId]['tax_amount'] += $item->getRowTotal() * $percent / 100; + $taxClassAmount[$taxClassId]['base_tax_amount'] += $item->getBaseRowTotal() * $percent / 100; + $taxClassAmount[$taxClassId]['hidden_tax_amount'] += $item->getHiddenTaxAmount(); + } else { + if ($i == 0) { + $i = 1; + $taxClassAmount[$taxClassId]['tax_amount'] = $shippingTaxAmount; + $taxClassAmount[$taxClassId]['base_tax_amount'] = $baseShippingTaxAmount; + $taxClassAmount[$taxClassId]['hidden_tax_amount'] = $shippingHiddenTaxAmount; + } else { + $taxClassAmount[$taxClassId]['tax_amount'] = 0; + $taxClassAmount[$taxClassId]['base_tax_amount'] = 0; + $taxClassAmount[$taxClassId]['hidden_tax_amount'] = 0; + } + $taxClassAmount[$taxClassId]['tax_amount'] += $item->getRowTotal() * $percent / 100; + $taxClassAmount[$taxClassId]['base_tax_amount'] += $item->getBaseRowTotal() * $percent / 100; + $taxClassAmount[$taxClassId]['hidden_tax_amount'] += $item->getHiddenTaxAmount(); + $taxClassAmount[$taxClassId]['title'] = $tax['title']; + $taxClassAmount[$taxClassId]['percent'] = $tax['percent']; + } + } + } + + foreach ($taxClassAmount as $key=>$tax) { + if ($tax['tax_amount'] == 0 && $tax['base_tax_amount'] == 0 && $tax['hidden_tax_amount'] == 0) { + unset($taxClassAmount[$key]); + } + } + + $taxClassAmount = array_values($taxClassAmount); + } + + return $taxClassAmount; + } +} diff --git a/app/code/core/Mage/Tax/Model/Observer.php b/app/code/core/Mage/Tax/Model/Observer.php index bb48e5223d..aa51507e84 100644 --- a/app/code/core/Mage/Tax/Model/Observer.php +++ b/app/code/core/Mage/Tax/Model/Observer.php @@ -59,12 +59,22 @@ public function salesEventConvertQuoteAddressToOrder(Varien_Event_Observer $obse public function salesEventOrderAfterSave(Varien_Event_Observer $observer) { $order = $observer->getEvent()->getOrder(); + if (!$order->getConvertingFromQuote() || $order->getAppliedTaxIsSaved()) { return; } - $taxes = $order->getAppliedTaxes(); - foreach ($taxes as $row) { + $getTaxesForItems = $order->getQuote()->getTaxesForItems(); + $taxes = $order->getAppliedTaxes(); + + $ratesIdQuoteItemId = array(); + foreach ($getTaxesForItems as $quoteItemId => $taxesArray) { + foreach ($taxesArray as $rates) { + $ratesIdQuoteItemId[$rates['id']][] = $quoteItemId; + } + } + + foreach ($taxes as $id => $row) { foreach ($row['rates'] as $tax) { if (is_null($row['percent'])) { $baseRealAmount = $row['base_amount']; @@ -72,26 +82,37 @@ public function salesEventOrderAfterSave(Varien_Event_Observer $observer) if ($row['percent'] == 0 || $tax['percent'] == 0) { continue; } - $baseRealAmount = $row['base_amount']/$row['percent']*$tax['percent']; + $baseRealAmount = $row['base_amount'] / $row['percent'] * $tax['percent']; } $hidden = (isset($row['hidden']) ? $row['hidden'] : 0); $data = array( - 'order_id' => $order->getId(), - 'code' => $tax['code'], - 'title' => $tax['title'], - 'hidden' => $hidden, - 'percent' => $tax['percent'], - 'priority' => $tax['priority'], - 'position' => $tax['position'], - 'amount' => $row['amount'], - 'base_amount' => $row['base_amount'], - 'process' => $row['process'], - 'base_real_amount' => $baseRealAmount, - ); - - Mage::getModel('tax/sales_order_tax')->setData($data)->save(); + 'order_id' => $order->getId(), + 'code' => $tax['code'], + 'title' => $tax['title'], + 'hidden' => $hidden, + 'percent' => $tax['percent'], + 'priority' => $tax['priority'], + 'position' => $tax['position'], + 'amount' => $row['amount'], + 'base_amount' => $row['base_amount'], + 'process' => $row['process'], + 'base_real_amount' => $baseRealAmount, + ); + + $result = Mage::getModel('tax/sales_order_tax')->setData($data)->save(); + if (isset($ratesIdQuoteItemId[$id])) { + foreach ($ratesIdQuoteItemId[$id] as $quoteItemId) { + $data = array( + 'item_id' => $order->getItemByQuoteItemId($quoteItemId)->getId(), + 'tax_id' => $result->getTaxId() + ); + Mage::getModel('tax/sales_order_tax_item')->setData($data)->save(); + } + } } } + + $order->setAppliedTaxIsSaved(true); } diff --git a/app/code/core/Mage/Tax/Model/Resource/Calculation.php b/app/code/core/Mage/Tax/Model/Resource/Calculation.php index d0b0674036..07b909a950 100755 --- a/app/code/core/Mage/Tax/Model/Resource/Calculation.php +++ b/app/code/core/Mage/Tax/Model/Resource/Calculation.php @@ -138,13 +138,15 @@ public function getCalculationProcess($request, $rates = null) $value = (isset($rate['value']) ? $rate['value'] : $rate['percent'])*1; $oneRate = array( - 'code'=>$rate['code'], - 'title'=>$rate['title'], - 'percent'=>$value, - 'position'=>$rate['position'], - 'priority'=>$rate['priority'], - ); - + 'code'=>$rate['code'], + 'title'=>$rate['title'], + 'percent'=>$value, + 'position'=>$rate['position'], + 'priority'=>$rate['priority'], + ); + if (isset($rate['tax_calculation_rule_id'])) { + $oneRate['rule_id'] = $rate['tax_calculation_rule_id']; + } if (isset($rate['hidden'])) { $row['hidden'] = $rate['hidden']; @@ -291,28 +293,35 @@ protected function _getRates($request) array('title' => $ifnullTitleValue)) ->where('rate.tax_country_id = ?', $countryId) ->where("rate.tax_region_id IN(?)", array(0, (int)$regionId)); - $postcodeIsNumeric = is_numeric($postcode); - if ($postcodeIsNumeric) { + $postcodeIsRange = is_string($postcode) && preg_match('/^(.+)-(.+)$/', $postcode, $matches); + if ($postcodeIsRange) { + $zipFrom = $matches[1]; + $zipTo = $matches[2]; + } + + if ($postcodeIsNumeric || $postcodeIsRange) { $selectClone = clone $select; $selectClone->where('rate.zip_is_range IS NOT NULL'); } $select->where('rate.zip_is_range IS NULL'); - if ($request->getPostcode() != '*') { + if ($postcode != '*' || $postcodeIsRange) { $select ->where("rate.tax_postcode IS NULL OR rate.tax_postcode IN('*', '', ?)", - $this->_createSearchPostCodeTemplates($postcode)); + $postcodeIsRange ? $postcode : $this->_createSearchPostCodeTemplates($postcode)); if ($postcodeIsNumeric) { $selectClone ->where('? BETWEEN rate.zip_from AND rate.zip_to', $postcode); + } else if ($postcodeIsRange) { + $selectClone->where("rate.zip_from >= {$zipFrom} AND rate.zip_to <= {$zipTo}"); } } /** * @see ZF-7592 issue http://framework.zend.com/issues/browse/ZF-7592 */ - if ($postcodeIsNumeric) { + if ($postcodeIsNumeric || $postcodeIsRange) { $select = $this->_getReadAdapter()->select()->union( array( '(' . $select . ')', diff --git a/app/code/core/Mage/Tax/Model/Resource/Report/Collection.php b/app/code/core/Mage/Tax/Model/Resource/Report/Collection.php index ba3360b4f7..8766b191e5 100755 --- a/app/code/core/Mage/Tax/Model/Resource/Report/Collection.php +++ b/app/code/core/Mage/Tax/Model/Resource/Report/Collection.php @@ -41,6 +41,13 @@ class Mage_Tax_Model_Resource_Report_Collection extends Mage_Sales_Model_Resourc */ protected $_periodFormat; + /** + * Aggregated Data Table + * + * @var string + */ + protected $_aggregationTable = 'tax/tax_order_aggregated_created'; + /** * Enter description here ... * @@ -56,7 +63,7 @@ public function __construct() { parent::_construct(); $this->setModel('adminhtml/report_item'); - $this->_resource = Mage::getResourceModel('sales/report')->init('tax/tax_order_aggregated_created'); + $this->_resource = Mage::getResourceModel('sales/report')->init($this->_aggregationTable); $this->setConnection($this->getResource()->getReadConnection()); } 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 77f44533dd..7a0acfc70b 100755 --- a/app/code/core/Mage/Tax/Model/Resource/Report/Tax.php +++ b/app/code/core/Mage/Tax/Model/Resource/Report/Tax.php @@ -51,92 +51,10 @@ protected function _construct() */ public function aggregate($from = null, $to = null) { - // convert input dates to UTC to be comparable with DATETIME fields in DB - $from = $this->_dateToUtc($from); - $to = $this->_dateToUtc($to); + Mage::getResourceModel('tax/report_tax_createdat')->aggregate($from, $to); + Mage::getResourceModel('tax/report_tax_updatedat')->aggregate($from, $to); + $this->_setFlagData(Mage_Reports_Model_Flag::REPORT_TAX_FLAG_CODE); - $this->_checkDates($from, $to); - $writeAdapter = $this->_getWriteAdapter(); - $writeAdapter->beginTransaction(); - - try { - if ($from !== null || $to !== null) { - $subSelect = $this->_getTableDateRangeSelect( - $this->getTable('sales/order'), - 'created_at', 'updated_at', $from, $to - ); - } else { - $subSelect = null; - } - - $this->_clearTableByDateRange($this->getMainTable(), $from, $to, $subSelect); - // convert dates from UTC to current admin timezone - $periodExpr = $writeAdapter->getDatePartSql( - $this->getStoreTZOffsetQuery( - array('e' => $this->getTable('sales/order')), - 'e.created_at', $from, $to - ) - ); - - $columns = array( - 'period' => $periodExpr, - 'store_id' => 'e.store_id', - 'code' => 'tax.code', - 'order_status' => 'e.status', - 'percent' => 'MAX(tax.' . $writeAdapter->quoteIdentifier('percent') .')', - 'orders_count' => 'COUNT(DISTINCT e.entity_id)', - 'tax_base_amount_sum' => 'SUM(tax.base_amount * e.base_to_global_rate)' - ); - - $select = $writeAdapter->select(); - $select->from(array('tax' => $this->getTable('tax/sales_order_tax')), $columns) - ->joinInner(array('e' => $this->getTable('sales/order')), 'e.entity_id = tax.order_id', array()) - ->useStraightJoin(); - - $select->where('e.state NOT IN (?)', array( - Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, - Mage_Sales_Model_Order::STATE_NEW - )); - - if ($subSelect !== null) { - $select->having($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); - } - - $select->group(array($periodExpr, 'e.store_id', 'code', 'tax.percent', 'e.status')); - - $insertQuery = $writeAdapter->insertFromSelect($select, $this->getMainTable(), array_keys($columns)); - $writeAdapter->query($insertQuery); - - $select->reset(); - - $columns = array( - 'period' => 'period', - 'store_id' => new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID), - 'code' => 'code', - 'order_status' => 'order_status', - 'percent' => 'MAX(' . $writeAdapter->quoteIdentifier('percent') . ')', - 'orders_count' => 'SUM(orders_count)', - 'tax_base_amount_sum' => 'SUM(tax_base_amount_sum)' - ); - - $select - ->from($this->getMainTable(), $columns) - ->where('store_id <> ?', 0); - - if ($subSelect !== null) { - $select->where($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); - } - - $select->group(array('period', 'code', 'percent', 'order_status')); - $insertQuery = $writeAdapter->insertFromSelect($select, $this->getMainTable(), array_keys($columns)); - $writeAdapter->query($insertQuery); - $this->_setFlagData(Mage_Reports_Model_Flag::REPORT_TAX_FLAG_CODE); - } catch (Exception $e) { - $writeAdapter->rollBack(); - throw $e; - } - - $writeAdapter->commit(); return $this; } } 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 new file mode 100644 index 0000000000..af7cf473f3 --- /dev/null +++ b/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Createdat.php @@ -0,0 +1,156 @@ + + */ +class Mage_Tax_Model_Resource_Report_Tax_Createdat extends Mage_Reports_Model_Resource_Report_Abstract +{ + /** + * Resource initialization + */ + protected function _construct() + { + $this->_init('tax/tax_order_aggregated_created', 'id'); + } + + /** + * Aggregate Tax data by order created at + * + * @param mixed $from + * @param mixed $to + * @return Mage_Tax_Model_Resource_Report_Tax_Createdat + */ + public function aggregate($from = null, $to = null) + { + return $this->_aggregateByOrder('created_at', $from, $to); + } + + /** + * Aggregate Tax data by orders + * + * @throws Exception + * @param string $aggregationField + * @param mixed $from + * @param mixed $to + * @return Mage_Tax_Model_Resource_Report_Tax_Createdat + */ + protected function _aggregateByOrder($aggregationField, $from, $to) + { + // convert input dates to UTC to be comparable with DATETIME fields in DB + $from = $this->_dateToUtc($from); + $to = $this->_dateToUtc($to); + + $this->_checkDates($from, $to); + $writeAdapter = $this->_getWriteAdapter(); + $writeAdapter->beginTransaction(); + + try { + if ($from !== null || $to !== null) { + $subSelect = $this->_getTableDateRangeSelect( + $this->getTable('sales/order'), + 'created_at', 'updated_at', $from, $to + ); + } else { + $subSelect = null; + } + + $this->_clearTableByDateRange($this->getMainTable(), $from, $to, $subSelect); + // convert dates from UTC to current admin timezone + $periodExpr = $writeAdapter->getDatePartSql( + $this->getStoreTZOffsetQuery( + array('e' => $this->getTable('sales/order')), + 'e.' . $aggregationField, + $from, $to + ) + ); + + $columns = array( + 'period' => $periodExpr, + 'store_id' => 'e.store_id', + 'code' => 'tax.code', + 'order_status' => 'e.status', + 'percent' => 'MAX(tax.' . $writeAdapter->quoteIdentifier('percent') .')', + 'orders_count' => 'COUNT(DISTINCT e.entity_id)', + 'tax_base_amount_sum' => 'SUM(tax.base_amount * e.base_to_global_rate)' + ); + + $select = $writeAdapter->select(); + $select->from(array('tax' => $this->getTable('tax/sales_order_tax')), $columns) + ->joinInner(array('e' => $this->getTable('sales/order')), 'e.entity_id = tax.order_id', array()) + ->useStraightJoin(); + + $select->where('e.state NOT IN (?)', array( + Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, + Mage_Sales_Model_Order::STATE_NEW + )); + + if ($subSelect !== null) { + $select->having($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); + } + + $select->group(array($periodExpr, 'e.store_id', 'code', 'tax.percent', 'e.status')); + + $insertQuery = $writeAdapter->insertFromSelect($select, $this->getMainTable(), array_keys($columns)); + $writeAdapter->query($insertQuery); + + $select->reset(); + + $columns = array( + 'period' => 'period', + 'store_id' => new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID), + 'code' => 'code', + 'order_status' => 'order_status', + 'percent' => 'MAX(' . $writeAdapter->quoteIdentifier('percent') . ')', + 'orders_count' => 'SUM(orders_count)', + 'tax_base_amount_sum' => 'SUM(tax_base_amount_sum)' + ); + + $select + ->from($this->getMainTable(), $columns) + ->where('store_id <> ?', 0); + + if ($subSelect !== null) { + $select->where($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); + } + + $select->group(array('period', 'code', 'percent', 'order_status')); + $insertQuery = $writeAdapter->insertFromSelect($select, $this->getMainTable(), array_keys($columns)); + $writeAdapter->query($insertQuery); + $writeAdapter->commit(); + } catch (Exception $e) { + $writeAdapter->rollBack(); + throw $e; + } + + return $this; + } +} diff --git a/app/code/community/Find/Feed/Model/Resource/Codes/Collection.php b/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Updatedat.php similarity index 59% rename from app/code/community/Find/Feed/Model/Resource/Codes/Collection.php rename to app/code/core/Mage/Tax/Model/Resource/Report/Tax/Updatedat.php index 9385168aac..48588495cb 100644 --- a/app/code/community/Find/Feed/Model/Resource/Codes/Collection.php +++ b/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Updatedat.php @@ -18,38 +18,39 @@ * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * - * @category - * @package _storage + * @category Mage + * @package Mage_Tax * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ + /** - * TheFind feed codes (attribute map) collection + * Tax report resource model with aggregation by updated at * - * @category Find - * @package Find_Feed + * @category Mage + * @package Mage_Tax + * @author Magento Core Team */ -class Find_Feed_Model_Resource_Codes_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract +class Mage_Tax_Model_Resource_Report_Tax_Updatedat extends Mage_Tax_Model_Resource_Report_Tax_Createdat { /** - * Local constructor - * + * Resource initialization */ protected function _construct() { - $this->_init('find_feed/codes'); + $this->_init('tax/tax_order_aggregated_updated', 'id'); } /** - * Fetch attributes to import + * Aggregate Tax data by order updated at * - * @return array + * @param mixed $from + * @param mixed $to + * @return Mage_Tax_Model_Resource_Report_Tax_Updatedat */ - public function getImportAttributes() + public function aggregate($from = null, $to = null) { - $this->addFieldToFilter('is_imported', array('eq' => '1')); - return $this->_toOptionHash('import_code', 'eav_code'); + return $this->_aggregateByOrder('updated_at', $from, $to); } - } diff --git a/app/code/core/Mage/Tax/Model/Resource/Report/Updatedat/Collection.php b/app/code/core/Mage/Tax/Model/Resource/Report/Updatedat/Collection.php index 096741c47f..bac46a4de3 100755 --- a/app/code/core/Mage/Tax/Model/Resource/Report/Updatedat/Collection.php +++ b/app/code/core/Mage/Tax/Model/Resource/Report/Updatedat/Collection.php @@ -32,194 +32,12 @@ * @package Mage_Tax * @author Magento Core Team */ -class Mage_Tax_Model_Resource_Report_Updatedat_Collection extends Mage_Sales_Model_Resource_Report_Collection_Abstract +class Mage_Tax_Model_Resource_Report_Updatedat_Collection extends Mage_Tax_Model_Resource_Report_Collection { /** - * Period format + * Aggregated Data Table * - * @var unknown + * @var string */ - protected $_periodFormat; - - /** - * Flag if collection was initiated - * - * @var unknown - */ - protected $_inited = false; - - /** - * Default selected columns - * - * @var unknown - */ - protected $_selectedColumns = array( - 'orders_count' => 'COUNT(DISTINCT(e.entity_id))', - 'tax_base_amount_sum' => 'SUM(tax.base_real_amount * e.base_to_global_rate)' - ); - - /** - * Initialize custom resource model - * - */ - public function __construct() - { - parent::_construct(); - $this->setModel('adminhtml/report_item'); - $this->_resource = Mage::getResourceModel('sales/report')->init('sales/order', 'entity_id'); - $this->setConnection($this->getResource()->getReadConnection()); - } - - /** - * Apply stores filter - * - * @return Mage_Tax_Model_Resource_Report_Updatedat_Collection - */ - protected function _applyStoresFilter() - { - $nullCheck = false; - $storeIds = $this->_storesIds; - - if (!is_array($storeIds)) { - $storeIds = array($storeIds); - } - - $storeIds = array_unique($storeIds); - - if ($index = array_search(null, $storeIds)) { - unset($storeIds[$index]); - $nullCheck = true; - } - - if ($nullCheck) { - $this->getSelect()->where('store_id IN(?) OR store_id IS NULL', $storeIds); - } elseif ($storeIds[0] != '') { - $this->getSelect()->where('store_id IN(?)', $storeIds); - } - - return $this; - } - - /** - * Apply order status filter - * - * @return Mage_Tax_Model_Resource_Report_Updatedat_Collection - */ - protected function _applyOrderStatusFilter() - { - if (is_null($this->_orderStatus)) { - return $this; - } - $orderStatus = $this->_orderStatus; - if (!is_array($orderStatus)) { - $orderStatus = array($orderStatus); - } - $this->getSelect()->where('status IN(?)', $orderStatus); - return $this; - } - - /** - * Retrieve array of columns to select - * - * @return array - */ - protected function _getSelectedColumns() - { - $adapter = $this->getConnection(); - - if ('month' == $this->_period) { - $this->_periodFormat = $adapter->getDateFormatSql('e.updated_at', '%Y-%m'); - } elseif ('year' == $this->_period) { - $this->_periodFormat = $adapter->getDateExtractSql('e.updated_at', Varien_Db_Adapter_Interface::INTERVAL_YEAR); - } else { - $this->_periodFormat = $adapter->getDateFormatSql('e.updated_at', '%Y-%m-%d'); - } - - // To make this query valid in MSSQL and Oralce we have to add - // MIN() for store_id, status, percent. - // You should aggregate additional columns if override - - if (!$this->isTotals() && !$this->isSubTotals()) { - $this->_selectedColumns = array( - 'period' => $this->_periodFormat, - 'store_id' => 'MIN(store_id)', - 'code' => 'tax.code', - 'order_status' => 'MIN(e.status)', - 'percent' => 'MIN(' . $this->getConnection()->quoteIdentifier('tax.percent') . ')', - 'orders_count' => 'COUNT(DISTINCT(e.entity_id))', - 'tax_base_amount_sum' => 'SUM(tax.base_real_amount * e.base_to_global_rate)' - ); - } - - if ($this->isSubTotals()) { - $this->_selectedColumns += array('period' => $this->_periodFormat); - } - - return $this->_selectedColumns; - } - - /** - * Add selected data - * - * @return Mage_Tax_Model_Resource_Report_Updatedat_Collection - */ - protected function _initSelect() - { - if ($this->_inited) { - return $this; - } - - $columns = $this->_getSelectedColumns(); - $mainTable = $this->getResource()->getMainTable(); - - $select = $this->getSelect() - ->from(array('e' => $mainTable), $columns) - ->joinInner(array('tax'=> $this->getTable('tax/sales_order_tax')), 'e.entity_id = tax.order_id', array()); - - $this->_applyStoresFilter(); - $this->_applyOrderStatusFilter(); - - $adapter = $this->getConnection(); - $dateUpdatedAt = $adapter->getDatePartSql('e.updated_at'); - - if ($this->_to !== null) { - $dateTo = $adapter->formatDate($this->_to, false); - $select->where("{$dateUpdatedAt} <= {$dateTo}"); - } - - if ($this->_from !== null) { - $dateFrom = $adapter->formatDate($this->_from, false); - $select->where("{$dateUpdatedAt} >= {$dateFrom}"); - } - - if (!$this->isTotals() && !$this->isSubTotals()) { - $select->group(array($this->_periodFormat, 'code', 'percent')); - } - - if ($this->isSubTotals()) { - $select->group(array( - $this->_periodFormat - )); - } - - $this->_inited = true; - return $this; - } - - /** - * Load - * - * @param boolean $printQuery - * @param boolean $logQuery - * @return Mage_Tax_Model_Resource_Report_Updatedat_Collection - */ - public function load($printQuery = false, $logQuery = false) - { - if ($this->isLoaded()) { - return $this; - } - $this->_initSelect(); - $this->setApplyFilters(false); - return parent::load($printQuery, $logQuery); - } + protected $_aggregationTable = 'tax/tax_order_aggregated_updated'; } diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Code/Category.php b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item.php old mode 100644 new mode 100755 similarity index 52% rename from app/code/core/Mage/GoogleOptimizer/Model/Code/Category.php rename to app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item.php index 3240a51d6b..37137c7b29 --- a/app/code/core/Mage/GoogleOptimizer/Model/Code/Category.php +++ b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item.php @@ -19,46 +19,47 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Tax * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** - * Google Optimizer Category model + * Sales order tax resource model * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Tax * @author Magento Core Team */ -class Mage_GoogleOptimizer_Model_Code_Category extends Mage_GoogleOptimizer_Model_Code +class Mage_Tax_Model_Resource_Sales_Order_Tax_Item extends Mage_Core_Model_Resource_Db_Abstract { - - protected $_entityType = 'category'; + /** + * Resource initialization + */ + protected function _construct() + { + $this->_init('tax/sales_order_tax_item', 'tax_item_id'); + } /** - * Removing scripts assigned to entity + * Get Tax Items with order tax information * - * @param integer $storeId - * @return Mage_GoogleOptimizer_Model_Code + * @param int $item_id + * @return array */ - public function deleteScripts($storeId) + public function getTaxItemsByItemId($item_id) { - $category = $this->getEntity(); - if ($category) { - /** - * We need check category children ids - */ - $ids = $category->getDeletedChildrenIds(); - if (is_array($ids)) { - $ids[] = $category->getId(); - } else { - $ids = array($category->getId()); - } - $this->setEntityIds($ids); - } - return parent::deleteScripts($storeId); - } + $adapter = $this->_getReadAdapter(); + $select = $adapter->select() + ->from(array('item' => $this->getTable('tax/sales_order_tax_item')), array('tax_id')) + ->join( + array('tax' => $this->getTable('tax/sales_order_tax')), + 'item.tax_id = tax.tax_id', + array('percent', 'title', 'percent') + ) + ->where('item_id = ?', $item_id); + return $adapter->fetchAll($select); + } } diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Resource/Code/Collection.php b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item/Collection.php similarity index 77% rename from app/code/core/Mage/GoogleOptimizer/Model/Resource/Code/Collection.php rename to app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item/Collection.php index 4382a4b64b..dbdb22871b 100755 --- a/app/code/core/Mage/GoogleOptimizer/Model/Resource/Code/Collection.php +++ b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item/Collection.php @@ -19,27 +19,26 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Tax * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** - * Google Optimizer collection + * Order Tax Item Collection * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_Tax * @author Magento Core Team */ -class Mage_GoogleOptimizer_Model_Resource_Code_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract +class Mage_Tax_Model_Resource_Sales_Order_Tax_Item_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract { /** - * Resource collection initialization - * + * Initialize resource */ protected function _construct() { - $this->_init('googleoptimizer/code'); + $this->_init('tax/sales_order_tax_item'); } } diff --git a/app/code/community/Find/Feed/Model/Resource/Codes.php b/app/code/core/Mage/Tax/Model/Sales/Order/Tax/Item.php similarity index 75% rename from app/code/community/Find/Feed/Model/Resource/Codes.php rename to app/code/core/Mage/Tax/Model/Sales/Order/Tax/Item.php index 2ebc08ee96..fa0f811aea 100644 --- a/app/code/community/Find/Feed/Model/Resource/Codes.php +++ b/app/code/core/Mage/Tax/Model/Sales/Order/Tax/Item.php @@ -18,25 +18,24 @@ * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * - * @category - * @package _storage + * @category Mage + * @package Mage_Tax * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** - * Thefind feed codes (attribute map) model - * - * @category Find - * @package Find_Feed + * @category Mage + * @package Mage_Tax + * @author Magento Core Team */ -class Find_Feed_Model_Resource_Codes extends Mage_Core_Model_Resource_Db_Abstract +class Mage_Tax_Model_Sales_Order_Tax_Item extends Mage_Core_Model_Abstract { /** - * Class local constructor + * Initialization */ protected function _construct() { - return $this->_init('find_feed/feed_import_codes', 'code_id'); + $this->_init('tax/sales_order_tax_item'); } } diff --git a/app/code/core/Mage/Tax/Model/Sales/Pdf/Grandtotal.php b/app/code/core/Mage/Tax/Model/Sales/Pdf/Grandtotal.php index be0d996285..f9d81baf7b 100644 --- a/app/code/core/Mage/Tax/Model/Sales/Pdf/Grandtotal.php +++ b/app/code/core/Mage/Tax/Model/Sales/Pdf/Grandtotal.php @@ -45,7 +45,8 @@ public function getTotalsForDisplay() return parent::getTotalsForDisplay(); } $amount = $this->getOrder()->formatPriceTxt($this->getAmount()); - $amountExclTax = $this->getAmount()-$this->getSource()->getTaxAmount(); + $amountExclTax = $this->getAmount() - $this->getSource()->getTaxAmount(); + $amountExclTax = ($amountExclTax > 0) ? $amountExclTax : 0; $amountExclTax = $this->getOrder()->formatPriceTxt($amountExclTax); $tax = $this->getOrder()->formatPriceTxt($this->getSource()->getTaxAmount()); $fontSize = $this->getFontSize() ? $this->getFontSize() : 7; 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 5c20e2c38a..b6292154fe 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 @@ -316,6 +316,7 @@ protected function _unitBaseCalculation(Mage_Sales_Model_Quote_Address $address, $child->getBaseTaxAmount(), $rate ); + $child->setTaxRates($applied); } $this->_recalculateParent($item); } @@ -333,6 +334,7 @@ protected function _unitBaseCalculation(Mage_Sales_Model_Quote_Address $address, $item->getBaseTaxAmount(), $rate ); + $item->setTaxRates($applied); } } return $this; @@ -373,7 +375,8 @@ protected function _calcUnitTaxAmount(Mage_Sales_Model_Quote_Item_Abstract $item $unitTax = max($unitTax - $unitTaxDiscount, 0); $baseUnitTax = $this->_calculator->calcTaxAmount($basePrice, $rate, $inclTax); $baseDiscountRate = ($baseUnitTax/$basePrice) * 100; - $baseUnitTaxDiscount = $this->_calculator->calcTaxAmount($baseDiscountAmount, $baseDiscountRate, $inclTax, false); + $baseUnitTaxDiscount = $this->_calculator + ->calcTaxAmount($baseDiscountAmount, $baseDiscountRate, $inclTax, false); $baseUnitTax = max($baseUnitTax - $baseUnitTaxDiscount, 0); if ($inclTax && $discountAmount > 0) { @@ -534,9 +537,10 @@ protected function _calcRowTaxAmount($item, $rate) */ protected function _totalBaseCalculation(Mage_Sales_Model_Quote_Address $address, $taxRateRequest) { - $items = $this->_getAddressItems($address); - $store = $address->getQuote()->getStore(); - $taxGroups = array(); + $items = $this->_getAddressItems($address); + $store = $address->getQuote()->getStore(); + $taxGroups = array(); + $itemTaxGroups = array(); $inclTax = false; foreach ($items as $item) { @@ -551,6 +555,7 @@ protected function _totalBaseCalculation(Mage_Sales_Model_Quote_Address $address $taxGroups[(string)$rate]['applied_rates'] = $this->_calculator->getAppliedRates($taxRateRequest); $this->_aggregateTaxPerRate($child, $rate, $taxGroups); $inclTax = $child->getIsPriceInclTax(); + $itemTaxGroups[$child->getId()] = $this->_calculator->getAppliedRates($taxRateRequest); } $this->_recalculateParent($item); } else { @@ -559,9 +564,11 @@ protected function _totalBaseCalculation(Mage_Sales_Model_Quote_Address $address $taxGroups[(string)$rate]['applied_rates'] = $this->_calculator->getAppliedRates($taxRateRequest); $this->_aggregateTaxPerRate($item, $rate, $taxGroups); $inclTax = $item->getIsPriceInclTax(); + $itemTaxGroups[$item->getId()] = $this->_calculator->getAppliedRates($taxRateRequest); } } + $address->getQuote()->setTaxesForItems($itemTaxGroups); foreach ($taxGroups as $rateKey => $data) { $rate = (float) $rateKey; $totalTax = $this->_calculator->calcTaxAmount(array_sum($data['totals']), $rate, $inclTax); diff --git a/app/code/core/Mage/Tax/etc/config.xml b/app/code/core/Mage/Tax/etc/config.xml index 767f063b39..c519309d6f 100644 --- a/app/code/core/Mage/Tax/etc/config.xml +++ b/app/code/core/Mage/Tax/etc/config.xml @@ -28,7 +28,7 @@ - 1.6.0.0 + 1.6.0.2 @@ -65,6 +65,9 @@ sales_order_tax
+ + sales_order_tax_item
+
diff --git a/app/code/core/Mage/Tax/sql/tax_setup/upgrade-1.6.0.0-1.6.0.1.php b/app/code/core/Mage/Tax/sql/tax_setup/upgrade-1.6.0.0-1.6.0.1.php new file mode 100644 index 0000000000..43ee81dfd4 --- /dev/null +++ b/app/code/core/Mage/Tax/sql/tax_setup/upgrade-1.6.0.0-1.6.0.1.php @@ -0,0 +1,34 @@ +getConnection(); +$connection->createTable($connection->createTableByDdl( + $installer->getTable('tax/tax_order_aggregated_created'), + $installer->getTable('tax/tax_order_aggregated_updated') +)); diff --git a/app/code/core/Mage/Tax/sql/tax_setup/upgrade-1.6.0.1-1.6.0.2.php b/app/code/core/Mage/Tax/sql/tax_setup/upgrade-1.6.0.1-1.6.0.2.php new file mode 100644 index 0000000000..01e02eb424 --- /dev/null +++ b/app/code/core/Mage/Tax/sql/tax_setup/upgrade-1.6.0.1-1.6.0.2.php @@ -0,0 +1,87 @@ +getConnection() + ->newTable($installer->getTable('tax/sales_order_tax_item')) + ->addColumn('tax_item_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array( + 'identity' => true, + 'unsigned' => true, + 'nullable' => false, + 'primary' => true, + ), 'Tax Item Id') + ->addColumn('tax_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array( + 'unsigned' => true, + 'nullable' => false, + ), 'Tax Id') + ->addColumn('item_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array( + 'unsigned' => true, + 'nullable' => false, + ), 'Item Id') + ->addIndex($installer->getIdxName('tax/sales_order_tax_item', array('tax_id')), + array('tax_id')) + ->addIndex($installer->getIdxName('tax/sales_order_tax_item', array('item_id')), + array('item_id')) + ->addIndex( + $installer->getIdxName( + 'tax/sales_order_tax_item', array('tax_id', 'item_id'), + Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE + ), + array('tax_id', 'item_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE) + ) + ->addForeignKey( + $installer->getFkName( + 'tax/sales_order_tax_item', + 'tax_id', + 'tax/sales_order_tax', + 'tax_id' + ), + 'tax_id', + $installer->getTable('tax/sales_order_tax'), + 'tax_id', + Varien_Db_Ddl_Table::ACTION_CASCADE, + Varien_Db_Ddl_Table::ACTION_CASCADE + ) + ->addForeignKey( + $installer->getFkName( + 'tax/sales_order_tax_item', + 'item_id', + 'sales_flat_order_item', + 'item_id' + ), + 'item_id', + $installer->getTable('sales_flat_order_item'), + 'item_id', + Varien_Db_Ddl_Table::ACTION_CASCADE, + Varien_Db_Ddl_Table::ACTION_CASCADE + ) + ->setComment('Sales Order Tax Item'); +$installer->getConnection()->createTable($table); 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 4685c6aa87..810fbfece2 100644 --- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php +++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php @@ -1248,16 +1248,8 @@ protected function _formUsExpressShipmentRequest(Varien_Object $request) )); } - if (strlen($request->getShipperAddressPostalCode()) == 5) { - $fromZip5 = $request->getShipperAddressPostalCode(); - } else { - $fromZip5 = ''; - } - if (strlen($request->getShipperAddressPostalCode()) == 4) { - $fromZip4 = $request->getShipperAddressPostalCode(); - } else { - $fromZip4 = ''; - } + list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode()); + list($toZip5, $toZip4) = $this->_parseZip($request->getRecipientAddressPostalCode(), true); $rootNode = 'ExpressMailLabelRequest'; // the wrap node needs for remove xml declaration above @@ -1287,8 +1279,8 @@ protected function _formUsExpressShipmentRequest(Varien_Object $request) $xml->addChild('ToAddress2', $request->getRecipientAddressStreet1()); $xml->addChild('ToCity', $request->getRecipientAddressCity()); $xml->addChild('ToState', $request->getRecipientAddressStateOrProvinceCode()); - $xml->addChild('ToZip5', $request->getRecipientAddressPostalCode()); - $xml->addChild('ToZip4'); + $xml->addChild('ToZip5', $toZip5); + $xml->addChild('ToZip4', $toZip4); $xml->addChild('ToPhone', $request->getRecipientContactPhoneNumber()); $xml->addChild('WeightInOunces', $packageWeight); $xml->addChild('WaiverOfSignature', $packageParams->getDeliveryConfirmation()); @@ -1338,16 +1330,9 @@ protected function _formUsSignatureConfirmationShipmentRequest(Varien_Object $re Zend_Measure_Weight::OUNCE )); } - if (strlen($request->getShipperAddressPostalCode()) == 5) { - $fromZip5 = $request->getShipperAddressPostalCode(); - } else { - $fromZip5 = ''; - } - if (strlen($request->getShipperAddressPostalCode()) == 4) { - $fromZip4 = $request->getShipperAddressPostalCode(); - } else { - $fromZip4 = ''; - } + + list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode()); + list($toZip5, $toZip4) = $this->_parseZip($request->getRecipientAddressPostalCode(), true); $rootNode = 'SigConfirmCertifyV3.0Request'; // the wrap node needs for remove xml declaration above @@ -1370,8 +1355,8 @@ protected function _formUsSignatureConfirmationShipmentRequest(Varien_Object $re $xml->addChild('ToAddress2', $request->getRecipientAddressStreet1()); $xml->addChild('ToCity', $request->getRecipientAddressCity()); $xml->addChild('ToState', $request->getRecipientAddressStateOrProvinceCode()); - $xml->addChild('ToZip5', $request->getRecipientAddressPostalCode()); - $xml->addChild('ToZip4'); + $xml->addChild('ToZip5', $toZip5); + $xml->addChild('ToZip4', $toZip4); $xml->addChild('WeightInOunces', $packageWeight); $xml->addChild('ServiceType', $serviceType); $xml->addChild('WaiverOfSignature', $packageParams->getDeliveryConfirmation()); @@ -1464,16 +1449,8 @@ protected function _formIntlShipmentRequest(Varien_Object $request) $container = 'VARIABLE'; } $shippingMethod = $request->getShippingMethod(); - if (strlen($request->getShipperAddressPostalCode()) == 5) { - $fromZip5 = $request->getShipperAddressPostalCode(); - } else { - $fromZip5 = ''; - } - if (strlen($request->getShipperAddressPostalCode()) == 4) { - $fromZip4 = $request->getShipperAddressPostalCode(); - } else { - $fromZip4 = ''; - } + list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode()); + // the wrap node needs for remove xml declaration above $xmlWrap = new SimpleXMLElement(''); $method = ''; @@ -1802,4 +1779,32 @@ public function getContentTypes(Varien_Object $params) return array(); } + /** + * Parse zip from string to zip5-zip4 + * + * @param string $zipString + * @param bool $returnFull + * @return array + */ + protected function _parseZip($zipString, $returnFull = false) + { + $zip4 = ''; + $zip5 = ''; + $zip = array($zipString); + if (preg_match('/[\\d\\w]{5}\\-[\\d\\w]{4}/', $zipString) != 0) { + $zip = explode('-', $zipString); + } + for ($i = 0; $i < count($zip); ++$i) { + if (strlen($zip[$i]) == 5) { + $zip5 = $zip[$i]; + } elseif (strlen($zip[$i]) == 4) { + $zip4 = $zip[$i]; + } + } + if (empty($zip5) && empty($zip4) && $returnFull) { + $zip5 = $zipString; + } + + return array($zip5, $zip4); + } } diff --git a/app/code/core/Mage/Wishlist/Block/Abstract.php b/app/code/core/Mage/Wishlist/Block/Abstract.php index 21ad232962..adf0da4073 100644 --- a/app/code/core/Mage/Wishlist/Block/Abstract.php +++ b/app/code/core/Mage/Wishlist/Block/Abstract.php @@ -42,7 +42,7 @@ abstract class Mage_Wishlist_Block_Abstract extends Mage_Catalog_Block_Product_A protected $_collection; /** - * Wishlist Model + * Store wishlist Model * * @var Mage_Wishlist_Model_Wishlist */ @@ -99,21 +99,7 @@ protected function _getCustomerSession() */ protected function _getWishlist() { - if (is_null($this->_wishlist)) { - if (Mage::registry('shared_wishlist')) { - $this->_wishlist = Mage::registry('shared_wishlist'); - } - elseif (Mage::registry('wishlist')) { - $this->_wishlist = Mage::registry('wishlist'); - } - else { - $this->_wishlist = Mage::getModel('wishlist/wishlist'); - if ($this->_getCustomerSession()->isLoggedIn()) { - $this->_wishlist->loadByCustomer($this->_getCustomerSession()->getCustomer()); - } - } - } - return $this->_wishlist; + return $this->_getHelper()->getWishlist(); } /** @@ -136,9 +122,7 @@ public function getWishlistItems() { if (is_null($this->_collection)) { $this->_collection = $this->_getWishlist() - ->getItemCollection() - ->addStoreFilter(); - + ->getItemCollection(); $this->_prepareCollection($this->_collection); } @@ -160,11 +144,12 @@ public function getWishlist() * Retrieve URL for Removing item from wishlist * * @param Mage_Catalog_Model_Product|Mage_Wishlist_Model_Item $item + * * @return string */ - public function getItemRemoveUrl($product) + public function getItemRemoveUrl($item) { - return $this->_getHelper()->getRemoveUrl($product); + return $this->_getHelper()->getRemoveUrl($item); } /** @@ -229,7 +214,7 @@ public function getItemConfigureUrl($product) public function getEscapedDescription($item) { if ($item->getDescription()) { - return $this->htmlEscape($item->getDescription()); + return $this->escapeHtml($item->getDescription()); } return ' '; } @@ -279,7 +264,7 @@ public function isSaleable() */ public function getWishlistItemsCount() { - return $this->getWishlistItems()->count(); + return $this->_getWishlist()->getItemsCount(); } /** @@ -352,8 +337,10 @@ protected function _getItemPriceBlock($productType) * non-configured products * * @param Mage_Catalog_Model_Product $product - * @param boolean $displayMinimalPrice + * @param bool $displayMinimalPrice * @param string $idSuffix + * + * @return string */ public function getPriceHtml($product, $displayMinimalPrice = false, $idSuffix = '') { diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php b/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php index bb8ee012aa..c1cae4e840 100644 --- a/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php +++ b/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php @@ -45,7 +45,7 @@ protected function _prepareCollection($collection) $collection->setCurPage(1) ->setPageSize(3) ->setInStockFilter(true) - ->addWishListSortOrder('added_at', 'desc'); + ->setOrder('added_at'); return $this; } @@ -57,7 +57,7 @@ protected function _prepareCollection($collection) */ protected function _toHtml() { - if (($this->getCustomWishlist() && $this->getItemCount()) || $this->_getHelper()->hasItems()) { + if (($this->getCustomWishlist() && $this->getItemCount()) || $this->hasWishlistItems()) { return parent::_toHtml(); } @@ -125,6 +125,6 @@ public function getItemCount() return $this->getCustomWishlist()->getItemsCount(); } - return $this->helper('wishlist')->getItemCount(); + return $this->getWishlistItemsCount(); } } diff --git a/app/code/core/Mage/Wishlist/Block/Share/Wishlist.php b/app/code/core/Mage/Wishlist/Block/Share/Wishlist.php index 6fcac49a11..c09ef2f5cc 100644 --- a/app/code/core/Mage/Wishlist/Block/Share/Wishlist.php +++ b/app/code/core/Mage/Wishlist/Block/Share/Wishlist.php @@ -80,6 +80,6 @@ public function getWishlistCustomer() */ public function getHeader() { - return Mage::helper('wishlist')->__("%s's Wishlist", $this->htmlEscape($this->getWishlistCustomer()->getFirstname())); + return Mage::helper('wishlist')->__("%s's Wishlist", $this->escapeHtml($this->getWishlistCustomer()->getFirstname())); } } diff --git a/app/code/core/Mage/Wishlist/Helper/Data.php b/app/code/core/Mage/Wishlist/Helper/Data.php index 062e9963ad..3940e0d83b 100644 --- a/app/code/core/Mage/Wishlist/Helper/Data.php +++ b/app/code/core/Mage/Wishlist/Helper/Data.php @@ -103,8 +103,18 @@ protected function _getCurrentCustomer() public function getWishlist() { if (is_null($this->_wishlist)) { - $this->_wishlist = Mage::getModel('wishlist/wishlist') - ->loadByCustomer($this->_getCurrentCustomer()); + if (Mage::registry('shared_wishlist')) { + $this->_wishlist = Mage::registry('shared_wishlist'); + } + elseif (Mage::registry('wishlist')) { + $this->_wishlist = Mage::registry('wishlist'); + } + else { + $this->_wishlist = Mage::getModel('wishlist/wishlist'); + if ($this->_getCustomerSession()->isLoggedIn()) { + $this->_wishlist->loadByCustomer($this->_getCustomerSession()->getCustomer()); + } + } } return $this->_wishlist; } @@ -112,15 +122,18 @@ public function getWishlist() /** * Retrieve wishlist items availability * + * @deprecated after 1.6.0.0 + * * @return bool */ public function hasItems() { - return $this->getItemCount() > 0; + return $this->getWishlist()->getItemsCount() > 0; } /** - * Retrieve wishlist item count (inchlude config settings) + * Retrieve wishlist item count (include config settings) + * Used in top link menu only * * @return int */ @@ -247,8 +260,9 @@ public function getConfigureUrl($item) /** * Retrieve url for adding product to wishlist * - * @param Mage_Catalog_Model_Product|Mage_Wishlist_Model_Item $product - * @return string|boolean + * @param Mage_Catalog_Model_Product|Mage_Wishlist_Model_Item $item + * + * @return string|bool */ public function getAddUrl($item) { @@ -258,8 +272,9 @@ public function getAddUrl($item) /** * Retrieve url for updating product in wishlist * - * @param Mage_Catalog_Model_Product|Mage_Wishlist_Model_Item $product - * @return string|boolean + * @param Mage_Catalog_Model_Product|Mage_Wishlist_Model_Item $item + * + * @return string|bool */ public function getUpdateUrl($item) { @@ -282,9 +297,10 @@ public function getUpdateUrl($item) /** * Retrieve url for adding product to wishlist with params * - * @param Mage_Catalog_Model_Product|Mage_Wishlist_Model_Item $product - * @param array $param - * @return string|boolean + * @param Mage_Catalog_Model_Product|Mage_Wishlist_Model_Item $item + * @param array $params + * + * @return string|bool */ public function getAddUrlWithParams($item, array $params = array()) { @@ -431,10 +447,7 @@ public function getRssUrl() */ public function isRssAllow() { - if (Mage::getStoreConfig('rss/wishlist/active')) { - return true; - } - return false; + return Mage::getStoreConfigFlag('rss/wishlist/active'); } /** @@ -457,15 +470,13 @@ public function defaultCommentString() public function calculate() { $session = $this->_getCustomerSession(); - if (!$this->_isCustomerLogIn()) { - $count = 0; - } else { + $count = 0; + if ($this->_isCustomerLogIn()) { + $collection = $this->getWishlistItemCollection()->setInStockFilter(true); if (Mage::getStoreConfig(self::XML_PATH_WISHLIST_LINK_USE_QTY)) { - $count = $this->getWishlistItemCollection() - ->setInStockFilter(true) - ->getItemsQty(); + $count = $collection->getItemsQty(); } else { - $count = count($this->getWishlistItemCollection()->setInStockFilter(true)); + $count = $collection->getSize(); } $session->setWishlistDisplayType(Mage::getStoreConfig(self::XML_PATH_WISHLIST_LINK_USE_QTY)); $session->setDisplayOutOfStockProducts( 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 e2c3dc0284..30954dabaf 100755 --- a/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php +++ b/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php @@ -130,8 +130,11 @@ protected function _afterLoad() protected function _assignOptions() { $itemIds = array_keys($this->_items); - $optionCollection = Mage::getModel('wishlist/item_option')->getCollection() - ->addItemFilter($itemIds); + /* @var $optionCollection Mage_Wishlist_Model_Resource_Item_Option_Collection */ + $optionCollection = Mage::getModel('wishlist/item_option')->getCollection(); + $optionCollection->addItemFilter($itemIds); + + /* @var $item Mage_Wishlist_Model_Item */ foreach ($this as $item) { $item->setOptions($optionCollection->getOptionsByItem($item)); } @@ -227,21 +230,18 @@ public function addWishlistFilter(Mage_Wishlist_Model_Wishlist $wishlist) /** * Add filter by shared stores * - * @param int|array $store + * @param array $storeIds + * * @return Mage_Wishlist_Model_Resource_Item_Collection */ - public function addStoreFilter($store = null) + public function addStoreFilter($storeIds = array()) { - if (is_null($store)) { - $store = Mage::app()->getStore()->getId(); + if (!is_array($storeIds)) { + $storeIds = array($storeIds); } + $this->_storeIds = $storeIds; + $this->addFieldToFilter('store_id', array('in' => $this->_storeIds)); - if (!is_array($store)) { - $store = array($store); - } - $this->_storeIds = $store; - - $this->addFieldToFilter('store_id', $store); return $this; } @@ -263,6 +263,9 @@ public function addStoreData() /** * Add wishlist sort order * + * @deprecated after 1.6.0.0-rc2 + * @see Varien_Data_Collection_Db::setOrder() is used instead + * * @param string $attribute * @param string $dir * @return Mage_Wishlist_Model_Resource_Item_Collection diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php index e0d7394bed..b4e42feb86 100755 --- a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php +++ b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php @@ -26,7 +26,7 @@ /** - * Wishlist model resource + * Wishlist resource model * * @category Mage * @package Mage_Wishlist @@ -35,22 +35,21 @@ class Mage_Wishlist_Model_Resource_Wishlist extends Mage_Core_Model_Resource_Db_Abstract { /** - * Items count + * Store wishlist items count * - * @var int + * @var null|int */ - protected $_itemsCount = null; + protected $_itemsCount = null; /** - * CustomerId field name + * Store customer ID field name * * @var string */ - protected $_customerIdFieldName = 'customer_id'; + protected $_customerIdFieldName = 'customer_id'; /** - * Wishlist constructor - * + * Set main entity table name and primary key field name */ protected function _construct() { @@ -58,7 +57,7 @@ protected function _construct() } /** - * CustomerId field name getter + * Getter for customer ID field name * * @return string */ @@ -68,9 +67,10 @@ public function getCustomerIdFieldName() } /** - * CustomerId field name setter + * Setter for customer ID field name + * + * @param $fieldName * - * @param string $fieldName * @return Mage_Wishlist_Model_Resource_Wishlist */ public function setCustomerIdFieldName($fieldName) @@ -80,21 +80,22 @@ public function setCustomerIdFieldName($fieldName) } /** - * Fetch items count + * Retrieve wishlist items count + * + * @deprecated after 1.6.0.0-rc2 + * @see Mage_Wishlist_Model_Wishlist::getItemsCount() * * @param Mage_Wishlist_Model_Wishlist $wishlist + * * @return int */ public function fetchItemsCount(Mage_Wishlist_Model_Wishlist $wishlist) { if (is_null($this->_itemsCount)) { - $collection = $wishlist->getItemCollection() - ->addStoreFilter() - ->setVisibilityFilter(); - - $this->_itemsCount = $collection->getSize(); + $this->_itemsCount = $wishlist->getItemsCount(); } return $this->_itemsCount; } + } diff --git a/app/code/core/Mage/Wishlist/Model/Wishlist.php b/app/code/core/Mage/Wishlist/Model/Wishlist.php index 5126b828ff..fa16549d7e 100644 --- a/app/code/core/Mage/Wishlist/Model/Wishlist.php +++ b/app/code/core/Mage/Wishlist/Model/Wishlist.php @@ -66,7 +66,6 @@ class Mage_Wishlist_Model_Wishlist extends Mage_Core_Model_Abstract /** * Initialize resource model - * */ protected function _construct() { @@ -86,6 +85,7 @@ public function loadByCustomer($customer, $create = false) $customer = $customer->getId(); } + $customer = (int) $customer; $customerIdFieldName = $this->_getResource()->getCustomerIdFieldName(); $this->_getResource()->load($this, $customer, $customerIdFieldName); if (!$this->getId() && $create) { @@ -151,11 +151,12 @@ protected function _afterSave() } /** - * Adding catalog product object data to wishlist + * Add catalog product object data to wishlist * * @param Mage_Catalog_Model_Product $product * @param int $qty * @param bool $forciblySetQty + * * @return Mage_Wishlist_Model_Item */ protected function _addCatalogProduct(Mage_Catalog_Model_Product $product, $qty = 1, $forciblySetQty = false) @@ -199,7 +200,9 @@ public function getItemCollection() { if (is_null($this->_itemCollection)) { $this->_itemCollection = Mage::getResourceModel('wishlist/item_collection') - ->addWishlistFilter($this); + ->addWishlistFilter($this) + ->addStoreFilter($this->getSharedStoreIds()) + ->setVisibilityFilter(); } return $this->_itemCollection; @@ -381,7 +384,7 @@ public function getDataForSave() */ public function getSharedStoreIds($current = true) { - if (is_null($this->_storeIds)) { + if (is_null($this->_storeIds) || !is_array($this->_storeIds)) { if ($current) { $this->_storeIds = $this->getStore()->getWebsite()->getStoreIds(); } else { @@ -403,7 +406,7 @@ public function getSharedStoreIds($current = true) */ public function setSharedStoreIds($storeIds) { - $this->_storeIds = $storeIds; + $this->_storeIds = (array) $storeIds; return $this; } @@ -439,7 +442,7 @@ public function setStore($store) */ public function getItemsCount() { - return $this->_getResource()->fetchItemsCount($this); + return $this->getItemCollection()->getSize(); } /** diff --git a/app/code/core/Mage/Wishlist/controllers/IndexController.php b/app/code/core/Mage/Wishlist/controllers/IndexController.php index 9bcc4db7c9..a81bb01249 100644 --- a/app/code/core/Mage/Wishlist/controllers/IndexController.php +++ b/app/code/core/Mage/Wishlist/controllers/IndexController.php @@ -602,7 +602,7 @@ public function downloadCustomOptionAction() $option = Mage::getModel('wishlist/item_option')->load($optionId); $hasError = false; - if ($option->getId()) { + if ($option->getId() && $option->getCode() !== 'info_buyRequest') { $info = unserialize($option->getValue()); $filePath = Mage::getBaseDir() . $info['quote_path']; $secretKey = $this->getRequest()->getParam('key'); @@ -615,7 +615,8 @@ public function downloadCustomOptionAction() } } } catch(Exception $e) { + $this->_forward('noRoute'); } - $this->_forward('noRoute'); + exit(0); } } diff --git a/app/code/core/Mage/Wishlist/controllers/SharedController.php b/app/code/core/Mage/Wishlist/controllers/SharedController.php index afa38845c1..947718b619 100644 --- a/app/code/core/Mage/Wishlist/controllers/SharedController.php +++ b/app/code/core/Mage/Wishlist/controllers/SharedController.php @@ -97,7 +97,7 @@ public function cartAction() $session = Mage::getSingleton('wishlist/session'); $cart = Mage::getSingleton('checkout/cart'); - $redirectUrl = Mage::getUrl('*/*'); + $redirectUrl = $this->_getRefererUrl(); try { $options = Mage::getModel('wishlist/item_option')->getCollection() @@ -109,18 +109,13 @@ public function cartAction() if (Mage::helper('checkout/cart')->getShouldRedirectToCart()) { $redirectUrl = Mage::helper('checkout/cart')->getCartUrl(); - } else if ($this->_getRefererUrl()) { - $redirectUrl = $this->_getRefererUrl(); } } catch (Mage_Core_Exception $e) { if ($e->getCode() == Mage_Wishlist_Model_Item::EXCEPTION_CODE_NOT_SALABLE) { $session->addError(Mage::helper('wishlist')->__('This product(s) is currently out of stock')); - } else if ($e->getCode() == Mage_Wishlist_Model_Item::EXCEPTION_CODE_HAS_REQUIRED_OPTIONS) { - Mage::getSingleton('catalog/session')->addNotice($e->getMessage()); - $redirectUrl = Mage::getUrl('*/*/configure/', array('id' => $item->getId())); } else { Mage::getSingleton('catalog/session')->addNotice($e->getMessage()); - $redirectUrl = Mage::getUrl('*/*/configure/', array('id' => $item->getId())); + $redirectUrl = $item->getProductUrl(); } } catch (Exception $e) { $session->addException($e, Mage::helper('wishlist')->__('Cannot add item to shopping cart')); diff --git a/app/design/adminhtml/default/default/layout/googleoptimizer.xml b/app/design/adminhtml/default/default/layout/googleoptimizer.xml deleted file mode 100644 index f8d02ac484..0000000000 --- a/app/design/adminhtml/default/default/layout/googleoptimizer.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - googleoptimizertab_googleoptimizer - - - - - - - - - - googleoptimizertab_googleoptimizer - - - - - - - - - - - - - cms_page_edit_tabs - addTab - - googleoptimizer_section - googleoptimizer/adminhtml_cms_page_edit_tab_googleoptimizer - - - - js - googleoptimizer_js - googleoptimizer/js - - - - - - - - - diff --git a/app/design/adminhtml/default/default/layout/promo.xml b/app/design/adminhtml/default/default/layout/promo.xml index 6916db131b..642380065e 100644 --- a/app/design/adminhtml/default/default/layout/promo.xml +++ b/app/design/adminhtml/default/default/layout/promo.xml @@ -51,6 +51,9 @@ + + + diff --git a/app/design/adminhtml/default/default/layout/sales.xml b/app/design/adminhtml/default/default/layout/sales.xml index 99742e844f..3ab7b25798 100644 --- a/app/design/adminhtml/default/default/layout/sales.xml +++ b/app/design/adminhtml/default/default/layout/sales.xml @@ -979,6 +979,10 @@ + + + + diff --git a/app/design/adminhtml/default/default/template/catalog/category/edit.phtml b/app/design/adminhtml/default/default/template/catalog/category/edit.phtml index 1cd8709ecc..7e60a6762e 100644 --- a/app/design/adminhtml/default/default/template/catalog/category/edit.phtml +++ b/app/design/adminhtml/default/default/template/catalog/category/edit.phtml @@ -196,4 +196,3 @@ } //]]> -getChildHtml('googleoptimizer_js') ?> diff --git a/app/design/adminhtml/default/default/template/catalog/product/edit/action/websites.phtml b/app/design/adminhtml/default/default/template/catalog/product/edit/action/websites.phtml index 236227c301..55b852f27e 100644 --- a/app/design/adminhtml/default/default/template/catalog/product/edit/action/websites.phtml +++ b/app/design/adminhtml/default/default/template/catalog/product/edit/action/websites.phtml @@ -33,16 +33,16 @@
getWebsitesReadonly()): ?>disabled="disabled" class="checkbox website-checkbox" id="add_product_website_getId() ?>" type="checkbox" /> - +
getGroupCollection($_website) as $_group): ?> -

getName() ?>

+

escapeHtml($_group->getName()) ?>

getStoreCollection($_group) as $_store): ?> - + @@ -71,16 +71,16 @@
getWebsitesReadonly()): ?>disabled="disabled" class="checkbox website-checkbox" id="remove_product_website_getId() ?>" type="checkbox"/> - +
getGroupCollection($_website) as $_group): ?> -

getName() ?>

+

escapeHtml($_group->getName()) ?>

getName() ?>escapeHtml($_store->getName()) ?>  
getStoreCollection($_group) as $_store): ?> - + diff --git a/app/design/adminhtml/default/default/template/catalog/product/edit/websites.phtml b/app/design/adminhtml/default/default/template/catalog/product/edit/websites.phtml index 85659c84f0..b0c7a1bc95 100644 --- a/app/design/adminhtml/default/default/template/catalog/product/edit/websites.phtml +++ b/app/design/adminhtml/default/default/template/catalog/product/edit/websites.phtml @@ -42,16 +42,16 @@
isReadonly()):?> disabled="disabled" class="checkbox website-checkbox" id="product_website_getId() ?>" type="checkbox"hasWebsite($_website->getId())): ?> checked="checked" /> - +
getGroupCollection($_website) as $_group): ?> -

getName() ?>

+

escapeHtml($_group->getName()) ?>

getName() ?>escapeHtml($_store->getName()) ?>  
getStoreCollection($_group) as $_store): ?> - + - + - - - - - - - - diff --git a/app/design/adminhtml/default/default/template/googleoptimizer/js.phtml b/app/design/adminhtml/default/default/template/googleoptimizer/js.phtml deleted file mode 100644 index 82f52d1b1e..0000000000 --- a/app/design/adminhtml/default/default/template/googleoptimizer/js.phtml +++ /dev/null @@ -1,177 +0,0 @@ - - diff --git a/app/design/adminhtml/default/default/template/payment/form/checkmo.phtml b/app/design/adminhtml/default/default/template/payment/form/checkmo.phtml index d727aec786..225721651a 100644 --- a/app/design/adminhtml/default/default/template/payment/form/checkmo.phtml +++ b/app/design/adminhtml/default/default/template/payment/form/checkmo.phtml @@ -28,12 +28,12 @@
  • getMethod()->getPayableTo()): ?> - __(' %s', $this->getMethod()->getPayableTo()) ?>
    + __(' %s', $this->escapeHtml($this->getMethod()->getPayableTo())) ?>
    getMethod()->getMailingAddress()): ?>
    - getMethod()->getMailingAddress()) ?> + escapeHtml($this->getMethod()->getMailingAddress())) ?>
    diff --git a/app/design/adminhtml/default/default/template/paypal/system/config/payflowlink/info.phtml b/app/design/adminhtml/default/default/template/paypal/system/config/payflowlink/info.phtml index fb64d002fe..b5e5351071 100644 --- a/app/design/adminhtml/default/default/template/paypal/system/config/payflowlink/info.phtml +++ b/app/design/adminhtml/default/default/template/paypal/system/config/payflowlink/info.phtml @@ -39,9 +39,9 @@ + + + diff --git a/app/design/adminhtml/default/default/template/catalog/form/renderer/googleoptimizer/import.phtml b/app/design/adminhtml/default/default/template/promo/js.phtml similarity index 51% rename from app/design/adminhtml/default/default/template/catalog/form/renderer/googleoptimizer/import.phtml rename to app/design/adminhtml/default/default/template/promo/js.phtml index 1c1db39c12..92551760ca 100644 --- a/app/design/adminhtml/default/default/template/catalog/form/renderer/googleoptimizer/import.phtml +++ b/app/design/adminhtml/default/default/template/promo/js.phtml @@ -24,32 +24,19 @@ * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ ?> -getElement()->getDisabled() || $this->getElement()->getReadonly()) { - $_disabled = ' disabled="disabled"'; + diff --git a/app/design/adminhtml/default/default/template/resetforgottenpassword.phtml b/app/design/adminhtml/default/default/template/resetforgottenpassword.phtml new file mode 100644 index 0000000000..98ca59ece7 --- /dev/null +++ b/app/design/adminhtml/default/default/template/resetforgottenpassword.phtml @@ -0,0 +1,78 @@ + + + + + + <?php echo Mage::helper('adminhtml')->__('Reset a Password'); ?> + + + + + + + + + + + + + + + diff --git a/app/design/adminhtml/default/default/template/sales/items/column/name.phtml b/app/design/adminhtml/default/default/template/sales/items/column/name.phtml index 12563e2b11..49d18806fc 100644 --- a/app/design/adminhtml/default/default/template/sales/items/column/name.phtml +++ b/app/design/adminhtml/default/default/template/sales/items/column/name.phtml @@ -41,17 +41,17 @@ getCustomizedOptionValue($_option); ?> - escapeHtml($_option['value'])); ?> - truncate($_option['value'], 55, '', $_remainder);?> - - ... + getFormattedOption($_option['value']); ?> + ... - - + + diff --git a/app/design/adminhtml/default/default/template/sales/order/create/js.phtml b/app/design/adminhtml/default/default/template/sales/order/create/js.phtml index 4d75a9ee7b..76a868fb7e 100644 --- a/app/design/adminhtml/default/default/template/sales/order/create/js.phtml +++ b/app/design/adminhtml/default/default/template/sales/order/create/js.phtml @@ -27,11 +27,13 @@ diff --git a/app/design/adminhtml/default/default/template/sales/order/totals/tax.phtml b/app/design/adminhtml/default/default/template/sales/order/totals/tax.phtml index d70ccf02f0..0000da9eb0 100644 --- a/app/design/adminhtml/default/default/template/sales/order/totals/tax.phtml +++ b/app/design/adminhtml/default/default/template/sales/order/totals/tax.phtml @@ -34,33 +34,58 @@ $_fullInfo = $this->getFullTaxInfo(); displayFullSummary()): ?> - - - + + + + - -
  • - - - - - - - - - - + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + displayFullSummary() && $_fullInfo): ?> diff --git a/app/design/adminhtml/default/default/template/sales/order/view/giftmessage.phtml b/app/design/adminhtml/default/default/template/sales/order/view/giftmessage.phtml index 19411c67b0..c1dae05959 100644 --- a/app/design/adminhtml/default/default/template/sales/order/view/giftmessage.phtml +++ b/app/design/adminhtml/default/default/template/sales/order/view/giftmessage.phtml @@ -45,7 +45,7 @@ - + diff --git a/app/design/adminhtml/default/default/template/sales/order/view/tab/history.phtml b/app/design/adminhtml/default/default/template/sales/order/view/tab/history.phtml index 49841c4fa9..63f3d57660 100644 --- a/app/design/adminhtml/default/default/template/sales/order/view/tab/history.phtml +++ b/app/design/adminhtml/default/default/template/sales/order/view/tab/history.phtml @@ -35,7 +35,9 @@ isItemNotified($_item, false)): ?> |helper('sales')->__('Customer') ?> - isItemNotified($_item)): ?> + isCustomerNotificationNotApplicable($_item)): ?> + helper('sales')->__('Notification Not Applicable') ?> + isItemNotified($_item)): ?> helper('sales')->__('Notified') ?> diff --git a/app/design/adminhtml/default/default/template/widget/grid.phtml b/app/design/adminhtml/default/default/template/widget/grid.phtml index 2a5877ecc2..15220c0343 100644 --- a/app/design/adminhtml/default/default/template/widget/grid.phtml +++ b/app/design/adminhtml/default/default/template/widget/grid.phtml @@ -159,7 +159,8 @@ $numColumns = sizeof($this->getColumns()); getRowspan($_item, $_column);?> shouldRenderEmptyCell($_item, $_column)):?> + + shouldRenderEmptyCell($_item, $_column)):?> diff --git a/app/design/adminhtml/default/find/layout/feed.xml b/app/design/adminhtml/default/find/layout/feed.xml deleted file mode 100644 index d95cf3aa28..0000000000 --- a/app/design/adminhtml/default/find/layout/feed.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - jsprototype/window.js - js_cssprototype/windows/themes/default.css - js_cssprototype/windows/themes/magento.css - - - - - - - - - - - - diff --git a/app/design/adminhtml/default/find/template/head/window.phtml b/app/design/adminhtml/default/find/template/head/window.phtml deleted file mode 100644 index 2883f1ca6d..0000000000 --- a/app/design/adminhtml/default/find/template/head/window.phtml +++ /dev/null @@ -1,42 +0,0 @@ - diff --git a/app/design/frontend/base/default/layout/customer.xml b/app/design/frontend/base/default/layout/customer.xml index 04475f2a78..a4be31dc1e 100644 --- a/app/design/frontend/base/default/layout/customer.xml +++ b/app/design/frontend/base/default/layout/customer.xml @@ -153,6 +153,29 @@ New customer registration + + + + + + + + Reset a Password + + + + + + + + Reset a Password + + + + + + + @@ -193,7 +216,7 @@ Customer account pages, rendered for all tabs in dashboard - + @@ -212,7 +235,7 @@ Customer account pages, rendered for all tabs in dashboard groupedcheckout/cart_item_renderer_grouped configurablecheckout/cart_item_renderer_configurable - + diff --git a/app/design/frontend/base/default/layout/googleoptimizer.xml b/app/design/frontend/base/default/layout/googleoptimizer.xml deleted file mode 100644 index 5b50989b10..0000000000 --- a/app/design/frontend/base/default/layout/googleoptimizer.xml +++ /dev/null @@ -1,140 +0,0 @@ - - - - - - - - - - control_script - - - - - tracking_script - - - - - - - - control_script - - - - - tracking_script - - - - - - - - control_script - - - - - tracking_script - - - - - - - - control_script - - - - - tracking_script - - - - - - - - conversion_script - checkout_cart - - - - - - - - conversion_script - checkout_onepage - - - - - - - - conversion_script - checkout_onepage_success - - - - - - - - conversion_script - checkout_multishipping_success - - - - - - - - conversion_script - checkout_multishipping - - - - - - - - conversion_script - customer_account_create - - - - - diff --git a/app/design/frontend/base/default/layout/paypal.xml b/app/design/frontend/base/default/layout/paypal.xml index 7308752b4c..d998024af6 100644 --- a/app/design/frontend/base/default/layout/paypal.xml +++ b/app/design/frontend/base/default/layout/paypal.xml @@ -171,11 +171,12 @@ Available logo types can be assigned with action="setLogoType": - + + - + diff --git a/app/design/frontend/base/default/template/catalog/product/view.phtml b/app/design/frontend/base/default/template/catalog/product/view.phtml index 48b5f19e7b..4ca4faefe8 100644 --- a/app/design/frontend/base/default/template/catalog/product/view.phtml +++ b/app/design/frontend/base/default/template/catalog/product/view.phtml @@ -71,6 +71,10 @@ getChildHtml('addto') ?> getChildHtml('extra_buttons') ?> + isSaleable()): ?> +
    + getChildHtml('addto') ?> +
    getShortDescription()):?> diff --git a/app/design/frontend/base/default/template/checkout/multishipping/agreements.phtml b/app/design/frontend/base/default/template/checkout/multishipping/agreements.phtml index 41689eeb46..d38203c04c 100644 --- a/app/design/frontend/base/default/template/checkout/multishipping/agreements.phtml +++ b/app/design/frontend/base/default/template/checkout/multishipping/agreements.phtml @@ -42,7 +42,7 @@

    - +

    diff --git a/app/design/frontend/base/default/template/checkout/onepage/agreements.phtml b/app/design/frontend/base/default/template/checkout/onepage/agreements.phtml index 95449b29eb..6f5e57a4e1 100644 --- a/app/design/frontend/base/default/template/checkout/onepage/agreements.phtml +++ b/app/design/frontend/base/default/template/checkout/onepage/agreements.phtml @@ -43,7 +43,7 @@

    - +

    diff --git a/app/design/frontend/base/default/template/checkout/onepage/payment.phtml b/app/design/frontend/base/default/template/checkout/onepage/payment.phtml index f9b2113bb6..8cae3a7a72 100644 --- a/app/design/frontend/base/default/template/checkout/onepage/payment.phtml +++ b/app/design/frontend/base/default/template/checkout/onepage/payment.phtml @@ -26,7 +26,10 @@ ?>
    diff --git a/app/design/frontend/base/default/template/customer/form/forgotpassword.phtml b/app/design/frontend/base/default/template/customer/form/forgotpassword.phtml index e3f7b3bc99..7ac734e4ff 100644 --- a/app/design/frontend/base/default/template/customer/form/forgotpassword.phtml +++ b/app/design/frontend/base/default/template/customer/form/forgotpassword.phtml @@ -31,7 +31,7 @@

    __('Retrieve your password here') ?>

    -

    __('Please enter your email below and we will send you a new password.') ?>

    +

    __('Please enter your email address below. You will receive a link to reset your password.') ?>

    • diff --git a/app/design/frontend/base/default/template/customer/form/resetforgottenpassword.phtml b/app/design/frontend/base/default/template/customer/form/resetforgottenpassword.phtml new file mode 100644 index 0000000000..df4b72e7ab --- /dev/null +++ b/app/design/frontend/base/default/template/customer/form/resetforgottenpassword.phtml @@ -0,0 +1,59 @@ + +
      +

      __('Reset a Password'); ?>

      +
      +getMessagesBlock()->getGroupedHtml(); ?> + +
      +
        +
      • +
        + +
        + +
        +
        +
        + +
        + +
        +
        +
      • +
      +
      +
      +

      __('* Required Fields'); ?>

      + +
      + + diff --git a/app/design/frontend/base/default/template/email/order/items/creditmemo/default.phtml b/app/design/frontend/base/default/template/email/order/items/creditmemo/default.phtml index 4a7a3eadae..0f0529be35 100644 --- a/app/design/frontend/base/default/template/email/order/items/creditmemo/default.phtml +++ b/app/design/frontend/base/default/template/email/order/items/creditmemo/default.phtml @@ -33,7 +33,7 @@
      getItemOptions() as $option): ?>
      -
      +
      diff --git a/app/design/frontend/base/default/template/email/order/items/invoice/default.phtml b/app/design/frontend/base/default/template/email/order/items/invoice/default.phtml index 4a7a3eadae..0f0529be35 100644 --- a/app/design/frontend/base/default/template/email/order/items/invoice/default.phtml +++ b/app/design/frontend/base/default/template/email/order/items/invoice/default.phtml @@ -33,7 +33,7 @@
      getItemOptions() as $option): ?>
      -
      +
      diff --git a/app/design/frontend/base/default/template/email/order/items/shipment/default.phtml b/app/design/frontend/base/default/template/email/order/items/shipment/default.phtml index b670897ec7..6aaa14d96a 100644 --- a/app/design/frontend/base/default/template/email/order/items/shipment/default.phtml +++ b/app/design/frontend/base/default/template/email/order/items/shipment/default.phtml @@ -32,7 +32,7 @@
      getItemOptions() as $option): ?>
      -
      +
      diff --git a/app/design/frontend/base/default/template/giftmessage/inline.phtml b/app/design/frontend/base/default/template/giftmessage/inline.phtml index e069c58bca..5353f9a060 100644 --- a/app/design/frontend/base/default/template/giftmessage/inline.phtml +++ b/app/design/frontend/base/default/template/giftmessage/inline.phtml @@ -36,33 +36,31 @@ if(!window.toogleVisibilityOnObjects) { item.removeClassName('validation-passed'); }); }); - - } else { objects.each(function(item){ - $(item).hide(); - $$('#' + item + ' .input-text').each(function(sitem) { - sitem.addClassName('validation-passed'); - }); - - $$('#' + item + ' .giftmessage-area').each(function(sitem) { - sitem.value = ''; - }); - $$('#' + item + ' .checkbox').each(function(sitem) { - sitem.checked = false; - }); - $$('#' + item + ' .select').each(function(sitem) { - sitem.value = ''; - }); - $$('#' + item + ' .price-box').each(function(sitem) { - sitem.addClassName('no-display'); - }); + if ($(item)) { + $(item).hide(); + $$('#' + item + ' .input-text').each(function(sitem) { + sitem.addClassName('validation-passed'); + }); + $$('#' + item + ' .giftmessage-area').each(function(sitem) { + sitem.value = ''; + }); + $$('#' + item + ' .checkbox').each(function(sitem) { + sitem.checked = false; + }); + $$('#' + item + ' .select').each(function(sitem) { + sitem.value = ''; + }); + $$('#' + item + ' .price-box').each(function(sitem) { + sitem.addClassName('no-display'); + }); + } }); - } - } } + if(!window.toogleRequired) { var toogleRequired = function (source, objects) { diff --git a/app/design/frontend/base/default/template/newsletter/subscribe.phtml b/app/design/frontend/base/default/template/newsletter/subscribe.phtml index e2565355b4..85e42a5872 100644 --- a/app/design/frontend/base/default/template/newsletter/subscribe.phtml +++ b/app/design/frontend/base/default/template/newsletter/subscribe.phtml @@ -30,6 +30,7 @@
    +
    diff --git a/app/design/frontend/base/default/template/pagecache/cookie.phtml b/app/design/frontend/base/default/template/pagecache/cookie.phtml index 454b5f09fa..d782782977 100644 --- a/app/design/frontend/base/default/template/pagecache/cookie.phtml +++ b/app/design/frontend/base/default/template/pagecache/cookie.phtml @@ -26,5 +26,11 @@ ?> diff --git a/app/design/frontend/base/default/template/payment/form/checkmo.phtml b/app/design/frontend/base/default/template/payment/form/checkmo.phtml index 82407a981c..5089d999b8 100644 --- a/app/design/frontend/base/default/template/payment/form/checkmo.phtml +++ b/app/design/frontend/base/default/template/payment/form/checkmo.phtml @@ -29,14 +29,14 @@ getMethod()->getPayableTo()): ?>
  • - getMethod()->getPayableTo() ?> + escapeHtml($this->getMethod()->getPayableTo()) ?>
  • getMethod()->getMailingAddress()): ?>
  • - getMethod()->getMailingAddress()) ?> + escapeHtml($this->getMethod()->getMailingAddress())) ?>
  • diff --git a/app/design/frontend/base/default/template/payment/info/checkmo.phtml b/app/design/frontend/base/default/template/payment/info/checkmo.phtml index 7037b0662a..1bbf4161a8 100644 --- a/app/design/frontend/base/default/template/payment/info/checkmo.phtml +++ b/app/design/frontend/base/default/template/payment/info/checkmo.phtml @@ -27,12 +27,12 @@

    getMethod()->getTitle() ?>

    getInfo()->getAdditionalData()): ?> getPayableTo()): ?> -

    __('Make Check payable to:') ?> htmlEscape($this->getPayableTo()) ?>

    +

    __('Make Check payable to:') ?> escapeHtml($this->getPayableTo()) ?>

    getMailingAddress()): ?>

    __('Send Check to:') ?>

    - htmlEscape($this->getMailingAddress())) ?> + escapeHtml($this->getMailingAddress())) ?>
    diff --git a/app/design/frontend/base/default/template/paypal/hss/iframe.phtml b/app/design/frontend/base/default/template/paypal/hss/iframe.phtml index d3bee8cbdc..1746f4502e 100644 --- a/app/design/frontend/base/default/template/paypal/hss/iframe.phtml +++ b/app/design/frontend/base/default/template/paypal/hss/iframe.phtml @@ -28,15 +28,15 @@
    __('Please do not refresh the page until you complete payment.') ?>
    - + + + diff --git a/app/design/frontend/base/default/template/paypal/payflowlink/iframe.phtml b/app/design/frontend/base/default/template/paypal/payflowlink/iframe.phtml new file mode 100644 index 0000000000..6e429a508c --- /dev/null +++ b/app/design/frontend/base/default/template/paypal/payflowlink/iframe.phtml @@ -0,0 +1,61 @@ + +getMethodCode() ?> + diff --git a/app/etc/modules/Find_Feed.xml b/app/design/frontend/base/default/template/paypal/payflowlink/info.phtml similarity index 73% rename from app/etc/modules/Find_Feed.xml rename to app/design/frontend/base/default/template/paypal/payflowlink/info.phtml index 4655dd9331..26bcb98cc1 100644 --- a/app/etc/modules/Find_Feed.xml +++ b/app/design/frontend/base/default/template/paypal/payflowlink/info.phtml @@ -1,5 +1,4 @@ - - - - - - true - community - - - + +/** + * @var $this Mage_Paypal_Block_Payflow_Link_Info + */ +?> + + + + + + diff --git a/app/design/frontend/base/default/template/paypal/payflowlink/redirect.phtml b/app/design/frontend/base/default/template/paypal/payflowlink/redirect.phtml new file mode 100644 index 0000000000..bbd7f539c6 --- /dev/null +++ b/app/design/frontend/base/default/template/paypal/payflowlink/redirect.phtml @@ -0,0 +1,82 @@ + + + + + + + diff --git a/app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml b/app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml index 7ebf78cd76..56be402b0b 100644 --- a/app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml +++ b/app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml @@ -199,16 +199,18 @@ $('billing-address-select') && billing.newAddress(!$('billing-address-select').value); var billingRegionUpdater = new RegionUpdater('billing:country_id', 'billing:region', 'billing:region_id', countryRegions, undefined, 'billing:postcode'); - Event.observe($('onepage-guest-register-button'), 'click', function(event) { - var billingRememberMe = $$('#billing-new-address-form li #remember-me-box'); - if(billingRememberMe.length > 0) { - billingRememberMe = $(billingRememberMe[0].parentNode); - if ($('login:guest') && $('login:guest').checked) { - billingRememberMe.hide(); - } else if ($('login:register') && ($('login:register').checked || $('login:register').type == 'hidden')) { - billingRememberMe.show(); + if ($('onepage-guest-register-button')) { + Event.observe($('onepage-guest-register-button'), 'click', function(event) { + var billingRememberMe = $$('#billing-new-address-form li #remember-me-box'); + if(billingRememberMe.length > 0) { + billingRememberMe = $(billingRememberMe[0].parentNode); + if ($('login:guest') && $('login:guest').checked) { + billingRememberMe.hide(); + } else if ($('login:register') && ($('login:register').checked || $('login:register').type == 'hidden')) { + billingRememberMe.show(); + } } - } - }) + }); + } //]]> diff --git a/app/design/frontend/base/default/template/wishlist/sidebar.phtml b/app/design/frontend/base/default/template/wishlist/sidebar.phtml index 8f36969803..50abb0bb19 100644 --- a/app/design/frontend/base/default/template/wishlist/sidebar.phtml +++ b/app/design/frontend/base/default/template/wishlist/sidebar.phtml @@ -37,13 +37,13 @@ getWishlistItems() as $_item): ?> getProduct(); ?>
  • - <?php echo $this->htmlEscape($product->getName()) ?> + <?php echo $this->escapeHtml($product->getName()) ?>
    __('Remove This Item') ?> -

    htmlEscape($product->getName()) ?>

    +

    escapeHtml($product->getName()) ?>

    getPriceHtml($product, false, '-wishlist') ?> isSaleable() && $product->isVisibleInSiteVisibility()): ?> - __('Add to Cart') ?> + __('Add to Cart') ?>
  • diff --git a/app/design/frontend/base/default/template/wishlist/view.phtml b/app/design/frontend/base/default/template/wishlist/view.phtml index baa2dafc92..31ec3437aa 100644 --- a/app/design/frontend/base/default/template/wishlist/view.phtml +++ b/app/design/frontend/base/default/template/wishlist/view.phtml @@ -25,6 +25,7 @@ */ /* @var $this Mage_Wishlist_Block_Customer_Wishlist */ ?> +helper('wishlist')->isAllow()) : ?>
    helper('wishlist')->isRssAllow() && $this->hasWishlistItems()): ?> @@ -60,8 +61,8 @@ ?>
    @@ -151,3 +152,4 @@ + diff --git a/app/design/frontend/default/iphone/template/wishlist/view.phtml b/app/design/frontend/default/iphone/template/wishlist/view.phtml index 0cc2ad604e..10e10d8410 100644 --- a/app/design/frontend/default/iphone/template/wishlist/view.phtml +++ b/app/design/frontend/default/iphone/template/wishlist/view.phtml @@ -25,6 +25,7 @@ */ /* @var $this Mage_Wishlist_Block_Customer_Wishlist */ ?> +helper('wishlist')->isAllow()) : ?>
    helper('wishlist')->isRssAllow() && $this->hasWishlistItems()): ?> @@ -53,8 +54,8 @@ getWishlistItems() as $item): ?>
    getName() ?>escapeHtml($_store->getName()) ?> getWebsites() && !$this->hasWebsite($_website->getId())): ?>
    /> getFieldValue('use_config_min_qty') || $this->IsNew()) ? 'checked="checked"' : '' ?> @@ -175,7 +175,8 @@ //
    - - - /> - __('Please copy and paste this value to experiment edit form') ?>  
    getSaveButtonHtml(); ?>class="getCssProperty() ?> "> getRowField($_item)) != '' ? $_html : ' ') ?> - getEmptyCellLabel()?>
    - <?php echo $this->htmlEscape($product->getName()) ?> -

    htmlEscape($product->getName()) ?>

    + <?php echo $this->escapeHtml($product->getName()) ?> +

    escapeHtml($product->getName()) ?>

    getPriceHtml($product) ?> getDetailsHtml($item) ?>
    - <?php echo $this->htmlEscape($item->getName()) ?> -

    htmlEscape($item->getName()) ?>

    + <?php echo $this->escapeHtml($item->getName()) ?> +

    escapeHtml($item->getName()) ?>

    getPriceHtml($item) ?>
    @@ -140,3 +141,4 @@ + diff --git a/app/design/frontend/default/modern/template/newsletter/subscribe.phtml b/app/design/frontend/default/modern/template/newsletter/subscribe.phtml index aadb52d5b4..2ef8a57cf0 100644 --- a/app/design/frontend/default/modern/template/newsletter/subscribe.phtml +++ b/app/design/frontend/default/modern/template/newsletter/subscribe.phtml @@ -26,6 +26,7 @@ ?>