diff --git a/RELEASE_NOTES.txt b/RELEASE_NOTES.txt index de3ea51e0f..b09f515d9a 100644 --- a/RELEASE_NOTES.txt +++ b/RELEASE_NOTES.txt @@ -1,3 +1,751 @@ +==== 1.6.1.0 ==== + +=== Major Highlights === +Added two-step password reset flow + +=== Improvements === +XmlConnect package release v22.0 +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 +Updated webservices API + +=== 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 Incorrect tax summary if taxes applied has different priorities +Fixed Shipping method extension after disable module returns error +Fixed Approved Review of a product is not displayed in the catalog +Fixed Special price is not considered for bundle dynamic products in "Your Customization" block +Fixed Incorrect behavior of changing quantity for composite products in Wishlist tab of customer's page in backend +Fixed MAP: Exc. Tax. amount is not shown on product's page when set apply map = 'On Gesture' +Fixed There has been an error processing your request is displayed by searching in Manage Checkout Terms and Conditions +Fixed Button Reorder is absent when Order contains Configurable product +Fixed Unable to place order if several tax rates with different priorities applied to bundle product +Fixed Incorrect Tracking Request to shipping carrier (in case with FedEx) +Fixed 'Click for price' not clickable after pressing 'Review' link in category +Fixed XML Connect: Impossible to submit application +Fixed MAP: with IE8 JS error appears in catalog +Fixed Error message appears after successful checkout with PayPal Express Checkout on IE9 +Fixed Incorrect invoice document creation behaviour for bundle dynamic product +Fixed XML Connect: Impossible to save template +Fixed Wrong focusing in WYSIWYG on IE9, impossible to save data after inserting content +Fixed Unable to set zero price for item in bundle product +Fixed Incorrect tax summary if several tax rates with different priorities applied to bundle product +Fixed Unable to create order from backend if Tax Calculation Method Based On = Unit Price/Row Total +Fixed Incorrect Tracking Request to shipping carrier (in case with FedEx) +Fixed Incorrect tax summary for partial documents if Tax Calculation Method Based On = Row Total/Unit Price +Fixed Problems with partial authorization process (Authorize.net) during Admin Order creation +Fixed Incorrect HTML markup of Installer page in IE7 and IE9 +Fixed "Apply Rules" button works incorrect in some cases +Fixed Incorrect behavior of changing quantity for composite products in Wishlist tab of customer's page in backend +Fixed Incorrect tax summary if product prices exclude tax +Fixed Redirect to blank page, when click Add Wishlist on the Bundle product page +Fixed Reviews not showing in category list page +Fixed QTY is wrong calculated for Bundle, Virtual, Simple, Configurable, Downloadable products after editing them in wishlist +Fixed Customer is redirected to shopping cart page instead to the "Ship to Multiple Addresses" page after login or register as a new customer +Fixed Configurable product with selected option is deleted from wishlist after updating another configurable product +Fixed After redirecting to product using tag 'click for price' doesn't work +Fixed "Notify for Quantity Below" doesn't work +Fixed Pending Reviews RSS doesn't show reviews, created for products, that are assigned not to Main Website +Fixed Authorize Direct Post: no successful notification about place order if do 'Edit' or 'Reorder' +Fixed Impossible to place Order with Payfowlink when Payment Action = Sale +Fixed Poll shows incorrect percentage +Fixed Message 'Cannot specify wishlist item.' is displayed by configuring products in wishlist in back-end +Fixed Billing Agreements: Order status is not updated if do actions from sandbox PayPal account +Fixed Additional authorization transaction is not displayed in Order's Transactions tab +Fixed Unable to update already created role by Admin +Fixed CDN Secure URL is used instead of non-secure +Fixed Attributes name disappeared during sorting +Fixed Typo in app/design/adminhtml/default/default/template/paypal/system/config/payflowlink/info.phtml +Fixed Report of Reviews shows all customer reviews when select certain user +Fixed Address Line Formats Incorrectly on PDF Invoices +Fixed Can't search transactions by order_id in manager.paypal.com +Fixed Wishlist Index Controller does unneeded logging of exception +Fixed Incorrect SQL generated in review product collection resource +Fixed Added shipping address rates collecting schedule for shipping method when shipping information step bypassed +Fixed Customer marked as guest in "Newsletter Subscribers" grid, after subscribing to newsletters in Google Checkout +Fixed Error is displayed by unchecking "Same As Billing Address" by creating order in admin +Fixed Tooltip doesn't appear if you put mouse pointer in to disabled package type field (in case with USPS Domestic) +Fixed Unable to select custom theme with underscores in name when creating a widget instance +Fixed When Redirect to Shopping Cart = No, choosing Remove item from shopping cart sidebar while editing an item leads to endless redirect loop +Fixed Saved CC form is not displayed, when there are no other available payment methods except Saved CC +Fixed It's impossible to create Catalog Price Rule +Fixed Fatal error on Multiple Addresses Checkout +Fixed Package Types that not available for current Shipping Method displayed in Create Packages pop-up +Fixed Stock item product getter not correspond to product setter +- added method getProduct() +Fixed Admin user interface: mistakes in labels names +Fixed Typo in Mage_Eav_Model_Resource_Entity_Attribute_Option model +Fixed Billing Agreement error +Fixed Payflow Link UI Changes +Fixed 'Website Payments Pro' impossible to place order during onepage checkout +Fixed Table rates works incorrect with asterisk +Fixed Typo in Category Resource Model +Fixed 3D secure with Saved CC works incorrectly +- removed unrelated message which told validation failed (even if it has actually succeeded) when trying to re-validate a card +Fixed Bug in Role Permission +Fixed Orders placed via Google Checkout were not created on the Magento side +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 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.1.0-rc1 ==== + +=== Major Highlights === +Added two-step password reset flow + +=== Improvements === +XmlConnect package release v22.0 +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 Incorrect behavior of changing quantity for composite products in Wishlist tab of customer's page in backend +Fixed Incorrect tax summary if product prices exclude tax +Fixed Redirect to blank page, when click Add Wishlist on the Bundle product page +Fixed Reviews not showing in category list page +Fixed QTY is wrong calculated for Bundle, Virtual, Simple, Configurable, Downloadable products after editing them in wishlist +Fixed Customer is redirected to shopping cart page instead to the "Ship to Multiple Addresses" page after login or register as a new customer +Fixed Configurable product with selected option is deleted from wishlist after updating another configurable product +Fixed After redirecting to product using tag 'click for price' doesn't work +Fixed "Notify for Quantity Below" doesn't work +Fixed Pending Reviews RSS doesn't show reviews, created for products, that are assigned not to Main Website +Fixed Authorize Direct Post: no successful notification about place order if do 'Edit' or 'Reorder' +Fixed Impossible to place Order with Payfowlink when Payment Action = Sale +Fixed Poll shows incorrect percentage +Fixed Message 'Cannot specify wishlist item.' is displayed by configuring products in wishlist in back-end +Fixed Billing Agreements: Order status is not updated if do actions from sandbox PayPal account +Fixed Additional authorization transaction is not displayed in Order's Transactions tab +Fixed Unable to update already created role by Admin +Fixed CDN Secure URL is used instead of non-secure +Fixed Attributes name disappeared during sorting +Fixed Typo in app/design/adminhtml/default/default/template/paypal/system/config/payflowlink/info.phtml +Fixed Report of Reviews shows all customer reviews when select certain user +Fixed Address Line Formats Incorrectly on PDF Invoices +Fixed Can't search transactions by order_id in manager.paypal.com +Fixed Wishlist Index Controller does unneeded logging of exception +Fixed Incorrect SQL generated in review product collection resource +Fixed Added shipping address rates collecting schedule for shipping method when shipping information step bypassed +Fixed Customer marked as guest in "Newsletter Subscribers" grid, after subscribing to newsletters in Google Checkout +Fixed Error is displayed by unchecking "Same As Billing Address" by creating order in admin +Fixed Tooltip doesn't appear if you put mouse pointer in to disabled package type field (in case with USPS Domestic) +Fixed Unable to select custom theme with underscores in name when creating a widget instance +Fixed When Redirect to Shopping Cart = No, choosing Remove item from shopping cart sidebar while editing an item leads to endless redirect loop +Fixed Saved CC form is not displayed, when there are no other available payment methods except Saved CC +Fixed It's impossible to create Catalog Price Rule +Fixed Fatal error on Multiple Addresses Checkout +Fixed Package Types that not available for current Shipping Method displayed in Create Packages pop-up +Fixed Stock item product getter not correspond to product setter +- added method getProduct() +Fixed Admin user interface: mistakes in labels names +Fixed Typo in Mage_Eav_Model_Resource_Entity_Attribute_Option model +Fixed Billing Agreement error +Fixed Payflow Link UI Changes +Fixed 'Website Payments Pro' impossible to place order during onepage checkout +Fixed Table rates works incorrect with asterisk +Fixed Typo in Category Resource Model +Fixed 3D secure with Saved CC works incorrectly +- removed unrelated message which told validation failed (even if it has actually succeeded) when trying to re-validate a card +Fixed Bug in Role Permission +Fixed Orders placed via Google Checkout were not created on the Magento side +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 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.1.0-beta1 ==== + +=== 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 Saved CC form is not displayed, when there are no other available payment methods except Saved CC +Fixed It's impossible to create Catalog Price Rule +Fixed Fatal error on Multiple Addresses Checkout +Fixed Package Types that not available for current Shipping Method displayed in Create Packages pop-up +Fixed Stock item product getter not correspond to product setter +- added method getProduct() +Fixed Admin user interface: mistakes in labels names +Fixed Typo in Mage_Eav_Model_Resource_Entity_Attribute_Option model +Fixed Billing Agreement error +Fixed Payflow Link UI Changes +Fixed 'Website Payments Pro' impossible to place order during onepage checkout +Fixed Table rates works incorrect with asterisk +Fixed Typo in Category Resource Model +Fixed 3D secure with Saved CC works incorrectly +- removed unrelated message which told validation failed (even if it has actually succeeded) when trying to re-validate a card +Fixed Bug in Role Permission +Fixed Orders placed via Google Checkout were not created on the Magento side +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.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..4d50995d90 100644 --- a/app/Mage.php +++ b/app/Mage.php @@ -152,7 +152,7 @@ public static function getVersionInfo() return array( 'major' => '1', 'minor' => '6', - 'revision' => '0', + 'revision' => '1', 'patch' => '0', 'stability' => '', 'number' => '', 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/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/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..fc89023963 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,20 @@ 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']); + } else { + $shippingTax = Mage::helper('tax')->getShippingTax($source); + $taxClassAmount = array_merge($shippingTax, $taxClassAmount); + } } - 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/Block/Widget/Grid/Column/Renderer/Options.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Options.php index 24c9952b57..1a1d984c0b 100644 --- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Options.php +++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Options.php @@ -56,9 +56,10 @@ public function render(Varien_Object $row) } } return implode(', ', $res); - } - elseif (isset($options[$value])) { + } elseif (isset($options[$value])) { return $options[$value]; + } elseif (in_array($value, $options)) { + return $value; } return ''; } 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 @@ -456,7 +463,8 @@ T: {{var telephone}} {{depend street2}}{{var street2}}|{{/depend}} {{depend street3}}{{var street3}}|{{/depend}} {{depend street4}}{{var street4}}|{{/depend}} -{{if city}}{{var city}}, {{/if}}{{if region}}{{var region}}, {{/if}}{{if postcode}}{{var postcode}}{{/if}}| +{{if city}}{{var city}},|{{/if}} +{{if region}}{{var region}}, {{/if}}{{if postcode}}{{var postcode}}{{/if}}| {{var country}}| {{depend telephone}}T: {{var telephone}}{{/depend}}| {{depend fax}}<br/>F: {{var fax}}{{/depend}}| 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/Downloadable/Model/Link/Api.php b/app/code/core/Mage/Downloadable/Model/Link/Api.php new file mode 100644 index 0000000000..96a30973c1 --- /dev/null +++ b/app/code/core/Mage/Downloadable/Model/Link/Api.php @@ -0,0 +1,276 @@ + + */ +class Mage_Downloadable_Model_Link_Api extends Mage_Catalog_Model_Api_Resource +{ + /** + * Return validator instance + * + * @return Mage_Downloadable_Model_Link_Api_Validator + */ + protected function _getValidator() + { + return Mage::getSingleton('downloadable/link_api_validator'); + } + + /** + * Decode file from base64 and upload it to donwloadable 'tmp' folder + * + * @param array $fileInfo + * @param string $type + * @return string + */ + protected function _uploadFile($fileInfo, $type) + { + $tmpPath = ''; + if ($type == 'sample') { + $tmpPath = Mage_Downloadable_Model_Sample::getBaseTmpPath(); + } elseif ($type == 'link') { + $tmpPath = Mage_Downloadable_Model_Link::getBaseTmpPath(); + } elseif ($type == 'link_samples') { + $tmpPath = Mage_Downloadable_Model_Link::getBaseSampleTmpPath(); + } + + $result = array(); + try { + $uploader = Mage::getModel('downloadable/link_api_uploader', $fileInfo); + $uploader->setAllowRenameFiles(true); + $uploader->setFilesDispersion(true); + $result = $uploader->save($tmpPath); + + if (isset($result['file'])) { + $fullPath = rtrim($tmpPath, DS) . DS . ltrim($result['file'], DS); + Mage::helper('core/file_storage_database')->saveFile($fullPath); + } + } catch (Exception $e) { + if ($e->getMessage() != '') { + $this->_fault('upload_failed', $e->getMessage()); + } else { + $this->_fault($e->getCode()); + } + } + + $result['status'] = 'new'; + $result['name'] = substr($result['file'], strrpos($result['file'], '/')+1); + return Mage::helper('core')->jsonEncode(array($result)); + } + + /** + * Add downloadable content to product + * + * @param int|string $productId + * @param array $resource + * @param string $resourceType + * @param string|int|null $store + * @param string|null $identifierType ('sku'|'id') + * @return boolean + */ + public function add($productId, $resource, $resourceType, $store = null, $identifierType = null) + { + try { + $this->_getValidator()->validateType($resourceType); + $this->_getValidator()->validateAttributes($resource, $resourceType); + } catch (Exception $e) { + $this->_fault('validation_error', $e->getMessage()); + } + + $resource['is_delete'] = 0; + if ($resourceType == 'link') { + $resource['link_id'] = 0; + } elseif ($resourceType == 'sample') { + $resource['sample_id'] = 0; + } + + if ($resource['type'] == 'file') { + if (isset($resource['file'])) { + $resource['file'] = $this->_uploadFile($resource['file'], $resourceType); + } + unset($resource[$resourceType.'_url']); + } elseif ($resource['type'] == 'url') { + unset($resource['file']); + } + + if ($resourceType == 'link' && $resource['sample']['type'] == 'file') { + if (isset($resource['sample']['file'])) { + $resource['sample']['file'] = $this->_uploadFile($resource['sample']['file'], 'link_samples'); + } + unset($resource['sample']['url']); + } elseif ($resourceType == 'link' && $resource['sample']['type'] == 'url') { + $resource['sample']['file'] = null; + } + + $product = $this->_getProduct($productId, $store, $identifierType); + try { + $downloadable = array($resourceType => array($resource)); + $product->setDownloadableData($downloadable); + $product->save(); + } catch (Exception $e) { + $this->_fault('save_error', $e->getMessage()); + } + + return true; + } + + /** + * Retrieve downloadable product links + * + * @param int|string $productId + * @param string|int $store + * @param string $identifierType ('sku'|'id') + * @return array + */ + public function items($productId, $store = null, $identifierType = null) + { + $product = $this->_getProduct($productId, $store, $identifierType); + + $linkArr = array(); + $links = $product->getTypeInstance(true)->getLinks($product); + foreach ($links as $item) { + $tmpLinkItem = array( + 'link_id' => $item->getId(), + 'title' => $item->getTitle(), + 'price' => $item->getPrice(), + 'number_of_downloads' => $item->getNumberOfDownloads(), + 'is_shareable' => $item->getIsShareable(), + 'link_url' => $item->getLinkUrl(), + 'link_type' => $item->getLinkType(), + 'sample_file' => $item->getSampleFile(), + 'sample_url' => $item->getSampleUrl(), + 'sample_type' => $item->getSampleType(), + 'sort_order' => $item->getSortOrder() + ); + $file = Mage::helper('downloadable/file')->getFilePath( + Mage_Downloadable_Model_Link::getBasePath(), $item->getLinkFile() + ); + + if ($item->getLinkFile() && !is_file($file)) { + Mage::helper('core/file_storage_database')->saveFileToFilesystem($file); + } + + if ($item->getLinkFile() && is_file($file)) { + $name = Mage::helper('downloadable/file')->getFileFromPathFile($item->getLinkFile()); + $tmpLinkItem['file_save'] = array( + array( + 'file' => $item->getLinkFile(), + 'name' => $name, + 'size' => filesize($file), + 'status' => 'old' + )); + } + $sampleFile = Mage::helper('downloadable/file')->getFilePath( + Mage_Downloadable_Model_Link::getBaseSamplePath(), $item->getSampleFile() + ); + if ($item->getSampleFile() && is_file($sampleFile)) { + $tmpLinkItem['sample_file_save'] = array( + array( + 'file' => $item->getSampleFile(), + 'name' => Mage::helper('downloadable/file')->getFileFromPathFile($item->getSampleFile()), + 'size' => filesize($sampleFile), + 'status' => 'old' + )); + } + if ($item->getNumberOfDownloads() == '0') { + $tmpLinkItem['is_unlimited'] = 1; + } + if ($product->getStoreId() && $item->getStoreTitle()) { + $tmpLinkItem['store_title'] = $item->getStoreTitle(); + } + if ($product->getStoreId() && Mage::helper('downloadable')->getIsPriceWebsiteScope()) { + $tmpLinkItem['website_price'] = $item->getWebsitePrice(); + } + $linkArr[] = $tmpLinkItem; + } + unset($item); + unset($tmpLinkItem); + unset($links); + + $samples = $product->getTypeInstance(true)->getSamples($product)->getData(); + return array('links' => $linkArr, 'samples' => $samples); + } + + /** + * Remove downloadable product link + * @param string $linkId + * @param string $resourceType + * @return bool + */ + public function remove($linkId, $resourceType) + { + try { + $this->_getValidator()->validateType($resourceType); + } catch (Exception $e) { + $this->_fault('validation_error', $e->getMessage()); + } + + switch($resourceType) { + case 'link': + $downloadableModel = Mage::getSingleton('downloadable/link'); + break; + case 'sample': + $downloadableModel = Mage::getSingleton('downloadable/sample'); + break; + } + + $downloadableModel->load($linkId); + if (is_null($downloadableModel->getId())) { + $this->_fault('link_was_not_found'); + } + + try { + $downloadableModel->delete(); + } catch (Exception $e) { + $this->_fault('remove_error', $e->getMessage()); + } + + return true; + } + + /** + * Return loaded downloadable product instance + * + * @param int|string $productId (SKU or ID) + * @param int|string $store + * @param string $identifierType + * @return Mage_Catalog_Model_Product + */ + protected function _getProduct($productId, $store = null, $identifierType = null) + { + $product = parent::_getProduct($productId, $store, $identifierType); + + if ($product->getTypeId() !== Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE) { + $this->_fault('product_not_downloadable'); + } + + return $product; + } +} diff --git a/app/code/core/Mage/Downloadable/Model/Link/Api/Uploader.php b/app/code/core/Mage/Downloadable/Model/Link/Api/Uploader.php new file mode 100644 index 0000000000..5751f8dac6 --- /dev/null +++ b/app/code/core/Mage/Downloadable/Model/Link/Api/Uploader.php @@ -0,0 +1,129 @@ + + */ +class Mage_Downloadable_Model_Link_Api_Uploader extends Mage_Core_Model_File_Uploader +{ + /** + * Filename prefix + * + * @var string + */ + protected $_filePrefix = 'Api'; + + /** + * Default file type + */ + const DEFAULT_FILE_TYPE = 'application/octet-stream'; + + /** + * Check if the uploaded file exists + * + * @throws Exception + * @param array $file + */ + public function __construct($file) + { + $this->_setUploadFile($file); + if( !file_exists($this->_file['tmp_name']) ) { + throw new Exception('', 'file_not_uploaded'); + } else { + $this->_fileExists = true; + } + } + + /** + * Sets uploaded file info and decodes the file + * + * @throws Exception + * @param array $fileInfo + * @return void + */ + private function _setUploadFile($fileInfo) + { + if (!is_array($fileInfo)) { + throw new Exception('', 'file_data_not_correct'); + } + + $this->_file = $this->_decodeFile($fileInfo); + $this->_uploadType = self::SINGLE_STYLE; + } + + /** + * Decode uploaded file base64 encoded content + * + * @param array $fileInfo + * @return array + */ + private function _decodeFile($fileInfo) + { + $tmpFileName = $this->_getTmpFilePath(); + + $file = new Varien_Io_File(); + $file->open(array('path' => sys_get_temp_dir())); + $file->streamOpen($tmpFileName); + $file->streamWrite(base64_decode($fileInfo['base64_content'])); + $file->streamClose(); + + return array( + 'name' => $fileInfo['name'], + 'type' => isset($fileInfo['type'])? $fileInfo['type'] : self::DEFAULT_FILE_TYPE, + 'tmp_name' => $tmpFileName, + 'error' => 0, + 'size' => filesize($tmpFileName) + ); + } + + /** + * Generate temporary file name + * + * @return string + */ + private function _getTmpFilePath() + { + return tempnam(sys_get_temp_dir(), $this->_filePrefix); + + } + + /** + * Moves a file + * + * @param string $sourceFile + * @param string $destinationFile + * @return bool + */ + protected function _moveFile($sourceFile, $destinationFile) + { + return rename($sourceFile, $destinationFile); + } + +} diff --git a/app/code/core/Mage/Downloadable/Model/Link/Api/V2.php b/app/code/core/Mage/Downloadable/Model/Link/Api/V2.php new file mode 100644 index 0000000000..7b9eb1dcbb --- /dev/null +++ b/app/code/core/Mage/Downloadable/Model/Link/Api/V2.php @@ -0,0 +1,67 @@ + + */ +class Mage_Downloadable_Model_Link_Api_V2 extends Mage_Downloadable_Model_Link_Api +{ + /** + * Clean the object, leave only property values + * + * @param object $var + * @return void + */ + protected function _prepareData(&$var) + { + if (is_object($var)) { + $var = get_object_vars($var); + foreach ($var as $key => &$value) { + $this->_prepareData($value); + } + } + } + + /** + * Add downloadable content to product + * + * @param int|string $productId + * @param object $resource + * @param string $resourceType + * @param string|int $store + * @param string $identifierType ('sku'|'id') + * @return type + */ + public function add($productId, $resource, $resourceType, $store = null, $identifierType = null) + { + $this->_prepareData($resource); + return parent::add($productId, $resource, $resourceType, $store, $identifierType); + } +} diff --git a/app/code/core/Mage/Downloadable/Model/Link/Api/Validator.php b/app/code/core/Mage/Downloadable/Model/Link/Api/Validator.php new file mode 100644 index 0000000000..3684a6d5bd --- /dev/null +++ b/app/code/core/Mage/Downloadable/Model/Link/Api/Validator.php @@ -0,0 +1,286 @@ + + */ +class Mage_Downloadable_Model_Link_Api_Validator //extends Mage_Api_Model_Resource_Abstract +{ + /** + * Acceptable resourceTypes array + * @var array + */ + protected $_types = array('link', 'sample'); + + /** + * Acceptable upload types array + * @var array + */ + protected $_uploadTypes = array('file', 'url'); + + /** + * List of all attributes and names endings of validation functions + * + * @var array + */ + protected $_defaultAttributes = array( + 'link' => array( + 'title' => 'Title', // $1 + 'price' => 'Price', // $2 + 'number_of_downloads' => 'NumOfDownloads', // if no set is_unlimited to 1 $3 + 'is_unlimited' => 'Unlimited', // 1|0 $4 + 'is_shareable' => 'Shareable', // 1|0|2 (2) $5 + 'type' => 'UploadType', // file|url (file) $6 + 'file' => 'File', // array(name, base64_content) $7 + 'link_url' => 'Url', // URL $8 + 'sort_order' => 'Order', // int (0) $9 + 'sample' => array( + 'type' => 'UploadType', // file|url (file) $6 + 'file' => 'File', // array(name, base64_content) $7 + 'url' => 'Url' // URL $8 + ) + ), + 'sample' => array( + 'title' => 'Title', // $1 + 'type' => 'UploadType', // file|url (file) $6 + 'file' => 'File', // array(name, base64_content) $7 + 'sample_url' => 'Url', // URL $8 + 'sort_order' => 'Order' // int (0) $9 + ) + ); + + /** + * Get resource types + * + * @return array + */ + public function getResourceTypes() + { + return $this->_types; + } + + /** + * Validate resourceType, it should be one of (links|samples|link_samples) + * + * @param string $type + * @return boolean + */ + public function validateType($type) + { + if (!in_array($type, $this->getResourceTypes())) { + throw new Exception('unknown_resource_type'); + } + return true; + } + + /** + * Validate all parameters and loads default values for omitted parameters. + * + * @param array $resource + * @param string $resourceType + */ + public function validateAttributes(&$resource, $resourceType) + { + $fields = $this->_defaultAttributes[$resourceType]; + $this->_dispatch($resource, $fields); + + $this->completeCheck($resource, $resourceType); + } + + /** + * Final check + * + * @param array $resource + * @param string $resourceType + */ + public function completeCheck(&$resource, $resourceType) + { + if ($resourceType == 'link') { + if ($resource['type'] == 'file') { + $this->validateFileDetails($resource['file']); + } + if ($resource['type'] == 'url' && empty($resource['link_url'])) { + throw new Exception('empty_url'); + } + // sample + if ($resource['sample']['type'] == 'file') { + $this->validateFileDetails($resource['sample']['file']); + } + if ($resource['sample']['type'] == 'url' && empty($resource['sample']['url'])) { + throw new Exception('empty_url'); + } + } + if ($resourceType == 'sample') { + if ($resource['type'] == 'file') { + $this->validateFileDetails($resource['file']); + } + if ($resource['type'] == 'url' && empty($resource['sample_url'])) { + throw new Exception('empty_url'); + } + } + } + + /** + * Validate variable, in case of fault throw exception + * + * @param mixed $var + */ + public function validateFileDetails(&$var) + { + if (!isset ($var['name']) || !is_string($var['name']) || strlen($var['name']) === 0) { + throw new Exception('no_filename'); + } + if (!isset ($var['base64_content']) + || !is_string($var['base64_content']) + || strlen($var['base64_content']) === 0 + ) { + throw new Exception('no_file_base64_content'); + } + } + + /** + * Runs all checks. + * + * @param array $resource + * @param array $fields + */ + protected function _dispatch(&$resource, $fields) + { + foreach ($fields as $name => $validator) { + if (is_string($validator) && strlen($validator) > 0 && array_key_exists($name, $resource)) { + $call = 'validate' . $validator; + $this->$call($resource[$name]); + } + if (is_array($validator)) { + $this->_dispatch($resource[$name], $validator); + } + } + } + + /** + * Validate variable, in case of fault loads default entity. + * + * @param string $var + */ + public function validateTitle(&$var) + { + if (!is_string($var) || strlen($var) === 0) { + throw new Exception('no_title'); + } + } + + /** + * Validate variable, in case of fault loads default entity. + * + * @param float $var + */ + public function validatePrice(&$var) + { + $var = is_numeric($var)? floatval($var) : floatval(0); + } + + /** + * Validate variable, in case of fault loads default entity. + * + * @param int $var + */ + public function validateNumOfDownloads(&$var) + { + $var = is_numeric($var)? intval($var) : 0; + } + + /** + * Validate variable, in case of fault loads default entity. + * + * @param int|boolean $var + */ + public function validateUnlimited(&$var) + { + $var = ((is_numeric($var) && $var >= 0 && $var <= 1) || (is_bool($var)))? intval($var) : 0; + } + + /** + * Validate variable, in case of fault loads default entity. + * + * @param int $var + */ + public function validateShareable(&$var) + { + $var = (is_numeric($var) && $var >= 0 && $var <= 2)? intval($var) : 2; + } + + /** + * Validate variable, in case of fault loads default entity. + * + * @param array $var + */ + public function validateFile(&$var) + { + $var = is_array($var)? $var : null; + } + + /** + * Validate variable, in case of fault loads default entity. + * + * @param string $var + */ + public function validateUrl(&$var) + { + + if (is_string($var) && strlen($var) > 0) { + $urlregex = "/^(https?|ftp)\:\/\/([a-z0-9+\!\*\(\)\,\;\?\&\=\$\_\.\-]+(\:[a-z0-9+\!\*\(\)\,\;\?\&\=\$\_\.\-]+)?@)?[a-z0-9\+\$\_\-]+(\.[a-z0-9+\$\_\-]+)*(\:[0-9]{2,5})?(\/([a-z0-9+\$\_\-]\.?)+)*\/?(\?[a-z\+\&\$\_\.\-][a-z0-9\;\:\@\/\&\%\=\+\$\_\.\-]*)?(#[a-z\_\.\-][a-z0-9\+\$\_\.\-]*)?$/i"; + if (!preg_match($urlregex, $var)) { + throw new Exception('url_not_valid'); + } + } else { + $var = ''; + } + } + + /** + * Validate variable, in case of fault loads default entity. + * + * @param int $var + */ + public function validateOrder(&$var) + { + $var = is_numeric($var)? intval($var) : 0; + } + + /** + * Validate variable, in case of fault loads default entity. + * + * @param string $var + */ + public function validateUploadType(&$var) + { + $var = in_array($var, $this->_uploadTypes)? $var : 'file'; + } +} diff --git a/app/code/core/Mage/Downloadable/Model/Resource/Indexer/Price.php b/app/code/core/Mage/Downloadable/Model/Resource/Indexer/Price.php index 25bd48402d..53cbc0ef08 100755 --- a/app/code/core/Mage/Downloadable/Model/Resource/Indexer/Price.php +++ b/app/code/core/Mage/Downloadable/Model/Resource/Indexer/Price.php @@ -156,7 +156,7 @@ protected function _applyDownloadableLink() $query = $select->crossUpdateFromSelect(array('i' => $this->_getDefaultFinalPriceTable())); $write->query($query); - if ($this->useIdxTable()) { + if ($this->useIdxTable() && $this->_allowTableChanges) { $write->truncateTable($table); } else { $write->delete($table); diff --git a/app/code/core/Mage/Downloadable/etc/api.xml b/app/code/core/Mage/Downloadable/etc/api.xml new file mode 100644 index 0000000000..21bb335751 --- /dev/null +++ b/app/code/core/Mage/Downloadable/etc/api.xml @@ -0,0 +1,156 @@ + + + + + + + downloadable/link_api + Category API + downloadable/link + + + Add links and samples to downloadable product + add + downloadable/link/add + + + Retrieve links and samples list from downloadable product + items + downloadable/link/list + + + Remove links and samples from downloadable product + downloadable/link/remove + + + + + 100 + Store with requested code/id does not exist. + + + 101 + Product with requested id does not exist. + + + 401 + Incorrect resourceType, only "links" and "samples" allowed. + + + 402 + URL cannot be empty. + + + 403 + Filename was omitted, or contains unallowed characters. + + + 404 + File content should be passed as base64 string. For details, please see http://en.wikipedia.org/wiki/Base64 + + + 405 + Title cannot be empty. + + + 406 + Incorrect content type only "link", "link_samples" and "sample" allowed. + + + 408 + Incorrect product type. Downloadable content, can be added only to "downloadable" products. + + + 409 + Incorrect extension of filename. + + + 410 + Uploaded file is too big. + + + 411 + Has no permissions for writing to temporary folder. + + + 411 + Cannot create sub folder in temporary folder. + + + 412 + Link or sample with specified ID was not found. + + + 413 + An allowed resource type values for remove method is: "links" and "samples". + + + 414 + Unable to save action. Details in error message. + + + 415 + Validation error has occurred. + + + 416 + Unable to remove link. Details in error message. + + + + + + catalog_product_downloadable_link + + + + catalogProductDownloadableLink + + + + + + + + Product downloadable links + + Add + + + List + + + Remove + + + + + + + + diff --git a/app/code/core/Mage/Downloadable/etc/wsdl.xml b/app/code/core/Mage/Downloadable/etc/wsdl.xml new file mode 100644 index 0000000000..b463be954b --- /dev/null +++ b/app/code/core/Mage/Downloadable/etc/wsdl.xml @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Add links to downloadable product + + + + + Retrieve list of links and samples for downloadable product + + + + + Remove links and samples from downloadable product + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/core/Mage/Downloadable/etc/wsi.xml b/app/code/core/Mage/Downloadable/etc/wsi.xml new file mode 100644 index 0000000000..498eb427f3 --- /dev/null +++ b/app/code/core/Mage/Downloadable/etc/wsi.xml @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Add links to downloadable product + + + + + Retrieve list of links and samples for downloadable product + + + + + Remove links and samples from downloadable product + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/core/Mage/Eav/Model/Entity/Attribute.php b/app/code/core/Mage/Eav/Model/Entity/Attribute.php index f4f2ea3c9a..15c644687b 100644 --- a/app/code/core/Mage/Eav/Model/Entity/Attribute.php +++ b/app/code/core/Mage/Eav/Model/Entity/Attribute.php @@ -112,6 +112,25 @@ public function deleteEntity() return $this->_getResource()->deleteEntity($this); } + /** + * Load entity_attribute_id into $this by $this->attribute_set_id + * + * @return Mage_Core_Model_Abstract + */ + public function loadEntityAttributeIdBySet() + { + // load attributes collection filtered by attribute_id and attribute_set_id + $filteredAttributes = $this->getResourceCollection() + ->setAttributeSetFilter($this->getAttributeSetId()) + ->addFieldToFilter('entity_attribute.attribute_id', $this->getId()) + ->load(); + if (count($filteredAttributes) > 0) { + // getFirstItem() can be used as we can have one or zero records in the collection + $this->setEntityAttributeId($filteredAttributes->getFirstItem()->getEntityAttributeId()); + } + return $this; + } + /** * Prepare data for save * @@ -129,10 +148,12 @@ protected function _beforeSave() /** * Check for maximum attribute_code length */ - if(isset($this->_data['attribute_code']) && - !Zend_Validate::is($this->_data['attribute_code'], - 'StringLength', - array('max' => self::ATTRIBUTE_CODE_MAX_LENGTH)) + if (isset($this->_data['attribute_code']) && + !Zend_Validate::is( + $this->_data['attribute_code'], + 'StringLength', + array('max' => self::ATTRIBUTE_CODE_MAX_LENGTH) + ) ) { throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Maximum length of attribute code must be less then %s symbols', self::ATTRIBUTE_CODE_MAX_LENGTH)); } @@ -141,9 +162,8 @@ protected function _beforeSave() $hasDefaultValue = ((string)$defaultValue != ''); if ($this->getBackendType() == 'decimal' && $hasDefaultValue) { - if (!Zend_Locale_Format::isNumber($defaultValue, - array('locale' => Mage::app()->getLocale()->getLocaleCode())) - ) { + $locale = Mage::app()->getLocale()->getLocaleCode(); + if (!Zend_Locale_Format::isNumber($defaultValue, array('locale' => $locale))) { throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Invalid default decimal value')); } 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/Option.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php index 192d1cdd06..114644f621 100755 --- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php +++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php @@ -94,38 +94,31 @@ public function getFlatUpdateSelect(Mage_Eav_Model_Entity_Attribute_Abstract $at $attributeCode = $attribute->getAttributeCode(); $joinConditionTemplate = "%s.entity_id = %s.entity_id" - ." AND %s.entity_type_id = ".$attribute->getEntityTypeId() - ." AND %s.attribute_id = ".$attribute->getId() - ." AND %s.store_id = %d"; - $joinCondition = sprintf($joinConditionTemplate, - 'e', 't1', 't1', 't1', 't1', + . " AND %s.entity_type_id = " . $attribute->getEntityTypeId() + . " AND %s.attribute_id = " . $attribute->getId() + . " AND %s.store_id = %d"; + $joinCondition = sprintf($joinConditionTemplate, 'e', 't1', 't1', 't1', 't1', Mage_Core_Model_App::ADMIN_STORE_ID); if ($attribute->getFlatAddChildData()) { $joinCondition .= ' AND e.child_id = t1.entity_id'; } - $valueExpr = $adapter->getCheckSql('t2.value_id > 0', 't2.value', 't1.value'); + $valueExpr = $adapter->getCheckSql('t2.value_id > 0', 't2.value', 't1.value'); /** @var $select Varien_Db_Select */ - $select = $adapter->select() - ->joinLeft( - array('t1' => $attributeTable), - $joinCondition, - array()) - ->joinLeft( - array('t2' => $attributeTable), + $select = $adapter->select() + ->joinLeft(array('t1' => $attributeTable), $joinCondition, array()) + ->joinLeft(array('t2' => $attributeTable), sprintf($joinConditionTemplate, 't1', 't2', 't2', 't2', 't2', $store), array($attributeCode => $valueExpr)); + if (($attribute->getFrontend()->getInputType() != 'multiselect') && $hasValueField) { - $valueIdExpr = $adapter->getCheckSql('to2.value_id > 0', 'to1.value', 'to2.value'); - $select->joinLeft( - array('to1' => $this->getTable('eav/attribute_option_value')), - "to1.option_id = {$valueExpr} AND to1.store_id = 0", - array()) - ->joinLeft( - array('to2' => $this->getTable('eav/attribute_option_value')), - $adapter->quoteInto("to2.option_id = {$valueExpr} AND to2.store_id = ?", $store), - array($attributeCode . '_value' => $valueIdExpr) - ); + $valueIdExpr = $adapter->getCheckSql('to2.value_id > 0', 'to2.value', 'to1.value'); + $select + ->joinLeft(array('to1' => $this->getTable('eav/attribute_option_value')), + "to1.option_id = {$valueExpr} AND to1.store_id = 0", array()) + ->joinLeft(array('to2' => $this->getTable('eav/attribute_option_value')), + $adapter->quoteInto("to2.option_id = {$valueExpr} AND to2.store_id = ?", $store), + array($attributeCode . '_value' => $valueIdExpr)); } if ($attribute->getFlatAddChildData()) { 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..05bf02c7d6 100644 --- a/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php +++ b/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php @@ -351,6 +351,16 @@ protected function _responseNewOrderNotification() /* @var $quote Mage_Sales_Model_Quote */ $quote = $this->_loadQuote(); $quote->setIsActive(true)->reserveOrderId(); + + Mage::dispatchEvent('googlecheckout_create_order_before', array('quote' => $quote)); + if ($quote->getErrorMessage()) { + $this->getGRequest()->SendCancelOrder($this->getGoogleOrderNumber(), + $this->__('Order creation error'), + $quote->getErrorMessage() + ); + return; + } + $storeId = $quote->getStoreId(); Mage::app()->setCurrentStore(Mage::app()->getStore($storeId)); @@ -436,11 +446,18 @@ protected function _responseNewOrderNotification() $order->place(); $order->save(); $order->sendNewOrderEmail(); + Mage::dispatchEvent('googlecheckout_save_order_after', array('order' => $order)); $quote->setIsActive(false)->save(); if ($emailAllowed) { - Mage::getModel('newsletter/subscriber')->subscribe($order->getCustomerEmail()); + $customer = $quote->getCustomer(); + if ($customer && $customer->getId()) { + $customer->setIsSubscribed(true); + Mage::getModel('newsletter/subscriber')->subscribeCustomer($customer); + } else { + Mage::getModel('newsletter/subscriber')->subscribe($order->getCustomerEmail()); + } } Mage::dispatchEvent('checkout_submit_all_after', array('order' => $order, 'quote' => $quote)); @@ -675,6 +692,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/controllers/RedirectController.php b/app/code/core/Mage/GoogleCheckout/controllers/RedirectController.php index a1e570c34b..0f37aeff90 100644 --- a/app/code/core/Mage/GoogleCheckout/controllers/RedirectController.php +++ b/app/code/core/Mage/GoogleCheckout/controllers/RedirectController.php @@ -170,7 +170,7 @@ public function continueAction() public function redirectLogin() { $this->setFlag('', 'no-dispatch', true); - Mage::getSingleton('customer/session')->setBeforeAuthUrl($this->_getRefererUrl()); + Mage::getSingleton('customer/session')->setBeforeAuthUrl(Mage::getUrl('*/*/*', array('_secure'=>true))); $this->getResponse()->setRedirect( Mage::helper('core/url')->addRequestParam( Mage::helper('customer')->getLoginUrl(), 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/Index/Model/Indexer.php b/app/code/core/Mage/Index/Model/Indexer.php index 74a222b2c4..4ac94a0373 100644 --- a/app/code/core/Mage/Index/Model/Indexer.php +++ b/app/code/core/Mage/Index/Model/Indexer.php @@ -43,6 +43,13 @@ class Mage_Index_Model_Indexer */ protected $_lockFlag = false; + /** + * Whether table changes are allowed + * + * @var bool + */ + protected $_allowTableChanges = true; + /** * Class constructor. Initialize index processes based on configuration */ @@ -216,7 +223,22 @@ public function processEntityAction(Varien_Object $entity, $entityType, $eventTy * Index and save event just in case if some process matched it */ if ($event->getProcessIds()) { - $this->indexEvent($event); + $this->_changeKeyStatus(false); + /** @var $resourceModel Mage_Index_Model_Resource_Abstract */ + $resourceModel = Mage::getResourceModel('index/process'); + $resourceModel->beginTransaction(); + $this->_allowTableChanges = false; + try { + $this->indexEvent($event); + $resourceModel->commit(); + $this->_allowTableChanges = true; + $this->_changeKeyStatus(); + } catch (Exception $e) { + $resourceModel->rollBack(); + $this->_allowTableChanges = true; + $this->_changeKeyStatus(); + throw $e; + } $event->save(); } return $this; @@ -239,18 +261,75 @@ protected function _runAll($method, $args) if (in_array($code, $processed)) { continue; } + + if (!$this->_allowTableChanges && is_callable(array($process, 'setAllowTableChanges'))) { + $process->setAllowTableChanges(false); + } if ($process->getDepends()) { foreach ($process->getDepends() as $processCode) { $dependProcess = $this->getProcessByCode($processCode); if ($dependProcess && !in_array($processCode, $processed)) { + if (!$this->_allowTableChanges && is_callable(array($dependProcess, 'setAllowTableChanges'))) { + $dependProcess->setAllowTableChanges(false); + } call_user_func_array(array($dependProcess, $method), $args); + if (!$this->_allowTableChanges && is_callable(array($dependProcess, 'setAllowTableChanges'))) { + $dependProcess->setAllowTableChanges(true); + } $processed[] = $processCode; } } } call_user_func_array(array($process, $method), $args); + if (!$this->_allowTableChanges && is_callable(array($process, 'setAllowTableChanges'))) { + $process->setAllowTableChanges(true); + } + $processed[] = $code; } } + + /** + * Enable/Disable keys in index tables + * + * @return Mage_Index_Model_Indexer + */ + protected function _changeKeyStatus($enable = true) + { + $processed = array(); + foreach ($this->_processesCollection as $process) { + $code = $process->getIndexerCode(); + if (in_array($code, $processed)) { + continue; + } + + if ($process->getDepends()) { + foreach ($process->getDepends() as $processCode) { + $dependProcess = $this->getProcessByCode($processCode); + if ($dependProcess && !in_array($processCode, $processed)) { + if ($dependProcess instanceof Mage_Index_Model_Process) { + if ($enable) { + $dependProcess->enableIndexerKeys(); + } else { + $dependProcess->disableIndexerKeys(); + } + $processed[] = $processCode; + } + } + } + } + + if ($process instanceof Mage_Index_Model_Process) { + if ($enable) { + $process->enableIndexerKeys(); + } else { + $process->disableIndexerKeys(); + } + $processed[] = $code; + } + } + + return $this; + } } diff --git a/app/code/core/Mage/Index/Model/Indexer/Abstract.php b/app/code/core/Mage/Index/Model/Indexer/Abstract.php index c22f3a97f8..f17c98cf20 100644 --- a/app/code/core/Mage/Index/Model/Indexer/Abstract.php +++ b/app/code/core/Mage/Index/Model/Indexer/Abstract.php @@ -32,6 +32,13 @@ abstract class Mage_Index_Model_Indexer_Abstract extends Mage_Core_Model_Abstrac { protected $_matchedEntities = array(); + /** + * Whether table changes are allowed + * + * @var bool + */ + protected $_allowTableChanges = true; + /** * Get Indexer name * @@ -140,9 +147,68 @@ public function callEventHandler(Mage_Index_Model_Event $event) $method = $this->_camelize($event->getType()); } - if (method_exists($this->_getResource(), $method)) { - $this->_getResource()->$method($event); + $resourceModel = $this->_getResource(); + if (method_exists($resourceModel, $method)) { + if (!$this->_allowTableChanges && is_callable(array($resourceModel, 'setAllowTableChanges'))) { + $resourceModel->setAllowTableChanges(false); + } + $resourceModel->$method($event); + if (!$this->_allowTableChanges && is_callable(array($resourceModel, 'setAllowTableChanges'))) { + $resourceModel->setAllowTableChanges(true); + } } return $this; } + + /** + * Set whether table changes are allowed + * + * @param bool $value + * @return Mage_Index_Model_Indexer_Abstract + */ + public function setAllowTableChanges($value = true) + { + $this->_allowTableChanges = $value; + return $this; + } + + /** + * Disable resource table keys + * + * @return Mage_Index_Model_Indexer_Abstract + */ + public function disableKeys() + { + if (empty($this->_resourceName)) { + return $this; + } + + $resourceModel = $this->getResource(); + if ($resourceModel instanceof Mage_Index_Model_Resource_Abstract) { + $resourceModel->useDisableKeys(true); + $resourceModel->disableTableKeys(); + } + + return $this; + } + + /** + * Enable resource table keys + * + * @return Mage_Index_Model_Indexer_Abstract + */ + public function enableKeys() + { + if (empty($this->_resourceName)) { + return $this; + } + + $resourceModel = $this->getResource(); + if ($resourceModel instanceof Mage_Index_Model_Resource_Abstract) { + $resourceModel->useDisableKeys(true); + $resourceModel->enableTableKeys(); + } + + return $this; + } } diff --git a/app/code/core/Mage/Index/Model/Process.php b/app/code/core/Mage/Index/Model/Process.php index afe0407d90..b2e355b277 100644 --- a/app/code/core/Mage/Index/Model/Process.php +++ b/app/code/core/Mage/Index/Model/Process.php @@ -82,6 +82,13 @@ class Mage_Index_Model_Process extends Mage_Core_Model_Abstract protected $_isLocked = null; protected $_lockFile = null; + /** + * Whether table changes are allowed + * + * @var bool + */ + protected $_allowTableChanges = true; + /** * Initialize resource */ @@ -203,7 +210,16 @@ public function processEvent(Mage_Index_Model_Event $event) return $this; } $this->_setEventNamespace($event); + + $indexer = $this->getIndexer(); + if (!$this->_allowTableChanges && is_callable(array($indexer, 'setAllowTableChanges'))) { + $indexer->setAllowTableChanges(false); + } $this->getIndexer()->processEvent($event); + if (!$this->_allowTableChanges && is_callable(array($indexer, 'setAllowTableChanges'))) { + $indexer->setAllowTableChanges(true); + } + $event->resetData(); $this->_resetEventNamespace($event); $event->addProcessId($this->getId(), self::EVENT_STATUS_DONE); @@ -459,4 +475,44 @@ public function getDepends() return $depends; } + + /** + * Set whether table changes are allowed + * + * @param bool $value + * @return Mage_Index_Model_Process + */ + public function setAllowTableChanges($value = true) + { + $this->_allowTableChanges = $value; + return $this; + } + + /** + * Disable keys in index table + * + * @return Mage_Index_Model_Process + */ + public function disableIndexerKeys() + { + $indexer = $this->getIndexer(); + if ($indexer) { + $indexer->disableKeys(); + } + return $this; + } + + /** + * Enable keys in index table + * + * @return Mage_Index_Model_Process + */ + public function enableIndexerKeys() + { + $indexer = $this->getIndexer(); + if ($indexer) { + $indexer->enableKeys(); + } + return $this; + } } diff --git a/app/code/core/Mage/Index/Model/Resource/Abstract.php b/app/code/core/Mage/Index/Model/Resource/Abstract.php index 45c0a71ce5..0484f929fe 100755 --- a/app/code/core/Mage/Index/Model/Resource/Abstract.php +++ b/app/code/core/Mage/Index/Model/Resource/Abstract.php @@ -50,6 +50,13 @@ abstract class Mage_Index_Model_Resource_Abstract extends Mage_Core_Model_Resour */ protected $_isDisableKeys = true; + /** + * Whether table changes are allowed + * + * @var bool + */ + protected $_allowTableChanges = true; + /** * Reindex all * @@ -161,7 +168,7 @@ public function insertFromSelect($select, $destTable, array $columns, $readToInd $to = $this->_getWriteAdapter(); } - if ($this->useDisableKeys()) { + if ($this->useDisableKeys() && $this->_allowTableChanges) { $to->disableTableKeys($destTable); } if ($from === $to) { @@ -184,7 +191,7 @@ public function insertFromSelect($select, $destTable, array $columns, $readToInd $to->insertArray($destTable, $columns, $data); } } - if ($this->useDisableKeys()) { + if ($this->useDisableKeys() && $this->_allowTableChanges) { $to->enableTableKeys($destTable); } return $this; @@ -226,4 +233,42 @@ public function clearTemporaryIndexTable() { $this->_getWriteAdapter()->delete($this->getIdxTable()); } + + /** + * Set whether table changes are allowed + * + * @param bool $value + * @return Mage_Index_Model_Resource_Abstract + */ + public function setAllowTableChanges($value = true) + { + $this->_allowTableChanges = $value; + return $this; + } + + /** + * Disable Main Table keys + * + * @return Mage_Index_Model_Resource_Abstract + */ + public function disableTableKeys() + { + if ($this->useDisableKeys()) { + $this->_getWriteAdapter()->disableTableKeys($this->getMainTable()); + } + return $this; + } + + /** + * Enable Main Table keys + * + * @return Mage_Index_Model_Resource_Abstract + */ + public function enableTableKeys() + { + if ($this->useDisableKeys()) { + $this->_getWriteAdapter()->enableTableKeys($this->getMainTable()); + } + return $this; + } } 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/Paygate/Model/Authorizenet.php b/app/code/core/Mage/Paygate/Model/Authorizenet.php index 00ea5f259e..76783007b8 100644 --- a/app/code/core/Mage/Paygate/Model/Authorizenet.php +++ b/app/code/core/Mage/Paygate/Model/Authorizenet.php @@ -1132,7 +1132,7 @@ protected function _buildRequest(Varien_Object $payment) break; case self::REQUEST_TYPE_CREDIT: /** - * need to send last 4 digit credit card number to authorize.net + * Send last 4 digits of credit card number to authorize.net * otherwise it will give an error */ $request->setXCardNum($payment->getCcLast4()); @@ -1167,7 +1167,7 @@ protected function _buildRequest(Varien_Object $payment) ->setXCountry($billing->getCountry()) ->setXPhone($billing->getTelephone()) ->setXFax($billing->getFax()) - ->setXCustId($billing->getCustomerId()) + ->setXCustId($order->getCustomerId()) ->setXCustomerIp($order->getRemoteIp()) ->setXCustomerTaxId($billing->getTaxId()) ->setXEmail($order->getCustomerEmail()) 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..54bbb7ec2e 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', ); /** @@ -487,7 +488,7 @@ class Mage_Paypal_Model_Api_Nvp extends Mage_Paypal_Model_Api_Abstract * @var array */ protected $_doReferenceTransactionRequest = array('REFERENCEID', 'PAYMENTACTION', 'AMT', 'ITEMAMT', 'SHIPPINGAMT', - 'TAXAMT' + 'TAXAMT', 'INVNUM', 'NOTIFYURL' ); protected $_doReferenceTransactionResponse = array('BILLINGAGREEMENTID', 'TRANSACTIONID'); diff --git a/app/code/core/Mage/Paypal/Model/Config.php b/app/code/core/Mage/Paypal/Model/Config.php index b8d4bb1769..e0f4a267a2 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 @@ -296,8 +304,8 @@ public function setStoreId($storeId) public function isMethodActive($method) { if ($this->isMethodSupportedForCountry($method) - && Mage::getStoreConfigFlag("payment/{$method}/active", $this->_storeId)) - { + && Mage::getStoreConfigFlag("payment/{$method}/active", $this->_storeId) + ) { return true; } return false; @@ -468,6 +476,7 @@ public function getCountryMethods($countryCode = null) self::METHOD_WPS, self::METHOD_WPP_DIRECT, self::METHOD_WPP_EXPRESS, + self::METHOD_BILLING_AGREEMENT, self::METHOD_WPP_PE_DIRECT, self::METHOD_WPP_PE_EXPRESS, self::METHOD_PAYFLOWPRO, @@ -477,6 +486,7 @@ public function getCountryMethods($countryCode = null) self::METHOD_WPS, self::METHOD_WPP_DIRECT, self::METHOD_WPP_EXPRESS, + self::METHOD_BILLING_AGREEMENT, self::METHOD_PAYFLOWPRO, self::METHOD_PAYFLOWLINK, ), @@ -484,6 +494,7 @@ public function getCountryMethods($countryCode = null) self::METHOD_WPS, self::METHOD_WPP_DIRECT, self::METHOD_WPP_EXPRESS, + self::METHOD_BILLING_AGREEMENT, self::METHOD_WPP_PE_DIRECT, self::METHOD_WPP_PE_EXPRESS, self::METHOD_HOSTEDPRO, @@ -491,23 +502,27 @@ public function getCountryMethods($countryCode = null) 'AU' => array( self::METHOD_WPS, self::METHOD_WPP_EXPRESS, + self::METHOD_BILLING_AGREEMENT, self::METHOD_PAYFLOWPRO, self::METHOD_HOSTEDPRO, ), 'NZ' => array( self::METHOD_WPS, self::METHOD_WPP_EXPRESS, + self::METHOD_BILLING_AGREEMENT, self::METHOD_PAYFLOWPRO, self::METHOD_HOSTEDPRO, ), 'DE' => array( self::METHOD_WPS, self::METHOD_WPP_EXPRESS, + self::METHOD_BILLING_AGREEMENT, self::METHOD_HOSTEDPRO, ), 'other' => array( self::METHOD_WPS, self::METHOD_WPP_EXPRESS, + self::METHOD_BILLING_AGREEMENT, self::METHOD_HOSTEDPRO, ) ); @@ -853,6 +868,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/Ipn.php b/app/code/core/Mage/Paypal/Model/Ipn.php index 44ecd92673..e9da8a45db 100644 --- a/app/code/core/Mage/Paypal/Model/Ipn.php +++ b/app/code/core/Mage/Paypal/Model/Ipn.php @@ -680,7 +680,7 @@ protected function _filterPaymentStatus($ipnPaymentStatus) */ protected function _debug() { - if ($this->_config->debug) { + if ($this->_config && $this->_config->debug) { $file = $this->_config->getMethodCode() ? "payment_{$this->_config->getMethodCode()}.log" : self::DEFAULT_LOG_FILE; Mage::getModel('core/log_adapter', $file)->log($this->_debugData); diff --git a/app/code/core/Mage/Paypal/Model/Method/Agreement.php b/app/code/core/Mage/Paypal/Model/Method/Agreement.php index d3d7d52ffb..497fd46355 100644 --- a/app/code/core/Mage/Paypal/Model/Method/Agreement.php +++ b/app/code/core/Mage/Paypal/Model/Method/Agreement.php @@ -307,6 +307,7 @@ protected function _placeOrder(Mage_Sales_Model_Order_Payment $payment, $amount) ->setNotifyUrl(Mage::getUrl('paypal/ipn/')) ->setPaypalCart(Mage::getModel('paypal/cart', array($order))) ->setIsLineItemsEnabled($this->_pro->getConfig()->lineItemsEnabled) + ->setInvNum($order->getIncrementId()) ; // call api and import transaction and other payment information 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..2d833e86f5 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,194 @@ 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; - default: + case Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_ONE: + $this->_initialize($payment, 1); break; + 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; + } + + /** + * Add transaction with correct transaction Id + * + * @param Varien_Object $payment + * @param string $txnId + * @return void + */ + protected function _addTransaction($payment, $txnId) + { + $previousTxnId = $payment->getTransactionId(); + $payment->setTransactionId($txnId); + $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH); + $payment->setTransactionId($previousTxnId); + } + /** + * 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); + } + + if ($transaction->getId() && $payment->getAdditionalInformation('authorization_amount') != + Mage_Paypal_Model_Config::AUTHORIZATION_AMOUNT_FULL + ) { + $this->_addTransaction($payment, $txnId); } + + $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; + $this->_authorize($payment, $amount, $transaction, $txnId); + + $this->_addTransaction($payment, $txnId); + + $payment->setReferenceTransactionId($payment->getAdditionalInformation('authorization_id')); + } + + $payment->setParentTransactionId($txnId); + + $payment->setRequestAmount(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); + $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_VOID); + 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 +346,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 +407,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($salesDocument->getPayment(), $response->getPnref()); + if (!isset($fetchData['custref']) || $fetchData['custref'] != $salesDocument->getReservedOrderId()) { + Mage::throwException($this->_formatStr(self::RESPONSE_ERROR_MSG, 'Transaction error')); } - $fetchData = $this->fetchTransactionInfo($order->getPayment(), $response->getPnref()); - if (!isset($fetchData['custref']) || $fetchData['custref'] != $order->getIncrementId()) { - Mage::throwException($this->_formatStr(self::RESPONSE_ERROR_MSG, 'Transaction')); - } - - return $order; + return $salesDocument; } /** @@ -299,27 +467,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 +511,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 +525,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 +563,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->getRequestAmount() > 0) { + $request->setAmt(round($payment->getRequestAmount(),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 +592,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 +627,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 +662,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..45af5ebe71 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()); @@ -397,7 +404,6 @@ protected function _buildPlaceRequest(Varien_Object $payment, $amount) { $request = $this->_buildBasicRequest($payment); $request->setAmt(round($amount,2)); - $request->setCurrency($payment->getOrder()->getBaseCurrencyCode()); $request->setAcct($payment->getCcNumber()); $request->setExpdate(sprintf('%02d',$payment->getCcExpMonth()) . substr($payment->getCcExpYear(),-2,2)); $request->setCvv2($payment->getCcCid()); @@ -410,6 +416,9 @@ protected function _buildPlaceRequest(Varien_Object $payment, $amount) $order = $payment->getOrder(); if(!empty($order)){ + $request->setCurrency($order->getBaseCurrencyCode()) + ->setCustref($order->getIncrementId()); + $billing = $order->getBillingAddress(); if (!empty($billing)) { $request->setFirstname($billing->getFirstname()) @@ -473,7 +482,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 +503,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..8da14aa53f 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..5d3f098cd4 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); } /** @@ -147,16 +169,15 @@ public function getVotedPollIdsByIp($ipAddress, $pollId = false) */ public function resetVotesCount($object) { - $read = $this->_getReadAdapter(); - $select = $read->select(); - $select->from($this->getTable('poll_answer'), new Zend_Db_Expr("SUM(votes_count)")) - ->where('poll_id = :poll_id'); - - $count = $read->fetchOne($select, array(':poll_id' => $object->getPollId())); - - $write = $this->_getWriteAdapter(); - $condition = $write->quoteInto("{$this->getIdFieldName()} = ?", $object->getPollId()); - $write->update($this->getMainTable(), array('votes_count' => $count), $condition); + $adapter = $this->_getWriteAdapter(); + $select = $adapter->select() + ->from($this->getTable('poll_answer'), new Zend_Db_Expr("SUM(votes_count)")) + ->where('poll_id = ?', $object->getPollId()); + $adapter->update( + $this->getMainTable(), + array('votes_count' => new Zend_Db_Expr("($select)")), + array('poll_id = ' . $adapter->quote($object->getPollId())) + ); return $object; } diff --git a/app/code/core/Mage/Reports/Model/Resource/Review/Customer/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Review/Customer/Collection.php index 590424d09b..fd13f65050 100755 --- a/app/code/core/Mage/Reports/Model/Resource/Review/Customer/Collection.php +++ b/app/code/core/Mage/Reports/Model/Resource/Review/Customer/Collection.php @@ -91,6 +91,7 @@ public function joinCustomers() implode(' AND ', $lastnameCondition), array()) ->columns(array( + 'customer_id' => 'detail.customer_id', 'customer_name' => $customerFullname, 'review_cnt' => 'COUNT(main_table.review_id)')) ->group('detail.customer_id'); 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/Review/Model/Resource/Review.php b/app/code/core/Mage/Review/Model/Resource/Review.php index d39b8b782b..7203a60111 100755 --- a/app/code/core/Mage/Review/Model/Resource/Review.php +++ b/app/code/core/Mage/Review/Model/Resource/Review.php @@ -242,10 +242,10 @@ protected function _beforeDelete(Mage_Core_Model_Abstract $object) /** * Perform actions after object delete * - * @param Varien_Object $object + * @param Mage_Core_Model_Abstract $object * @return Mage_Review_Model_Resource_Review */ - protected function _afterDelete(Mage_Core_Model_Abstract $object) + public function afterDeleteCommit(Mage_Core_Model_Abstract $object) { $this->aggregate($object); @@ -313,7 +313,11 @@ public function aggregate($object) $ratingSummary = $ratingSummaryObject->getSum(); } - $reviewsCount = $this->getTotalReviews($object->getEntityPkValue(), true, $ratingSummaryObject->getStoreId()); + $reviewsCount = $this->getTotalReviews( + $object->getEntityPkValue(), + true, + $ratingSummaryObject->getStoreId() + ); $select = $readAdapter->select() ->from($this->_aggregateTable) ->where('entity_pk_value = :pk_value') diff --git a/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php b/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php index da4753b03e..1101d18034 100755 --- a/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php +++ b/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php @@ -380,7 +380,7 @@ public function addAttributeToFilter($attribute, $condition = null, $joinType = case 'type': if ($condition == 1) { $conditionParts = array( - $this->_getConditionSql('rdt.customer_id', array('is' => 'NULL')), + $this->_getConditionSql('rdt.customer_id', array('is' => new Zend_Db_Expr('NULL'))), $this->_getConditionSql('rdt.store_id', array('eq' => Mage_Core_Model_App::ADMIN_STORE_ID)) ); $conditionSql = implode(' AND ', $conditionParts); @@ -388,7 +388,7 @@ public function addAttributeToFilter($attribute, $condition = null, $joinType = $conditionSql = $this->_getConditionSql('rdt.customer_id', array('gt' => 0)); } else { $conditionParts = array( - $this->_getConditionSql('rdt.customer_id', array('is' => 'NULL')), + $this->_getConditionSql('rdt.customer_id', array('is' => new Zend_Db_Expr('NULL'))), $this->_getConditionSql('rdt.store_id', array('neq' => Mage_Core_Model_App::ADMIN_STORE_ID)) ); $conditionSql = implode(' AND ', $conditionParts); diff --git a/app/code/core/Mage/Review/Model/Review.php b/app/code/core/Mage/Review/Model/Review.php index 132343bcee..949a29f5d9 100644 --- a/app/code/core/Mage/Review/Model/Review.php +++ b/app/code/core/Mage/Review/Model/Review.php @@ -139,6 +139,17 @@ public function validate() return $errors; } + /** + * Perform actions after object delete + * + * @return Mage_Core_Model_Abstract + */ + protected function _afterDeleteCommit() + { + $this->getResource()->afterDeleteCommit($this); + return parent::_afterDeleteCommit(); + } + /** * Append review summary to product collection * 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/Rss/Block/Catalog/NotifyStock.php b/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php index 382156bd4d..b2f824d6dc 100644 --- a/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php +++ b/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php @@ -41,6 +41,11 @@ class Mage_Rss_Block_Catalog_NotifyStock extends Mage_Rss_Block_Abstract */ const CACHE_TAG = 'block_html_rss_catalog_notifystock'; + /** + * Constructor + * + * @return null + */ protected function _construct() { $this->setCacheTags(array(self::CACHE_TAG)); @@ -51,45 +56,68 @@ protected function _construct() $this->setCacheLifetime(600); } + /** + * Render RSS + * + * @return string + */ protected function _toHtml() { - $newurl = Mage::getUrl('rss/catalog/notifystock'); - $title = Mage::helper('rss')->__('Low Stock Products'); + $newUrl = Mage::getUrl('rss/catalog/notifystock'); + /* @var $helper Mage_Rss_Helper_Data */ + $helper = Mage::helper('rss'); + $title = $helper->__('Low Stock Products'); $rssObj = Mage::getModel('rss/rss'); - $data = array('title' => $title, - 'description' => $title, - 'link' => $newurl, - 'charset' => 'UTF-8', + $data = array( + 'title' => $title, + 'description' => $title, + 'link' => $newUrl, + 'charset' => 'UTF-8', ); $rssObj->_addHeader($data); - $_configManageStock = (int)Mage::getStoreConfigFlag(Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MANAGE_STOCK); - $stockItemWhere = "({{table}}.low_stock_date is not null) " - . " AND ( ({{table}}.use_config_manage_stock=1 AND ".$_configManageStock."=1)" - . " OR ({{table}}.use_config_manage_stock=0 AND {{table}}.manage_stock=1) )"; - + $configManageStock = (int) Mage::getStoreConfigFlag( + Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MANAGE_STOCK); + $globalNotifyStockQty = (float) Mage::getStoreConfig( + Mage_CatalogInventory_Model_Stock_Item::XML_PATH_NOTIFY_STOCK_QTY); + $helper->disableFlat(); + /* @var $product Mage_Catalog_Model_Product */ $product = Mage::getModel('catalog/product'); - $collection = $product->getCollection() - ->addAttributeToSelect('name', true) + /* @var $collection Mage_Catalog_Model_Resource_Product_Collection */ + $collection = $product->getCollection(); + $stockItemTable = $collection->getTable('cataloginventory/stock_item'); + + $stockItemWhere = '({{table}}.low_stock_date is not null) ' + . " AND ( ({{table}}.use_config_manage_stock=1 AND {$configManageStock}=1)" + . " AND {{table}}.qty < " + . "IF({$stockItemTable}.`use_config_notify_stock_qty`, {$globalNotifyStockQty}, {{table}}.notify_stock_qty)" + . ' OR ({{table}}.use_config_manage_stock=0 AND {{table}}.manage_stock=1) )'; + + $collection ->addAttributeToSelect('name', true) ->joinTable('cataloginventory/stock_item', 'product_id=entity_id', - array('qty'=>'qty', 'notify_stock_qty'=>'notify_stock_qty', 'use_config' => 'use_config_notify_stock_qty','low_stock_date' => 'low_stock_date'), + array( + 'qty'=>'qty', + 'notify_stock_qty'=>'notify_stock_qty', + 'use_config' => 'use_config_notify_stock_qty', + 'low_stock_date' => 'low_stock_date'), $stockItemWhere, 'inner') - ->setOrder('low_stock_date') - ; - $collection->addAttributeToFilter('status', array('in' => Mage::getSingleton('catalog/product_status')->getVisibleStatusIds())); - - $_globalNotifyStockQty = (float) Mage::getStoreConfig(Mage_CatalogInventory_Model_Stock_Item::XML_PATH_NOTIFY_STOCK_QTY); + ->setOrder('low_stock_date'); + $collection->addAttributeToFilter('status', + array('in' => Mage::getSingleton('catalog/product_status')->getVisibleStatusIds())); Mage::dispatchEvent('rss_catalog_notify_stock_collection_select', array('collection' => $collection)); /* using resource iterator to load the data one by one instead of loading all at the same time. loading all data at the same time can cause the big memory allocation. */ - Mage::getSingleton('core/resource_iterator') - ->walk($collection->getSelect(), array(array($this, 'addNotifyItemXmlCallback')), array('rssObj'=> $rssObj, 'product'=>$product, 'globalQty' => $_globalNotifyStockQty)); + Mage::getSingleton('core/resource_iterator')->walk( + $collection->getSelect(), + array(array($this, 'addNotifyItemXmlCallback')), + array('rssObj'=> $rssObj, 'product'=>$product, 'globalQty' => $globalNotifyStockQty) + ); return $rssObj->createRssXml(); } @@ -104,13 +132,15 @@ public function addNotifyItemXmlCallback($args) { $product = $args['product']; $product->setData($args['row']); - $url = Mage::helper('adminhtml')->getUrl('adminhtml/catalog_product/edit/', array('id'=>$product->getId(),'_secure' => true,'_nosecret' => true)); - $description = Mage::helper('rss')->__('%s has reached a quantity of %s.', $product->getName(),(1*$product->getQty())); + $url = Mage::helper('adminhtml')->getUrl('adminhtml/catalog_product/edit/', + array('id' => $product->getId(), '_secure' => true, '_nosecret' => true)); + $qty = 1 * $product->getQty(); + $description = Mage::helper('rss')->__('%s has reached a quantity of %s.', $product->getName(), $qty); $rssObj = $args['rssObj']; $data = array( - 'title' => $product->getName(), - 'link' => $url, - 'description' => $description, + 'title' => $product->getName(), + 'link' => $url, + 'description' => $description, ); $rssObj->_addEntry($data); } diff --git a/app/code/core/Mage/Rss/Block/Catalog/Review.php b/app/code/core/Mage/Rss/Block/Catalog/Review.php index 8086d87e58..456cd3cf09 100644 --- a/app/code/core/Mage/Rss/Block/Catalog/Review.php +++ b/app/code/core/Mage/Rss/Block/Catalog/Review.php @@ -41,6 +41,11 @@ class Mage_Rss_Block_Catalog_Review extends Mage_Rss_Block_Abstract */ const CACHE_TAG = 'block_html_rss_catalog_review'; + /** + * Initialize cache + * + * @return null + */ protected function _construct() { $this->setCacheTags(array(self::CACHE_TAG)); @@ -51,17 +56,26 @@ protected function _construct() $this->setCacheLifetime(600); } + /** + * Render XML response + * + * @return string + */ protected function _toHtml() { - $newurl = Mage::getUrl('rss/catalog/review'); - $title = Mage::helper('rss')->__('Pending product review(s)'); + $newUrl = Mage::getUrl('rss/catalog/review'); + /* @var $helper Mage_Rss_Helper_Data */ + $helper = Mage::helper('rss'); + $title = $helper->__('Pending product review(s)'); + $helper->disableFlat(); $rssObj = Mage::getModel('rss/rss'); - $data = array('title' => $title, - 'description' => $title, - 'link' => $newurl, - 'charset' => 'UTF-8', - ); + $data = array( + 'title' => $title, + 'description' => $title, + 'link' => $newUrl, + 'charset' => 'UTF-8', + ); $rssObj->_addHeader($data); $reviewModel = Mage::getModel('review/review'); @@ -73,36 +87,44 @@ protected function _toHtml() Mage::dispatchEvent('rss_catalog_review_collection_select', array('collection' => $collection)); - Mage::getSingleton('core/resource_iterator') - ->walk($collection->getSelect(), array(array($this, 'addReviewItemXmlCallback')), array('rssObj'=> $rssObj, 'reviewModel'=> $reviewModel)); + Mage::getSingleton('core/resource_iterator')->walk( + $collection->getSelect(), + array(array($this, 'addReviewItemXmlCallback')), + array('rssObj'=> $rssObj, 'reviewModel'=> $reviewModel)); return $rssObj->createRssXml(); } + /** + * Format single RSS element + * + * @param array $args + * @return null + */ public function addReviewItemXmlCallback($args) { $rssObj = $args['rssObj']; - $reviewModel = $args['reviewModel']; $row = $args['row']; $store = Mage::app()->getStore($row['store_id']); $urlModel = Mage::getModel('core/url')->setStore($store); - $productUrl = $urlModel->getUrl('catalog/product/view', array('id'=>$row['entity_id'])); - $reviewUrl = Mage::helper('adminhtml')->getUrl('adminhtml/catalog_product_review/edit/', array('id'=>$row['review_id'], '_secure' => true, '_nosecret'=>true)); + $productUrl = $urlModel->getUrl('catalog/product/view', array('id' => $row['entity_id'])); + $reviewUrl = Mage::helper('adminhtml')->getUrl( + 'adminhtml/catalog_product_review/edit/', + array('id' => $row['review_id'], '_secure' => true, '_nosecret' => true)); $storeName = $store->getName(); - $description = '

'. - $this->__('Product: %s
',$productUrl,$row['name']). - $this->__('Summary of review: %s
',$row['title']). - $this->__('Review: %s
', $row['detail']). - $this->__('Store: %s
', $storeName ). - $this->__('click here to view the review',$reviewUrl). - '

' - ; + $description = '

' + . $this->__('Product: %s
', $productUrl, $row['name']) + . $this->__('Summary of review: %s
', $row['title']) + . $this->__('Review: %s
', $row['detail']) + . $this->__('Store: %s
', $storeName ) + . $this->__('click here to view the review', $reviewUrl) + . '

'; $data = array( - 'title' => $this->__('Product: "%s" review By: %s',$row['name'],$row['nickname']), - 'link' => 'test', - 'description' => $description, - ); + 'title' => $this->__('Product: "%s" review By: %s', $row['name'], $row['nickname']), + 'link' => 'test', + 'description' => $description, + ); $rssObj->_addEntry($data); } } diff --git a/app/code/core/Mage/Rss/Helper/Data.php b/app/code/core/Mage/Rss/Helper/Data.php index 98369c9aea..a5f64b117f 100644 --- a/app/code/core/Mage/Rss/Helper/Data.php +++ b/app/code/core/Mage/Rss/Helper/Data.php @@ -96,4 +96,23 @@ public function authFailed() { Mage::helper('core/http')->authFailed(); } + + /** + * Disable using of flat catalog and/or product model to prevent limiting results to single store. Probably won't + * work inside a controller. + * + * @return null + */ + public function disableFlat() + { + /* @var $flatHelper Mage_Catalog_Helper_Product_Flat */ + $flatHelper = Mage::helper('catalog/product_flat'); + if ($flatHelper->isEnabled()) { + /* @var $emulationModel Mage_Core_Model_App_Emulation */ + $emulationModel = Mage::getModel('core/app_emulation'); + // Emulate admin environment to disable using flat model - otherwise we won't get global stats + // for all stores + $emulationModel->startEnvironmentEmulation(0, Mage_Core_Model_App_Area::AREA_ADMINHTML); + } + } } 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/Billing/Agreement/Grid.php b/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/Grid.php index 1d1e06c679..7819615365 100644 --- a/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/Grid.php +++ b/app/code/core/Mage/Sales/Block/Adminhtml/Billing/Agreement/Grid.php @@ -133,7 +133,7 @@ protected function _prepareColumns() $this->addColumn('created_at', array( 'header' => Mage::helper('sales')->__('Created At'), - 'index' => 'created_at', + 'index' => 'agreement_created_at', 'width' => 1, 'type' => 'datetime', 'align' => 'center', @@ -143,7 +143,7 @@ protected function _prepareColumns() $this->addColumn('updated_at', array( 'header' => Mage::helper('sales')->__('Updated At'), - 'index' => 'updated_at', + 'index' => 'agreement_updated_at', 'width' => 1, 'type' => 'datetime', 'align' => 'center', 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..414d45f67b 100644 --- a/app/code/core/Mage/Sales/Model/Convert/Quote.php +++ b/app/code/core/Mage/Sales/Model/Convert/Quote.php @@ -50,6 +50,7 @@ public function toOrder(Mage_Sales_Model_Quote $quote, $order=null) $order->setIncrementId($quote->getReservedOrderId()) ->setStoreId($quote->getStoreId()) ->setQuoteId($quote->getId()) + ->setQuote($quote) ->setCustomer($quote->getCustomer()); Mage::helper('core')->copyFieldset('sales_convert_quote', 'to_order', $quote, $order); @@ -132,7 +133,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.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo.php index dfd55cd296..b5fd93a6c0 100644 --- a/app/code/core/Mage/Sales/Model/Order/Creditmemo.php +++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo.php @@ -880,4 +880,15 @@ protected function _beforeSave() return $this; } + + /** + * Get creditmemos collection filtered by $filter + * + * @param array|null $filter + * @return Mage_Sales_Model_Resource_Order_Creditmemo_Collection + */ + public function getFilteredCollectionItems($filter = null) + { + return $this->getResourceCollection()->getFiltered($filter); + } } diff --git a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api.php new file mode 100644 index 0000000000..9fd46b4eb3 --- /dev/null +++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api.php @@ -0,0 +1,278 @@ + + */ +class Mage_Sales_Model_Order_Creditmemo_Api extends Mage_Sales_Model_Api_Resource +{ + + /** + * Initialize attributes' mapping + */ + public function __construct() + { + $this->_attributesMap['creditmemo'] = array( + 'creditmemo_id' => 'entity_id' + ); + $this->_attributesMap['creditmemo_item'] = array( + 'item_id' => 'entity_id' + ); + $this->_attributesMap['creditmemo_comment'] = array( + 'comment_id' => 'entity_id' + ); + } + + /** + * Retrieve credit memos by filters + * + * @param array|null $filter + * @return array + */ + public function items($filter = null) + { + $filter = $this->_prepareListFilter($filter); + try { + $result = array(); + /** @var $creditmemoModel Mage_Sales_Model_Order_Creditmemo */ + $creditmemoModel = Mage::getModel('sales/order_creditmemo'); + // map field name entity_id to creditmemo_id + foreach ($creditmemoModel->getFilteredCollectionItems($filter) as $creditmemo) { + $result[] = $this->_getAttributes($creditmemo, 'creditmemo'); + } + } catch (Exception $e) { + $this->_fault('invalid_filter', $e->getMessage()); + } + return $result; + } + + /** + * Make filter of appropriate format for list method + * + * @param array|null $filter + * @return array|null + */ + protected function _prepareListFilter($filter = null) + { + // prepare filter, map field creditmemo_id to entity_id + if (is_array($filter)) { + foreach ($filter as $field => $value) { + if (isset($this->_attributesMap['creditmemo'][$field])) { + $filter[$this->_attributesMap['creditmemo'][$field]] = $value; + unset($filter[$field]); + } + } + } + return $filter; + } + + /** + * Retrieve credit memo information + * + * @param string $creditmemoIncrementId + * @return array + */ + public function info($creditmemoIncrementId) + { + $creditmemo = $this->_getCreditmemo($creditmemoIncrementId); + // get credit memo attributes with entity_id' => 'creditmemo_id' mapping + $result = $this->_getAttributes($creditmemo, 'creditmemo'); + $result['order_increment_id'] = $creditmemo->getOrder()->load($creditmemo->getOrderId())->getIncrementId(); + // items refunded + $result['items'] = array(); + foreach ($creditmemo->getAllItems() as $item) { + $result['items'][] = $this->_getAttributes($item, 'creditmemo_item'); + } + // credit memo comments + $result['comments'] = array(); + foreach ($creditmemo->getCommentsCollection() as $comment) { + $result['comments'][] = $this->_getAttributes($comment, 'creditmemo_comment'); + } + return $result; + } + + /** + * Create new credit memo for order + * + * @param string $orderIncrementId + * @param array $data array('qtys' => array('sku1' => qty1, ... , 'skuN' => qtyN), + * 'shipping_amount' => value, 'adjustment_positive' => value, 'adjustment_negative' => value) + * @param string|null $comment + * @param bool $notifyCustomer + * @param bool $includeComment + * @param string $refundToStoreCreditAmount + * @return string $creditmemoIncrementId + */ + public function create($orderIncrementId, $data = null, $comment = null, $notifyCustomer = false, + $includeComment = false, $refundToStoreCreditAmount = null) + { + /** @var $order Mage_Sales_Model_Order */ + $order = Mage::getModel('sales/order')->load($orderIncrementId, 'increment_id'); + if (!$order->getId()) { + $this->_fault('order_not_exists'); + } + if (!$order->canCreditmemo()) { + $this->_fault('cannot_create_creditmemo'); + } + $data = $this->_prepareCreateData($data); + + /** @var $service Mage_Sales_Model_Service_Order */ + $service = Mage::getModel('sales/service_order', $order); + /** @var $creditmemo Mage_Sales_Model_Order_Creditmemo */ + $creditmemo = $service->prepareCreditmemo($data); + + // refund to Store Credit + if ($refundToStoreCreditAmount) { + // check if refund to Store Credit is available + if ($order->getCustomerIsGuest()) { + $this->_fault('cannot_refund_to_storecredit'); + } + $refundToStoreCreditAmount = max( + 0, + min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount) + ); + if ($refundToStoreCreditAmount) { + $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount); + $creditmemo->setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount); + $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice( + $refundToStoreCreditAmount*$order->getStoreToOrderRate() + ); + // this field can be used by customer balance observer + $creditmemo->setBsCustomerBalTotalRefunded($refundToStoreCreditAmount); + // setting flag to make actual refund to customer balance after credit memo save + $creditmemo->setCustomerBalanceRefundFlag(true); + } + } + $creditmemo->setPaymentRefundDisallowed(true)->register(); + // add comment to creditmemo + if (!empty($comment)) { + $creditmemo->addComment($comment, $notifyCustomer); + } + try { + Mage::getModel('core/resource_transaction') + ->addObject($creditmemo) + ->addObject($order) + ->save(); + // send email notification + $creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : '')); + } catch (Mage_Core_Exception $e) { + $this->_fault('data_invalid', $e->getMessage()); + } + return $creditmemo->getIncrementId(); + } + + /** + * Add comment to credit memo + * + * @param string $creditmemoIncrementId + * @param string $comment + * @param boolean $notifyCustomer + * @param boolean $includeComment + * @return boolean + */ + public function addComment($creditmemoIncrementId, $comment, $notifyCustomer = false, $includeComment = false) + { + $creditmemo = $this->_getCreditmemo($creditmemoIncrementId); + try { + $creditmemo->addComment($comment, $notifyCustomer)->save(); + $creditmemo->sendUpdateEmail($notifyCustomer, ($includeComment ? $comment : '')); + } catch (Mage_Core_Exception $e) { + $this->_fault('data_invalid', $e->getMessage()); + } + + return true; + } + + /** + * Cancel credit memo + * + * @param string $creditmemoIncrementId + * @return boolean + */ + public function cancel($creditmemoIncrementId) + { + $creditmemo = $this->_getCreditmemo($creditmemoIncrementId); + + if (!$creditmemo->canCancel()) { + $this->_fault('status_not_changed', Mage::helper('sales')->__('Credit memo cannot be canceled.')); + } + try { + $creditmemo->cancel()->save(); + } catch (Exception $e) { + $this->_fault('status_not_changed', Mage::helper('sales')->__('Credit memo canceling problem.')); + } + + return true; + } + + /** + * Hook method, could be replaced in derived classes + * + * @param array $data + * @return array + */ + protected function _prepareCreateData($data) + { + $data = isset($data) ? $data : array(); + + if (isset($data['qtys']) && count($data['qtys'])) { + $qtysArray = array(); + foreach ($data['qtys'] as $qKey => $qVal) { + // Save backward compatibility + if (is_array($qVal)) { + if (isset($qVal['order_item_id']) && isset($qVal['qty'])) { + $qtysArray[$qVal['order_item_id']] = $qVal['qty']; + } + } else { + $qtysArray[$qKey] = $qVal; + } + } + $data['qtys'] = $qtysArray; + } + return $data; + } + + /** + * Load CreditMemo by IncrementId + * + * @param mixed $incrementId + * @return Mage_Core_Model_Abstract|Mage_Sales_Model_Order_Creditmemo + */ + protected function _getCreditmemo($incrementId) + { + /** @var $creditmemo Mage_Sales_Model_Order_Creditmemo */ + $creditmemo = Mage::getModel('sales/order_creditmemo')->load($incrementId, 'increment_id'); + if (!$creditmemo->getId()) { + $this->_fault('not_exists'); + } + return $creditmemo; + } + +} diff --git a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api/V2.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api/V2.php new file mode 100644 index 0000000000..1af1ffc6a1 --- /dev/null +++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Api/V2.php @@ -0,0 +1,90 @@ + + */ +class Mage_Sales_Model_Order_Creditmemo_Api_V2 extends Mage_Sales_Model_Order_Creditmemo_Api +{ + + /** + * Prepare filters + * + * @param null|object $filters + * @return array + */ + protected function _prepareListFilter($filters = null) + { + $preparedFilters = array(); + $helper = Mage::helper('api'); + if (isset($filters->filter)) { + $helper->associativeArrayUnpack($filters->filter); + $preparedFilters += $filters->filter; + } + if (isset($filters->complex_filter)) { + $helper->associativeArrayUnpack($filters->complex_filter); + foreach ($filters->complex_filter as &$filter) { + $helper->associativeArrayUnpack($filter); + } + $preparedFilters += $filters->complex_filter; + } + foreach ($preparedFilters as $field => $value) { + if (isset($this->_attributesMap['creditmemo'][$field])) { + $preparedFilters[$this->_attributesMap['creditmemo'][$field]] = $value; + unset($preparedFilters[$field]); + } + } + + return $preparedFilters; + } + + /** + * Prepare data + * + * @param null|object $data + * @return array + */ + protected function _prepareCreateData($data) + { + // convert data object to array, if it's null turn it into empty array + $data = (isset($data) and is_object($data)) ? get_object_vars($data) : array(); + // convert qtys object to array + if (isset($data['qtys']) && count($data['qtys'])) { + $qtysArray = array(); + foreach ($data['qtys'] as &$item) { + if (isset($item->order_item_id) && isset($item->qty)) { + $qtysArray[$item->order_item_id] = $item->qty; + } + } + $data['qtys'] = $qtysArray; + } + return $data; + } +} 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/Payment.php b/app/code/core/Mage/Sales/Model/Order/Payment.php index 0e96b68cd2..a3530f8a54 100644 --- a/app/code/core/Mage/Sales/Model/Order/Payment.php +++ b/app/code/core/Mage/Sales/Model/Order/Payment.php @@ -1382,7 +1382,8 @@ protected function _lookupTransaction($txnId, $txnType = false) ->setOrderFilter($this->getOrder()) ->addPaymentIdFilter($this->getId()) ->addTxnTypeFilter($txnType) - ->setOrder('created_at', Varien_Data_Collection::SORT_ORDER_DESC); + ->setOrder('created_at', Varien_Data_Collection::SORT_ORDER_DESC) + ->setOrder('transaction_id', Varien_Data_Collection::SORT_ORDER_DESC); foreach ($collection as $txn) { $txn->setOrderPaymentObject($this); $this->_transactionsLookup[$txn->getTxnId()] = $txn; 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..cc41f5cd9a 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,47 @@ 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)) { + $shippingTax = Mage::helper('tax')->getShippingTax($this->getOrder()); + $taxClassAmount = array_merge($shippingTax, $taxClassAmount); - $_amount = $info['amount']; + 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(); - foreach ($info['rates'] as $rate) { - $percent = $rate['percent'] ? ' (' . $rate['percent']. '%)' : ''; + if ($fullInfo) { + foreach ($fullInfo as $info) { + if (isset($info['hidden']) && $info['hidden']) { + continue; + } - $tax_info[] = array( - 'amount' => $this->getAmountPrefix().$this->getOrder()->formatPriceTxt($_amount), - 'label' => Mage::helper('tax')->__($rate['title']) . $percent . ':', - 'font_size' => $fontSize - ); - } - } - } + $_amount = $info['amount']; - return $tax_info; + foreach ($info['rates'] as $rate) { + $percent = $rate['percent'] ? ' (' . $rate['percent']. '%)' : ''; + + $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/Quote.php b/app/code/core/Mage/Sales/Model/Quote.php index 5082549cea..11461cc4c9 100644 --- a/app/code/core/Mage/Sales/Model/Quote.php +++ b/app/code/core/Mage/Sales/Model/Quote.php @@ -1531,25 +1531,36 @@ public function validateMinimumAmount($multishipping = false) $storeId = $this->getStoreId(); $minOrderActive = Mage::getStoreConfigFlag('sales/minimum_order/active', $storeId); $minOrderMulti = Mage::getStoreConfigFlag('sales/minimum_order/multi_address', $storeId); + $minAmount = Mage::getStoreConfig('sales/minimum_order/amount', $storeId); if (!$minOrderActive) { return true; } + $addresses = $this->getAllAddresses(); + if ($multishipping) { if ($minOrderMulti) { + foreach ($addresses as $address) { + foreach ($address->getQuote()->getItemsCollection() as $item) { + $amount = $item->getBaseRowTotal() - $item->getBaseDiscountAmount(); + if ($amount < $minAmount) { + return false; + } + } + } + } else { $baseTotal = 0; - foreach ($this->getAllAddresses() as $address) { + foreach ($addresses as $address) { /* @var $address Mage_Sales_Model_Quote_Address */ $baseTotal += $address->getBaseSubtotalWithDiscount(); } - - if ($baseTotal < Mage::getStoreConfig('sales/minimum_order/amount', $storeId)) { + if ($baseTotal < $minAmount) { return false; } } } else { - foreach ($this->getAllAddresses() as $address) { + foreach ($addresses as $address) { /* @var $address Mage_Sales_Model_Quote_Address */ if (!$address->validateMinimumAmount()) { return false; diff --git a/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement/Collection.php index af10bcdb7a..89b3b107a5 100755 --- a/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement/Collection.php +++ b/app/code/core/Mage/Sales/Model/Resource/Billing/Agreement/Collection.php @@ -40,9 +40,11 @@ class Mage_Sales_Model_Resource_Billing_Agreement_Collection extends Mage_Core_M * @var array */ protected $_map = array('fields' => array( - 'customer_email' => 'ce.email', - 'customer_firstname' => 'firstname.value', - 'customer_lastname' => 'lastname.value' + 'customer_email' => 'ce.email', + 'customer_firstname' => 'firstname.value', + 'customer_lastname' => 'lastname.value', + 'agreement_created_at' => 'main_table.created_at', + 'agreement_updated_at' => 'main_table.updated_at', )); /** diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Collection.php index f13bd467c3..0edad5411e 100755 --- a/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Collection.php +++ b/app/code/core/Mage/Sales/Model/Resource/Order/Creditmemo/Collection.php @@ -74,4 +74,20 @@ protected function _afterLoad() $this->walk('afterLoad'); return $this; } + + /** + * Add filtration conditions + * + * @param array|null $filter + * @return Mage_Sales_Model_Resource_Order_Creditmemo_Collection + */ + public function getFiltered($filter = null) + { + if (is_array($filter)) { + foreach ($filter as $field => $value) { + $this->addFieldToFilter($field, $value); + } + } + return $this; + } } 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/Model/Service/Order.php b/app/code/core/Mage/Sales/Model/Service/Order.php index f1a17f132a..88a5935661 100644 --- a/app/code/core/Mage/Sales/Model/Service/Order.php +++ b/app/code/core/Mage/Sales/Model/Service/Order.php @@ -87,7 +87,7 @@ public function prepareInvoice($qtys = array()) $invoice = $this->_convertor->toInvoice($this->_order); $totalQty = 0; foreach ($this->_order->getAllItems() as $orderItem) { - if (!$this->_canInvoiceItem($orderItem, $qtys)) { + if (!$this->_canInvoiceItem($orderItem, array())) { continue; } $item = $this->_convertor->itemToInvoiceItem($orderItem); diff --git a/app/code/core/Mage/Sales/controllers/DownloadController.php b/app/code/core/Mage/Sales/controllers/DownloadController.php index 0c92232d34..2fb7e71504 100644 --- a/app/code/core/Mage/Sales/controllers/DownloadController.php +++ b/app/code/core/Mage/Sales/controllers/DownloadController.php @@ -113,7 +113,26 @@ public function downloadProfileCustomOptionAction() $orderItemInfo = $recurringProfile->getData('order_item_info'); try { $request = unserialize($orderItemInfo['info_buyRequest']); - if (!isset($request['options'][$this->getRequest()->getParam('option_id')])) { + + if ($request['product'] != $orderItemInfo['product_id']) { + $this->_forward('noRoute'); + return; + } + + $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 +140,6 @@ public function downloadProfileCustomOptionAction() } catch (Exception $e) { $this->_forward('noRoute'); } - $info = array( - '' - ); } /** @@ -132,11 +148,33 @@ public function downloadProfileCustomOptionAction() public function downloadCustomOptionAction() { $quoteItemOptionId = $this->getRequest()->getParam('id'); + /** @var $option Mage_Sales_Model_Quote_Item_Option */ $option = Mage::getModel('sales/quote_item_option')->load($quoteItemOptionId); if (!$option->getId()) { $this->_forward('noRoute'); + return; + } + + $optionId = null; + if (strpos($option->getCode(), Mage_Catalog_Model_Product_Type_Abstract::OPTION_PREFIX) === 0) { + $optionId = str_replace(Mage_Catalog_Model_Product_Type_Abstract::OPTION_PREFIX, '', $option->getCode()); + if ((int)$optionId != $optionId) { + $optionId = null; + } } + $productOption = null; + if ($optionId) { + /** @var $productOption Mage_Catalog_Model_Product_Option */ + $productOption = Mage::getModel('catalog/product_option')->load($optionId); + } + if (!$productOption || !$productOption->getId() + || $productOption->getProductId() != $option->getProductId() || $productOption->getType() != 'file' + ) { + $this->_forward('noRoute'); + return; + } + try { $info = unserialize($option->getValue()); $this->_downloadFileAction($info); diff --git a/app/code/core/Mage/Sales/etc/api.xml b/app/code/core/Mage/Sales/etc/api.xml index 7beb6c37fa..d01713a76c 100644 --- a/app/code/core/Mage/Sales/etc/api.xml +++ b/app/code/core/Mage/Sales/etc/api.xml @@ -179,10 +179,10 @@ 100 Requested invoice does not exist. - + 101 - Invalid filters given. Details in error message. - + Invalid filter given. Details in error message. + 102 Invalid data given. Details in error message. @@ -196,20 +196,103 @@ Invoice status not changed - + + + Credit memo API + sales/order_creditmemo_api + sales/order/creditmemo + + + Retrieve list of credit memos by filters + items + sales/order/creditmemo/list + + + Retrieve credit memo information + sales/order/creditmemo/info + + + Create new credit memo for order + sales/order/creditmemo/create + + + Add new comment to credit memo + sales/order/creditmemo/comment + + + Cancel credit memo + sales/order/creditmemo/cancel + + + + + 100 + Requested credit memo does not exist + + + 101 + Invalid filter given. Details in error message + + + 102 + Invalid data given. Details in error message + + + 103 + Requested order does not exist + + + 104 + Credit memo status not changed + + + 105 + Money can not be refunded to the store credit account as order was created by guest + + + 106 + Credit memo for requested order can not be created. + + + sales_order sales_order_shipment sales_order_invoice + sales_order_creditmemo salesOrder salesOrderShipment salesOrderInvoice + salesOrderCreditmemo + + + + + cancel + + + cart + order + + + + + cancel + + + + + cancel + + + + @@ -259,6 +342,24 @@ Retrieve invoice info + + Order credit memo + + Create + + + Comments + + + Cancel + + + Retrieve credit memo info + + + Retrieve credit memo list + + 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/etc/wsdl.xml b/app/code/core/Mage/Sales/etc/wsdl.xml index 2ed242078e..9c14c2e519 100644 --- a/app/code/core/Mage/Sales/etc/wsdl.xml +++ b/app/code/core/Mage/Sales/etc/wsdl.xml @@ -603,6 +603,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -627,28 +779,28 @@ - + - + - + - + @@ -673,7 +825,7 @@ - + @@ -683,7 +835,7 @@ - + @@ -701,7 +853,7 @@ - + @@ -733,7 +885,7 @@ - + @@ -743,28 +895,71 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + - + @@ -867,6 +1062,31 @@ + + Retrieve list of creditmemos by filters + + + + + Retrieve creditmemo information + + + + + Create new creditmemo for order + + + + + Add new comment to shipment + + + + + Cancel creditmemo + + + @@ -1050,6 +1270,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/core/Mage/Sales/etc/wsi.xml b/app/code/core/Mage/Sales/etc/wsi.xml index e48160047d..afb499ffe6 100644 --- a/app/code/core/Mage/Sales/etc/wsi.xml +++ b/app/code/core/Mage/Sales/etc/wsi.xml @@ -584,6 +584,152 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -906,6 +1052,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1028,6 +1257,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Retrieve list of orders by filters @@ -1129,6 +1388,31 @@ + + Retrieve list of creditmemos by filters + + + + + Retrieve creditmemo information + + + + + Create new creditmemo for order + + + + + Add new comment to creditmemo + + + + + Cancel creditmemo + + + @@ -1312,6 +1596,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Shipping/Model/Config.php b/app/code/core/Mage/Shipping/Model/Config.php index 4b81e4d998..f724d731ec 100644 --- a/app/code/core/Mage/Shipping/Model/Config.php +++ b/app/code/core/Mage/Shipping/Model/Config.php @@ -103,13 +103,8 @@ public function getCarrierInstance($carrierCode, $store = null) */ protected function _getCarrier($code, $config, $store = null) { -/* - if (isset(self::$_carriers[$code])) { - return self::$_carriers[$code]; - } -*/ if (!isset($config['model'])) { - throw Mage::exception('Mage_Shipping', 'Invalid model for shipping method: '.$code); + return false; } $modelName = $config['model']; diff --git a/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php b/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php index 2487df987a..60e78c47d7 100755 --- a/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php +++ b/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php @@ -111,43 +111,49 @@ protected function _construct() * Return table rate array or false by rate request * * @param Mage_Shipping_Model_Rate_Request $request - * @return array + * @return array|boolean */ public function getRate(Mage_Shipping_Model_Rate_Request $request) { $adapter = $this->_getReadAdapter(); - $bind = array( - ':website_id' => (int)$request->getWebsiteId(), - ':country_id' => $request->getDestCountryId(), - ':region_id' => (int)$request->getDestRegionId(), - ':postcode' => $request->getDestPostcode() + $bind = array( + ':website_id' => (int) $request->getWebsiteId(), + ':country_id' => $request->getDestCountryId(), + ':region_id' => (int) $request->getDestRegionId(), + ':postcode' => $request->getDestPostcode() ); - $select = $adapter->select() + $select = $adapter->select() ->from($this->getMainTable()) ->where('website_id = :website_id') ->order(array('dest_country_id DESC', 'dest_region_id DESC', 'dest_zip DESC')) ->limit(1); - // render destination condition + // Render destination condition $orWhere = '(' . implode(') OR (', array( "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = :postcode", "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = ''", + + // Handle asterix in dest_zip field + "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = '*'", + "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = '*'", + "dest_country_id = '0' AND dest_region_id = :region_id AND dest_zip = '*'", + "dest_country_id = '0' AND dest_region_id = 0 AND dest_zip = '*'", + "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = ''", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = :postcode", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = '*'", - "dest_country_id = '0' AND dest_region_id = 0 AND dest_zip = '*'", )) . ')'; $select->where($orWhere); - // render condition by condition name + // Render condition by condition name if (is_array($request->getConditionName())) { $orWhere = array(); - $i = 0; + $i = 0; foreach ($request->getConditionName() as $conditionName) { $bindNameKey = sprintf(':condition_name_%d', $i); $bindValueKey = sprintf(':condition_value_%d', $i); $orWhere[] = "(condition_name = {$bindNameKey} AND condition_value <= {$bindValueKey})"; - $bind[$bindNameKey] = $conditionName; + $bind[$bindNameKey] = $conditionName; $bind[$bindValueKey] = $request->getData($conditionName); $i++; } @@ -164,7 +170,7 @@ public function getRate(Mage_Shipping_Model_Rate_Request $request) } $result = $adapter->fetchRow($select, $bind); - // normalize destination zip code + // Normalize destination zip code if ($result && $result['dest_zip'] == '*') { $result['dest_zip'] = ''; } diff --git a/app/code/core/Mage/Tag/Helper/Data.php b/app/code/core/Mage/Tag/Helper/Data.php index 423d299f1e..95307308b2 100644 --- a/app/code/core/Mage/Tag/Helper/Data.php +++ b/app/code/core/Mage/Tag/Helper/Data.php @@ -55,4 +55,34 @@ public function getStatusesOptionsArray() ) ); } + + /** + * Check tags on the correctness of symbols and split string to array of tags + * + * @param string $tagNamesInString + * @return array + */ + public function extractTags($tagNamesInString) + { + return explode("\n", preg_replace("/(\'(.*?)\')|(\s+)/i", "$1\n", $tagNamesInString)); + } + + /** + * Clear tag from the separating characters + * + * @param array $tagNamesArr + * @return array + */ + public function cleanTags(array $tagNamesArr) + { + foreach ($tagNamesArr as $key => $tagName) { + $tagNamesArr[$key] = trim($tagNamesArr[$key], '\''); + $tagNamesArr[$key] = trim($tagNamesArr[$key]); + if ($tagNamesArr[$key] == '') { + unset($tagNamesArr[$key]); + } + } + return $tagNamesArr; + } + } diff --git a/app/code/core/Mage/Tag/Model/Api.php b/app/code/core/Mage/Tag/Model/Api.php new file mode 100644 index 0000000000..e6a3fee04b --- /dev/null +++ b/app/code/core/Mage/Tag/Model/Api.php @@ -0,0 +1,244 @@ + + */ +class Mage_Tag_Model_Api extends Mage_Catalog_Model_Api_Resource +{ + /** + * Retrieve list of tags for specified product + * + * @param int $productId + * @param string|int $store + * @return array + */ + public function items($productId, $store = null) + { + $result = array(); + // fields list to return + $fieldsForResult = array('tag_id', 'name'); + + /** @var $product Mage_Catalog_Model_Product */ + $product = Mage::getModel('catalog/product')->load($productId); + if (!$product->getId()) { + $this->_fault('product_not_exists'); + } + + /** @var $tags Mage_Tag_Model_Resource_Tag_Collection */ + $tags = Mage::getModel('tag/tag')->getCollection()->joinRel()->addProductFilter($productId); + if ($store) { + $tags->addStoreFilter($this->_getStoreId($store)); + } + + /** @var $tag Mage_Tag_Model_Tag */ + foreach ($tags as $tag) { + $result[$tag->getId()] = $tag->toArray($fieldsForResult); + } + + return $result; + } + + /** + * Retrieve tag info as array('name'-> .., 'status' => .., + * 'base_popularity' => .., 'products' => array($productId => $popularity, ...)) + * + * @param int $tagId + * @param string|int $store + * @return array + */ + public function info($tagId, $store) + { + $result = array(); + $storeId = $this->_getStoreId($store); + /** @var $tag Mage_Tag_Model_Tag */ + $tag = Mage::getModel('tag/tag')->setStoreId($storeId)->setAddBasePopularity()->load($tagId); + if (!$tag->getId()) { + $this->_fault('tag_not_exists'); + } + $result['status'] = $tag->getStatus(); + $result['name'] = $tag->getName(); + $result['base_popularity'] = (is_numeric($tag->getBasePopularity())) ? $tag->getBasePopularity() : 0; + // retrieve array($productId => $popularity, ...) + $result['products'] = array(); + $relatedProductsCollection = $tag->getEntityCollection()->addTagFilter($tagId) + ->addStoreFilter($storeId)->addPopularity($tagId); + foreach ($relatedProductsCollection as $product) { + $result['products'][$product->getId()] = $product->getPopularity(); + } + + return $result; + } + + /** + * Add tag(s) to product. + * Return array of added/updated tags as array($tagName => $tagId, ...) + * + * @param array $data + * @return array + */ + public function add($data) + { + $data = $this->_prepareDataForAdd($data); + /** @var $product Mage_Catalog_Model_Product */ + $product = Mage::getModel('catalog/product')->load($data['product_id']); + if (!$product->getId()) { + $this->_fault('product_not_exists'); + } + /** @var $customer Mage_Customer_Model_Customer */ + $customer = Mage::getModel('customer/customer')->load($data['customer_id']); + if (!$customer->getId()) { + $this->_fault('customer_not_exists'); + } + $storeId = $this->_getStoreId($data['store']); + + try { + /** @var $tag Mage_Tag_Model_Tag */ + $tag = Mage::getModel('tag/tag'); + $tagNamesArr = Mage::helper('tag')->cleanTags(Mage::helper('tag')->extractTags($data['tag'])); + foreach ($tagNamesArr as $tagName) { + // unset previously added tag data + $tag->unsetData(); + $tag->loadByName($tagName); + if (!$tag->getId()) { + $tag->setName($tagName) + ->setFirstCustomerId($customer->getId()) + ->setFirstStoreId($storeId) + ->setStatus($tag->getPendingStatus()) + ->save(); + } + $tag->saveRelation($product->getId(), $customer->getId(), $storeId); + $result[$tagName] = $tag->getId(); + } + } catch (Mage_Core_Exception $e) { + $this->_fault('save_error', $e->getMessage()); + } + + return $result; + } + + /** + * Change existing tag information + * + * @param int $tagId + * @param array $data + * @param string|int $store + * @return bool + */ + public function update($tagId, $data, $store) + { + $data = $this->_prepareDataForUpdate($data); + $storeId = $this->_getStoreId($store); + /** @var $tag Mage_Tag_Model_Tag */ + $tag = Mage::getModel('tag/tag')->setStoreId($storeId)->setAddBasePopularity()->load($tagId); + if (!$tag->getId()) { + $this->_fault('tag_not_exists'); + } + + // store should be set for 'base_popularity' to be saved in Mage_Tag_Model_Resource_Tag::_afterSave() + $tag->setStore($storeId); + if (isset($data['base_popularity'])) { + $tag->setBasePopularity($data['base_popularity']); + } + if (isset($data['name'])) { + $tag->setName(trim($data['name'])); + } + if (isset($data['status'])) { + // validate tag status + if (!in_array($data['status'], array( + $tag->getApprovedStatus(), $tag->getPendingStatus(), $tag->getDisabledStatus()))) { + $this->_fault('invalid_data'); + } + $tag->setStatus($data['status']); + } + + try { + $tag->save(); + } catch (Mage_Core_Exception $e) { + $this->_fault('save_error', $e->getMessage()); + } + + return true; + } + + /** + * Remove existing tag + * + * @param int $tagId + * @return bool + */ + public function remove($tagId) + { + /** @var $tag Mage_Tag_Model_Tag */ + $tag = Mage::getModel('tag/tag')->load($tagId); + if (!$tag->getId()) { + $this->_fault('tag_not_exists'); + } + try { + $tag->delete(); + } catch (Mage_Core_Exception $e) { + $this->_fault('remove_error', $e->getMessage()); + } + + return true; + } + + /** + * Check data before add + * + * @param array $data + * @return array + */ + protected function _prepareDataForAdd($data) + { + if (!isset($data['product_id']) or !isset($data['tag']) + or !isset($data['customer_id']) or !isset($data['store'])) { + $this->_fault('invalid_data'); + } + + return $data; + } + + /** + * Check data before update + * + * @param $data + * @return + */ + protected function _prepareDataForUpdate($data) + { + // $data should contain at least one field to change + if ( !(isset($data['name']) or isset($data['status']) or isset($data['base_popularity']))) { + $this->_fault('invalid_data'); + } + + return $data; + } +} diff --git a/app/code/core/Mage/Tag/Model/Api/V2.php b/app/code/core/Mage/Tag/Model/Api/V2.php new file mode 100644 index 0000000000..a0bc9acc16 --- /dev/null +++ b/app/code/core/Mage/Tag/Model/Api/V2.php @@ -0,0 +1,109 @@ + + */ +class Mage_Tag_Model_Api_V2 extends Mage_Tag_Model_Api +{ + /** + * Retrieve list of tags for specified product as array of objects + * + * @param int $productId + * @param string|int $store + * @return array + */ + public function items($productId, $store) + { + $result = parent::items($productId, $store); + foreach ($result as $key => $tag) { + $result[$key] = Mage::helper('api')->wsiArrayPacker($tag); + } + return $result; + } + + /** + * Add tag(s) to product. + * Return array of objects + * + * @param array $data + * @return array + */ + public function add($data) + { + $result = array(); + foreach (parent::add($data) as $key => $value) { + $result[] = array('key' => $key, 'value' => $value); + } + + return $result; + } + + /** + * Retrieve tag info as object + * + * @param int $tagId + * @param string|int $store + * @return object + */ + public function info($tagId, $store) + { + $result = parent::info($tagId, $store); + $result = Mage::helper('api')->wsiArrayPacker($result); + foreach ($result->products as $key => $value) { + $result->products[$key] = array('key' => $key, 'value' => $value); + } + return $result; + } + + /** + * Convert data from object to array before add + * + * @param object $data + * @return array + */ + protected function _prepareDataForAdd($data) + { + Mage::helper('api')->toArray($data); + return parent::_prepareDataForAdd($data); + } + + /** + * Convert data from object to array before update + * + * @param object $data + * @return array + */ + protected function _prepareDataForUpdate($data) + { + Mage::helper('api')->toArray($data); + return parent::_prepareDataForUpdate($data); + } +} 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/Tag/etc/api.xml b/app/code/core/Mage/Tag/etc/api.xml new file mode 100644 index 0000000000..3f64d1d415 --- /dev/null +++ b/app/code/core/Mage/Tag/etc/api.xml @@ -0,0 +1,138 @@ + + + + + + + Product Tag API + tag/api + catalog/product/tag + + + Retrieve list of tags by product + items + catalog/product/tag/list + + + Retrieve product tag info + catalog/product/tag/info + + + Add tag(s) to product + catalog/product/tag/add + + + Update product tag + catalog/product/tag/update + + + Remove product tag + catalog/product/tag/remove + + + + + 101 + Requested store does not exist. + + + 102 + Requested product does not exist. + + + 103 + Requested customer does not exist. + + + 104 + Requested tag does not exist. + + + 105 + Provided data is invalid. + + + 106 + Error while saving tag. Details in error message. + + + 107 + Error while removing tag. Details in error message. + + + + + + catalog_product_tag + + + + catalogProductTag + + + + + + + add + + + remove + + + + + + + + + + Tag + 103 + + List + + + Info + + + Add + + + Update + + + Remove + + + + + + + + diff --git a/app/code/core/Mage/Tag/etc/wsdl.xml b/app/code/core/Mage/Tag/etc/wsdl.xml new file mode 100644 index 0000000000..c7d114736c --- /dev/null +++ b/app/code/core/Mage/Tag/etc/wsdl.xml @@ -0,0 +1,189 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Retrieve list of tags by product + + + + + + + Retrieve product tag info + + + + + + + Add tag(s) to product + + + + + + + Update product tag + + + + + + + Remove product tag + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/core/Mage/Tag/etc/wsi.xml b/app/code/core/Mage/Tag/etc/wsi.xml new file mode 100644 index 0000000000..615e2a4458 --- /dev/null +++ b/app/code/core/Mage/Tag/etc/wsi.xml @@ -0,0 +1,262 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Retrieve list of tags by product + + + + + + + Retrieve product tag info + + + + + + + Add tag(s) to product + + + + + + + Update product tag + + + + + + + Remove product tag + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/core/Mage/Tax/Helper/Data.php b/app/code/core/Mage/Tax/Helper/Data.php index 6e20e4477d..fc614c3db0 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,117 @@ public function getCalculationAgorithm($store=null) { return $this->_config->getAlgorithm($store); } -} + /** + * Get calculated taxes for each tax class + * + * This method returns array with format: + * array( + * $index => array( + * 'tax_amount' => $taxAmount, + * 'base_tax_amount' => $baseTaxAmount, + * 'hidden_tax_amount' => $hiddenTaxAmount + * 'title' => $title + * 'percent' => $percent + * ) + * ) + * + * @param Mage_Sales_Model_Order $source + * @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) { + 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['tax_percent']; + + $price = $item->getRowTotal(); + $basePrice = $item->getBaseRowTotal(); + if ($this->applyTaxAfterDiscount($item->getStoreId())) { + $price = $price - $item->getDiscountAmount() + $item->getHiddenTaxAmount(); + $basePrice = $basePrice - $item->getBaseDiscountAmount() + $item->getBaseHiddenTaxAmount(); + } + + if (isset($taxClassAmount[$taxClassId])) { + $taxClassAmount[$taxClassId]['tax_amount'] += $price * $percent / 100; + $taxClassAmount[$taxClassId]['base_tax_amount'] += $basePrice * $percent / 100; + } else { + $taxClassAmount[$taxClassId]['tax_amount'] = $price * $percent / 100; + $taxClassAmount[$taxClassId]['base_tax_amount'] = $basePrice * $percent / 100; + $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) { + unset($taxClassAmount[$key]); + } + } + + $taxClassAmount = array_values($taxClassAmount); + } + + return $taxClassAmount; + } + + /** + * Get calculated Shipping & Handling Tax + * + * This method returns array with format: + * array( + * $index => array( + * 'tax_amount' => $taxAmount, + * 'base_tax_amount' => $baseTaxAmount, + * 'hidden_tax_amount' => $hiddenTaxAmount + * 'title' => $title + * 'percent' => $percent + * ) + * ) + * + * @param Mage_Sales_Model_Order $source + * @return array + */ + public function getShippingTax($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) { + if ($current->getShippingTaxAmount() != 0 && $current->getBaseShippingTaxAmount() != 0) { + $taxClassAmount[0]['tax_amount'] = $current->getShippingTaxAmount(); + $taxClassAmount[0]['base_tax_amount'] = $current->getBaseShippingTaxAmount(); + if ($current->getShippingHiddenTaxAmount() > 0) { + $taxClassAmount[0]['hidden_tax_amount'] = $current->getShippingHiddenTaxAmount(); + } + $taxClassAmount[0]['title'] = $this->__('Shipping & Handling Tax'); + $taxClassAmount[0]['percent'] = NULL; + } + } + + return $taxClassAmount; + } +} diff --git a/app/code/core/Mage/Tax/Model/Observer.php b/app/code/core/Mage/Tax/Model/Observer.php index bb48e5223d..e14d6d178f 100644 --- a/app/code/core/Mage/Tax/Model/Observer.php +++ b/app/code/core/Mage/Tax/Model/Observer.php @@ -59,12 +59,52 @@ 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(); + if (!is_array($getTaxesForItems)) { + $getTaxesForItems = array(); + } + foreach ($getTaxesForItems as $quoteItemId => $taxesArray) { + foreach ($taxesArray as $rates) { + if (count($rates['rates']) == 1) { + $ratesIdQuoteItemId[$rates['id']][] = array( + 'id' => $quoteItemId, + 'percent' => $rates['percent'], + 'code' => $rates['rates'][0]['code'] + ); + } else { + $percentDelta = $rates['percent']; + $percentSum = 0; + foreach ($rates['rates'] as $rate) { + $ratesIdQuoteItemId[$rates['id']][] = array( + 'id' => $quoteItemId, + 'percent' => $rate['percent'], + 'code' => $rate['code'] + ); + $percentSum += $rate['percent']; + } + + if ($percentDelta != $percentSum) { + $delta = $percentDelta - $percentSum; + foreach ($ratesIdQuoteItemId[$rates['id']] as &$rateTax) { + if ($rateTax['id'] == $quoteItemId) { + $rateTax['percent'] = (($rateTax['percent'] / $percentSum) * $delta) + + $rateTax['percent']; + } + } + } + } + } + } + + foreach ($taxes as $id => $row) { foreach ($row['rates'] as $tax) { if (is_null($row['percent'])) { $baseRealAmount = $row['base_amount']; @@ -72,26 +112,43 @@ 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) { + if ($quoteItemId['code'] == $tax['code']) { + $item = $order->getItemByQuoteItemId($quoteItemId['id']); + if ($item) { + $data = array( + 'item_id' => $item->getId(), + 'tax_id' => $result->getTaxId(), + 'tax_percent' => $quoteItemId['percent'] + ); + 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..cb048adfed 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,36 @@ 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) + ->where('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/Tax/Model/Resource/Sales/Order/Tax/Item.php b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item.php new file mode 100755 index 0000000000..c986b31e6f --- /dev/null +++ b/app/code/core/Mage/Tax/Model/Resource/Sales/Order/Tax/Item.php @@ -0,0 +1,65 @@ + + */ +class Mage_Tax_Model_Resource_Sales_Order_Tax_Item extends Mage_Core_Model_Resource_Db_Abstract +{ + /** + * Resource initialization + */ + protected function _construct() + { + $this->_init('tax/sales_order_tax_item', 'tax_item_id'); + } + + /** + * Get Tax Items with order tax information + * + * @param int $item_id + * @return array + */ + public function getTaxItemsByItemId($item_id) + { + $adapter = $this->_getReadAdapter(); + $select = $adapter->select() + ->from(array('item' => $this->getTable('tax/sales_order_tax_item')), array('tax_id', 'tax_percent')) + ->join( + array('tax' => $this->getTable('tax/sales_order_tax')), + 'item.tax_id = tax.tax_id', + array('title', 'percent', 'base_amount') + ) + ->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..8e197ee9d8 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 @@ -296,6 +296,7 @@ protected function _calculateShippingTax(Mage_Sales_Model_Quote_Address $address protected function _unitBaseCalculation(Mage_Sales_Model_Quote_Address $address, $taxRateRequest) { $items = $this->_getAddressItems($address); + $itemTaxGroups = array(); foreach ($items as $item) { if ($item->getParentItem()) { continue; @@ -309,6 +310,9 @@ protected function _unitBaseCalculation(Mage_Sales_Model_Quote_Address $address, $this->_addAmount($child->getTaxAmount()); $this->_addBaseAmount($child->getBaseTaxAmount()); $applied = $this->_calculator->getAppliedRates($taxRateRequest); + if ($rate > 0) { + $itemTaxGroups[$child->getId()] = $applied; + } $this->_saveAppliedTaxes( $address, $applied, @@ -316,6 +320,7 @@ protected function _unitBaseCalculation(Mage_Sales_Model_Quote_Address $address, $child->getBaseTaxAmount(), $rate ); + $child->setTaxRates($applied); } $this->_recalculateParent($item); } @@ -326,6 +331,9 @@ protected function _unitBaseCalculation(Mage_Sales_Model_Quote_Address $address, $this->_addAmount($item->getTaxAmount()); $this->_addBaseAmount($item->getBaseTaxAmount()); $applied = $this->_calculator->getAppliedRates($taxRateRequest); + if ($rate > 0) { + $itemTaxGroups[$item->getId()] = $applied; + } $this->_saveAppliedTaxes( $address, $applied, @@ -333,8 +341,13 @@ protected function _unitBaseCalculation(Mage_Sales_Model_Quote_Address $address, $item->getBaseTaxAmount(), $rate ); + $item->setTaxRates($applied); } } + if ($address->getQuote()->getTaxesForItems()) { + $itemTaxGroups += $address->getQuote()->getTaxesForItems(); + } + $address->getQuote()->setTaxesForItems($itemTaxGroups); return $this; } @@ -373,7 +386,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) { @@ -417,6 +431,7 @@ protected function _calcUnitTaxAmount(Mage_Sales_Model_Quote_Item_Abstract $item protected function _rowBaseCalculation(Mage_Sales_Model_Quote_Address $address, $taxRateRequest) { $items = $this->_getAddressItems($address); + $itemTaxGroups = array(); foreach ($items as $item) { if ($item->getParentItem()) { continue; @@ -429,6 +444,9 @@ protected function _rowBaseCalculation(Mage_Sales_Model_Quote_Address $address, $this->_addAmount($child->getTaxAmount()); $this->_addBaseAmount($child->getBaseTaxAmount()); $applied = $this->_calculator->getAppliedRates($taxRateRequest); + if ($rate > 0) { + $itemTaxGroups[$child->getId()] = $applied; + } $this->_saveAppliedTaxes( $address, $applied, @@ -446,6 +464,9 @@ protected function _rowBaseCalculation(Mage_Sales_Model_Quote_Address $address, $this->_addAmount($item->getTaxAmount()); $this->_addBaseAmount($item->getBaseTaxAmount()); $applied = $this->_calculator->getAppliedRates($taxRateRequest); + if ($rate > 0) { + $itemTaxGroups[$item->getId()] = $applied; + } $this->_saveAppliedTaxes( $address, $applied, @@ -455,6 +476,11 @@ protected function _rowBaseCalculation(Mage_Sales_Model_Quote_Address $address, ); } } + + if ($address->getQuote()->getTaxesForItems()) { + $itemTaxGroups += $address->getQuote()->getTaxesForItems(); + } + $address->getQuote()->setTaxesForItems($itemTaxGroups); return $this; } @@ -534,9 +560,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) { @@ -548,20 +575,33 @@ protected function _totalBaseCalculation(Mage_Sales_Model_Quote_Address $address foreach ($item->getChildren() as $child) { $taxRateRequest->setProductClassId($child->getProduct()->getTaxClassId()); $rate = $this->_calculator->getRate($taxRateRequest); - $taxGroups[(string)$rate]['applied_rates'] = $this->_calculator->getAppliedRates($taxRateRequest); + $applied_rates = $this->_calculator->getAppliedRates($taxRateRequest); + $taxGroups[(string)$rate]['applied_rates'] = $applied_rates; $this->_aggregateTaxPerRate($child, $rate, $taxGroups); $inclTax = $child->getIsPriceInclTax(); + if ($rate > 0) { + $itemTaxGroups[$child->getId()] = $applied_rates; + } } $this->_recalculateParent($item); } else { $taxRateRequest->setProductClassId($item->getProduct()->getTaxClassId()); $rate = $this->_calculator->getRate($taxRateRequest); - $taxGroups[(string)$rate]['applied_rates'] = $this->_calculator->getAppliedRates($taxRateRequest); + $applied_rates = $this->_calculator->getAppliedRates($taxRateRequest); + $taxGroups[(string)$rate]['applied_rates'] = $applied_rates; $this->_aggregateTaxPerRate($item, $rate, $taxGroups); $inclTax = $item->getIsPriceInclTax(); + if ($rate > 0) { + $itemTaxGroups[$item->getId()] = $applied_rates; + } } } + if ($address->getQuote()->getTaxesForItems()) { + $itemTaxGroups += $address->getQuote()->getTaxesForItems(); + } + $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..e25aa95302 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.3 @@ -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/Tax/sql/tax_setup/upgrade-1.6.0.2-1.6.0.3.php b/app/code/core/Mage/Tax/sql/tax_setup/upgrade-1.6.0.2-1.6.0.3.php new file mode 100644 index 0000000000..8dcf938873 --- /dev/null +++ b/app/code/core/Mage/Tax/sql/tax_setup/upgrade-1.6.0.2-1.6.0.3.php @@ -0,0 +1,44 @@ +getConnection() + ->addColumn( + $installer->getTable('tax/sales_order_tax_item'), + 'tax_percent', + array( + 'TYPE' => Varien_Db_Ddl_Table::TYPE_DECIMAL, + 'SCALE' => 4, + 'PRECISION' => 12, + 'NULLABLE' => false, + 'COMMENT' => 'Real Tax Percent For Item', + ) + ); diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php index 8166cb4f9a..d567b6e3c3 100644 --- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php +++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php @@ -85,6 +85,13 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex */ protected $_shipServiceWsdl = null; + /** + * Path to wsdl file of track service + * + * @var string + */ + protected $_trackServiceWsdl = null; + /** * Container types that could be customized for FedEx carrier * @@ -95,27 +102,40 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex public function __construct() { parent::__construct(); - $this->_shipServiceWsdl = Mage::getModuleDir('etc', 'Mage_Usa') . DS . 'wsdl' . DS . 'FedEx' - . DS . 'ShipService_v9.wsdl'; - $this->_rateServiceWsdl = Mage::getModuleDir('etc', 'Mage_Usa') . DS . 'wsdl' . DS . 'FedEx' - . DS . 'RateService_v9.wsdl'; + $wsdlBasePath = Mage::getModuleDir('etc', 'Mage_Usa') . DS . 'wsdl' . DS . 'FedEx' . DS; + $this->_shipServiceWsdl = $wsdlBasePath . 'ShipService_v9.wsdl'; + $this->_rateServiceWsdl = $wsdlBasePath . 'RateService_v9.wsdl'; + $this->_trackServiceWsdl = $wsdlBasePath . 'TrackService_v5.wsdl'; } /** - * Create rate soap client + * Create soap client with selected wsdl * + * @param string $wsdl + * @param bool|int $trace * @return SoapClient */ - protected function _createRateSoapClient() + protected function _createSoapClient($wsdl, $trace = false) { - $client = new SoapClient($this->_rateServiceWsdl); + $client = new SoapClient($wsdl, array('trace' => $trace)); $client->__setLocation($this->getConfigFlag('sandbox_mode') ? 'https://wsbeta.fedex.com:443/web-services/rate' : 'https://ws.fedex.com:443/web-services/rate' ); + return $client; } + /** + * Create rate soap client + * + * @return SoapClient + */ + protected function _createRateSoapClient() + { + return $this->_createSoapClient($this->_rateServiceWsdl); + } + /** * Create ship soap client * @@ -123,12 +143,17 @@ protected function _createRateSoapClient() */ protected function _createShipSoapClient() { - $client = new SoapClient($this->_shipServiceWsdl, array('trace' => 1)); - $client->__setLocation($this->getConfigFlag('sandbox_mode') - ? 'https://wsbeta.fedex.com:443/web-services/ship' - : 'https://ws.fedex.com:443/web-services/ship' - ); - return $client; + return $this->_createSoapClient($this->_shipServiceWsdl, 1); + } + + /** + * Create track soap client + * + * @return SoapClient + */ + protected function _createTrackSoapClient() + { + return $this->_createSoapClient($this->_trackServiceWsdl, 1); } /** @@ -704,6 +729,11 @@ public function getCode($type, $code='') 'STANDARD_OVERNIGHT', 'PRIORITY_OVERNIGHT', 'FIRST_OVERNIGHT', + 'FEDEX_FREIGHT', + 'FEDEX_1_DAY_FREIGHT', + 'FEDEX_2_DAY_FREIGHT', + 'FEDEX_3_DAY_FREIGHT', + 'FEDEX_NATIONAL_FREIGHT', ) ), 'from_us' => array( @@ -712,6 +742,13 @@ public function getCode($type, $code='') 'INTERNATIONAL_ECONOMY', 'INTERNATIONAL_PRIORITY', 'INTERNATIONAL_GROUND', + 'FEDEX_FREIGHT', + 'FEDEX_1_DAY_FREIGHT', + 'FEDEX_2_DAY_FREIGHT', + 'FEDEX_3_DAY_FREIGHT', + 'FEDEX_NATIONAL_FREIGHT', + 'INTERNATIONAL_ECONOMY_FREIGHT', + 'INTERNATIONAL_PRIORITY_FREIGHT', ) ) ) @@ -811,58 +848,165 @@ protected function setTrackingReqeust() */ protected function _getXMLTracking($tracking) { - $r = $this->_rawTrackingRequest; - - $xml = new SimpleXMLElement(''); - $xml->addAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); - $xml->addAttribute('xsi:noNamespaceSchemaLocation', 'FDXTrack2Request.xsd'); + $trackRequest = array( + 'WebAuthenticationDetail' => array( + 'UserCredential' => array( + 'Key' => $this->getConfigData('key'), + 'Password' => $this->getConfigData('password') + ) + ), + 'ClientDetail' => array( + 'AccountNumber' => $this->getConfigData('account'), + 'MeterNumber' => $this->getConfigData('meter_number') + ), + 'Version' => array( + 'ServiceId' => 'trck', + 'Major' => '5', + 'Intermediate' => '0', + 'Minor' => '0' + ), + 'PackageIdentifier' => array( + 'Type' => 'TRACKING_NUMBER_OR_DOORTAG', + 'Value' => $tracking, + ), + /* + * 0 = summary data, one signle scan structure with the most recent scan + * 1 = multiple sacn activity for each package + */ + 'IncludeDetailedScans' => 1, + ); + $requestString = serialize($trackRequest); + $response = $this->_getCachedQuotes($requestString); + $debugData = array('request' => $trackRequest); + if ($response === null) { + try { + $client = $this->_createTrackSoapClient(); + $response = $client->track($trackRequest); + $this->_setCachedQuotes($requestString, serialize($response)); + $debugData['result'] = $response; + } catch (Exception $e) { + $debugData['result'] = array('error' => $e->getMessage(), 'code' => $e->getCode()); + Mage::logException($e); + } + } else { + $response = unserialize($response); + $debugData['result'] = $response; + } + $this->_debug($debugData); - $requestHeader = $xml->addChild('RequestHeader'); - $requestHeader->addChild('AccountNumber', $r->getAccount()); + $this->_parseTrackingResponse($tracking, $response); + } - /* - * for tracking result, actual meter number is not needed - */ - $requestHeader->addChild('MeterNumber', '0'); + /** + * Parse tracking response + * + * @param array $trackingValue + * @param stdClass $response + */ + protected function _parseTrackingResponse($trackingValue, $response) + { + if (is_object($response)) { + if ($response->HighestSeverity == 'FAILURE' || $response->HighestSeverity == 'ERROR') { + $errorTitle = (string)$response->Notifications->Message; + } elseif (isset($response->TrackDetails)) { + $trackInfo = $response->TrackDetails; + $resultArray['status'] = (string)$trackInfo->StatusDescription; + $resultArray['service'] = (string)$trackInfo->ServiceInfo; + $timestamp = isset($trackInfo->EstimatedDeliveryTimestamp) ? + $trackInfo->EstimatedDeliveryTimestamp : $trackInfo->ActualDeliveryTimestamp; + $timestamp = strtotime((string)$timestamp); + if ($timestamp) { + $resultArray['deliverydate'] = date('Y-m-d', $timestamp); + $resultArray['deliverytime'] = date('H:i:s', $timestamp); + } - $packageIdentifier = $xml->addChild('PackageIdentifier'); - $packageIdentifier->addChild('Value', $tracking); + $deliveryLocation = isset($trackInfo->EstimatedDeliveryAddress) ? + $trackInfo->EstimatedDeliveryAddress : $trackInfo->ActualDeliveryAddress; + $deliveryLocationArray = array(); + if (isset($deliveryLocation->City)) { + $deliveryLocationArray[] = (string)$deliveryLocation->City; + } + if (isset($deliveryLocation->StateOrProvinceCode)) { + $deliveryLocationArray[] = (string)$deliveryLocation->StateOrProvinceCode; + } + if (isset($deliveryLocation->CountryCode)) { + $deliveryLocationArray[] = (string)$deliveryLocation->CountryCode; + } + if ($deliveryLocationArray) { + $resultArray['deliverylocation'] = implode(', ', $deliveryLocationArray); + } - /* - * 0 = summary data, one signle scan structure with the most recent scan - * 1 = multiple sacn activity for each package - */ - $xml->addChild('DetailScans', '1'); + $resultArray['signedby'] = (string)$trackInfo->DeliverySignatureName; + $resultArray['shippeddate'] = date('Y-m-d', (int)$trackInfo->ShipTimestamp); + if (isset($trackInfo->PackageWeight) && isset($trackInfo->Units)) { + $weight = (string)$trackInfo->PackageWeight; + $unit = (string)$trackInfo->Units; + $resultArray['weight'] = "{$weight} {$unit}"; + } - $request = $xml->asXML(); - $debugData = array('request' => $request); + $packageProgress = array(); + if (isset($trackInfo->Events)) { + $events = $trackInfo->Events; + if (isset($events->Address)) { + $events = array($events); + } + foreach ($events as $event) { + $tempArray = array(); + $tempArray['activity'] = (string)$event->EventDescription; + $timestamp = strtotime((string)$event->Timestamp); + if ($timestamp) { + $tempArray['deliverydate'] = date('Y-m-d', $timestamp); + $tempArray['deliverytime'] = date('H:i:s', $timestamp); + } + if (isset($event->Address)) { + $addressArray = array(); + $address = $event->Address; + if (isset($address->City)) { + $addressArray[] = (string)$address->City; + } + if (isset($address->StateOrProvinceCode)) { + $addressArray[] = (string)$address->StateOrProvinceCode; + } + if (isset($address->CountryCode)) { + $addressArray[] = (string)$address->CountryCode; + } + if ($addressArray) { + $tempArray['deliverylocation'] = implode(', ', $addressArray); + } + } + $packageProgress[] = $tempArray; + } + } - try { - $url = $this->getConfigData('gateway_url'); - if (!$url) { - $url = $this->_defaultGatewayUrl; + $resultArray['progressdetail'] = $packageProgress; } - $ch = curl_init(); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_POSTFIELDS, $request); - $responseBody = curl_exec($ch); - $debugData['result'] = $responseBody; - curl_close ($ch); } - catch (Exception $e) { - $debugData['result'] = array('error' => $e->getMessage(), 'code' => $e->getCode()); - $responseBody = ''; + + if(!$this->_result){ + $this->_result = Mage::getModel('shipping/tracking_result'); + } + + if(isset($resultArray)) { + $tracking = Mage::getModel('shipping/tracking_result_status'); + $tracking->setCarrier('fedex'); + $tracking->setCarrierTitle($this->getConfigData('title')); + $tracking->setTracking($trackingValue); + $tracking->addData($resultArray); + $this->_result->append($tracking); + } else { + $error = Mage::getModel('shipping/tracking_result_error'); + $error->setCarrier('fedex'); + $error->setCarrierTitle($this->getConfigData('title')); + $error->setTracking($trackingValue); + $error->setErrorMessage($errorTitle ? $errorTitle : Mage::helper('usa')->__('Unable to retrieve tracking')); + $this->_result->append($error); } - $this->_debug($debugData); - $this->_parseXmlTrackingResponse($tracking, $responseBody); } /** * Parse xml tracking response * + * @deprecated after 1.6.0.0 see _parseTrackingResponse() * @param array $trackingvalue * @param string $response * @return void diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php index 1f884d9a72..3819a2e6c8 100644 --- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php +++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php @@ -739,6 +739,7 @@ public function getCode($type, $code='') '14', // Next Day Air Early AM '02', // 2nd Day Air '59', // 2nd Day Air AM + '13', // Next Day Air Saver ) ), 'from_us' => array( @@ -1696,10 +1697,22 @@ public function getContainerTypes(Varien_Object $params = null) $containerTypes = $containerTypes + array( '03' => Mage::helper('usa')->__('UPS Tube'), '04' => Mage::helper('usa')->__('PAK'), - '21' => Mage::helper('usa')->__('UPS Express Box'), + '2a' => Mage::helper('usa')->__('Small Express Box'), + '2b' => Mage::helper('usa')->__('Medium Express Box'), + '2c' => Mage::helper('usa')->__('Large Express Box'), ); } return array('00' => Mage::helper('usa')->__('Customer Packaging')) + $containerTypes; + } elseif ($countryShipper == self::USA_COUNTRY_ID && $countryRecipient == self::PUERTORICO_COUNTRY_ID + && ($method == '03' // UPS Ground + || $method == '02' // UPS Second Day Air + || $method == '01' // UPS Next Day Air + )) { + // Container types should be the same as for domestic + $params->setCountryRecipient(self::USA_COUNTRY_ID); + $containerTypes = $this->_getAllowedContainers($params); + $params->setCountryRecipient($countryRecipient); + return $containerTypes; } return $this->_getAllowedContainers($params); } 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/Usa/etc/wsdl/FedEx/TrackService_v5.wsdl b/app/code/core/Mage/Usa/etc/wsdl/FedEx/TrackService_v5.wsdl new file mode 100644 index 0000000000..1f275b3104 --- /dev/null +++ b/app/code/core/Mage/Usa/etc/wsdl/FedEx/TrackService_v5.wsdl @@ -0,0 +1,1510 @@ + + + + + + + + + + + + + + Descriptive data for a physical location. May be used as an actual physical address (place to which one could go), or as a container of "address parts" which should be handled as a unit (such as a city-state-ZIP combination within the US). + + + + + Combination of number, street name, etc. At least one line is required for a valid physical address; empty lines should not be included. + + + + + Name of city, town, etc. + + + + + Identifying abbreviation for US state, Canada province, etc. Format and presence of this field will vary, depending on country. + + + + + Identification of a region (usually small) for mail/package delivery. Format and presence of this field will vary, depending on country. + + + + + Relevant only to addresses in Puerto Rico. + + + + + The two-letter code used to identify a country. + + + + + Indicates whether this address residential (as opposed to commercial). + + + + + + + Identifies where a tracking event occurs. + + + + + + + + + + + + + + + + + + + + + + + + + + + Identification of a FedEx operating company (transportation). + + + + + + + + + + + + + Descriptive data for the client submitting a transaction. + + + + + The FedEx account number associated with this transaction. + + + + + This number is assigned by FedEx and identifies the unique device from which the request is originating + + + + + Only used in transactions which require identification of the Fed Ex Office integrator. + + + + + The language to be used for human-readable Notification.localizedMessages in responses to the request containing this ClientDetail object. Different requests from the same client may contain different Localization data. (Contrast with TransactionDetail.localization, which governs data payload language/translation.) + + + + + + + The descriptive data for a point-of-contact person. + + + + + Identifies the contact person's name. + + + + + Identifies the contact person's title. + + + + + Identifies the company this contact is associated with. + + + + + Identifies the phone number associated with this contact. + + + + + Identifies the phone extension associated with this contact. + + + + + Identifies the pager number associated with this contact. + + + + + Identifies the fax number associated with this contact. + + + + + Identifies the email address associated with this contact. + + + + + + + + + + + + + The dimensions of this package and the unit type used for the measurements. + + + + + + + + + + + Driving or other transportation distances, distinct from dimension measurements. + + + + + Identifies the distance quantity. + + + + + Identifies the unit of measure for the distance value. + + + + + + + Identifies the collection of units of measure that can be associated with a distance value. + + + + + + + + + Information describing email notifications that will be sent in relation to events that occur during package movement + + + + + A message that will be included in the email notifications + + + + + Information describing the destination of the email, format of the email and events to be notified on + + + + + + + + + + + + + + + The format of the email + + + + + + + + + + + + Identifies the relationship this email recipient has to the shipment. + + + + + The email address to send the notification to + + + + + The types of email notifications being requested for this recipient. + + + + + The format of the email notification. + + + + + The language/locale to be used in this email notification. + + + + + + + + + + + + + + + CM = centimeters, IN = inches + + + + + + + + + Identifies the representation of human-readable text. + + + + + Two-letter code for language (e.g. EN, FR, etc.) + + + + + Two-letter code for the region (e.g. us, ca, etc..). + + + + + + + The descriptive data regarding the result of the submitted transaction. + + + + + The severity of this notification. This can indicate success or failure or some other information about the request. The values that can be returned are SUCCESS - Your transaction succeeded with no other applicable information. NOTE - Additional information that may be of interest to you about your transaction. WARNING - Additional information that you need to know about your transaction that you may need to take action on. ERROR - Information about an error that occurred while processing your transaction. FAILURE - FedEx was unable to process your transaction at this time due to a system failure. Please try again later + + + + + Indicates the source of this notification. Combined with the Code it uniquely identifies this notification + + + + + A code that represents this notification. Combined with the Source it uniquely identifies this notification. + + + + + Human-readable text that explains this notification. + + + + + The translated message. The language and locale specified in the ClientDetail. Localization are used to determine the representation. Currently only supported in a TrackReply. + + + + + A collection of name/value pairs that provide specific data to help the client determine the nature of an error (or warning, etc.) witout having to parse the message string. + + + + + + + + + Identifies the type of data contained in Value (e.g. SERVICE_TYPE, PACKAGE_SEQUENCE, etc..). + + + + + The value of the parameter (e.g. PRIORITY_OVERNIGHT, 2, etc..). + + + + + + + Identifies the set of severity values for a Notification. + + + + + + + + + + + + + + + + + + + + Identification for a FedEx operating company (transportation and non-transportation). + + + + + + + + The enumerated packaging type used for this package. + + + + + + + + + + + + + + Tracking number and additional shipment data used to identify a unique shipment for proof of delivery. + + + + + FedEx assigned identifier for a package/shipment. + + + + + The date the package was shipped. + + + + + If the account number used to ship the package is provided in the request the shipper and recipient information is included on the letter or fax. + + + + + FedEx operating company that delivered the package. + + + + + Only country is used for elimination of duplicate tracking numbers. + + + + + + + + + + + + + + The service type of the package/shipment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + FedEx Signature Proof Of Delivery Fax reply. + + + + + This contains the severity type of the most severe Notification in the Notifications array. + + + + + Information about the request/reply such was the transaction successful or not, and any additional information relevant to the request and/or reply. There may be multiple Notifications in a reply. + + + + + Contains the CustomerTransactionDetail that is echoed back to the caller for matching requests and replies and a Localization element for defining the language/translation used in the reply data. + + + + + Contains the version of the reply being used. + + + + + Confirmation of fax transmission. + + + + + + + FedEx Signature Proof Of Delivery Fax request. + + + + + Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services). + + + + + Descriptive data identifying the client submitting the transaction. + + + + + Contains a free form field that is echoed back in the reply to match requests with replies and data that governs the data payload language/translations. + + + + + The version of the request being used. + + + + + Tracking number and additional shipment data used to identify a unique shipment for proof of delivery. + + + + + Additional customer-supplied text to be added to the body of the letter. + + + + + Contact and address information about the person requesting the fax to be sent. + + + + + Contact and address information, including the fax number, about the person to receive the fax. + + + + + + + Identifies the set of SPOD image types. + + + + + + + + FedEx Signature Proof Of Delivery Letter reply. + + + + + This contains the severity type of the most severe Notification in the Notifications array. + + + + + Information about the request/reply such was the transaction successful or not, and any additional information relevant to the request and/or reply. There may be multiple Notifications in a reply. + + + + + Contains the CustomerTransactionDetail that is echoed back to the caller for matching requests and replies and a Localization element for defining the language/translation used in the reply data. + + + + + Image of letter encoded in Base64 format. + + + + + Image of letter encoded in Base64 format. + + + + + + + FedEx Signature Proof Of Delivery Letter request. + + + + + Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services). + + + + + Descriptive data identifying the client submitting the transaction. + + + + + Contains a free form field that is echoed back in the reply to match requests with replies and data that governs the data payload language/translations. + + + + + The version of the request being used. + + + + + Tracking number and additional shipment data used to identify a unique shipment for proof of delivery. + + + + + Additional customer-supplied text to be added to the body of the letter. + + + + + Identifies the set of SPOD image types. + + + + + If provided this information will be print on the letter. + + + + + + + Each instance of this data type represents a barcode whose content must be represented as ASCII text (i.e. not binary data). + + + + + The kind of barcode data in this instance. + + + + + The data content of this instance. + + + + + + + + + + + + + + + + + The delivery location at the delivered to address. + + + + + + + + + + + + + + + + Detailed tracking information about a particular package. + + + + + To report soft error on an individual track detail. + + + + + The FedEx package identifier. + + + + + + When duplicate tracking numbers exist this data is returned with summary information for each of the duplicates. The summary information is used to determine which of the duplicates the intended tracking number is. This identifier is used on a subsequent track request to retrieve the tracking data for the desired tracking number. + + + + + A code that identifies this type of status. This is the most recent status. + + + + + A human-readable description of this status. + + + + + Used to report the status of a piece of a multiple piece shipment which is no longer traveling with the rest of the packages in the shipment or has not been accounted for. + + + + + Used to convey information such as. 1. FedEx has received information about a package but has not yet taken possession of it. 2. FedEx has handed the package off to a third party for final delivery. 3. The package delivery has been cancelled + + + + + Identifies a FedEx operating company (transportation). + + + + + Identifies operating transportation company that is the specific to the carrier code. + + + + + Specifies the FXO production centre contact and address. + + + + + Other related identifiers for this package such as reference numbers. + + + + + Retained for legacy compatibility only. User/screen friendly description of the Service type (e.g. Priority Overnight). + + + + + Strict representation of the Service type (e.g. PRIORITY_OVERNIGHT). + + + + + The weight of this package. + + + + + Physical dimensions of the package. + + + + + The dimensional weight of the package. + + + + + The weight of the entire shipment. + + + + + Retained for legacy compatibility only. + + + + + Strict representation of the Packaging type (e.g. FEDEX_BOX, YOUR_PACKAGING). + + + + + The sequence number of this package in a shipment. This would be 2 if it was package number 2 of 4. + + + + + The number of packages in this shipment. + + + + + + + The address information for the shipper. + + + + + The address of the FedEx pickup location/facility. + + + + + Estimated package pickup time for shipments that haven't been picked up. + + + + + Time package was shipped/tendered over to FedEx. Time portion will be populated if available, otherwise will be set to midnight. + + + + + The distance from the origin to the destination. Returned for Custom Critical shipments. + + + + + Total distance package still has to travel. Returned for Custom Critical shipments. + + + + + The address this package is to be (or has been) delivered. + + + + + The address of the FedEx delivery location/facility. + + + + + Projected package delivery time based on ship time stamp, service and destination. Not populated if delivery has already occurred. + + + + + The time the package was actually delivered. + + + + + Actual address where package was delivered. Differs from destinationAddress, which indicates where the package was to be delivered; This field tells where delivery actually occurred (next door, at station, etc.) + + + + + Identifies the method of office order delivery. + + + + + Strict text indicating the delivery location at the delivered to address. + + + + + User/screen friendly representation of the DeliveryLocationType (delivery location at the delivered to address). Can be returned in localized text. + + + + + This is either the name of the person that signed for the package or "Signature not requested" or "Signature on file". + + + + + True if signed for by signature image is available. + + + + + The types of email notifications that are available for the package. + + + + + Returned for cargo shipments only when they are currently split across vehicles. + + + + + Indicates redirection eligibility as determined by tracking service, subject to refinement/override by redirect-to-hold service. + + + + + Event information for a tracking number. + + + + + + + FedEx scanning information about a package. + + + + + The time this event occurred. + + + + + Carrier's scan code. Pairs with EventDescription. + + + + + Literal description that pairs with the EventType. + + + + + Further defines the Scan Type code's specific type (e.g., DEX08 business closed). Pairs with StatusExceptionDescription. + + + + + Literal description that pairs with the StatusExceptionCode. + + + + + Address information of the station that is responsible for the scan. + + + + + Indicates where the arrival actually occurred. + + + + + + + The type of track to be performed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + FedEx assigned identifier for a package/shipment. + + + + + When duplicate tracking numbers exist this data is returned with summary information for each of the duplicates. The summary information is used to determine which of the duplicates the intended tracking number is. This identifier is used on a subsequent track request to retrieve the tracking data for the desired tracking number. + + + + + Identification of a FedEx operating company (transportation). + + + + + The date the package was shipped (tendered to FedEx). + + + + + The destination address of this package. Only city, state/province, and country are returned. + + + + + Options available for a tracking notification recipient. + + + + + + + Options available for a tracking notification recipient. + + + + + The types of email notifications available for this recipient. + + + + + + + FedEx Track Notification reply. + + + + + This contains the severity type of the most severe Notification in the Notifications array. + + + + + Information about the request/reply such was the transaction successful or not, and any additional information relevant to the request and/or reply. There may be multiple Notifications in a reply. + + + + + Contains the CustomerTransactionDetail that is echoed back to the caller for matching requests and replies and a Localization element for defining the language/translation used in the reply data. + + + + + Contains the version of the reply being used. + + + + + True if duplicate packages (more than one package with the same tracking number) have been found, the packages array contains information about each duplicate. Use this information to determine which of the tracking numbers is the one you need and resend your request using the tracking number and TrackingNumberUniqueIdentifier for that package. + + + + + True if additional packages remain to be retrieved. + + + + + Value that must be passed in a TrackNotification request to retrieve the next set of packages (when MoreDataAvailable = true). + + + + + Information about the notifications that are available for this tracking number. If there are duplicates the ship date and destination address information is returned for determining which TrackingNumberUniqueIdentifier to use on a subsequent request. + + + + + + + FedEx Track Notification request. + + + + + Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services). + + + + + Descriptive data identifying the client submitting the transaction. + + + + + Contains a free form field that is echoed back in the reply to match requests with replies and data that governs the data payload language/translations + + + + + Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply). + + + + + The tracking number to which the notifications will be triggered from. + + + + + Indicates whether to return tracking information for all associated packages. + + + + + When the MoreDataAvailable field is true in a TrackNotificationReply the PagingToken must be sent in the subsequent TrackNotificationRequest to retrieve the next page of data. + + + + + Use this field when your original request informs you that there are duplicates of this tracking number. If you get duplicates you will also receive some information about each of the duplicate tracking numbers to enable you to chose one and resend that number along with the TrackingNumberUniqueId to get notifications for that tracking number. + + + + + To narrow the search to a period in time the ShipDateRangeBegin and ShipDateRangeEnd can be used to help eliminate duplicates. + + + + + To narrow the search to a period in time the ShipDateRangeBegin and ShipDateRangeEnd can be used to help eliminate duplicates. + + + + + Included in the email notification identifying the requester of this notification. + + + + + Included in the email notification identifying the requester of this notification. + + + + + Who to send the email notifications to and for which events. The notificationRecipientType and NotifyOnShipment fields are not used in this request. + + + + + + + The type and value of the package identifier that is to be used to retrieve the tracking information for a package. + + + + + The value to be used to retrieve tracking information for a package. + + + + + The type of the Value to be used to retrieve tracking information for a package (e.g. SHIPPER_REFERENCE, PURCHASE_ORDER, TRACKING_NUMBER_OR_DOORTAG, etc..) . + + + + + + + Used to report the status of a piece of a multiple piece shipment which is no longer traveling with the rest of the packages in the shipment or has not been accounted for. + + + + + An identifier for this type of status. + + + + + A human-readable description of this status. + + + + + + + The descriptive data returned from a FedEx package tracking request. + + + + + This contains the severity type of the most severe Notification in the Notifications array. + + + + + Information about the request/reply such was the transaction successful or not, and any additional information relevant to the request and/or reply. There may be multiple Notifications in a reply. + + + + + Contains the CustomerTransactionDetail that is echoed back to the caller for matching requests and replies and a Localization element for defining the language/translation used in the reply data. + + + + + Contains the version of the reply being used. + + + + + True if duplicate packages (more than one package with the same tracking number) have been found, and only limited data will be provided for each one. + + + + + True if additional packages remain to be retrieved. + + + + + Value that must be passed in a TrackNotification request to retrieve the next set of packages (when MoreDataAvailable = true). + + + + + Contains detailed tracking information for the requested packages(s). + + + + + + + The descriptive data sent by a client to track a FedEx package. + + + + + Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services). + + + + + Descriptive data identifying the client submitting the transaction. + + + + + Contains a free form field that is echoed back in the reply to match requests with replies and data that governs the data payload language/translations. + + + + + The version of the request being used. + + + + + The FedEx operating company (transportation) used for this package's delivery. + + + + + Identifies operating transportation company that is the specific to the carrier code. + + + + + The type and value of the package identifier that is to be used to retrieve the tracking information for a package or group of packages. + + + + + Used to distinguish duplicate FedEx tracking numbers. + + + + + To narrow the search to a period in time the ShipDateRangeBegin and ShipDateRangeEnd can be used to help eliminate duplicates. + + + + + To narrow the search to a period in time the ShipDateRangeBegin and ShipDateRangeEnd can be used to help eliminate duplicates. + + + + + For tracking by references information either the account number or destination postal code and country must be provided. + + + + + For tracking by references information either the account number or destination postal code and country must be provided. + + + + + If false the reply will contain summary/profile data including current status. If true the reply contains profile + detailed scan activity for each package. + + + + + When the MoreData field = true in a TrackReply the PagingToken must be sent in the subsequent TrackRequest to retrieve the next page of data. + + + + + + + + + + + + + Used when a cargo shipment is split across vehicles. This is used to give the status of each part of the shipment. + + + + + The number of pieces in this part. + + + + + The date and time this status began. + + + + + A code that identifies this type of status. + + + + + A human-readable description of this status. + + + + + + + Descriptive data that governs data payload language/translations. The TransactionDetail from the request is echoed back to the caller in the corresponding reply. + + + + + Free form text to be echoed back in the reply. Used to match requests and replies. + + + + + Governs data payload language/translations (contrasted with ClientDetail.localization, which governs Notification.localizedMessage language selection). + + + + + + + The descriptive data for the heaviness of an object. + + + + + Identifies the unit of measure associated with a weight value. + + + + + Identifies the weight value of a package/shipment. + + + + + + + Identifies the collection of units of measure that can be associated with a weight value. + + + + + + + + + Used in authentication of the sender's identity. + + + + + Credential used to authenticate a specific software application. This value is provided by FedEx after registration. + + + + + + + Two part authentication string used for the sender's identity + + + + + Identifying part of authentication credential. This value is provided by FedEx after registration + + + + + Secret part of authentication key. This value is provided by FedEx after registration. + + + + + + + Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply). + + + + + Identifies a system or sub-system which performs an operation. + + + + + Identifies the service business level. + + + + + Identifies the service interface level. + + + + + Identifies the service code level. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php index e981b1cc3c..ce7da0159c 100644 --- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php +++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php @@ -150,10 +150,10 @@ protected function _prepareForm() public function getContinueUrl() { return $this->getUrl('*/*/*', array( - '_current' => true, - 'type' => '{{type}}', - 'package' => '{{mpackage}}', - 'theme' => '{{mtheme}}' + '_current' => true, + 'type' => '{{type}}', + 'package' => '{{package}}', + 'theme' => '{{theme}}' )); } diff --git a/app/code/core/Mage/Widget/Model/Widget/Instance.php b/app/code/core/Mage/Widget/Model/Widget/Instance.php index 7140edb55b..c85b0c7799 100644 --- a/app/code/core/Mage/Widget/Model/Widget/Instance.php +++ b/app/code/core/Mage/Widget/Model/Widget/Instance.php @@ -236,7 +236,6 @@ protected function _prepareType() public function setPackageTheme($packageTheme) { $this->setData('package_theme', $packageTheme); - $this->_preparePackageTheme(); return $this; } @@ -248,20 +247,18 @@ public function setPackageTheme($packageTheme) */ public function getPackageTheme() { - $this->_preparePackageTheme(); return $this->_getData('package_theme'); } /** * Replace '_' to '/', if was set from request(GET request) * + * @deprecated after 1.6.1.0-alpha1 + * * @return Mage_Widget_Model_Widget_Instance */ protected function _preparePackageTheme() { - if (strpos($this->_getData('package_theme'), '_') >= 0) { - $this->setData('package_theme', str_replace('_', '/', $this->_getData('package_theme'))); - } return $this; } diff --git a/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php b/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php index 7392750f79..f77bd1873e 100644 --- a/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php +++ b/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php @@ -68,19 +68,22 @@ protected function _initWidgetInstance() { $this->_title($this->__('CMS'))->_title($this->__('Widgets')); + /** @var $widgetInstance Mage_Widget_Model_Widget_Instance */ $widgetInstance = Mage::getModel('widget/widget_instance'); + $instanceId = $this->getRequest()->getParam('instance_id', null); - $type = $this->getRequest()->getParam('type', null); - $packageTheme = $this->getRequest()->getParam('package', null) . '/' - . $this->getRequest()->getParam('theme', null); - $packageTheme = $packageTheme === '/' ? null : $packageTheme; + $type = $this->getRequest()->getParam('type', null); + $package = $this->getRequest()->getParam('package', null); + $theme = $this->getRequest()->getParam('theme', null); + if ($instanceId) { $widgetInstance->load($instanceId); if (!$widgetInstance->getId()) { - $this->_getSession()->addError(Mage::helper('widget')->__('Wrong wigdet instance specified.')); + $this->_getSession()->addError(Mage::helper('widget')->__('Wrong widget instance specified.')); return false; } } else { + $packageTheme = $package . '/' . $theme == '/' ? null : $package . '/' . $theme; $widgetInstance->setType($type) ->setPackageTheme($packageTheme); } 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..df9965b8ed 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) @@ -198,8 +199,12 @@ protected function _addCatalogProduct(Mage_Catalog_Model_Product $product, $qty public function getItemCollection() { if (is_null($this->_itemCollection)) { + /** @var $currentWebsiteOnly boolean */ + $currentWebsiteOnly = !Mage::app()->getStore()->isAdmin(); $this->_itemCollection = Mage::getResourceModel('wishlist/item_collection') - ->addWishlistFilter($this); + ->addWishlistFilter($this) + ->addStoreFilter($this->getSharedStoreIds($currentWebsiteOnly)) + ->setVisibilityFilter(); } return $this->_itemCollection; @@ -381,12 +386,13 @@ 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 { $_storeIds = array(); - foreach (Mage::app()->getStores() as $store) { + $stores = Mage::app()->getStores(); + foreach ($stores as $store) { $_storeIds[] = $store->getId(); } $this->_storeIds = $_storeIds; @@ -403,7 +409,7 @@ public function getSharedStoreIds($current = true) */ public function setSharedStoreIds($storeIds) { - $this->_storeIds = $storeIds; + $this->_storeIds = (array) $storeIds; return $this; } @@ -439,7 +445,7 @@ public function setStore($store) */ public function getItemsCount() { - return $this->_getResource()->fetchItemsCount($this); + return $this->getItemCollection()->getSize(); } /** @@ -509,7 +515,18 @@ public function updateItem($itemId, $buyRequest, $params = null) $buyRequest = Mage::helper('catalog/product')->addParamsToBuyRequest($buyRequest, $params); $product->setWishlistStoreId($item->getStoreId()); - $resultItem = $this->addNewItem($product, $buyRequest, true); + $items = $this->getItemCollection(); + $isForceSetQuantity = true; + foreach ($items as $_item) { + /* @var $_item Mage_Wishlist_Model_Item */ + if ($_item->getProductId() == $product->getId() + && $_item->representProduct($product) + && $_item->getId() != $item->getId()) { + // We do not add new wishlist item, but updating the existing one + $isForceSetQuantity = false; + } + } + $resultItem = $this->addNewItem($product, $buyRequest, $isForceSetQuantity); /** * Error message */ @@ -523,18 +540,9 @@ public function updateItem($itemId, $buyRequest, $params = null) } $item->isDeleted(true); $this->setDataChanges(true); - - $items = $this->getItemCollection(); - foreach ($items as $_item) { - if ($_item->getProductId() == $productId && $_item->getId() != $resultItem->getId()) { - if ($resultItem->compareOptions($resultItem->getOptions(), $_item->getOptions())) { - $resultItem->setQty($resultItem->getQty() + $_item->getQty()); - $_item->isDeleted(true); - } - } - } } else { - $resultItem->setQty($buyRequest->getQty()*1); + $resultItem->setQty($buyRequest->getQty() * 1); + $resultItem->setOrigData('qty', 0); } } else { Mage::throwException(Mage::helper('checkout')->__('The product does not exist.')); diff --git a/app/code/core/Mage/Wishlist/controllers/IndexController.php b/app/code/core/Mage/Wishlist/controllers/IndexController.php index 9bcc4db7c9..db76caa080 100644 --- a/app/code/core/Mage/Wishlist/controllers/IndexController.php +++ b/app/code/core/Mage/Wishlist/controllers/IndexController.php @@ -200,7 +200,6 @@ public function addAction() $session->addError($this->__('An error occurred while adding item to wishlist: %s', $e->getMessage())); } catch (Exception $e) { - mage::log($e->getMessage()); $session->addError($this->__('An error occurred while adding item to wishlist.')); } @@ -602,7 +601,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 +614,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/code/core/Mage/XmlConnect/Block/Adminhtml/History.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/History.php index 08a88462f3..eb4169af97 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/History.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/History.php @@ -27,9 +27,9 @@ /** * XmlConnect application submission history grid * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Adminhtml_History extends Mage_Adminhtml_Block_Widget_Grid_Container { diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/History/Grid.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/History/Grid.php index 4a159a7dc5..79fb163932 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/History/Grid.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/History/Grid.php @@ -27,9 +27,9 @@ /** * XmlConnect application history grid * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Adminhtml_History_Grid extends Mage_Adminhtml_Block_Widget_Grid { diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile.php index 04ceb529da..310acf8d36 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile.php @@ -27,9 +27,9 @@ /** * XmlConnect application grid * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Adminhtml_Mobile extends Mage_Adminhtml_Block_Widget_Grid_Container { @@ -40,7 +40,12 @@ public function __construct() { $this->_controller = 'adminhtml_mobile'; $this->_blockGroup = 'xmlconnect'; - $this->_headerText = $this->__('Manage Apps'); + $xmlconnectVersion = Mage::getConfig()->getNode( + Mage_XmlConnect_Model_Application::XML_PATH_MODULE_VERSION + ); + $this->_headerText = $this->__('Manage Apps') + . ' ' + . $this->__('ver. %s', $xmlconnectVersion); $this->_addButtonLabel = $this->__('Add App'); parent::__construct(); diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit.php index 02bd7a268b..2144e9bab0 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit extends Mage_Adminhtml_Block_Widget_Form_Container + +/** + * Application edit block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit + extends Mage_Adminhtml_Block_Widget_Form_Container { /** * Setting app action buttons for application @@ -119,7 +128,7 @@ public function getHeaderText() } if (isset($app) && $app->getId()) { - return $this->__('Edit App "%s"', $this->htmlEscape($app->getName())); + return $this->__('Edit App "%s"', $this->escapeHtml($app->getName())); } else { return $this->__('New App'); } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Form.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Form.php index a9a93f2983..0117686836 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Form.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * Application Form block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Form extends Mage_Adminhtml_Block_Widget_Form { /** @@ -33,9 +41,10 @@ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Form extends Mage_Adminhtml_Bl */ protected function _prepareForm() { - $form = new Varien_Data_Form(array('id' => 'edit_form', + $form = new Varien_Data_Form(array('id' => 'edit_form', 'action' => Mage::getSingleton('adminhtml/session')->getNewApplication() - ? $this->getUrl('*/mobile/edit', array('_current' => true)) : $this->getUrl('*/mobile/save'), + ? $this->getUrl('*/mobile/edit', array('_current' => true)) + : $this->getUrl('*/mobile/save'), 'method' => 'post', 'enctype' => 'multipart/form-data' )); diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Submission.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Submission.php index 3ac44d0e0f..6c1af9ac6e 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Submission.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Submission.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Submission extends Mage_Adminhtml_Block_Widget_Tabs + +/** + * Application Submission block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Submission + extends Mage_Adminhtml_Block_Widget_Tabs { /** * Constructor diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Cache.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Cache.php index a351fd658b..fd5ed70bce 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Cache.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Cache.php @@ -31,7 +31,8 @@ * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Cache extends Mage_Adminhtml_Block_Widget_Form +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Cache + extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface { /** diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Content.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Content.php index 031b42b80f..57e97bb4e6 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Content.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Content.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * Tab for Content Management + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Content extends Mage_XmlConnect_Block_Adminhtml_Mobile_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface @@ -47,10 +55,10 @@ public function __construct() */ protected function _addPage($fieldset, $fieldPrefix) { - $el = $fieldset->addField($fieldPrefix, 'page', array( + $element = $fieldset->addField($fieldPrefix, 'page', array( 'name' => $fieldPrefix, )); - $el->initFields(array( + $element->initFields(array( 'name' => $fieldPrefix, 'values' => $this->_pages, )); diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design.php index 39e6cbbab7..5ef12f4e69 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Design extends Mage_Adminhtml_Block_Template + +/** + * Tab for Design Management + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Design + extends Mage_Adminhtml_Block_Template implements Mage_Adminhtml_Block_Widget_Tab_Interface { /** diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion.php index 80f3db6d00..5045b69c57 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Design_Accordion extends Mage_Adminhtml_Block_Widget_Accordion + +/** + * Tab design accordion xml renderer + * + * @category Mage + * @package Mage_Xmlconnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Design_Accordion + extends Mage_Adminhtml_Block_Widget_Accordion { /** * Add accordion item by specified block diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion/Images.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion/Images.php index 7ac9589ea0..38f366cc6e 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion/Images.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion/Images.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * Tab design Accordion Images xml renderer + * + * @category Mage + * @package Mage_Xmlconnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Design_Accordion_Images extends Mage_XmlConnect_Block_Adminhtml_Mobile_Widget_Form { diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion/Tabs.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion/Tabs.php index ca8cc9e8ca..d62626d6fb 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion/Tabs.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Accordion/Tabs.php @@ -25,7 +25,7 @@ */ /** - * Device tabs accourdion block + * Device tabs accordion block * * @category Mage * @package Mage_XmlConnect diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Preview.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Preview.php index 876a80553a..527edf358a 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Preview.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Preview.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Design_Preview extends Mage_Adminhtml_Block_Template + +/** + * Tab design preview xml renderer + * + * @category Mage + * @package Mage_Xmlconnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Design_Preview + extends Mage_Adminhtml_Block_Template { /** * Set preview template @@ -36,7 +45,9 @@ public function __construct() if (array_key_exists($device, Mage::helper('xmlconnect')->getSupportedDevices())) { $template = 'xmlconnect/edit/tab/design/preview_' . strtolower($device) . '.phtml'; } else { - Mage::throwException($this->__('Device doesn\'t recognized. Unable to load a template.')); + Mage::throwException( + $this->__('Device doesn\'t recognized. Unable to load a template.') + ); } $this->setTemplate($template); @@ -58,7 +69,6 @@ public function getPreviewActionUrl($page = 'home') } else { $params = array('devtype' => $model->getType()); } - } return $this->getUrl('*/*/preview' . $page, $params); } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Themes.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Themes.php index a10067cab2..4307b30df1 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Themes.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Themes.php @@ -34,8 +34,7 @@ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Design_Themes extends Mage_Adminhtml_Block_Template { /** - * Set themes template - * Set color fieldsets + * Set themes template and color fieldsets */ public function __construct() { diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Flurryanalytics.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Flurryanalytics.php index 2216fb75c9..2a4124638e 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Flurryanalytics.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Flurryanalytics.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * Tab for Flurry Analytics Management + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Flurryanalytics extends Mage_XmlConnect_Block_Adminhtml_Mobile_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface @@ -30,7 +38,7 @@ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Flurryanalytics protected $_pages; /** - * Construnctor + * Constructor * Setting view options */ public function __construct() @@ -74,7 +82,7 @@ protected function _prepareForm() Mage::getStoreConfig('xmlconnect/flurry_analytics/statistics_url') ); - $flurryLink = $fieldset->addField('flurry_analytics_link', 'link', array( + $fieldset->addField('flurry_analytics_link', 'link', array( 'title' => $this->__('Flurry Analytics Site'), 'label' => $this->__('Flurry Analytics Site'), 'value' => $flurryAnalyticsUrl, diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/General.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/General.php index 8de396d899..0b325ccf95 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/General.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/General.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_General extends Mage_Adminhtml_Block_Widget_Form + +/** + * Tab for General Info Management + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_General + extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface { /** @@ -57,7 +66,7 @@ protected function _prepareForm() )); if ($model->getId()) { - $field = $fieldset->addField('code', 'label', array( + $fieldset->addField('code', 'label', array( 'label' => $this->__('App Code'), 'title' => $this->__('App Code'), 'value' => $model->getCode(), diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Notification.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Notification.php index 6c14ba4109..e339b4065b 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Notification.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Notification.php @@ -23,12 +23,20 @@ * @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) */ + +/** + * Tab for Notifications Management + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Notification extends Mage_XmlConnect_Block_Adminhtml_Mobile_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface { /** - * Construnctor + * Constructor * Setting view options */ public function __construct() @@ -179,7 +187,7 @@ public function getTabTitle() public function canShowTab() { return (bool) !Mage::getSingleton('adminhtml/session')->getNewApplication() - && Mage::helper('xmlconnect')->getDeviceType() == Mage_XmlConnect_Helper_Data::DEVICE_TYPE_IPHONE; + && Mage::helper('xmlconnect')->isNotificationsAllowed(); } /** diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Payment.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Payment.php index e61c124b6e..742d212785 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Payment.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Payment.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * Tab for Payments Management + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Payment extends Mage_XmlConnect_Block_Adminhtml_Mobile_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface @@ -30,7 +38,7 @@ class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Payment protected $_pages; /** - * Construnctor + * Constructor * Setting view options */ public function __construct() @@ -77,32 +85,33 @@ protected function _prepareForm() /** * PayPal MEP management */ - $isExpressCheckoutAvailable = Mage::getModel('xmlconnect/payment_method_paypal_mep') + $fieldsetPaypal = $form->addFieldset('paypal_mep_checkout', array( + 'legend' => $this->__('PayPal Mobile Embedded Payment (MEP)') + )); + + $paypalMepIsAvailable = Mage::getModel('xmlconnect/payment_method_paypal_mep') ->isAvailable(null); $paypalActive = 0; if (isset($data['conf[native][paypal][isActive]'])) { - $paypalActive = (int)($data['conf[native][paypal][isActive]'] && $isExpressCheckoutAvailable); + $paypalActive = (int)($data['conf[native][paypal][isActive]'] && $paypalMepIsAvailable); } - $fieldsetPaypal = $form->addFieldset('paypal_mep_checkout', array( - 'legend' => $this->__('PayPal Mobile Embedded Payment (MEP)') - )); - - $activateMepMethodNote = $this->__('To activate PayPal MEP payment method activate Express checkout first. '); $paypalConfigurationUrl = $this->escapeHtml( $this->getUrl('adminhtml/system_config/edit', array('section' => 'paypal')) ); + $activateMepMethodNote = $this->__('To activate PayPal MEP payment method activate Express checkout first. '); + $businessAccountNote = $this->__('MEP is PayPal\'s native checkout experience for the iPhone. You can choose to use MEP alongside standard checkout, or use it as your only checkout method for Magento mobile. PayPal MEP requires a PayPal business account', $paypalConfigurationUrl); $paypalActiveField = $fieldsetPaypal->addField('conf/native/paypal/isActive', 'select', array( 'label' => $this->__('Activate PayPal Checkout'), 'name' => 'conf[native][paypal][isActive]', - 'note' => (!$isExpressCheckoutAvailable ? $activateMepMethodNote : $businessAccountNote), + 'note' => (!$paypalMepIsAvailable ? $activateMepMethodNote : $businessAccountNote), 'values' => $yesNoValues, 'value' => $paypalActive, - 'disabled' => !$isExpressCheckoutAvailable + 'disabled' => !$paypalMepIsAvailable )); if (isset($data['conf[special][merchantLabel]'])) { @@ -184,6 +193,41 @@ protected function _prepareForm() ); break; case Mage_XmlConnect_Helper_Data::DEVICE_TYPE_ANDROID: + /** + * PayPal MECL management + */ + if (Mage::app()->isSingleStoreMode() || Mage::helper('xmlconnect')->getApplication()->getId()) { + $paypalMeclIsAvailable = Mage::getModel('xmlconnect/payment_method_paypal_mecl') + ->isAvailable(); + $activateMeclMethodNote = $this->__('You need to enable PayPal Express Checkout first from the Payment configuration before enabling PayPal MECL.'); + } else { + $paypalMeclIsAvailable = false; + $activateMeclMethodNote = $this->__('Please create and save an application first.'); + } + + $fieldsetMecl = $form->addFieldset('paypal_mecl_checkout', array( + 'legend' => $this->__('PayPal Mobile Express Checkout Library (MECL)') + )); + + $meclAccountNote = $this->__('PayPal MECL is the mobile version of PayPal\'s Express Checkout service. You can choose to use MECL alongside standard checkout, or use it as your only checkout method for Magento Mobile.'); + + $paypalMeclActive = 0; + if (isset($data['config_data[payment][paypalmecl_is_active]'])) { + $paypalMeclActive = (int) $data['config_data[payment][paypalmecl_is_active]']; + } + + $fieldsetMecl->addField('config_data/paypalmecl_is_active', 'select', array( + 'label' => $this->__('Activate PayPal MECL'), + 'name' => 'config_data[payment:paypalmecl_is_active]', + 'note' => (!$paypalMeclIsAvailable ? $activateMeclMethodNote : $meclAccountNote), + 'values' => $yesNoValues, + 'value' => $paypalMeclActive, + 'disabled' => !$paypalMeclIsAvailable + )); + + /** + * PayPal MEP management + */ $fieldsetPaypal = $form->addFieldset('paypal_mep_checkout', array( 'legend' => $this->__('PayPal Mobile Embedded Payment (MEP)') )); diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Settings.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Settings.php index 7b450ae565..faac69b2e4 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Settings.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Settings.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Settings extends Mage_Adminhtml_Block_Widget_Form + +/** + * Tab for Settings Management + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Settings + extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface { protected function _prepareLayout() @@ -34,8 +43,9 @@ protected function _prepareLayout() 'label' => Mage::helper('catalog')->__('Continue'), 'onclick' => "if (editForm.submit()) { return false }", 'class' => 'save' - )) - ); + ) + ) + ); return parent::_prepareLayout(); } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Submission/History.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Submission/History.php index 9119471835..c73fc34e76 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Submission/History.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Submission/History.php @@ -27,11 +27,12 @@ /** * XmlConnect application history grid * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Submission_History extends Mage_Adminhtml_Block_Widget_Grid +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Submission_History + extends Mage_Adminhtml_Block_Widget_Grid implements Mage_Adminhtml_Block_Widget_Tab_Interface { /** @@ -92,8 +93,8 @@ public function isHidden() } /** - * Initialize history colelction - * Set aaplication filter + * Initialize history collection + * Set application filter * * @return Mage_Adminhtml_Block_Widget_Grid */ diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tabs.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tabs.php index 3d9042b07f..7cfc88b7ba 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tabs.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tabs.php @@ -23,13 +23,20 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs + +/** + * Application Tabs block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tabs + extends Mage_Adminhtml_Block_Widget_Tabs { /** * Constructor - * * Setting grid_id, DOM destination element id, Title - * */ public function __construct() { @@ -49,7 +56,9 @@ protected function _prepareLayout() if (Mage::getSingleton('adminhtml/session')->getNewApplication()) { $this->addTab('set', array( 'label' => $this->__('Settings'), - 'content' => $this->getLayout()->createBlock('xmlconnect/adminhtml_mobile_edit_tab_settings')->toHtml(), + 'content' => $this->getLayout() + ->createBlock('xmlconnect/adminhtml_mobile_edit_tab_settings') + ->toHtml(), 'active' => true )); } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Addrow.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Addrow.php index 02dae6f2a5..67cabb2c70 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Addrow.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Addrow.php @@ -24,7 +24,15 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Addrow extends Varien_Data_Form_Element_Button +/** + * Xmlconnect Add row form element + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Addrow + extends Varien_Data_Form_Element_Button { /** * Render Element Html @@ -33,10 +41,17 @@ class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Addrow extends Varien_ */ public function getElementHtml() { - $html = $this->getBeforeElementHtml() . ''.$this->getAfterElementHtml(); + . ' >' + . $this->getEscapedValue() + . '' + . $this->getAfterElementHtml(); return $html; } @@ -52,25 +67,27 @@ public function getBeforeElementHtml() /** * Return label html code - * + * * @param string $idSuffix * @return string */ public function getLabelHtml($idSuffix = '') { - if (!is_null($this->getLabel())) { - $html = ''; + if ($this->getLabel() !== null) { + $html = ''; } else { $html = ''; } return $html; } - + /** * Overriding toHtml parent method * Adding addrow Block to element renderer - * + * * @return string */ public function toHtml() diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Color.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Color.php index 060d0153b6..b4e7472c54 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Color.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Color.php @@ -24,11 +24,19 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Color extends Varien_Data_Form_Element_Text +/** + * Xmlconnect color form element + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Color + extends Varien_Data_Form_Element_Text { /** * Return html code for current block - * + * * @return mixed|string */ public function getHtml() diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Country.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Country.php index b0c8842e42..75143b51d8 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Country.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Country.php @@ -27,11 +27,12 @@ /** * XmlConnect Country selector form element * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Country extends Varien_Data_Form_Element_Checkboxes +class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Country + extends Varien_Data_Form_Element_Checkboxes { /** * Flag of using the border in the table's TD @@ -90,7 +91,7 @@ public function getElementHtml() $id = $this->getData('id'); $id = empty($id) ? '' : ' id="' . $id . '-table"'; $class = $this->getData('class'); - $html = "\n\n"; + $html = PHP_EOL . "
" . PHP_EOL; $zebrine = ''; $stripy = false; @@ -100,7 +101,7 @@ public function getElementHtml() $columns--; foreach ($options as $row) { - $html .= " \n "; + $html .= "" . PHP_EOL; if ($stripy) { $zebrine = empty($zebrine) ? ' class="odd"' : ''; @@ -123,11 +124,10 @@ public function getElementHtml() } } - $html .= "\n \n"; + $html .= PHP_EOL . '' . PHP_EOL; } - $html .= "
\n" - . $this->getAfterElementHtml(); + $html .= '' . PHP_EOL . $this->getAfterElementHtml(); return $html; } @@ -149,7 +149,8 @@ protected function _optionToHtml($option) $border = $this->_useBorderClass ? ' class="border"' : ''; $html = 'getHtmlAttributes() as $attribute) { - if ($value = $this->getDataUsingMethod($attribute, $option['value'])) { + $value = $this->getDataUsingMethod($attribute, $option['value']); + if ($value) { $html .= ' ' . $attribute . '="' . $value . '"'; } } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Datetime.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Datetime.php index d6d92577a8..cf421029ed 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Datetime.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Datetime.php @@ -27,13 +27,16 @@ /** * XmlConnect data selector form element * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Datetime extends Varien_Data_Form_Element_Abstract +class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Datetime + extends Varien_Data_Form_Element_Abstract { /** + * Date + * * @var Zend_Date */ protected $_value; @@ -63,7 +66,7 @@ protected function _toTimestamp($value) } return $value; } - + /** * Set date value * If Zend_Date instance is provided instead of value, other params will be ignored. @@ -156,19 +159,25 @@ public function getElementHtml() $html = sprintf( '' .' ', - $this->getName(), $this->getHtmlId(), $this->_escape($this->getValue()), $this->serialize($this->getHtmlAttributes()), - $this->getImage(), $this->getHtmlId(), 'Select Date', ($this->getDisabled() ? 'display:none;' : '') + $this->getName(), + $this->getHtmlId(), + $this->_escape($this->getValue()), + $this->serialize($this->getHtmlAttributes()), + $this->getImage(), + $this->getHtmlId(), + 'Select Date', + ($this->getDisabled() ? 'display:none;' : '') ); $outputFormat = $this->getFormat(); $outputTimeFormat = $this->getFormatT(); if (empty($outputFormat)) { - throw new Exception('Output format is not specified. Please, specify "format" key in constructor, or set it using setFormat().'); + Mage::throwException( + $this->__('Output format is not specified. Please, specify "format" key in constructor, or set it using setFormat().') + ); } $displayFormat = Varien_Date::convertZendToStrFtime($outputFormat, true, false); $displayTimeFormat = Varien_Date::convertZendToStrFtime($outputTimeFormat, false, true); - - - + $html .= sprintf(' ', - $this->getHtmlId(), $displayFormat . " " . $displayTimeFormat, - $this->getTime() ? 'true' : 'false', $this->getHtmlId() + $this->getHtmlId(), + $displayFormat . " " . $displayTimeFormat, + $this->getTime() ? 'true' : 'false', + $this->getHtmlId() ); $html .= $this->getAfterElementHtml(); diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Font.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Font.php index c3b7eb4856..ab86d400b1 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Font.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Font.php @@ -24,10 +24,18 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Font extends Varien_Data_Form_Element_Abstract +/** + * XmlConnect font form element + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Font + extends Varien_Data_Form_Element_Abstract { /** - * Constructor... + * Init font element * * @param array $attributes */ @@ -68,13 +76,13 @@ public function initFields($conf) * Add form element * * @param Varien_Data_Form_Element_Abstract $element - * @param boolean|'^'|string $after + * @param bool|string $after also can be '^' * @return Varien_Data_Form */ - public function addElement(Varien_Data_Form_Element_Abstract $element, $after=false) + public function addElement(Varien_Data_Form_Element_Abstract $element, $after = false) { $element->setId($element->getData('name')); - $element->setNoSpan(TRUE); + $element->setNoSpan(true); parent::addElement($element, $after); } @@ -85,10 +93,13 @@ public function addElement(Varien_Data_Form_Element_Abstract $element, $after=fa */ public function getElementHtml() { - $el = array(); + $elementsArray = array(); foreach ($this->getElements() as $element) { - $el[] .= $element->toHtml(); + $elementsArray[] .= $element->toHtml(); } - return $el[0] . $el[1] . '' . $el[2]; + return $elementsArray[0] + . $elementsArray[1] + . '' + . $elementsArray[2]; } } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Image.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Image.php index c00f893525..b355132b42 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Image.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Image.php @@ -24,7 +24,15 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Image extends Varien_Data_Form_Element_Image +/** + * XmlConnect image form element + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Image + extends Varien_Data_Form_Element_Image { /** * Function fetches image Url actual or default @@ -33,9 +41,8 @@ class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Image extends Varien_D */ protected function _getUrl() { - $url = false; if ($this->getValue()) { - if (strpos($this->getValue(), '://') === FALSE ) { + if (strpos($this->getValue(), '://') === false) { $url = Mage::helper('xmlconnect/image')->getFileDefaultSizeSuffixAsUrl($this->getValue()); $url = Mage::helper('xmlconnect/image')->getMediaUrl($url); } else { @@ -82,7 +89,7 @@ public function getElementHtml() $this->setClass('input-file'); $html .= '' . "\n"; + $html .= '" value="' . $this->getEscapedValue() . '" ' . $attr . '/>' . PHP_EOL; $html .= $this->getAfterElementHtml(); $html .= ''; diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Page.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Page.php index 5ad9f49ce6..cca94ca4f5 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Page.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Page.php @@ -24,10 +24,18 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Page extends Varien_Data_Form_Element_Abstract +/** + * XmlConnect page form element + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Page + extends Varien_Data_Form_Element_Abstract { /** - * Enter description here... + * Init page element * * @param array $attributes */ @@ -45,8 +53,8 @@ public function __construct($attributes=array()) public function initFields($conf) { $this->addElement(new Varien_Data_Form_Element_Text(array( - 'name' => $conf['name'] . '[label]', - 'class' => 'label onclick_text', + 'name' => $conf['name'] . '[label]', + 'class' => 'label onclick_text', ))); $this->addElement(new Varien_Data_Form_Element_Select(array( @@ -59,10 +67,10 @@ public function initFields($conf) * Add form element * * @param Varien_Data_Form_Element_Abstract $element - * @param boolean|'^'|string $after + * @param boolean|string $after also can be '^' * @return Varien_Data_Form */ - public function addElement(Varien_Data_Form_Element_Abstract $element, $after=false) + public function addElement(Varien_Data_Form_Element_Abstract $element, $after = false) { $element->setId($element->getData('name')); parent::addElement($element, $after); @@ -82,7 +90,7 @@ public function getLabelHtml($idSuffix = '') } /** - * Gettter for second part of rendered field ("selectbox" and "delete button") + * Getter for second part of rendered field ("selectbox" and "delete button") * fetching second element as * * @return string @@ -90,8 +98,10 @@ public function getLabelHtml($idSuffix = '') public function getElementHtml() { list($label, $element) = $this->getElements(); - return $element->toHtml() . '' + return $element->toHtml() + . '' . ''; + . Mage::helper('xmlconnect')->__('Delete') + . ''; } } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Tabs.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Tabs.php index fd676eeefe..e9b55f0087 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Tabs.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Tabs.php @@ -24,7 +24,15 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Tabs extends Varien_Data_Form_Element_Text +/** + * XmlConnect tabs form element + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Tabs + extends Varien_Data_Form_Element_Text { /** * Generate application tabs html @@ -43,7 +51,9 @@ public function getHtml() if (array_key_exists($device, Mage::helper('xmlconnect')->getSupportedDevices())) { $template = 'xmlconnect/form/element/app_tabs_' . strtolower($device) . '.phtml'; } else { - Mage::throwException($this->__('Device doesn\'t recognized. Unable to load a template.')); + Mage::throwException( + $this->__('Device doesn\'t recognized. Unable to load a template.') + ); } $block->setTemplate($template); diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Theme.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Theme.php index 1a1ff95af0..387a0594c4 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Theme.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Form/Element/Theme.php @@ -24,7 +24,15 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Theme extends Varien_Data_Form_Element_Text +/** + * XmlConnect theme form element + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Theme + extends Varien_Data_Form_Element_Text { /** * Generate themes (colors) html @@ -33,7 +41,8 @@ class Mage_XmlConnect_Block_Adminhtml_Mobile_Form_Element_Theme extends Varien_D */ public function getHtml() { - $blockClassName = Mage::getConfig()->getBlockClassName('xmlconnect/adminhtml_mobile_edit_tab_design_themes'); + $blockClassName = Mage::getConfig() + ->getBlockClassName('xmlconnect/adminhtml_mobile_edit_tab_design_themes'); $block = new $blockClassName; $block->setThemes($this->getThemes()); $block->setName($this->getName()); diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid.php index 4adad9e7da..f8104e89b3 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * Application grid block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_Xmlconnect_Block_Adminhtml_Mobile_Grid extends Mage_Adminhtml_Block_Widget_Grid { /** diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid/Renderer/Bool.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid/Renderer/Bool.php index 7af683e6cb..b7ad0302cf 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid/Renderer/Bool.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid/Renderer/Bool.php @@ -27,11 +27,12 @@ /** * XmlConnect status field grid renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Grid_Renderer_Bool extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Mage_XmlConnect_Block_Adminhtml_Mobile_Grid_Renderer_Bool + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { /** * Render application status image @@ -45,11 +46,15 @@ public function render(Varien_Object $row) $status = (int) $row->getData($this->getColumn()->getIndex()); $options = Mage::helper('xmlconnect')->getStatusOptions(); if ($status == Mage_XmlConnect_Model_Application::APP_STATUS_SUCCESS) { - $result = ' ' . (isset($options[$status]) ? $options[$status] : ''); + $result = ' ' + . (isset($options[$status]) ? $options[$status] : ''); } else if ($status == Mage_XmlConnect_Model_Application::APP_STATUS_INACTIVE) { - $result = ' ' . (isset($options[$status]) ? $options[$status] : ''); + $result = ' ' + . (isset($options[$status]) ? $options[$status] : ''); } return $result; } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid/Renderer/Type.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid/Renderer/Type.php index f1255ce7c6..1e4ef26887 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid/Renderer/Type.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Grid/Renderer/Type.php @@ -27,11 +27,12 @@ /** * Adminhtml catalog super product link grid checkbox renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Grid_Renderer_Type extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Mage_XmlConnect_Block_Adminhtml_Mobile_Grid_Renderer_Type + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { /** * Renders grid column diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Preview/Content.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Preview/Content.php index a79a5ba9fb..b404f60ce4 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Preview/Content.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Preview/Content.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * XmlConnect preview content block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Content extends Mage_Adminhtml_Block_Template { /** diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Preview/Tabitems.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Preview/Tabitems.php index 6b1100544b..686d041f95 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Preview/Tabitems.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Preview/Tabitems.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * XmlConnect Tab items block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Tabitems extends Mage_Adminhtml_Block_Template { /** @@ -33,7 +41,6 @@ public function __construct() parent::__construct(); $deviceType = Mage::helper('xmlconnect')->getDeviceType(); - $this->setTemplate('xmlconnect/edit/tab/design/preview/tab_items_' . $deviceType . '.phtml'); } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission.php index 851b51a359..4a40c9f1da 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission.php @@ -23,11 +23,18 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission extends Mage_Adminhtml_Block_Widget_Form_Container + +/** + * Application submission block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission + extends Mage_Adminhtml_Block_Widget_Form_Container { /** - * Class construct - * * Setting buttons for submit application page */ public function __construct() @@ -56,8 +63,11 @@ public function __construct() )); $this->_updateButton('back', 'label', $this->__('Back to App Edit')); - $this->_updateButton('back', 'onclick', 'setLocation(\''. $this->getUrl('*/*/edit', - array('application_id' => $app->getId())) . '\')'); + $this->_updateButton( + 'back', + 'onclick', + 'setLocation(\'' . $this->getUrl('*/*/edit', array('application_id' => $app->getId())) . '\')' + ); } /** @@ -104,7 +114,7 @@ public function getHeaderText() { $app = Mage::helper('xmlconnect')->getApplication(); if ($app && $app->getId()) { - return $this->__('Submit App "%s"', $this->htmlEscape($app->getName())); + return $this->__('Submit App "%s"', $this->escapeHtml($app->getName())); } return ''; } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Form.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Form.php index 4bba1b6c06..c68925f62d 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Form.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission_Form extends Mage_Adminhtml_Block_Widget_Form + +/** + * Device submission form block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission_Form + extends Mage_Adminhtml_Block_Widget_Form { /** * Prepare form before rendering HTML diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Renderer/Country/Androidmarket.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Renderer/Country/Androidmarket.php index 6d0aa59233..88727eb231 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Renderer/Country/Androidmarket.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Renderer/Country/Androidmarket.php @@ -38,7 +38,7 @@ class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission_Renderer_Country_Android /** * Override setting the template * - * @return void + * @return null */ protected function _construct() { diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Renderer/Country/Istore.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Renderer/Country/Istore.php index 55b4aa35c6..36aec5fa42 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Renderer/Country/Istore.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Renderer/Country/Istore.php @@ -38,7 +38,7 @@ class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission_Renderer_Country_Istore /** * Override setting the template * - * @return void + * @return null */ protected function _construct() { diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tab/Container.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tab/Container.php index f34cb64436..0ef2f1e2c3 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tab/Container.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tab/Container.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission_Tab_Container extends Mage_Adminhtml_Block_Template + +/** + * Device container block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission_Tab_Container + extends Mage_Adminhtml_Block_Template implements Mage_Adminhtml_Block_Widget_Tab_Interface { /** @@ -58,7 +67,7 @@ public function getTabTitle() } /** - * Returns status flag about this tab can be showen or not + * Returns status flag about this tab can be shown or not * * @return true */ diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tab/Container/Submission.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tab/Container/Submission.php index 814eaabb59..179bd6b834 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tab/Container/Submission.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tab/Container/Submission.php @@ -76,6 +76,7 @@ public function addImage($fieldset, $fieldName, $title, $note = '', $default = ' 'name' => $fieldName, 'label' => $title, 'note' => !empty($note) ? $note : null, + 'default_value' => $default, 'required' => $required, )); } @@ -344,7 +345,7 @@ public function getTabTitle() } /** - * Returns status flag about this tab can be showen or not + * Returns status flag about this tab can be shown or not * * @return true */ diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tabs.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tabs.php index 13d1d819bd..864ede2790 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tabs.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Submission/Tabs.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission_Tabs extends Mage_Adminhtml_Block_Widget_Tabs + +/** + * Device submission tabs block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Mobile_Submission_Tabs + extends Mage_Adminhtml_Block_Widget_Tabs { /** * Constructor diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Widget/Form.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Widget/Form.php index 44ee685f87..79b93c2167 100644 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Widget/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Widget/Form.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * Xmlconnect widget form block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Mobile_Widget_Form extends Mage_Adminhtml_Block_Widget_Form { /** @@ -56,7 +64,7 @@ public function addImage($fieldset, $fieldName, $title, $note = null, $default = 'name' => $fieldName, 'label' => $title, 'note' => $note, - 'default_value' => $default, + 'default_value' => $default, 'required' => $required, )); } @@ -70,12 +78,12 @@ public function addImage($fieldset, $fieldName, $title, $note = null, $default = */ public function addFont($fieldset, $fieldPrefix, $title) { - $el = $fieldset->addField($fieldPrefix, 'font', array( + $element = $fieldset->addField($fieldPrefix, 'font', array( 'name' => $fieldPrefix, 'label' => $title, )); - $el->initFields(array( + $element->initFields(array( 'name' => $fieldPrefix, 'fontNames' => Mage::helper('xmlconnect')->getDeviceHelper()->getFontList(), 'fontSizes' => Mage::helper('xmlconnect')->getDeviceHelper()->getFontSizes(), diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue.php index e9c501591e..7c6dcc0b11 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue.php @@ -31,8 +31,8 @@ * @package Mage_XmlConnect * @author Magento Core Team */ - class Mage_XmlConnect_Block_Adminhtml_Queue extends Mage_Adminhtml_Block_Widget_Grid_Container - { +class Mage_XmlConnect_Block_Adminhtml_Queue extends Mage_Adminhtml_Block_Widget_Grid_Container +{ /** * Class constructor */ @@ -45,4 +45,4 @@ public function __construct() parent::__construct(); $this->removeButton('add'); } - } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Edit.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Edit.php index c03bf096ac..ef150e638a 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Edit.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Edit.php @@ -24,7 +24,15 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Block_Adminhtml_Queue_Edit extends Mage_Adminhtml_Block_Widget_Form_Container +/** + * Xmlconnect queue edit block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Queue_Edit + extends Mage_Adminhtml_Block_Widget_Form_Container { /** * Constructor @@ -72,7 +80,7 @@ public function getHeaderText() { $message = Mage::registry('current_message'); if ($message && $message->getId()) { - return $this->__('Edit AirMail Message Queue #%s', $this->htmlEscape($message->getId())); + return $this->__('Edit AirMail Message Queue #%s', $this->escapeHtml($message->getId())); } else { return $this->__('New AirMail Message Queue'); } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Edit/Form.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Edit/Form.php index 2657bd4fc3..875d4831b8 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Edit/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Edit/Form.php @@ -23,7 +23,16 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Queue_Edit_Form extends Mage_XmlConnect_Block_Adminhtml_Template_Edit_Form + +/** + * Xmlconnect queue edit form block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Queue_Edit_Form + extends Mage_XmlConnect_Block_Adminhtml_Template_Edit_Form { /** * Prepare form before rendering HTML @@ -34,7 +43,12 @@ class Mage_XmlConnect_Block_Adminhtml_Queue_Edit_Form extends Mage_XmlConnect_Bl protected function _prepareForm() { $model = Mage::registry('current_message'); - $this->_fieldsEnabled = $model->getStatus() == Mage_XmlConnect_Model_Queue::STATUS_IN_QUEUE ? true : false; + + if ($model->getStatus() == Mage_XmlConnect_Model_Queue::STATUS_IN_QUEUE) { + $this->_fieldsEnabled = true; + } else { + $this->_fieldsEnabled = false; + } parent::_prepareForm(); @@ -44,7 +58,11 @@ protected function _prepareForm() $templateModel = Mage::getModel('xmlconnect/template')->load($model->getTemplateId()); } - $fieldset = $this->getForm()->addFieldset("message_settings", array('legend' => $this->__('Message Settings')), '^'); + $fieldset = $this->getForm()->addFieldset( + "message_settings", + array('legend' => $this->__('Message Settings')), + '^' + ); if ($model->getId()) { $fieldset->addField('message_id', 'hidden', array( @@ -55,7 +73,7 @@ protected function _prepareForm() // set exec_time for showing accordingly to locale datetime settings $model->setExecTime(Mage::getSingleton('core/date')->date(null, $model->getExecTime())); - /*@var $sovereignField Varien_Data_Form_Element_Abstract */ + /** @var $sovereignField Varien_Data_Form_Element_Abstract */ $sovereignField = $fieldset->addField('type', 'select', array( 'name' => 'type', 'values' => Mage::helper('xmlconnect')->getMessageTypeOptions(), @@ -80,30 +98,40 @@ protected function _prepareForm() $this->_addElementTypes($fieldset); // field dependencies - // i don't know how to not hardcoded this dependence (I mean 'airmail' message type is now used for set these dependences) if (isset($this->_dependentFields['message_title']) || isset($this->_dependentFields['content'])) { $dependenceBlock = $this->getLayout()->createBlock('adminhtml/widget_form_element_dependence'); - $dependenceBlock->addFieldMap($this->_dependentFields['message_title']->getHtmlId(), $this->_dependentFields['message_title']->getName()) - ->addFieldMap($this->_dependentFields['content']->getHtmlId(), $this->_dependentFields['content']->getName()) - ->addFieldMap($sovereignField->getHtmlId(), $sovereignField->getName()); - - if (isset($this->_dependentFields['message_title']) && $this->_dependentFields['message_title']) { + $dependenceBlock->addFieldMap( + $this->_dependentFields['message_title']->getHtmlId(), + $this->_dependentFields['message_title']->getName() + ) + ->addFieldMap( + $this->_dependentFields['content']->getHtmlId(), + $this->_dependentFields['content']->getName() + ) + ->addFieldMap( + $sovereignField->getHtmlId(), + $sovereignField->getName() + ); + + if (!empty($this->_dependentFields['message_title'])) { $dependenceBlock->addFieldDependence( $this->_dependentFields['message_title']->getName(), $sovereignField->getName(), - Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL); + Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL + ); if (!$this->_fieldsEnabled) { $this->_dependentFields['message_title']->setReadonly(true, true); } } - if (isset($this->_dependentFields['content']) && $this->_dependentFields['content']) { + if (!empty($this->_dependentFields['content'])) { $dependenceBlock->addFieldDependence( $this->_dependentFields['content']->getName(), $sovereignField->getName(), - Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL); + Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL + ); if (!$this->_fieldsEnabled) { $this->_dependentFields['content']->setReadonly(true, true); @@ -128,6 +156,7 @@ protected function _prepareForm() $model->setTemplateId($templateModel->getId()); } $model->setMessageId($model->getId()); + $model->setData('app_code', $templateModel->getData('app_code')); $this->getForm()->setAction($this->getUrl('*/*/saveMessage')); $this->getForm()->setValues($model->getData()); diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid.php index c6e12eec8c..aa690dd73b 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid.php @@ -34,8 +34,6 @@ class Mage_XmlConnect_Block_Adminhtml_Queue_Grid extends Mage_Adminhtml_Block_Widget_Grid { /** - * Constructor - * * Setting grid_id, sort order and sort direction */ public function __construct() diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Action.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Action.php index 1cfa571d86..4c550dc62c 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Action.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Action.php @@ -27,11 +27,12 @@ /** * Adminhtml airmail queue grid block action item renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Action extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Action +class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Action + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Action { /** * Render grid row diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Application.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Application.php index 7563ddf483..b094db007e 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Application.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Application.php @@ -27,11 +27,12 @@ /** * Adminhtml airmail queue grid block action item renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Application extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Application + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { /** * Render grid row @@ -41,7 +42,7 @@ class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Application extends Ma */ public function render(Varien_Object $row) { - $str = htmlspecialchars($row->getAppName()); + $str = $this->escapeHtml($row->getAppName()); if ($str == '') { $str = ' --- '; } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Id.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Id.php index 71c58e040a..d0e8ca4396 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Id.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Id.php @@ -27,11 +27,12 @@ /** * Adminhtml airmail queue grid block action item renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Id extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Id + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { /** * Render grid row diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Msgtitle.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Msgtitle.php index c086643110..29639ebcad 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Msgtitle.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Msgtitle.php @@ -27,11 +27,12 @@ /** * Adminhtml airmail queue grid block action item renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Msgtitle extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Msgtitle + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { /** * Render grid row @@ -45,6 +46,6 @@ public function render(Varien_Object $row) if (strlen($msgTitle) > 50) { $msgTitle = substr($msgTitle, 0, 50) . '...'; } - return htmlspecialchars($msgTitle); + return $this->escapeHtml($msgTitle); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Pushtitle.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Pushtitle.php index 045c83806c..7e28ee3e6a 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Pushtitle.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Pushtitle.php @@ -27,12 +27,12 @@ /** * Adminhtml airmail queue grid block action item renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ - -class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Pushtitle extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Pushtitle + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { /** * Render grid row @@ -42,6 +42,6 @@ class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Pushtitle extends Mage */ public function render(Varien_Object $row) { - return htmlspecialchars($row->getPushTitle()); - } + return $this->escapeHtml($row->getPushTitle()); + } } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Status.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Status.php index dd4f22359a..c097e2881c 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Status.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Status.php @@ -27,12 +27,12 @@ /** * Adminhtml airmail queue grid block action item renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ - -class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Status extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Status + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { /** * Render grid row @@ -64,6 +64,6 @@ public function render(Varien_Object $row) $str = $this->__('Undefined'); } - return htmlspecialchars($str); + return $this->escapeHtml($str); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Template.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Template.php index 27cb02e885..622603e809 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Template.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Queue/Grid/Renderer/Template.php @@ -27,12 +27,12 @@ /** * Adminhtml airmail queue grid block action item renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ - -class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Template extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Template + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { /** * Render grid row @@ -42,10 +42,10 @@ class Mage_XmlConnect_Block_Adminhtml_Queue_Grid_Renderer_Template extends Mage_ */ public function render(Varien_Object $row) { - $str = htmlspecialchars($row->getTplName()); + $str = $this->escapeHtml($row->getTplName()); if ($str == '') { $str .= '---'; } return $str; - } + } } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template.php index 21ce0bf34c..7244adfd0f 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template.php @@ -31,8 +31,8 @@ * @package Mage_XmlConnect * @author Magento Core Team */ - class Mage_XmlConnect_Block_Adminhtml_Template extends Mage_Adminhtml_Block_Widget_Grid_Container - { +class Mage_XmlConnect_Block_Adminhtml_Template extends Mage_Adminhtml_Block_Widget_Grid_Container +{ /** * Class constructor */ @@ -45,11 +45,11 @@ public function __construct() parent::__construct(); $this->removeButton('add'); } - + /** * Prepare layout * Add new button - * + * * @return Mage_Adminhtml_Block_Widget_Grid_Container */ protected function _prepareLayout() @@ -59,7 +59,7 @@ protected function _prepareLayout() 'onclick' => "setLocation('{$this->getUrl('*/*/newTemplate')}')", 'class' => 'add' )); - + return parent::_prepareLayout(); } - } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Edit.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Edit.php index b3ee7f5d8f..ecf2dc965a 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Edit.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Edit.php @@ -24,6 +24,13 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ +/** + * Xmlconnect template edit block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Adminhtml_Template_Edit extends Mage_Adminhtml_Block_Widget_Form_Container { /** @@ -37,8 +44,9 @@ public function __construct() parent::__construct(); $this->_updateButton('delete', 'onclick', 'deleteConfirm(\'' - . Mage::helper('adminhtml')->__('Warning: All related AirMail messages will be deteted!\n Are you sure you want to do this?') - .'\', \'' . $this->getDeleteUrl() . '\')'); + . $this->__('Warning: All related AirMail messages will be deleted!') . PHP_EOL + . $this->__('Are you sure you want to do this?') .'\', \'' . $this->getDeleteUrl() . '\')' + ); $this->_updateButton('save', 'label', $this->__('Save')); $this->_updateButton('save', 'onclick', 'if (editForm.submit()) {disableElements(\'save\')}'); $this->_updateButton('back', 'onclick', 'setLocation(\'' . $this->getUrl('*/*/template') . '\')'); @@ -63,7 +71,7 @@ public function getHeaderText() { $template = Mage::registry('current_template'); if ($template && $template->getId()) { - return $this->__('Edit Template "%s"', $this->htmlEscape($template->getName())); + return $this->__('Edit Template "%s"', $this->escapeHtml($template->getName())); } else { return $this->__('New Template'); } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Edit/Form.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Edit/Form.php index 4b01f9cbe8..ffa43c1632 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Edit/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Edit/Form.php @@ -23,9 +23,29 @@ * @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) */ -class Mage_XmlConnect_Block_Adminhtml_Template_Edit_Form extends Mage_XmlConnect_Block_Adminhtml_Mobile_Widget_Form + +/** + * Xmlconnect template edit form block + * + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Block_Adminhtml_Template_Edit_Form + extends Mage_XmlConnect_Block_Adminhtml_Mobile_Widget_Form { + /** + * Enabled fields flag + * + * @var bool + */ protected $_fieldsEnabled = true; + + /** + * Field dependencies + * + * @var array + */ protected $_dependentFields = array(); /** @@ -55,10 +75,10 @@ protected function _prepareForm() $action = $this->getUrl('*/*/saveTemplate'); $form = new Varien_Data_Form(array( - 'id' => 'edit_form', - 'action' => $action, - 'method' => 'post', - 'enctype' => 'multipart/form-data' + 'id' => 'edit_form', + 'action' => $action, + 'method' => 'post', + 'enctype' => 'multipart/form-data' )); $form->setHtmlIdPrefix('template_'); diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Grid.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Grid.php index eb8b356b66..1ab0ee9d8b 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Grid.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Grid.php @@ -33,10 +33,7 @@ */ class Mage_XmlConnect_Block_Adminhtml_Template_Grid extends Mage_Adminhtml_Block_Widget_Grid { - /** - * Constructor - * * Setting grid_id, sort order and sort direction */ public function __construct() @@ -130,15 +127,15 @@ protected function _prepareColumns() array( 'caption' => $this->__('Preview'), 'url' => array( - 'base' => '*/*/previewTemplate' + 'base' => '*/*/previewTemplate' ), - 'popup' => true, + 'popup' => true, 'field' => 'id' ), array( 'caption' => $this->__('Queue Message'), 'url' => array( - 'base' => '*/*/queueMessage', + 'base' => '*/*/queueMessage', ), 'field' => 'template_id' ), diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Grid/Renderer/Application.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Grid/Renderer/Application.php index ea28360376..bb47be885b 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Grid/Renderer/Application.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Grid/Renderer/Application.php @@ -47,5 +47,5 @@ public function render(Varien_Object $row) $str = ' --- '; } return $str; - } + } } diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Preview.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Preview.php index 4df9f7d6bf..bc44abd4c9 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Preview.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Preview.php @@ -27,9 +27,9 @@ /** * XmlConnect Adminhtml AirMail template preview block * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Adminhtml_Template_Preview extends Mage_Adminhtml_Block_Widget { diff --git a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Preview/Form.php b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Preview/Form.php index 30bfc62ed1..51b7d068e8 100755 --- a/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Preview/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Preview/Form.php @@ -27,13 +27,13 @@ /** * Admin form widget * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ -class Mage_XmlConnect_Block_Adminhtml_Template_Preview_Form extends Mage_Adminhtml_Block_Widget_Form +class Mage_XmlConnect_Block_Adminhtml_Template_Preview_Form + extends Mage_Adminhtml_Block_Widget_Form { - /** * Preparing from for revision page * @@ -42,17 +42,16 @@ class Mage_XmlConnect_Block_Adminhtml_Template_Preview_Form extends Mage_Adminht protected function _prepareForm() { $form = new Varien_Data_Form(array( - 'id' => 'preview_form', - 'action' => $this->getUrl('*/*/drop', array('_current' => true)), - 'method' => 'post' - )); - - if ($data = $this->getFormData()) { + 'id' => 'preview_form', + 'action' => $this->getUrl('*/*/drop', array('_current' => true)), + 'method' => 'post' + )); + if ($data = $this->getTemplateFormData()) { $mapper = array('preview_store_id' => 'store_id'); foreach ($data as $key => $value) { - if(array_key_exists($key, $mapper)) { + if (array_key_exists($key, $mapper)) { $name = $mapper[$key]; } else { $name = $key; diff --git a/app/code/core/Mage/XmlConnect/Block/Cart.php b/app/code/core/Mage/XmlConnect/Block/Cart.php index 06411a593d..a86f34f78b 100644 --- a/app/code/core/Mage/XmlConnect/Block/Cart.php +++ b/app/code/core/Mage/XmlConnect/Block/Cart.php @@ -28,7 +28,7 @@ * Shopping cart xml renderer * * @category Mage - * @package Mage_Checkout + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_Block_Cart extends Mage_Checkout_Block_Cart_Abstract @@ -40,179 +40,180 @@ class Mage_XmlConnect_Block_Cart extends Mage_Checkout_Block_Cart_Abstract */ protected function _toHtml() { - $cartMessages = $this->getMessages(); - $quote = $this->getQuote(); - $xmlObject = Mage::getModel('xmlconnect/simplexml_element', ''); - $xmlObject->addAttribute('is_virtual', (int)$this->helper('checkout/cart')->getIsVirtualQuote()); - $xmlObject->addAttribute('summary_qty', (int)$this->helper('checkout/cart')->getSummaryCount()); - if (strlen($quote->getCouponCode())) { - $xmlObject->addAttribute('has_coupon_code', 1); - } - $products = $xmlObject->addChild('products'); - + $cartMessages = $this->getMessages(); + $quote = $this->getQuote(); + /** @var $xmlObject Mage_XmlConnect_Model_Simplexml_Element */ + $xmlObject = Mage::getModel('xmlconnect/simplexml_element', ''); + $xmlObject->addAttribute('is_virtual', (int)$this->helper('checkout/cart')->getIsVirtualQuote()); + $xmlObject->addAttribute('summary_qty', (int)$this->helper('checkout/cart')->getSummaryCount()); + if (strlen($quote->getCouponCode())) { + $xmlObject->addAttribute('has_coupon_code', 1); + } + $products = $xmlObject->addChild('products'); /* @var $item Mage_Sales_Model_Quote_Item */ - foreach ($this->getItems() as $item) { - $type = $item->getProductType(); - $renderer = $this->getItemRenderer($type)->setItem($item); - - /** - * General information - */ - $itemXml = $products->addChild('item'); - $itemXml->addChild('entity_id', $item->getProduct()->getId()); - $itemXml->addChild('entity_type', $type); - $itemXml->addChild('item_id', $item->getId()); - $itemXml->addChild('name', $xmlObject->xmlentities(strip_tags($renderer->getProductName()))); - $itemXml->addChild('code', 'cart[' . $item->getId() . '][qty]'); - $itemXml->addChild('qty', $renderer->getQty()); - $icon = $renderer->getProductThumbnail()->resize( - Mage::helper('xmlconnect/image')->getImageSizeForContent('product_small') - ); - - $iconXml = $itemXml->addChild('icon', $icon); - - $file = Mage::helper('xmlconnect')->urlToPath($icon); - - $iconXml->addAttribute('modification_time', filemtime($file)); - - /** - * Price - */ - $exclPrice = $inclPrice = 0.00; - if ($this->helper('tax')->displayCartPriceExclTax() || $this->helper('tax')->displayCartBothPrices()) { - if (Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales') - && $item->getWeeeTaxAppliedAmount() - ) { - $exclPrice = $item->getCalculationPrice() - + $item->getWeeeTaxAppliedAmount() - + $item->getWeeeTaxDisposition(); - } else { - $exclPrice = $item->getCalculationPrice(); - } - } - - if ($this->helper('tax')->displayCartPriceInclTax() || $this->helper('tax')->displayCartBothPrices()) { - $_incl = $this->helper('checkout')->getPriceInclTax($item); - if (Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales') - && $item->getWeeeTaxAppliedAmount() - ) { - $inclPrice = $_incl + $item->getWeeeTaxAppliedAmount(); - } else { + foreach ($this->getItems() as $item) { + $type = $item->getProductType(); + $renderer = $this->getItemRenderer($type)->setItem($item); + /** + * General information + */ + $itemXml = $products->addChild('item'); + $itemXml->addChild('entity_id', $item->getProduct()->getId()); + $itemXml->addChild('entity_type', $type); + $itemXml->addChild('item_id', $item->getId()); + $itemXml->addChild('name', $xmlObject->xmlentities($renderer->getProductName())); + $itemXml->addChild('code', 'cart[' . $item->getId() . '][qty]'); + $itemXml->addChild('qty', $renderer->getQty()); + $icon = $renderer->getProductThumbnail()->resize( + Mage::helper('xmlconnect/image')->getImageSizeForContent('product_small') + ); + $iconXml = $itemXml->addChild('icon', $icon); + $file = Mage::helper('xmlconnect')->urlToPath($icon); + $iconXml->addAttribute('modification_time', filemtime($file)); + /** + * Price + */ + $exclPrice = $inclPrice = 0; + if ($this->helper('tax')->displayCartPriceExclTax() || $this->helper('tax')->displayCartBothPrices()) { + if (Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales') + && $item->getWeeeTaxAppliedAmount() + ) { + $exclPrice = $item->getCalculationPrice() + $item->getWeeeTaxAppliedAmount() + + $item->getWeeeTaxDisposition(); + } else { + $exclPrice = $item->getCalculationPrice(); + } + } + if ($this->helper('tax')->displayCartPriceInclTax() || $this->helper('tax')->displayCartBothPrices()) { + $_incl = $this->helper('checkout')->getPriceInclTax($item); + if (Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales') + && $item->getWeeeTaxAppliedAmount() + ) { + $inclPrice = $_incl + $item->getWeeeTaxAppliedAmount(); + } else { $inclPrice = $_incl - $item->getWeeeTaxDisposition(); - } - } - - $exclPrice = Mage::helper('xmlconnect')->formatPriceForXml($exclPrice); - $formatedExclPrice = $quote->getStore()->formatPrice($exclPrice, false); - - $inclPrice = Mage::helper('xmlconnect')->formatPriceForXml($inclPrice); - $formatedInclPrice = $quote->getStore()->formatPrice($inclPrice, false); + } + } + $exclPrice = Mage::helper('xmlconnect')->formatPriceForXml($exclPrice); + $paypalPrice = Mage::helper('xmlconnect')->formatPriceForXml($item->getCalculationPrice()); + $formattedExclPrice = $quote->getStore()->formatPrice($exclPrice, false); + $inclPrice = Mage::helper('xmlconnect')->formatPriceForXml($inclPrice); + $formattedInclPrice = $quote->getStore()->formatPrice($inclPrice, false); - $priceXmlObj = $itemXml->addChild('price'); - $formatedPriceXmlObj = $itemXml->addChild('formated_price'); + $priceXmlObj = $itemXml->addChild('price'); + $formattedPriceXmlObj = $itemXml->addChild('formated_price'); - if ($this->helper('tax')->displayCartBothPrices()) { + if ($this->helper('tax')->displayCartBothPrices()) { $priceXmlObj->addAttribute('excluding_tax', $exclPrice); $priceXmlObj->addAttribute('including_tax', $inclPrice); - $formatedPriceXmlObj->addAttribute('excluding_tax', $formatedExclPrice); - $formatedPriceXmlObj->addAttribute('including_tax', $formatedInclPrice); - } else { - if ($this->helper('tax')->displayCartPriceExclTax()) { - $priceXmlObj->addAttribute('regular', $exclPrice); - $formatedPriceXmlObj->addAttribute('regular', $formatedExclPrice); - } - if ($this->helper('tax')->displayCartPriceInclTax()) { - $priceXmlObj->addAttribute('regular', $inclPrice); - $formatedPriceXmlObj->addAttribute('regular', $formatedInclPrice); - } - } - - - /** + $formattedPriceXmlObj->addAttribute('excluding_tax', $formattedExclPrice); + $formattedPriceXmlObj->addAttribute('including_tax', $formattedInclPrice); + } else { + if ($this->helper('tax')->displayCartPriceExclTax()) { + $priceXmlObj->addAttribute('regular', $exclPrice); + $formattedPriceXmlObj->addAttribute('regular', $formattedExclPrice); + } + if ($this->helper('tax')->displayCartPriceInclTax()) { + $priceXmlObj->addAttribute('regular', $inclPrice); + $formattedPriceXmlObj->addAttribute('regular', $formattedInclPrice); + } + } + + /** + * Info for paypal MEP if it's enabled + */ + $appConfig = Mage::helper('xmlconnect')->getApplication()->loadConfiguration()->getRenderConf(); + + $isMepActive = $appConfig['paypal']['isActive']; + + $paypalMepIsAvailable = Mage::getModel('xmlconnect/payment_method_paypal_mep')->isAvailable(null); + if ($paypalMepIsAvailable && $isMepActive) { + $paypalPriceXmlObj = $itemXml->addChild('paypal_price'); + $paypalPriceXmlObj->addAttribute('regular', $paypalPrice); + $paypalPriceXmlObj->addAttribute( + 'subtotal', Mage::helper('xmlconnect')->formatPriceForXml($item->getRowTotal()) + ); + } + + /** * Subtotal */ - $exclPrice = $inclPrice = 0.00; - if ($this->helper('tax')->displayCartPriceExclTax() || $this->helper('tax')->displayCartBothPrices()) { - if (Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales') - && $item->getWeeeTaxAppliedAmount() - ) { - $exclPrice = $item->getRowTotal() - + $item->getWeeeTaxAppliedRowAmount() - + $item->getWeeeTaxRowDisposition(); - } else { + $exclPrice = $inclPrice = 0; + if ($this->helper('tax')->displayCartPriceExclTax() || $this->helper('tax')->displayCartBothPrices()) { + if (Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales') + && $item->getWeeeTaxAppliedAmount() + ) { + $exclPrice = $item->getRowTotal() + $item->getWeeeTaxAppliedRowAmount() + + $item->getWeeeTaxRowDisposition(); + } else { $exclPrice = $item->getRowTotal(); - } - } - if ($this->helper('tax')->displayCartPriceInclTax() || $this->helper('tax')->displayCartBothPrices()) { - $_incl = $this->helper('checkout')->getSubtotalInclTax($item); - if (Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales') - && $item->getWeeeTaxAppliedAmount() - ) { - $inclPrice = $_incl + $item->getWeeeTaxAppliedRowAmount(); - } else { - $inclPrice = $_incl - $item->getWeeeTaxRowDisposition(); - } - } - - $exclPrice = Mage::helper('xmlconnect')->formatPriceForXml($exclPrice); - $formatedExclPrice = $quote->getStore()->formatPrice($exclPrice, false); - - $inclPrice = Mage::helper('xmlconnect')->formatPriceForXml($inclPrice); - $formatedInclPrice = $quote->getStore()->formatPrice($inclPrice, false); - - $subtotalPriceXmlObj = $itemXml->addChild('subtotal'); - $subtotalFormatedPriceXmlObj = $itemXml->addChild('formated_subtotal'); - - if ($this->helper('tax')->displayCartBothPrices()) { - $subtotalPriceXmlObj->addAttribute('excluding_tax', $exclPrice); - $subtotalPriceXmlObj->addAttribute('including_tax', $inclPrice); - - $subtotalFormatedPriceXmlObj->addAttribute('excluding_tax', $formatedExclPrice); - $subtotalFormatedPriceXmlObj->addAttribute('including_tax', $formatedInclPrice); - } else { - if ($this->helper('tax')->displayCartPriceExclTax()) { - $subtotalPriceXmlObj->addAttribute('regular', $exclPrice); - $subtotalFormatedPriceXmlObj->addAttribute('regular', $formatedExclPrice); - } - if ($this->helper('tax')->displayCartPriceInclTax()) { - $subtotalPriceXmlObj->addAttribute('regular', $inclPrice); - $subtotalFormatedPriceXmlObj->addAttribute('regular', $formatedInclPrice); - } - } - - /** + } + } + if ($this->helper('tax')->displayCartPriceInclTax() || $this->helper('tax')->displayCartBothPrices()) { + $_incl = $this->helper('checkout')->getSubtotalInclTax($item); + if (Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales') + && $item->getWeeeTaxAppliedAmount() + ) { + $inclPrice = $_incl + $item->getWeeeTaxAppliedRowAmount(); + } else { + $inclPrice = $_incl - $item->getWeeeTaxRowDisposition(); + } + } + + $exclPrice = Mage::helper('xmlconnect')->formatPriceForXml($exclPrice); + $formattedExclPrice = $quote->getStore()->formatPrice($exclPrice, false); + + $inclPrice = Mage::helper('xmlconnect')->formatPriceForXml($inclPrice); + $formattedInclPrice = $quote->getStore()->formatPrice($inclPrice, false); + + $subtotalPriceXmlObj = $itemXml->addChild('subtotal'); + $subtotalFormattedPriceXmlObj = $itemXml->addChild('formated_subtotal'); + + if ($this->helper('tax')->displayCartBothPrices()) { + $subtotalPriceXmlObj->addAttribute('excluding_tax', $exclPrice); + $subtotalPriceXmlObj->addAttribute('including_tax', $inclPrice); + + $subtotalFormattedPriceXmlObj->addAttribute('excluding_tax', $formattedExclPrice); + $subtotalFormattedPriceXmlObj->addAttribute('including_tax', $formattedInclPrice); + } else { + if ($this->helper('tax')->displayCartPriceExclTax()) { + $subtotalPriceXmlObj->addAttribute('regular', $exclPrice); + $subtotalFormattedPriceXmlObj->addAttribute('regular', $formattedExclPrice); + } + if ($this->helper('tax')->displayCartPriceInclTax()) { + $subtotalPriceXmlObj->addAttribute('regular', $inclPrice); + $subtotalFormattedPriceXmlObj->addAttribute('regular', $formattedInclPrice); + } + } + + /** * Options list */ - if ($_options = $renderer->getOptionList()) { - $itemOptionsXml = $itemXml->addChild('options'); - foreach ($_options as $_option) { - $_formatedOptionValue = $renderer->getFormatedOptionValue($_option); - $optionXml = $itemOptionsXml->addChild('option'); - $optionXml->addAttribute('label', $xmlObject->xmlentities(strip_tags($_option['label']))); - $optionXml->addAttribute( - 'text', - $xmlObject->xmlentities(strip_tags($_formatedOptionValue['value'])) - ); -// if (isset($_formatedOptionValue['full_view'])) { -// $label = strip_tags($_option['label']); -// $value = strip_tags($_formatedOptionValue['full_view']); -// } - } - } - - /** + if ($_options = $renderer->getOptionList()) { + $itemOptionsXml = $itemXml->addChild('options'); + foreach ($_options as $_option) { + $_formattedOptionValue = $renderer->getFormatedOptionValue($_option); + $optionXml = $itemOptionsXml->addChild('option'); + $optionXml->addAttribute('label', $xmlObject->xmlAttribute($_option['label'])); + $optionXml->addAttribute( + 'text', $xmlObject->xmlAttribute(strip_tags($_formattedOptionValue['value'])) + ); + } + } + + /** * Item messages */ - if ($messages = $renderer->getMessages()) { - $itemMessagesXml = $itemXml->addChild('messages'); - foreach ($messages as $message) { - $messageXml = $itemMessagesXml->addChild('option'); - $messageXml->addChild('type', $message['type']); - $messageXml->addChild('text', $xmlObject->xmlentities(strip_tags($message['text']))); - } - } - } + if ($messages = $renderer->getMessages()) { + $itemMessagesXml = $itemXml->addChild('messages'); + foreach ($messages as $message) { + $messageXml = $itemMessagesXml->addChild('option'); + $messageXml->addChild('type', $message['type']); + $messageXml->addChild('text', $xmlObject->xmlentities($message['text'])); + } + } + } /** * Cart messages diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Crosssell.php b/app/code/core/Mage/XmlConnect/Block/Cart/Crosssell.php index a16aeb9807..ed5f40b6aa 100644 --- a/app/code/core/Mage/XmlConnect/Block/Cart/Crosssell.php +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Crosssell.php @@ -75,7 +75,7 @@ protected function _toHtml() } $itemXmlObj->addChild('has_options', (int)$product->getHasOptions()); - $itemXmlObj->addChild('in_stock', (int)$product->isInStock()); + $itemXmlObj->addChild('in_stock', (int)$product->getIsInStock()); if ($product->getTypeId() == Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE) { $itemXmlObj->addChild('is_salable', 0); } else { @@ -83,14 +83,12 @@ protected function _toHtml() } if ($this->getChild('product_price')) { - $this->getChild('product_price')->setProduct($product) - ->setProductXmlObj($itemXmlObj) + $this->getChild('product_price')->setProduct($product)->setProductXmlObj($itemXmlObj) ->collectProductPrices(); } if (!$product->getRatingSummary()) { - Mage::getModel('review/review') - ->getEntitySummary($product, Mage::app()->getStore()->getId()); + Mage::getModel('review/review')->getEntitySummary($product, Mage::app()->getStore()->getId()); } $itemXmlObj->addChild('rating_summary', round((int)$product->getRatingSummary()->getRatingSummary() / 10)); diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Info.php b/app/code/core/Mage/XmlConnect/Block/Cart/Info.php index 53c74a69f9..ad7e66cd24 100644 --- a/app/code/core/Mage/XmlConnect/Block/Cart/Info.php +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Info.php @@ -28,7 +28,7 @@ * Shopping cart summary information xml renderer * * @category Mage - * @package Mage_Checkout + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_Block_Cart_Info extends Mage_XmlConnect_Block_Cart @@ -45,18 +45,11 @@ protected function _toHtml() /** @var $xmlObject Mage_XmlConnect_Model_Simplexml_Element */ $xmlObject = Mage::getModel('xmlconnect/simplexml_element', ''); - $xmlObject->addChild( - 'is_virtual', - (int)$this->helper('checkout/cart')->getIsVirtualQuote() - ); - $xmlObject->addChild( - 'summary_qty', - (int)$this->helper('checkout/cart')->getSummaryCount() - ); - $xmlObject->addChild( - 'virtual_qty', - (int)$quote->getItemVirtualQty() - ); + $xmlObject->addChild('is_virtual', (int)$this->helper('checkout/cart')->getIsVirtualQuote()); + + $xmlObject->addChild('summary_qty', (int)$this->helper('checkout/cart')->getSummaryCount()); + + $xmlObject->addChild('virtual_qty', (int)$quote->getItemVirtualQty()); if (strlen($quote->getCouponCode())) { $xmlObject->addChild('has_coupon_code', 1); @@ -68,7 +61,6 @@ protected function _toHtml() $totalsXmlObj = Mage::getModel('xmlconnect/simplexml_element', $totalsXml); $xmlObject->appendChild($totalsXmlObj); } - return $xmlObject->asNiceXml(); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Item/Renderer.php b/app/code/core/Mage/XmlConnect/Block/Cart/Item/Renderer.php new file mode 100644 index 0000000000..3a6f0f2c15 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Item/Renderer.php @@ -0,0 +1,262 @@ + + */ +class Mage_XmlConnect_Block_Cart_Item_Renderer extends Mage_Checkout_Block_Cart_Item_Renderer +{ + /** + * Add product details to XML object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $reviewXmlObj + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function addProductToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $reviewXmlObj) + { + $_item = $this->getItem(); + $productXmlObj = $reviewXmlObj->addCustomChild('item'); + $productXmlObj->addCustomChild('name', $this->escapeHtml($this->getProductName())); + + if ($_options = $this->getOptionList()) { + $optionsXmlObj = $productXmlObj->addChild('options'); + foreach ($_options as $_option) { + $_formattedOptionValue = $this->getFormatedOptionValue($_option); + + if (isset($_formattedOptionValue['full_view'])) { + $value = $_formattedOptionValue['full_view']; + } else { + $value = null; + } + + $optionsXmlObj->addCustomChild('option', $value, array( + 'label' => $this->escapeHtml($_option['label']), + 'value' => $_formattedOptionValue['value'] + )); + } + } + + $this->_addPriceToXmlObj($productXmlObj); + $this->_addSubtotalToXmlObj($productXmlObj); + + $productXmlObj->addCustomChild('qty', $_item->getQty()); + + return $reviewXmlObj; + } + + /** + * Add product subtotal info to xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $productXmlObj + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + protected function _addSubtotalToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $productXmlObj) + { + $_item = $this->getItem(); + $subtotalXmlObj = $productXmlObj->addCustomChild('subtotal'); + + if ($this->helper('tax')->displayCartPriceExclTax() || $this->helper('tax')->displayCartBothPrices()) { + if (Mage::helper('weee')->typeOfDisplay($_item, array(0, 1, 4), 'sales') + && $_item->getWeeeTaxAppliedAmount() + ) { + $exclPrice = $_item->getRowTotal() + $_item->getWeeeTaxAppliedRowAmount() + + $_item->getWeeeTaxRowDisposition(); + } else { + $exclPrice = $_item->getRowTotal(); + } + $exclPrice = $this->_formatPrice($exclPrice); + $subtotalXmlObj->addAttribute('excluding_tax', $subtotalXmlObj->xmlentities($exclPrice)); + } + + if ($this->helper('tax')->displayCartPriceInclTax() || $this->helper('tax')->displayCartBothPrices()) { + $_incl = $this->helper('checkout')->getSubtotalInclTax($_item); + + if (Mage::helper('weee')->typeOfDisplay($_item, array(0, 1, 4), 'sales') + && $_item->getWeeeTaxAppliedAmount() + ) { + $inclPrice = $_incl + $_item->getWeeeTaxAppliedRowAmount(); + } else { + $inclPrice = $_incl - $_item->getWeeeTaxRowDisposition(); + } + $inclPrice = $this->_formatPrice($inclPrice); + + $subtotalXmlObj->addAttribute('including_tax', $subtotalXmlObj->xmlentities($inclPrice)); + } + + if (Mage::helper('weee')->getApplied($_item)) { + $this->_addWeeeToXmlObj($subtotalXmlObj, true); + } + + return $productXmlObj; + } + + /** + * Format product price + * + * @param int $price + * @return float + */ + protected function _formatPrice($price) + { + return $this->getQuote()->getStore()->formatPrice($price, false); + } + + /** + * Add product price info to xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $productXmlObj + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + protected function _addPriceToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $productXmlObj) + { + $_item = $this->getItem(); + $priceXmlObj = $productXmlObj->addCustomChild('price'); + + if ($this->helper('tax')->displayCartPriceExclTax() + || $this->helper('tax')->displayCartBothPrices() + ) { + if (Mage::helper('weee')->typeOfDisplay($_item, array(0, 1, 4), 'sales') + && $_item->getWeeeTaxAppliedAmount() + ) { + $exclPrice = $_item->getCalculationPrice() + $_item->getWeeeTaxAppliedAmount() + + $_item->getWeeeTaxDisposition(); + } else { + $exclPrice = $_item->getCalculationPrice(); + } + $exclPrice = $this->_formatPrice($exclPrice); + + $priceXmlObj->addAttribute('excluding_tax', $priceXmlObj->xmlentities($exclPrice)); + } + + if ($this->helper('tax')->displayCartPriceInclTax() + || $this->helper('tax')->displayCartBothPrices() + ) { + $_incl = $this->helper('checkout')->getPriceInclTax($_item); + + if (Mage::helper('weee')->typeOfDisplay($_item, array(0, 1, 4), 'sales') + && $_item->getWeeeTaxAppliedAmount() + ) { + $inclPrice = $_incl + $_item->getWeeeTaxAppliedAmount(); + } else { + $inclPrice = $_incl - $_item->getWeeeTaxDisposition(); + } + $inclPrice = $this->_formatPrice($inclPrice); + + $priceXmlObj->addAttribute('including_tax', $priceXmlObj->xmlentities($inclPrice)); + } + + if (Mage::helper('weee')->getApplied($_item)) { + $this->_addWeeeToXmlObj($priceXmlObj); + } + + return $productXmlObj; + } + + /** + * Add weee tax product info to xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $priceXmlObj + * @param bool $subtotalFlag use true to get subtotal product info + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + protected function _addWeeeToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $priceXmlObj, $subtotalFlag = false) + { + $_item = $this->getItem(); + $weeeXmlObj = $priceXmlObj->addCustomChild('weee'); + + if ($subtotalFlag) { + $_incl = $this->helper('checkout')->getSubtotalInclTax($_item); + } else { + $_incl = $this->helper('checkout')->getPriceInclTax($_item); + } + + $typeOfDisplay2 = Mage::helper('weee')->typeOfDisplay($_item, 2, 'sales'); + + if (Mage::helper('weee')->typeOfDisplay($_item, 1, 'sales') && $_item->getWeeeTaxAppliedAmount()) { + foreach (Mage::helper('weee')->getApplied($_item) as $tax) { + + if ($subtotalFlag) { + $amount = $tax['row_amount']; + } else { + $amount = $tax['amount']; + } + + $weeeXmlObj->addCustomChild('item', null, array( + 'name' => $tax['title'], + 'amount' => $this->_formatPrice($amount) + )); + } + } elseif ($_item->getWeeeTaxAppliedAmount() + && ($typeOfDisplay2 || Mage::helper('weee')->typeOfDisplay($_item, 4, 'sales')) + ) { + foreach (Mage::helper('weee')->getApplied($_item) as $tax) { + if ($subtotalFlag) { + $amount = $tax['row_amount_incl_tax']; + } else { + $amount = $tax['amount_incl_tax']; + } + + $weeeXmlObj->addCustomChild('item', null, array( + 'name' => $tax['title'], + 'amount' => $this->_formatPrice($amount) + )); + } + } + + if ($typeOfDisplay2 && $_item->getWeeeTaxAppliedAmount()) { + if ($subtotalFlag) { + $totalExcl = $_item->getRowTotal() + $_item->getWeeeTaxAppliedRowAmount() + + $_item->getWeeeTaxRowDisposition(); + } else { + $totalExcl = $_item->getCalculationPrice() + $_item->getWeeeTaxAppliedAmount() + + $_item->getWeeeTaxDisposition(); + } + + $totalExcl = $this->_formatPrice($totalExcl); + $priceXmlObj->addAttribute( + 'total_excluding_tax', + $priceXmlObj->xmlentities($totalExcl) + ); + } + + if ($typeOfDisplay2 && $_item->getWeeeTaxAppliedAmount()) { + if ($subtotalFlag) { + $totalIncl = $_incl + $_item->getWeeeTaxAppliedRowAmount(); + } else { + $totalIncl = $_incl + $_item->getWeeeTaxAppliedAmount(); + } + + $totalIncl = $this->_formatPrice($totalIncl); + $priceXmlObj->addAttribute('total_including_tax', $priceXmlObj->xmlentities($totalIncl)); + } + + return $priceXmlObj; + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Item/Renderer/Configurable.php b/app/code/core/Mage/XmlConnect/Block/Cart/Item/Renderer/Configurable.php new file mode 100644 index 0000000000..86e2b530c5 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Item/Renderer/Configurable.php @@ -0,0 +1,88 @@ + + */ +class Mage_XmlConnect_Block_Cart_Item_Renderer_Configurable extends Mage_XmlConnect_Block_Cart_Item_Renderer +{ + const CONFIGURABLE_PRODUCT_IMAGE = 'checkout/cart/configurable_product_image'; + const USE_PARENT_IMAGE = 'parent'; + + /** + * Get item configurable product + * + * @return Mage_Catalog_Model_Product + */ + public function getConfigurableProduct() + { + $option = $this->getItem()->getOptionByCode('product_type'); + if ($option) { + return $option->getProduct(); + } + return $this->getProduct(); + } + + /** + * Get item configurable child product + * + * @return Mage_Catalog_Model_Product + */ + public function getChildProduct() + { + $option = $this->getItem()->getOptionByCode('simple_product'); + if ($option) { + return $option->getProduct(); + } + return $this->getProduct(); + } + + /** + * Get item product name + * + * @return string + */ + public function getProductName() + { + return $this->getProduct()->getName(); + } + + /** + * Get list of all options for product + * + * @return array + */ + public function getOptionList() + { + /* @var $helper Mage_Catalog_Helper_Product_Configuration */ + $helper = Mage::helper('catalog/product_configuration'); + return $helper->getConfigurableOptions($this->getItem()); + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Item/Renderer/Grouped.php b/app/code/core/Mage/XmlConnect/Block/Cart/Item/Renderer/Grouped.php new file mode 100644 index 0000000000..49e539e4c6 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Item/Renderer/Grouped.php @@ -0,0 +1,52 @@ + + */ +class Mage_XmlConnect_Block_Cart_Item_Renderer_Grouped extends Mage_XmlConnect_Block_Cart_Item_Renderer +{ + const GROUPED_PRODUCT_IMAGE = 'checkout/cart/grouped_product_image'; + const USE_PARENT_IMAGE = 'parent'; + + /** + * Get item grouped product + * + * @return Mage_Catalog_Model_Product + */ + public function getGroupedProduct() + { + $option = $this->getItem()->getOptionByCode('product_type'); + if ($option) { + return $option->getProduct(); + } + return $this->getProduct(); + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Details.php b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Details.php new file mode 100644 index 0000000000..59561df5b8 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Details.php @@ -0,0 +1,87 @@ + + */ +class Mage_XmlConnect_Block_Cart_Paypal_Mecl_Details extends Mage_Paypal_Block_Express_Review_Details +{ + /** + * Add cart details to XML object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $reviewXmlObj + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function addDetailsToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $reviewXmlObj) + { + $itemsXmlObj = $reviewXmlObj->addChild('ordered_items'); + foreach ($this->getItems() as $_item) { + $this->getItemXml($_item, $itemsXmlObj); + } + + $reviewXmlObj->appendChild($this->getChild('totals')->setReturnObjectFlag(true)->_toHtml()); + + return $reviewXmlObj; + } + + /** + * Get item row xml + * + * @param Mage_Sales_Model_Quote_Item $item + * @param Mage_XmlConnect_Model_Simplexml_Element $reviewXmlObj + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function getItemXml( + Mage_Sales_Model_Quote_Item $item, + Mage_XmlConnect_Model_Simplexml_Element $reviewXmlObj + ) + { + $renderer = $this->getItemRenderer($item->getProductType())->setItem($item)->setQuote($this->getQuote()); + return $renderer->addProductToXmlObj($reviewXmlObj); + } + + /** + * Add renderer for item product type + * + * @param string $productType + * @param string $blockType + * @param string $template + * @return Mage_Checkout_Block_Cart_Abstract + */ + public function addItemRender($productType, $blockType, $template) + { + $this->_itemRenders[$productType] = array( + 'block' => $blockType, + 'template' => $template, + 'blockInstance' => null + ); + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Review.php b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Review.php new file mode 100644 index 0000000000..a2c8a07e87 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Review.php @@ -0,0 +1,94 @@ + + */ +class Mage_XmlConnect_Block_Cart_Paypal_Mecl_Review extends Mage_Paypal_Block_Express_Review +{ + /** + * Render PayPal MECL details xml + * + * @return string xml + */ + protected function _toHtml() + { + /** @var $reviewXmlObj Mage_XmlConnect_Model_Simplexml_Element */ + $reviewXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); + + if ($this->getPaypalMessages()) { + $reviewXmlObj->addChild('paypal_message', implode(PHP_EOL, $this->getPaypalMessages())); + } + + if ($this->getShippingAddress()) { + $reviewXmlObj->addCustomChild( + 'shipping_address', + Mage::helper('xmlconnect')->trimLineBreaks($this->getShippingAddress()->format('text')), + array('label' => $this->__('Shipping Address')) + ); + } + + if ($this->_quote->isVirtual()) { + $reviewXmlObj->addCustomChild('shipping_method', null, array( + 'label' => $this->__('No shipping method required.') + )); + } elseif ($this->getCanEditShippingMethod() || !$this->getCurrentShippingRate()) { + if ($groups = $this->getShippingRateGroups()) { + $currentRate = $this->getCurrentShippingRate(); + foreach ($groups as $code => $rates) { + foreach ($rates as $rate) { + if ($currentRate === $rate) { + $reviewXmlObj->addCustomChild('shipping_method', null, array( + 'rate' => strip_tags($this->renderShippingRateOption($rate)), + 'label' => $this->getCarrierName($code) + )); + break(2); + } + } + } + } + } + $reviewXmlObj->addCustomChild('payment_method', $this->escapeHtml($this->getPaymentMethodTitle()), array( + 'label' => $this->__('Payment Method') + )); + + $reviewXmlObj->addCustomChild( + 'billing_address', + Mage::helper('xmlconnect')->trimLineBreaks($this->getBillingAddress()->format('text')), + array( + 'label' => $this->__('Billing Address'), + 'payer_email' => $this->__('Payer Email: %s', $this->getBillingAddress()->getEmail()) + )); + + $this->getChild('details')->addDetailsToXmlObj($reviewXmlObj); + + return $reviewXmlObj->asNiceXml(); + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Shippingmethods.php b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Shippingmethods.php new file mode 100644 index 0000000000..d8d5f2dff9 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Shippingmethods.php @@ -0,0 +1,97 @@ + + */ +class Mage_XmlConnect_Block_Cart_Paypal_Mecl_Shippingmethods + extends Mage_Paypal_Block_Express_Review +{ + /** + * Render PayPal MECL shipping method list xml + * + * @return string xml + */ + protected function _toHtml() + { + /** @var $listXmlObj Mage_XmlConnect_Model_Simplexml_Element */ + $methodListXmlObj = Mage::getModel( + 'xmlconnect/simplexml_element', + '' + ); + + $methodListXmlObj->addAttribute('label', $this->__('Shipping Method')); + + if ($this->getCanEditShippingMethod() || !$this->getCurrentShippingRate()) { + $groups = $this->getShippingRateGroups(); + if ($groups) { + $currentRate = $this->getCurrentShippingRate(); + foreach ($groups as $code => $rates) { + $rateXmlObj = $this->_addRatesToXmlObj($methodListXmlObj, $code); + foreach ($rates as $rate) { + $rateAttributes = array( + 'label' => strip_tags($this->renderShippingRateOption($rate)), + 'code' => $this->renderShippingRateValue($rate) + ); + if ($currentRate === $rate) { + $rateAttributes += array('selected' => 1); + } + $rateXmlObj->addCustomChild('rate', null, $rateAttributes); + } + } + } else { + $message = $this->_quote->isVirtual() ? $this->__('No shipping method required.') + : $this->__('Sorry, no quotes are available for this order at this time.'); + $methodListXmlObj->addCustomChild('method', null, array('label' => $message)); + } + } else { + $rateXmlObj = $this->_addRatesToXmlObj($methodListXmlObj); + $rateXmlObj->addCustomChild('rate', null, array( + 'label' => $this->renderShippingRateOption($this->getCurrentShippingRate()), + 'selected' => 1 + )); + } + + return $methodListXmlObj->asNiceXml(); + } + + /** + * Add cart details to XML object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $methodListXmlObj + * @param string $code + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + protected function _addRatesToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $methodListXmlObj, $code = '') + { + $attributes = $code ? array('label' => $this->getCarrierName($code)) : array(); + return $methodListXmlObj->addCustomChild('method', null, $attributes)->addCustomChild('rates'); + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mep/Totals.php b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mep/Totals.php index 65f8feb501..0903d6b3f1 100644 --- a/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mep/Totals.php +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mep/Totals.php @@ -28,7 +28,7 @@ * PayPal MEP Shopping cart totals xml renderer * * @category Mage - * @package Mage_Cart + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_Block_Cart_Paypal_Mep_Totals extends Mage_Checkout_Block_Cart_Totals @@ -48,6 +48,39 @@ protected function _toHtml() $currencyAmount = $this->helper('core')->currency($amount, false, false); $totalsXmlObj->addChild($code, sprintf('%01.2F', $currencyAmount)); } + + $paypalTotals = $totalsXmlObj->addChild('paypal_totals'); + foreach ($this->getQuote()->getTotals() as $total) { + $code = $total->getCode(); + if ($code == 'giftcardaccount' || $code == 'giftwrapping') { + continue; + } + $renderer = $this->_getTotalRenderer($code)->setTotal($total); + switch ($code) { + case 'subtotal': + $subtotal = intval($total->getValueExclTax()) ? $total->getValueExclTax() : $total->getValue(); + $paypalTotals->addAttribute( + $code, + Mage::helper('xmlconnect')->formatPriceForXml($subtotal) + ); + break; + case 'tax': + $paypalTotals->addAttribute( + $code, + Mage::helper('xmlconnect')->formatPriceForXml($total->getValue()) + ); + break; + case 'shipping': + $paypalTotals->addAttribute( + $code, + Mage::helper('xmlconnect')->formatPriceForXml($renderer->getShippingExcludeTax()) + ); + break; + default: + break; + } + } + return $totalsXmlObj->asNiceXml(); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Totals.php b/app/code/core/Mage/XmlConnect/Block/Cart/Totals.php index 1a1a5c5c7d..19d4819eeb 100644 --- a/app/code/core/Mage/XmlConnect/Block/Cart/Totals.php +++ b/app/code/core/Mage/XmlConnect/Block/Cart/Totals.php @@ -28,7 +28,7 @@ * Shopping cart totals xml renderer * * @category Mage - * @package Mage_Checkout + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_Block_Cart_Totals extends Mage_Checkout_Block_Cart_Totals @@ -36,30 +36,30 @@ class Mage_XmlConnect_Block_Cart_Totals extends Mage_Checkout_Block_Cart_Totals /** * Render cart totals xml * - * @return string + * @return string|Mage_XmlConnect_Model_Simplexml_Element */ protected function _toHtml() { /** @var $totalsXmlObj Mage_XmlConnect_Model_Simplexml_Element */ $totalsXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); -// $taxConfig = Mage::getSingleton('tax/config'); foreach ($this->getQuote()->getTotals() as $total) { $code = $total->getCode(); - if ($code == 'giftcardaccount' || $code == 'giftwrapping') { + if ($code == 'giftwrapping') { continue; } + $title = ''; $value = null; $renderer = $this->_getTotalRenderer($code)->setTotal($total); + switch ($code) { case 'subtotal': if ($renderer->displayBoth()) { $title = $this->__('Subtotal (Excl. Tax)'); $this->_addTotalDataToXmlObj( $totalsXmlObj, - $code . - '_excl_tax', + $code . '_excl_tax', $title, $total->getValueExclTax() ); @@ -73,11 +73,7 @@ protected function _toHtml() if ($renderer->displayBoth()) { $title = $renderer->getExcludeTaxLabel(); $this->_addTotalDataToXmlObj( - $totalsXmlObj, - $code . - '_excl_tax', - $title, - $renderer->getShippingExcludeTax() + $totalsXmlObj, $code . '_excl_tax', $title, $renderer->getShippingExcludeTax() ); $code = $code . '_incl_tax'; @@ -95,28 +91,50 @@ protected function _toHtml() if ($displayBoth) { $title = $this->__('Grand Total (Excl. Tax)'); $this->_addTotalDataToXmlObj( - $totalsXmlObj, - $code . '_excl_tax', - $title, - $grandTotalExlTax + $totalsXmlObj, $code . '_excl_tax', $title, $grandTotalExlTax ); $code = $code . '_incl_tax'; $title = $this->__('Grand Total (Incl. Tax)'); } break; + case 'giftwrapping': + foreach ($renderer->getValues() as $title => $value) { + $this->_addTotalDataToXmlObj($totalsXmlObj, $code, $title, $value); + } + continue 2; + case 'giftcardaccount': + $_cards = $renderer->getTotal()->getGiftCards(); + if (!$_cards) { + $_cards = $renderer->getQuoteGiftCards(); + } + if ($renderer->getTotal()->getValue()) { + foreach ($_cards as $cardCode) { + $title = $this->__('Gift Card (%s)', $cardCode['c']); + $value = $cardCode['c']; + $totalXmlObj = $totalsXmlObj->addChild($code); + $totalXmlObj->addChild('title', $totalsXmlObj->xmlentities($title)); + $totalXmlObj->addChild('value', $value); + $value = Mage::helper('xmlconnect')->formatPriceForXml($cardCode['a']); + $formattedValue = $this->getQuote()->getStore()->formatPrice($value, false); + $totalXmlObj->addChild('formated_value', '-' . $formattedValue); + } + } + continue 2; default: break; } if (empty($title)) { $title = $total->getTitle(); } - if (is_null($value)) { + if (null === $value) { $value = $total->getValue(); } - $this->_addTotalDataToXmlObj($totalsXmlObj, $code, $title, $value); + if (null !== $value) { + $this->_addTotalDataToXmlObj($totalsXmlObj, $code, $title, $value); + } } - return $totalsXmlObj->asNiceXml(); + return $this->getReturnObjectFlag() ? $totalsXmlObj : $totalsXmlObj->asNiceXml(); } /** diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog.php b/app/code/core/Mage/XmlConnect/Block/Catalog.php index c261b001b4..54e8b01832 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog.php @@ -23,6 +23,14 @@ * @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) */ + +/** + * Catalog xml renderer + * + * @category Mage + * @package Mage_Xmlconnect + * @author Magento Core Team + */ class Mage_XmlConnect_Block_Catalog extends Mage_Core_Block_Template { /** diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Category.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Category.php index 6cc1d87231..eb5aa2c9cf 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Category.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Category.php @@ -55,31 +55,30 @@ protected function _toHtml() $productListBlock = $this->getChild('product_list'); if ($productListBlock && $categoryModel->getLevel() > 1) { $layer = Mage::getSingleton('catalog/layer'); - $productsXmlObj = $productListBlock->setCategory($categoryModel) - ->setLayer($layer) + $productsXmlObj = $productListBlock->setCategory($categoryModel)->setLayer($layer) ->getProductsXmlObject(); $hasMoreProductItems = (int)$productListBlock->getHasProductItems(); } $infoBlock = $this->getChild('category_info'); if ($infoBlock) { - $categoryInfoXmlObj = $infoBlock->setCategory($categoryModel) - ->getCategoryInfoXmlObject(); + $categoryInfoXmlObj = $infoBlock->setCategory($categoryModel)->getCategoryInfoXmlObject(); $categoryInfoXmlObj->addChild('has_more_items', $hasMoreProductItems); $categoryXmlObj->appendChild($categoryInfoXmlObj); } } - $categoryCollection = $categoryModel->getCategories($categoryId, 0, false, true); + $categoryCollection = $this->getCurrentChildCategories(); // subcategories are exists if (sizeof($categoryCollection)) { $itemsXmlObj = $categoryXmlObj->addChild('items'); foreach ($categoryCollection as $item) { - $itemXmlObj = $itemsXmlObj->addChild('item'); /** @var $item Mage_Catalog_Model_Category */ $item = Mage::getModel('catalog/category')->load($item->getId()); - $itemXmlObj->addChild('label', $categoryXmlObj->xmlentities(strip_tags($item->getName()))); + + $itemXmlObj = $itemsXmlObj->addChild('item'); + $itemXmlObj->addChild('label', $categoryXmlObj->xmlentities($item->getName())); $itemXmlObj->addChild('entity_id', $item->getId()); $itemXmlObj->addChild('content_type', $item->hasChildren() ? 'categories' : 'products'); if (!is_null($categoryId)) { @@ -100,4 +99,21 @@ protected function _toHtml() } return $categoryXmlObj->asNiceXml(); } + + /** + * Retrieve child categories of current category + * + * @return Varien_Data_Tree_Node_Collection + */ + public function getCurrentChildCategories() + { + $layer = Mage::getSingleton('catalog/layer'); + $category = $layer->getCurrentCategory(); + /* @var $category Mage_Catalog_Model_Category */ + $categories = $category->getChildrenCategories(); + $productCollection = Mage::getResourceModel('catalog/product_collection'); + $layer->prepareProductCollection($productCollection); + $productCollection->addCountToCategories($categories); + return $categories; + } } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Category/Info.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Category/Info.php index 6abd9945e2..ba74afce1e 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Category/Info.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Category/Info.php @@ -42,7 +42,7 @@ public function getCategoryInfoXmlObject() { $infoXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); $category = $this->getCategory(); - if ($category && is_object($category) && $category->getId()) { + if (is_object($category) && $category->getId()) { /** * @var string $title * @@ -50,7 +50,7 @@ public function getCategoryInfoXmlObject() */ $title = $this->__('Shop'); if ($category->getParentCategory()->getLevel() > 1) { - $title = $infoXmlObj->xmlentities(strip_tags($category->getParentCategory()->getName())); + $title = $infoXmlObj->xmlentities($category->getParentCategory()->getName()); } $infoXmlObj->addChild('parent_title', $title); diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Filters.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Filters.php index 1cf068c0d2..cb72d40270 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Filters.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Filters.php @@ -50,7 +50,7 @@ protected function _toHtml() continue; } $itemXmlObj = $filtersXmlObj->addChild('item'); - $itemXmlObj->addChild('name', $categoryXmlObj->xmlentities(strip_tags($item->getName()))); + $itemXmlObj->addChild('name', $categoryXmlObj->xmlentities($item->getName())); $itemXmlObj->addChild('code', $categoryXmlObj->xmlentities($item->getCode())); $valuesXmlObj = $itemXmlObj->addChild('values'); diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product.php index b2f54fb82b..701afbdd90 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product.php @@ -46,9 +46,9 @@ public function productToXmlObject(Mage_Catalog_Model_Product $product, $itemNod $item = Mage::getModel('xmlconnect/simplexml_element', '<' . $itemNodeName . '>'); if ($product && $product->getId()) { $item->addChild('entity_id', $product->getId()); - $item->addChild('name', $item->xmlentities(strip_tags($product->getName()))); + $item->addChild('name', $item->xmlentities($product->getName())); $item->addChild('entity_type', $product->getTypeId()); - $item->addChild('short_description', $item->xmlentities(strip_tags($product->getShortDescription()))); + $item->addChild('short_description', $item->xmlentities($product->getShortDescription())); $description = Mage::helper('xmlconnect')->htmlize($item->xmlentities($product->getDescription())); $item->addChild('description', $description); $item->addChild('link', $product->getProductUrl()); @@ -61,15 +61,14 @@ public function productToXmlObject(Mage_Catalog_Model_Product $product, $itemNod $propertyToResizeName = 'image'; } - $icon = clone Mage::helper('catalog/image')->init($product, $propertyToResizeName) - ->resize($imageToResize); + $icon = clone Mage::helper('catalog/image')->init($product, $propertyToResizeName)->resize($imageToResize); $iconXml = $item->addChild('icon', $icon); $file = Mage::helper('xmlconnect')->urlToPath($icon); $iconXml->addAttribute('modification_time', filemtime($file)); - $item->addChild('in_stock', (int)$product->isInStock()); + $item->addChild('in_stock', (int)$product->getIsInStock()); $item->addChild('is_salable', (int)$product->isSalable()); /** * By default all products has gallery (because of collection not load gallery attribute) @@ -92,17 +91,15 @@ public function productToXmlObject(Mage_Catalog_Model_Product $product, $itemNod } if (!$product->getRatingSummary()) { - Mage::getModel('review/review') - ->getEntitySummary($product, Mage::app()->getStore()->getId()); + Mage::getModel('review/review')->getEntitySummary($product, Mage::app()->getStore()->getId()); } $item->addChild('rating_summary', round((int)$product->getRatingSummary()->getRatingSummary() / 10)); $item->addChild('reviews_count', $product->getRatingSummary()->getReviewsCount()); if ($this->getChild('product_price')) { - $this->getChild('product_price')->setProduct($product) - ->setProductXmlObj($item) - ->collectProductPrices(); + $this->getChild('product_price')->setProduct($product)->setProductXmlObj($item) + ->collectProductPrices(); } if ($this->getChild('additional_info')) { @@ -138,8 +135,7 @@ protected function _getMinimalQty($product) protected function _toHtml() { /** @var $product Mage_Catalog_Model_Product */ - $product = Mage::getModel('catalog/product') - ->setStoreId(Mage::app()->getStore()->getId()) + $product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId()) ->load($this->getRequest()->getParam('id', 0)); if (!$product) { diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Attributes.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Attributes.php index 3116c53520..6daac159e8 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Attributes.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Attributes.php @@ -40,10 +40,8 @@ class Mage_XmlConnect_Block_Catalog_Product_Attributes extends Mage_Catalog_Bloc * @param Mage_XmlConnect_Model_Simplexml_Element $productXmlObject */ public function addAdditionalData( - Mage_Catalog_Model_Product $product, - Mage_XmlConnect_Model_Simplexml_Element $productXmlObject - ) - { + Mage_Catalog_Model_Product $product, Mage_XmlConnect_Model_Simplexml_Element $productXmlObject + ) { if ($product && $productXmlObject && $product->getId()) { $this->_product = $product; $additionalData = $this->getAdditionalData(); diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Gallery.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Gallery.php index 125070591b..44c78c096e 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Gallery.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Gallery.php @@ -41,9 +41,7 @@ class Mage_XmlConnect_Block_Catalog_Product_Gallery extends Mage_XmlConnect_Bloc protected function _toHtml() { $productId = $this->getRequest()->getParam('id', null); - $product = Mage::getModel('catalog/product') - ->setStoreId(Mage::app()->getStore()->getId()) - ->load($productId); + $product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($productId); $collection = $product->getMediaGalleryImages(); $imagesNode = Mage::getModel('xmlconnect/simplexml_element', ''); @@ -55,9 +53,7 @@ protected function _toHtml() /** * Big image */ - $bigImage = $helper->init($product, 'image', $item->getFile()) - ->constrainOnly(true) - ->keepFrame(false) + $bigImage = $helper->init($product, 'image', $item->getFile())->constrainOnly(true)->keepFrame(false) ->resize(Mage::helper('xmlconnect/image')->getImageSizeForContent('product_gallery_big')); $fileNode = $imageNode->addChild('file'); @@ -72,9 +68,7 @@ protected function _toHtml() /** * Small image */ - $smallImage = $helper->init($product, 'thumbnail', $item->getFile()) - ->constrainOnly(true) - ->keepFrame(false) + $smallImage = $helper->init($product, 'thumbnail', $item->getFile())->constrainOnly(true)->keepFrame(false) ->resize(Mage::helper('xmlconnect/image')->getImageSizeForContent('product_gallery_small')); $fileNode = $imageNode->addChild('file'); diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/List.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/List.php index 985e49ce41..602028af47 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/List.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/List.php @@ -99,7 +99,6 @@ protected function _getProductCollection() if ($category && is_object($category) && $category->getId()) { $layer->setCurrentCategory($category); } - if (!$this->getNeedBlockApplyingFilters()) { $attributes = $layer->getFilterableAttributes(); /** @@ -107,10 +106,9 @@ protected function _getProductCollection() */ foreach ($attributes as $attributeItem) { $attributeCode = $attributeItem->getAttributeCode(); - $filterModel = $this->helper('xmlconnect')->getFilterByKey($attributeCode); + list($filterModel, $filterBlock) = $this->helper('xmlconnect')->getFilterByKey($attributeCode); - $filterModel->setLayer($layer) - ->setAttributeModel($attributeItem); + $filterModel->setLayer($layer)->setAttributeModel($attributeItem); $filterParam = parent::REQUEST_FILTER_PARAM_REFIX . $attributeCode; /** @@ -119,18 +117,17 @@ protected function _getProductCollection() if (isset($requestParams[$filterParam])) { $filterModel->setRequestVar($filterParam); } - $filterModel->apply($request, null); + $filterModel->apply($request, $filterBlock); $filters[] = $filterModel; } /** * Separately apply and save category filter */ - $categoryFilter = $this->helper('xmlconnect')->getFilterByKey('category'); - $filterParam = parent::REQUEST_FILTER_PARAM_REFIX . $categoryFilter->getRequestVar(); - $categoryFilter->setLayer($layer) - ->setRequestVar($filterParam) - ->apply($this->getRequest(), null); + list($categoryFilter, $categoryFilterBlock) = $this->helper('xmlconnect')->getFilterByKey('category'); + $filterParam = parent::REQUEST_FILTER_PARAM_REFIX . $categoryFilter->getRequestVar(); + $categoryFilter->setLayer($layer)->setRequestVar($filterParam) + ->apply($this->getRequest(), $categoryFilterBlock); $filters[] = $categoryFilter; $this->_collectedFilters = $filters; @@ -157,7 +154,6 @@ protected function _getProductCollection() $this->setHasProductItems(1); } $collection->getSelect()->limit($count, $offset); - $collection->setFlag('require_stock_items', true); $this->_productCollection = $collection; diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options.php index f6fd9d0a66..1d159608b7 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options.php @@ -87,7 +87,7 @@ public function getProductCustomOptionsXmlObject(Mage_Catalog_Model_Product $pro } $optionNode->addAttribute('code', $code); $optionNode->addAttribute('type', $type); - $optionNode->addAttribute('label', $xmlModel->xmlentities(strip_tags($option->getTitle()))); + $optionNode->addAttribute('label', $xmlModel->xmlentities($option->getTitle())); if ($option->getIsRequire()) { $optionNode->addAttribute('is_required', 1); } @@ -98,21 +98,20 @@ public function getProductCustomOptionsXmlObject(Mage_Catalog_Model_Product $pro $price = $option->getPrice(); if ($price) { $optionNode->addAttribute('price', Mage::helper('xmlconnect')->formatPriceForXml($price)); - $formatedPrice = Mage::app()->getStore($product->getStoreId())->formatPrice($price, false); - $optionNode->addAttribute('formated_price', $formatedPrice); + $formattedPrice = Mage::app()->getStore($product->getStoreId())->formatPrice($price, false); + $optionNode->addAttribute('formated_price', $formattedPrice); } - if ($type == self::OPTION_TYPE_CHECKBOX || - $type == self::OPTION_TYPE_SELECT) { + if ($type == self::OPTION_TYPE_CHECKBOX || $type == self::OPTION_TYPE_SELECT) { foreach ($option->getValues() as $value) { $valueNode = $optionNode->addChild('value'); $valueNode->addAttribute('code', $value->getId()); - $valueNode->addAttribute('label', $xmlModel->xmlentities(strip_tags($value->getTitle()))); + $valueNode->addAttribute('label', $xmlModel->xmlentities($value->getTitle())); - $price = Mage::helper('xmlconnect')->formatPriceForXml($value->getPrice()); - if ((float)$price != 0.00) { + if ($value->getPrice() != 0) { + $price = Mage::helper('xmlconnect')->formatPriceForXml($value->getPrice()); $valueNode->addAttribute('price', $price); - $formatedPrice = $this->_formatPriceString($price, $product); - $valueNode->addAttribute('formated_price', $formatedPrice); + $formattedPrice = $this->_formatPriceString($price, $product); + $valueNode->addAttribute('formated_price', $formattedPrice); } } } @@ -133,12 +132,9 @@ protected function _formatPriceString($price, $product) $priceIncTax = Mage::helper('tax')->getPrice($product, $price, true); if (Mage::helper('tax')->displayBothPrices() && $priceTax != $priceIncTax) { - $formatted = Mage::helper('core')->currency($priceTax, true, false) - . ' (+' - . Mage::helper('core')->currency($priceIncTax, true, false) - . ' ' - . Mage::helper('tax')->__('Incl. Tax') - . ')'; + $formatted = Mage::helper('core')->currency($priceTax, true, false) . ' (+' + . Mage::helper('core')->currency($priceIncTax, true, false) . ' ' + . Mage::helper('tax')->__('Incl. Tax') . ')'; } else { $formatted = $this->helper('core')->currency($priceTax, true, false); } @@ -201,6 +197,7 @@ protected function _toHtml() { $productId = $this->getRequest()->getParam('id', null); $product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId()); + if ($productId) { $product->load($productId); } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Bundle.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Bundle.php index 100023eccc..94ed27c17c 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Bundle.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Bundle.php @@ -27,11 +27,10 @@ /** * Bundle product options xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ - class Mage_XmlConnect_Block_Catalog_Product_Options_Bundle extends Mage_XmlConnect_Block_Catalog_Product_Options { /** @@ -43,7 +42,6 @@ class Mage_XmlConnect_Block_Catalog_Product_Options_Bundle extends Mage_XmlConne */ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObject = false) { - $xmlModel = $this->getProductCustomOptionsXmlObject($product); $optionsXmlObj = $xmlModel->options; @@ -57,8 +55,7 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj $product->getTypeInstance(true)->setStoreFilter($product->getStoreId(), $product); $optionCollection = $product->getTypeInstance(true)->getOptionsCollection($product); $selectionCollection = $product->getTypeInstance(true)->getSelectionsCollection( - $product->getTypeInstance(true)->getOptionsIds($product), - $product + $product->getTypeInstance(true)->getOptionsIds($product), $product ); $bundleOptions = $optionCollection->appendSelections($selectionCollection, false, false); if (!sizeof($bundleOptions)) { @@ -83,13 +80,11 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj } $optionNode->addAttribute('code', $code); $optionNode->addAttribute('type', $type); - $optionNode->addAttribute('label', $optionsXmlObj->xmlentities(strip_tags($_option->getTitle()))); + $optionNode->addAttribute('label', $optionsXmlObj->xmlentities($_option->getTitle())); if ($_option->getRequired()) { $optionNode->addAttribute('is_required', 1); } -// $_default = $_option->getDefaultSelection(); - foreach ($selections as $_selection) { if (!$_selection->isSaleable()) { continue; @@ -98,7 +93,7 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj $valueNode = $optionNode->addChild('value'); $valueNode->addAttribute('code', $_selection->getSelectionId()); - $valueNode->addAttribute('label', $optionsXmlObj->xmlentities(strip_tags($_selection->getName()))); + $valueNode->addAttribute('label', $optionsXmlObj->xmlentities($_selection->getName())); if (!$_option->isMultiSelection()) { if ($_selection->getSelectionCanChangeQty()) { $valueNode->addAttribute('is_qty_editable', 1); @@ -114,8 +109,6 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj )); $valueNode->addAttribute('formated_price', $this->_formatPriceString($price, $product)); } - -// $_selection->getIsDefault(); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Configurable.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Configurable.php index fc7c22f9ed..cbaaa866af 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Configurable.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Configurable.php @@ -27,11 +27,10 @@ /** * Configurable product options xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ - class Mage_XmlConnect_Block_Catalog_Product_Options_Configurable extends Mage_XmlConnect_Block_Catalog_Product_Options { /** @@ -132,13 +131,13 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj $optionNode = $optionsXmlObj->addChild('option'); $optionNode->addAttribute('code', 'super_attribute[' . $id . ']'); $optionNode->addAttribute('type', 'select'); - $optionNode->addAttribute('label', strip_tags($attribute['label'])); + $optionNode->addAttribute('label', $optionsXmlObj->xmlentities($attribute['label'])); $optionNode->addAttribute('is_required', 1); if ($isFirst) { foreach ($attribute['options'] as $option) { $valueNode = $optionNode->addChild('value'); $valueNode->addAttribute('code', $option['id']); - $valueNode->addAttribute('label', $optionsXmlObj->xmlentities(strip_tags($option['label']))); + $valueNode->addAttribute('label', $optionsXmlObj->xmlentities($option['label'])); if ((float)$option['price'] != 0.00) { $valueNode->addAttribute('price', $option['price']); $valueNode->addAttribute('formated_price', $option['formated_price']); @@ -157,7 +156,7 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj /** * Add recursively relations on each option * - * @param &Mage_XmlConnect_Model_Simplexml_Element &$valueNode value node object + * @param Mage_XmlConnect_Model_Simplexml_Element &$valueNode value node object * @param array $attributes all products attributes (options) * @param array $productIds prodcuts to search in next levels attributes * @param int $cycle @@ -188,7 +187,7 @@ protected function _prepareRecursivelyRelatedValues(&$valueNode, $attributes, $p $_valueNode = $relatedNode->addChild('value'); $_valueNode->addAttribute('code', $option['id']); - $_valueNode->addAttribute('label', $_valueNode->xmlentities(strip_tags($option['label']))); + $_valueNode->addAttribute('label', $_valueNode->xmlentities($option['label'])); if ((float)$option['price'] != 0.00) { $_valueNode->addAttribute('price', $option['price']); $_valueNode->addAttribute('formated_price', $option['formated_price']); @@ -210,7 +209,7 @@ protected function _prepareRecursivelyRelatedValues(&$valueNode, $attributes, $p * * @param Mage_Catalog_Model_Product $product * @param float|int|string $price - * @param unknown_type $isPercent + * @param bool $isPercent * @return float */ protected function _preparePrice($product, $price, $isPercent = false) diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Giftcard.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Giftcard.php index 198a9f1dbf..5aee915c91 100755 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Giftcard.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Giftcard.php @@ -27,9 +27,9 @@ /** * Gift Card product options xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Catalog_Product_Options_Giftcard extends Mage_XmlConnect_Block_Catalog_Product_Options { @@ -70,7 +70,7 @@ public function getSenderEmail() } /** - * Get preconfigured values from product + * Get pre-configured values from product * * @param $value param id * @return string @@ -145,144 +145,125 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj /** @var $optionsXmlObj Mage_XmlConnect_Model_Simplexml_Element */ $optionsXmlObj = $xmlModel->options; - if (!$product->isSaleable()) { + if (!$product->isSalable()) { return $isObject ? $xmlModel : $xmlModel->asNiceXml(); } - /** @var $test Enterprise_GiftCard_Model_Catalog_Product_Type_Giftcard */ - $giftCard = $product->getTypeInstance(true); - /** @var $priceModel Enterprise_GiftCard_Block_Catalog_Product_Price */ $priceModel = $product->getPriceModel(); /** @var $coreHelper Mage_Core_Helper_Data */ $coreHelper = Mage::helper('core'); - if ($this->isAmountAvailable($product)) { + $configValue = $this->getDefaultValue('giftcard_amount'); - $configValue = $this->getDefaultValue('giftcard_amount'); + /** + * Render fixed amounts options + */ - /** - * Render fixed amounts options - */ - if (count($amounts = $priceModel->getSortedAmounts($product))) { - $amountNode = $optionsXmlObj->addChild('fixed_amounts'); + /** @var $fixedAmountsNode Mage_XmlConnect_Model_Simplexml_Element */ + $fixedAmountsNode = $optionsXmlObj->addChild('fixed_amounts'); + if ($this->isAmountAvailable($product)) { + $amounts = $priceModel->getSortedAmounts($product); + if (count($amounts)) { foreach ($amounts as $price) { - $amount = $amountNode->addChild('amount'); + $amountNode = $fixedAmountsNode->addChild('amount'); if ($configValue == $price) { - $amount->addAttribute('selected', 1); + $amountNode->addAttribute('selected', 1); } - $amount->addAttribute( - 'price', + $amountNode->addAttribute('formatted_price', $xmlModel->xmlAttribute( $coreHelper->currency($price, true, false) - ); + )); + $amountNode->addAttribute('price', $price); } } + } - /** - * Render open amount options - */ - $openAmountNode = $optionsXmlObj->addChild('open_amount'); - if ($product->getAllowOpenAmount()) { - $openAmountNode->addAttribute('enabled', 1); - if ($configValue == 'custom') { - $openAmountNode->addAttribute( - 'selected_amount', - $this->getDefaultValue('custom_giftcard_amount') - ); - } - if ($priceModel->getMinAmount($product)) { - $minAmount = $xmlModel->xmlentities( - $coreHelper->currency( - $product->getOpenAmountMin(), - true, - false - ) - ); - } else { - $minAmount = 0; - } - $openAmountNode->addAttribute('min_amount', $minAmount); + /** + * Render open amount options + */ + /** @var $openAmountNode Mage_XmlConnect_Model_Simplexml_Element */ + $openAmountNode = $optionsXmlObj->addChild('open_amount'); + if ($product->getAllowOpenAmount()) { + $openAmountNode->addAttribute('enabled', 1); - if ($priceModel->getMaxAmount($product)) { - $maxAmount = $xmlModel->xmlentities( - $coreHelper->currency( - $product->getOpenAmountMax(), - true, - false - ) - ); - } else { - $maxAmount = 0; - } - $openAmountNode->addAttribute('max_amount', $maxAmount); + if ($configValue == 'custom') { + $openAmountNode->addAttribute('selected_amount', $this->getDefaultValue('custom_giftcard_amount')); + } + if ($priceModel->getMinAmount($product)) { + $minPrice = $product->getOpenAmountMin(); + $minAmount = $coreHelper->currency($minPrice, true, false); + } else { + $minAmount = $minPrice = 0; + } + $openAmountNode->addAttribute('formatted_min_amount', $xmlModel->xmlAttribute($minAmount)); + $openAmountNode->addAttribute('min_amount', $minPrice); + + if ($priceModel->getMaxAmount($product)) { + $maxPrice = $product->getOpenAmountMax(); + $maxAmount = $coreHelper->currency($maxPrice, true, false); } else { - $openAmountNode->addAttribute('enabled', 0); + $maxAmount = $maxPrice = 0; } + $openAmountNode->addAttribute('formatted_max_amount', $xmlModel->xmlAttribute($maxAmount)); + $openAmountNode->addAttribute('max_amount', $maxPrice); + } else { + $openAmountNode->addAttribute('enabled', 0); } /** * Render Gift Card form options */ $form = $optionsXmlObj->addCustomChild('form', null, array( - 'name' => 'giftcard-send-form', - 'method' => 'post' - ) - ); + 'name' => 'giftcard-send-form', + 'method' => 'post' + )); $senderFieldset = $form->addCustomChild('fieldset', null, array( - 'legend' => $this->__('Sender Information') - ) - ); + 'legend' => $this->__('Sender Information') + )); $senderFieldset->addField('giftcard_sender_name', 'text', array( - 'label' => Mage::helper('enterprise_giftcard')->__('Sender Name'), - 'required' => 'true', - 'value' => $this->getSenderName() - ) - ); + 'label' => Mage::helper('enterprise_giftcard')->__('Sender Name'), + 'required' => 'true', + 'value' => $this->getSenderName() + )); $recipientFieldset = $form->addCustomChild('fieldset', null, array( - 'legend' => $this->__('Recipient Information') - ) - ); + 'legend' => $this->__('Recipient Information') + )); $recipientFieldset->addField('giftcard_recipient_name', 'text', array( - 'label' => Mage::helper('enterprise_giftcard')->__('Recipient Name'), - 'required' => 'true', - 'value' => $this->getDefaultValue('giftcard_recipient_name') - ) - ); + 'label' => Mage::helper('enterprise_giftcard')->__('Recipient Name'), + 'required' => 'true', + 'value' => $this->getDefaultValue('giftcard_recipient_name') + )); if ($this->isEmailAvailable($product)) { - $senderFieldset->addField('giftcard_sender_email', 'text', array( - 'label' => Mage::helper('enterprise_giftcard')->__('Sender Email'), - 'required' => 'true', - 'value' => $this->getSenderEmail() - ) - ); + $senderFieldset->addField('giftcard_sender_email', 'email', array( + 'label' => Mage::helper('enterprise_giftcard')->__('Sender Email'), + 'required' => 'true', + 'value' => $this->getSenderEmail() + )); - $recipientFieldset->addField('giftcard_recipient_email', 'text', array( - 'label' => Mage::helper('enterprise_giftcard')->__('Recipient Email'), - 'required' => 'true', - 'value' => $this->getDefaultValue('giftcard_recipient_email') - ) - ); + $recipientFieldset->addField('giftcard_recipient_email', 'email', array( + 'label' => Mage::helper('enterprise_giftcard')->__('Recipient Email'), + 'required' => 'true', + 'value' => $this->getDefaultValue('giftcard_recipient_email') + )); } if ($this->isMessageAvailable($product)) { $messageMaxLength = (int) Mage::getStoreConfig( Enterprise_GiftCard_Model_Giftcard::XML_PATH_MESSAGE_MAX_LENGTH ); - $recipientFieldset->addField('giftcard_message', 'text', array( - 'label' => Mage::helper('enterprise_giftcard')->__('Message'), - 'required' => 'false', - 'max_length'=> $messageMaxLength, - 'value' => $this->getDefaultValue('giftcard_message') - ) - ); + $recipientFieldset->addField('giftcard_message', 'textarea', array( + 'label' => Mage::helper('enterprise_giftcard')->__('Message'), + 'required' => 'false', + 'max_length'=> $messageMaxLength, + 'value' => $this->getDefaultValue('giftcard_message') + )); } - return $isObject ? $xmlModel : $xmlModel->asNiceXml(); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Grouped.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Grouped.php index 02e095ab99..8c90bb5c32 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Grouped.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Grouped.php @@ -59,6 +59,7 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj if (!sizeof($_associatedProducts)) { return $isObject ? $xmlModel : $xmlModel->asNiceXml(); } + foreach ($_associatedProducts as $_item) { if (!$_item->isSaleable()) { continue; @@ -67,11 +68,10 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj $optionNode->addAttribute('code', 'super_group[' . $_item->getId() . ']'); $optionNode->addAttribute('type', 'product'); - $optionNode->addAttribute('label', $xmlModel->xmlentities(strip_tags($_item->getName()))); + $optionNode->addAttribute('label', $xmlModel->xmlentities($_item->getName())); $optionNode->addAttribute('is_qty_editable', 1); $optionNode->addAttribute('qty', $_item->getQty()*1); - /** * Process product price */ @@ -80,8 +80,9 @@ public function getProductOptionsXml(Mage_Catalog_Model_Product $product, $isObj } else { $productPrice = $_item->getPrice(); } - $productPrice = Mage::helper('xmlconnect')->formatPriceForXml($productPrice); - if ($productPrice != 0.00) { + + if ($productPrice != 0) { + $productPrice = Mage::helper('xmlconnect')->formatPriceForXml($productPrice); $optionNode->addAttribute('price', Mage::helper('xmlconnect')->formatPriceForXml( Mage::helper('core')->currency($productPrice, false, false) )); diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Simple.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Simple.php index 113b9b232c..a4e1d42e0e 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Simple.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Simple.php @@ -27,11 +27,10 @@ /** * Simple product options xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ - class Mage_XmlConnect_Block_Catalog_Product_Options_Simple extends Mage_XmlConnect_Block_Catalog_Product_Options { /** diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Virtual.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Virtual.php index d8cd010b93..8c6b189cd6 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Virtual.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Options/Virtual.php @@ -27,11 +27,10 @@ /** * Virtual product options xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ - class Mage_XmlConnect_Block_Catalog_Product_Options_Virtual extends Mage_XmlConnect_Block_Catalog_Product_Options { /** diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price.php index caa49b80e1..7e8fca1128 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price.php @@ -25,7 +25,7 @@ */ /** - * Product Options xml renderer + * Product price xml renderer * * @category Mage * @package Mage_XmlConnect diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Bundle.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Bundle.php index 5410ce54b1..d446da2754 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Bundle.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Bundle.php @@ -27,11 +27,10 @@ /** * Bundle product price xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ - class Mage_XmlConnect_Block_Catalog_Product_Price_Bundle extends Mage_Bundle_Block_Catalog_Product_Price { /** @@ -40,37 +39,34 @@ class Mage_XmlConnect_Block_Catalog_Product_Price_Bundle extends Mage_Bundle_Blo * @param Mage_Catalog_Model_Product $product * @param Mage_XmlConnect_Model_Simplexml_Element $item */ - public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_XmlConnect_Model_Simplexml_Element $item) - { - $this->setProduct($product) - ->setDisplayMinimalPrice(true) - ->setUseLinkForAsLowAs(false); + public function collectProductPrices( + Mage_Catalog_Model_Product $product, Mage_XmlConnect_Model_Simplexml_Element $item + ) { + $this->setProduct($product)->setDisplayMinimalPrice(true) ->setUseLinkForAsLowAs(false); $priceXmlObj = $item->addChild('price'); + /** @var $_coreHelper Mage_Core_Helper_Data */ $_coreHelper = $this->helper('core'); + /** @var $_weeeHelper Mage_Weee_Helper_Data */ $_weeeHelper = $this->helper('weee'); + /** @var $_taxHelper Mage_Tax_Helper_Data */ $_taxHelper = $this->helper('tax'); - /* @var $_coreHelper Mage_Core_Helper_Data */ - /* @var $_weeeHelper Mage_Weee_Helper_Data */ - /* @var $_taxHelper Mage_Tax_Helper_Data */ $_tierPrices = $this->_getTierPrices($product); if (count($_tierPrices) > 0) { $tierPricesTextArray = array(); foreach ($_tierPrices as $_price) { - $tierPricesTextArray[] = Mage::helper('catalog')->__('Buy %1$s with %2$s discount each', $_price['price_qty'], ' '.($_price['price']*1).'%'); + $discount = ' ' . ($_price['price'] * 1) . '%'; + $tierPricesTextArray[] = $this->__('Buy %1$s with %2$s discount each', $_price['price_qty'], $discount); } - $item->addChild('price_tier', implode("\n", $tierPricesTextArray)); + $item->addChild('price_tier', implode(PHP_EOL, $tierPricesTextArray)); } - list($_minimalPrice, $_maximalPrice) = $product->getPriceModel()->getPrices($product); - $_id = $product->getId(); $_weeeTaxAmount = 0; - $_minimalPriceTax = $_taxHelper->getPrice($product, $_minimalPrice); $_minimalPriceInclTax = $_taxHelper->getPrice($product, $_minimalPrice, true); @@ -84,15 +80,19 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $_minimalPriceInclTax += $_weeeTaxAmount; } - if ($_weeeHelper->typeOfDisplay($product, array(1,2,4))) { + if ($_weeeHelper->typeOfDisplay($product, array(1, 2, 4))) { $_weeeTaxAttributes = $_weeeHelper->getProductWeeeAttributesForDisplay($product); } } if ($product->getPriceView()) { if ($_taxHelper->displayBothPrices()) { - $priceXmlObj->addAttribute('as_low_as_excluding_tax', $_coreHelper->currency($_minimalPriceTax, true, false)); - if ($_weeeTaxAmount && $product->getPriceType() == 1 && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4))) { + $priceXmlObj->addAttribute( + 'as_low_as_excluding_tax', $_coreHelper->currency($_minimalPriceTax, true, false) + ); + if ($_weeeTaxAmount && $product->getPriceType() == 1 + && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4)) + ) { $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); @@ -103,14 +103,24 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $amount = $_weeeTaxAttribute->getAmount(); } $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($amount, true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($amount, true, false) + ); } } - $priceXmlObj->addAttribute('as_low_as_including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false)); + $priceXmlObj->addAttribute( + 'as_low_as_including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false) + ); } else { - $priceXmlObj->addAttribute('as_low_as', $_coreHelper->currency($_minimalPriceTax, true, false)); - if ($_weeeTaxAmount && $product->getPriceType() == 1 && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4))) { + $priceXmlObj->addAttribute( + 'as_low_as', $_coreHelper->currency($_minimalPriceTax, true, false) + ); + if ($_weeeTaxAmount && $product->getPriceType() == 1 + && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4)) + ) { $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); @@ -121,12 +131,18 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $amount = $_weeeTaxAttribute->getAmount(); } $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($amount, true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($amount, true, false) + ); } } if ($_weeeHelper->typeOfDisplay($product, 2) && $_weeeTaxAmount) { - $priceXmlObj->addAttribute('as_low_as_including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false)); + $priceXmlObj->addAttribute( + 'as_low_as_including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false) + ); } } /** @@ -135,8 +151,12 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X } else { if ($_minimalPrice <> $_maximalPrice) { if ($_taxHelper->displayBothPrices()) { - $priceXmlObj->addAttribute('from_excluding_tax', $_coreHelper->currency($_minimalPriceTax, true, false)); - if ($_weeeTaxAmount && $product->getPriceType() == 1 && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4))) { + $priceXmlObj->addAttribute( + 'from_excluding_tax', $_coreHelper->currency($_minimalPriceTax, true, false) + ); + if ($_weeeTaxAmount && $product->getPriceType() == 1 + && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4)) + ) { $weeeXmlObj = $priceXmlObj->addChild('from_weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); @@ -147,14 +167,22 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $amount = $_weeeTaxAttribute->getAmount(); } $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($amount, true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($amount, true, false) + ); } } - $priceXmlObj->addAttribute('from_including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false)); + $priceXmlObj->addAttribute( + 'from_including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false) + ); } else { $priceXmlObj->addAttribute('from', $_coreHelper->currency($_minimalPriceTax, true, false)); - if ($_weeeTaxAmount && $product->getPriceType() == 1 && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4))) { + if ($_weeeTaxAmount && $product->getPriceType() == 1 + && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4)) + ) { $weeeXmlObj = $priceXmlObj->addChild('from_weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); @@ -165,12 +193,16 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $amount = $_weeeTaxAttribute->getAmount(); } $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($amount, true, false)); } } if ($_weeeHelper->typeOfDisplay($product, 2) && $_weeeTaxAmount) { - $priceXmlObj->addAttribute('from_including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false)); + $priceXmlObj->addAttribute( + 'from_including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false) + ); } } @@ -188,8 +220,12 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X } if ($_taxHelper->displayBothPrices()) { - $priceXmlObj->addAttribute('to_excluding_tax', $_coreHelper->currency($_maximalPriceTax, true, false)); - if ($_weeeTaxAmount && $product->getPriceType() == 1 && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4))) { + $priceXmlObj->addAttribute( + 'to_excluding_tax', $_coreHelper->currency($_maximalPriceTax, true, false) + ); + if ($_weeeTaxAmount && $product->getPriceType() == 1 + && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4)) + ) { $weeeXmlObj = $priceXmlObj->addChild('to_weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); @@ -200,14 +236,24 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $amount = $_weeeTaxAttribute->getAmount(); } $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($amount, true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($amount, true, false) + ); } } - $priceXmlObj->addAttribute('to_including_tax', $_coreHelper->currency($_maximalPriceInclTax, true, false)); + $priceXmlObj->addAttribute( + 'to_including_tax', $_coreHelper->currency($_maximalPriceInclTax, true, false) + ); } else { - $priceXmlObj->addAttribute('to', $_coreHelper->currency($_maximalPriceTax, true, false)); - if ($_weeeTaxAmount && $product->getPriceType() == 1 && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4))) { + $priceXmlObj->addAttribute( + 'to', $_coreHelper->currency($_maximalPriceTax, true, false) + ); + if ($_weeeTaxAmount && $product->getPriceType() == 1 + && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4)) + ) { $weeeXmlObj = $priceXmlObj->addChild('to_weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); @@ -218,12 +264,18 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $amount = $_weeeTaxAttribute->getAmount(); } $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($amount, true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($amount, true, false) + ); } } if ($_weeeHelper->typeOfDisplay($product, 2) && $_weeeTaxAmount) { - $priceXmlObj->addAttribute('to_including_tax', $_coreHelper->currency($_maximalPriceInclTax, true, false)); + $priceXmlObj->addAttribute( + 'to_including_tax', $_coreHelper->currency($_maximalPriceInclTax, true, false) + ); } } /** @@ -231,8 +283,12 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X */ } else { if ($_taxHelper->displayBothPrices()) { - $priceXmlObj->addAttribute('excluding_tax', $_coreHelper->currency($_minimalPriceTax, true, false)); - if ($_weeeTaxAmount && $product->getPriceType() == 1 && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4))) { + $priceXmlObj->addAttribute( + 'excluding_tax', $_coreHelper->currency($_minimalPriceTax, true, false) + ); + if ($_weeeTaxAmount && $product->getPriceType() == 1 + && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4)) + ) { $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); @@ -243,14 +299,24 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $amount = $_weeeTaxAttribute->getAmount(); } $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($amount, true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($amount, true, false) + ); } } - $priceXmlObj->addAttribute('including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false)); + $priceXmlObj->addAttribute( + 'including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false) + ); } else { - $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_minimalPriceTax, true, false)); - if ($_weeeTaxAmount && $product->getPriceType() == 1 && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4))) { + $priceXmlObj->addAttribute( + 'regular', $_coreHelper->currency($_minimalPriceTax, true, false) + ); + if ($_weeeTaxAmount && $product->getPriceType() == 1 + && $_weeeHelper->typeOfDisplay($product, array(2, 1, 4)) + ) { $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); @@ -261,12 +327,18 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $amount = $_weeeTaxAttribute->getAmount(); } $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($amount, true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($amount, true, false) + ); } } if ($_weeeHelper->typeOfDisplay($product, 2) && $_weeeTaxAmount) { - $priceXmlObj->addAttribute('including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false)); + $priceXmlObj->addAttribute( + 'including_tax', $_coreHelper->currency($_minimalPriceInclTax, true, false) + ); } } } @@ -290,15 +362,19 @@ protected function _getTierPrices($product) if (is_array($prices)) { foreach ($prices as $price) { $price['price_qty'] = $price['price_qty']*1; - $price['savePercent'] = ceil(100 - $price['price'] ); + $price['savePercent'] = ceil(100 - $price['price']); $price['formated_price'] = Mage::app()->getStore()->formatPrice( Mage::app()->getStore()->convertPrice( - Mage::helper('tax')->getPrice($product, $price['website_price'])), - false); + Mage::helper('tax')->getPrice($product, $price['website_price']) + ), + false + ); $price['formated_price_incl_tax'] = Mage::app()->getStore()->formatPrice( Mage::app()->getStore()->convertPrice( - Mage::helper('tax')->getPrice($product, $price['website_price'], true)), - false); + Mage::helper('tax')->getPrice($product, $price['website_price'], true) + ), + false + ); $res[] = $price; } } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Default.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Default.php index 63a44cffb8..33de63ad5d 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Default.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Default.php @@ -27,11 +27,10 @@ /** * Default product price xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ - class Mage_XmlConnect_Block_Catalog_Product_Price_Default extends Mage_Catalog_Block_Product_Price { /** @@ -40,37 +39,32 @@ class Mage_XmlConnect_Block_Catalog_Product_Price_Default extends Mage_Catalog_B * @param Mage_Catalog_Model_Product $product * @param Mage_XmlConnect_Model_Simplexml_Element $item */ - public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_XmlConnect_Model_Simplexml_Element $item) - { - $this->setProduct($product) - ->setDisplayMinimalPrice(true) - ->setUseLinkForAsLowAs(false); + public function collectProductPrices( + Mage_Catalog_Model_Product $product, Mage_XmlConnect_Model_Simplexml_Element $item + ) { + $this->setProduct($product)->setDisplayMinimalPrice(true)->setUseLinkForAsLowAs(false); $priceXmlObj = $item->addChild('price'); $_tierPrices = $this->_getTierPrices($product); if (count($_tierPrices) > 0) { - $tierPricesTextArray = array(); $tierPricesTextArray = $this->_getTierPricesTextArray($_tierPrices, $product); - $item->addChild('price_tier', implode("\n", $tierPricesTextArray)); + $item->addChild('price_tier', implode(PHP_EOL, $tierPricesTextArray)); } + /** @var $_coreHelper Mage_Core_Helper_Data */ $_coreHelper = $this->helper('core'); + /** @var $_weeeHelper Mage_Weee_Helper_Data */ $_weeeHelper = $this->helper('weee'); + /** @var $_taxHelper Mage_Tax_Helper_Data */ $_taxHelper = $this->helper('tax'); - /* @var $_coreHelper Mage_Core_Helper_Data */ - /* @var $_weeeHelper Mage_Weee_Helper_Data */ - /* @var $_taxHelper Mage_Tax_Helper_Data */ - - $_id = $product->getId(); - $_weeeSeparator = ''; $_simplePricesTax = ($_taxHelper->displayPriceIncludingTax() || $_taxHelper->displayBothPrices()); $_minimalPriceValue = $product->getMinimalPrice(); $_minimalPrice = $_taxHelper->getPrice($product, $_minimalPriceValue, $_simplePricesTax); if (!$product->isGrouped()) { $_weeeTaxAmount = $_weeeHelper->getAmountForDisplay($product); - if ($_weeeHelper->typeOfDisplay($product, array(1,2,4))) { + if ($_weeeHelper->typeOfDisplay($product, array(1, 2, 4))) { $_weeeTaxAmount = $_weeeHelper->getAmount($product); $_weeeTaxAttributes = $_weeeHelper->getProductWeeeAttributesForDisplay($product); } @@ -79,42 +73,62 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $_regularPrice = $_taxHelper->getPrice($product, $product->getPrice(), $_simplePricesTax); $_finalPrice = $_taxHelper->getPrice($product, $product->getFinalPrice()); $_finalPriceInclTax = $_taxHelper->getPrice($product, $product->getFinalPrice(), true); - $_weeeDisplayType = $_weeeHelper->getPriceDisplayType(); + $_weeeHelper->getPriceDisplayType(); if ($_finalPrice == $_price) { if ($_taxHelper->displayBothPrices()) { /** * Including */ if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 0)) { - $priceXmlObj->addAttribute('excluding_tax', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false)); - $priceXmlObj->addAttribute('including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute( + 'excluding_tax', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) + ); + $priceXmlObj->addAttribute( + 'including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) + ); } elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 1)) { /** * Including + Weee */ - $priceXmlObj->addAttribute('excluding_tax', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false)); - $priceXmlObj->addAttribute('including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute( + 'excluding_tax', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) + ); + $priceXmlObj->addAttribute( + 'including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) + ); $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); foreach ($_weeeTaxAttributes as $_weeeTaxAttribute) { $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false) + ); } } elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 4)) { /** * Including + Weee */ - $priceXmlObj->addAttribute('excluding_tax', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false)); - $priceXmlObj->addAttribute('including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute( + 'excluding_tax', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) + ); + $priceXmlObj->addAttribute( + 'including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) + ); $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); foreach ($_weeeTaxAttributes as $_weeeTaxAttribute) { $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency( + $_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, false + )); } } elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 2)) { /** @@ -124,13 +138,21 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X $weeeXmlObj = $priceXmlObj->addChild('weee'); foreach ($_weeeTaxAttributes as $_weeeTaxAttribute) { $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false) + ); } - $priceXmlObj->addAttribute('including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('including_tax', $_coreHelper->currency( + $_finalPriceInclTax + $_weeeTaxAmount, true, false + )); } else { - $priceXmlObj->addAttribute('excluding_tax', $_coreHelper->currency($_price, true, false)); - $priceXmlObj->addAttribute('including_tax', $_coreHelper->currency($_finalPriceInclTax, true, false)); + $priceXmlObj->addAttribute('excluding_tax', $_coreHelper->currency($_price, true, false)); + $priceXmlObj->addAttribute( + 'including_tax', $_coreHelper->currency($_finalPriceInclTax, true, false) + ); } /** * if ($_taxHelper->displayBothPrices()) { @@ -140,46 +162,67 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X * Including */ if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 0)) { - $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('regular', $_coreHelper->currency( + $_price + $_weeeTaxAmount, true, false + )); } elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 1)) { /** * Including + Weee */ - - $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('regular', $_coreHelper->currency( + $_price + $_weeeTaxAmount, true, false + )); $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); foreach ($_weeeTaxAttributes as $_weeeTaxAttribute) { $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false) + ); } } elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 4)) { /** * Including + Weee */ - $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('regular', $_coreHelper->currency( + $_price + $_weeeTaxAmount, true, false + )); $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); foreach ($_weeeTaxAttributes as $_weeeTaxAttribute) { $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency( + $_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, false + )); } } elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 2)) { /** * Excluding + Weee + Final */ - $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_price, true, false)); + $priceXmlObj->addAttribute( + 'regular', $_coreHelper->currency($_price, true, false) + ); $weeeXmlObj = $priceXmlObj->addChild('weee'); foreach ($_weeeTaxAttributes as $_weeeTaxAttribute) { $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute( + 'amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false) + ); } - $priceXmlObj->addAttribute('including_tax', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute( + 'including_tax', $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) + ); } else { $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_price, true, false)); } @@ -193,91 +236,143 @@ public function collectProductPrices(Mage_Catalog_Model_Product $product, Mage_X * Including */ if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 0)) { - $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_regularPrice + $_originalWeeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('regular', $_coreHelper->currency( + $_regularPrice + $_originalWeeeTaxAmount, true, false + )); if ($_taxHelper->displayBothPrices()) { - $priceXmlObj->addAttribute('special_excluding_tax', $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false)); - $priceXmlObj->addAttribute('special_including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('special_excluding_tax', $_coreHelper->currency( + $_finalPrice + $_weeeTaxAmount, true, false + )); + $priceXmlObj->addAttribute('special_including_tax', $_coreHelper->currency( + $_finalPriceInclTax + $_weeeTaxAmount, true, false + )); } else { - $priceXmlObj->addAttribute('special', $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('special', $_coreHelper->currency( + $_finalPrice + $_weeeTaxAmount, true, false + )); } } elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 1)) { /** * Including + Weee */ - $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_regularPrice + $_originalWeeeTaxAmount, true, false)); - $priceXmlObj->addAttribute('special_excluding_tax', $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('regular', $_coreHelper->currency( + $_regularPrice + $_originalWeeeTaxAmount, true, false + )); + $priceXmlObj->addAttribute('special_excluding_tax', $_coreHelper->currency( + $_finalPrice + $_weeeTaxAmount, true, false + )); $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); foreach ($_weeeTaxAttributes as $_weeeTaxAttribute) { $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency( + $_weeeTaxAttribute->getAmount(), true, false + )); } - $priceXmlObj->addAttribute('special_including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('special_including_tax', $_coreHelper->currency( + $_finalPriceInclTax + $_weeeTaxAmount, true, false + )); } elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 4)) { /** * Including + Weee */ - $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_regularPrice + $_originalWeeeTaxAmount, true, false)); - $priceXmlObj->addAttribute('special_excluding_tax', $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('regular', $_coreHelper->currency( + $_regularPrice + $_originalWeeeTaxAmount, true, false + )); + $priceXmlObj->addAttribute('special_excluding_tax', $_coreHelper->currency( + $_finalPrice + $_weeeTaxAmount, true, false + )); $weeeXmlObj = $priceXmlObj->addChild('weee'); $_weeeSeparator = ' + '; $weeeXmlObj->addAttribute('separator', $_weeeSeparator); foreach ($_weeeTaxAttributes as $_weeeTaxAttribute) { $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency( + $_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, false + )); } - $priceXmlObj->addAttribute('special_including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('special_including_tax', $_coreHelper->currency( + $_finalPriceInclTax + $_weeeTaxAmount, true, false + )); } elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, 2)) { /** * Excluding + Weee + Final */ $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_regularPrice, true, false)); - $priceXmlObj->addAttribute('special_excluding_tax', $_coreHelper->currency($_finalPrice, true, false)); + $priceXmlObj->addAttribute( + 'special_excluding_tax', $_coreHelper->currency($_finalPrice, true, false) + ); $weeeXmlObj = $priceXmlObj->addChild('weee'); foreach ($_weeeTaxAttributes as $_weeeTaxAttribute) { $weeeItemXmlObj = $weeeXmlObj->addChild('item'); - $weeeItemXmlObj->addAttribute('name', $weeeItemXmlObj->xmlentities(strip_tags($_weeeTaxAttribute->getName()))); - $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency($_weeeTaxAttribute->getAmount(), true, false)); + $weeeItemXmlObj->addAttribute( + 'name', $weeeItemXmlObj->xmlentities($_weeeTaxAttribute->getName()) + ); + $weeeItemXmlObj->addAttribute('amount', $_coreHelper->currency( + $_weeeTaxAttribute->getAmount(), true, false + )); } - $priceXmlObj->addAttribute('special_including_tax', $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false)); + $priceXmlObj->addAttribute('special_including_tax', $_coreHelper->currency( + $_finalPriceInclTax + $_weeeTaxAmount, true, false + )); } else { /** * Excluding */ $priceXmlObj->addAttribute('regular', $_coreHelper->currency($_regularPrice, true, false)); if ($_taxHelper->displayBothPrices()) { - $priceXmlObj->addAttribute('special_excluding_tax', $_coreHelper->currency($_finalPrice, true, false)); - $priceXmlObj->addAttribute('special_including_tax', $_coreHelper->currency($_finalPriceInclTax, true, false)); + $priceXmlObj->addAttribute( + 'special_excluding_tax', $_coreHelper->currency($_finalPrice, true, false) + ); + $priceXmlObj->addAttribute( + 'special_including_tax', $_coreHelper->currency($_finalPriceInclTax, true, false) + ); } else { - $priceXmlObj->addAttribute('special', $_coreHelper->currency($_finalPrice, true, false)); + $priceXmlObj->addAttribute( + 'special', $_coreHelper->currency($_finalPrice, true, false) + ); } } } - if ($this->getDisplayMinimalPrice() && $_minimalPriceValue && $_minimalPriceValue < $product->getFinalPrice()) { + if ($this->getDisplayMinimalPrice() + && $_minimalPriceValue + && $_minimalPriceValue < $product->getFinalPrice() + ) { $_minimalPriceDisplayValue = $_minimalPrice; + if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($product, array(0, 1, 4))) { $_minimalPriceDisplayValue = $_minimalPrice + $_weeeTaxAmount; } if (!$this->getUseLinkForAsLowAs()) { - $priceXmlObj->addAttribute('as_low_as', $_coreHelper->currency($_minimalPriceDisplayValue, true, false)); + $priceXmlObj->addAttribute('as_low_as', $_coreHelper->currency( + $_minimalPriceDisplayValue, true, false + )); } } /** * if (!$product->isGrouped()) { */ } else { - $_exclTax = $_taxHelper->getPrice($product, $_minimalPriceValue, $includingTax = null); - $_inclTax = $_taxHelper->getPrice($product, $_minimalPriceValue, $includingTax = true); + $_exclTax = $_taxHelper->getPrice($product, $_minimalPriceValue, null); + $_inclTax = $_taxHelper->getPrice($product, $_minimalPriceValue, true); if ($this->getDisplayMinimalPrice() && $_minimalPriceValue) { if ($_taxHelper->displayBothPrices()) { - $priceXmlObj->addAttribute('starting_at_excluding_tax', $_coreHelper->currency($_exclTax, true, false)); - $priceXmlObj->addAttribute('starting_at_including_tax', $_coreHelper->currency($_inclTax, true, false)); + $priceXmlObj->addAttribute('starting_at_excluding_tax', $_coreHelper->currency( + $_exclTax, true, false + )); + $priceXmlObj->addAttribute('starting_at_including_tax', $_coreHelper->currency( + $_inclTax, true, false + )); } else { $_showPrice = $_inclTax; if (!$_taxHelper->displayPriceIncludingTax()) { @@ -307,23 +402,42 @@ protected function _getTierPrices(Mage_Catalog_Model_Product $product) foreach ($prices as $price) { $price['price_qty'] = $price['price_qty']*1; if ($product->getPrice() != $product->getFinalPrice()) { - if ($price['price']<$product->getFinalPrice()) { - $price['savePercent'] = ceil(100 - (( 100/$product->getFinalPrice() ) * $price['price'] )); - $price['formated_price'] = Mage::app()->getStore()->formatPrice(Mage::app()->getStore()->convertPrice(Mage::helper('tax')->getPrice($product, $price['website_price'])), false); - $price['formated_price_incl_tax'] = Mage::app()->getStore()->formatPrice(Mage::app()->getStore()->convertPrice(Mage::helper('tax')->getPrice($product, $price['website_price'], true)), false); + if ($price['price'] < $product->getFinalPrice()) { + $price['savePercent'] = ceil(100 - ((100 / $product->getFinalPrice()) * $price['price'])); + $price['formated_price'] = Mage::app()->getStore()->formatPrice( + Mage::app()->getStore()->convertPrice( + Mage::helper('tax')->getPrice($product, $price['website_price']) + ), + false + ); + $price['formated_price_incl_tax'] = Mage::app()->getStore()->formatPrice( + Mage::app()->getStore()->convertPrice( + Mage::helper('tax')->getPrice($product, $price['website_price'], true) + ), + false + ); $res[] = $price; } } else { - if ($price['price']<$product->getPrice()) { - $price['savePercent'] = ceil(100 - (( 100/$product->getPrice() ) * $price['price'] )); - $price['formated_price'] = Mage::app()->getStore()->formatPrice(Mage::app()->getStore()->convertPrice(Mage::helper('tax')->getPrice($product, $price['website_price'])), false); - $price['formated_price_incl_tax'] = Mage::app()->getStore()->formatPrice(Mage::app()->getStore()->convertPrice(Mage::helper('tax')->getPrice($product, $price['website_price'], true)), false); + if ($price['price'] < $product->getPrice()) { + $price['savePercent'] = ceil(100 - ((100 / $product->getPrice()) * $price['price'])); + $price['formated_price'] = Mage::app()->getStore()->formatPrice( + Mage::app()->getStore()->convertPrice( + Mage::helper('tax')->getPrice($product, $price['website_price']) + ), + false + ); + $price['formated_price_incl_tax'] = Mage::app()->getStore()->formatPrice( + Mage::app()->getStore()->convertPrice( + Mage::helper('tax')->getPrice($product, $price['website_price'], true) + ), + false + ); $res[] = $price; } } } } - return $res; } @@ -332,12 +446,11 @@ protected function _getTierPrices(Mage_Catalog_Model_Product $product) * * @param array $_tierPrices * @param Mage_Catalog_Model_Product $_product - * + * * @return array */ protected function _getTierPricesTextArray($_tierPrices, $_product) { - $pricesArray = array(); if (Mage::helper('weee')->typeOfDisplay($_product, array(1, 2, 4))) { $_weeeTaxAttributes = Mage::helper('weee')->getProductWeeeAttributesForDisplay($_product); @@ -356,12 +469,11 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) } else if (Mage::helper('weee')->typeOfDisplay($_product, 1)) { $s .= $this->__('Buy %1$s for %2$s', $_price['price_qty'], $_price['formated_price_incl_weee_only']); if ($_weeeTaxAttributes) { - $s .= '('; - $s .= $this->__('%1$s incl tax.', $_price['formated_price_incl_weee']); + $s .= '(' . $this->__('%1$s incl tax.', $_price['formated_price_incl_weee']); $separator = ' + '; foreach ($_weeeTaxAttributes as $_attribute) { - $s .= $separator; - $s .= $_attribute->getName() . ': ' . Mage::helper('core')->currency($_attribute->getAmount()); + $s .= $separator . $_attribute->getName() . ': '; + $s .= Mage::helper('core')->currency($_attribute->getAmount()); } $s .= ')'; } @@ -369,12 +481,13 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) } else if (Mage::helper('weee')->typeOfDisplay($_product, 4)) { $s .= $this->__('Buy %1$s for %2$s', $_price['price_qty'], $_price['formated_price_incl_weee_only']); if ($_weeeTaxAttributes) { - $s .= '('; - $s .= $this->__('%1$s incl tax.', $_price['formated_price_incl_weee']); + $s .= '(' . $this->__('%1$s incl tax.', $_price['formated_price_incl_weee']); $separator = ' + '; foreach ($_weeeTaxAttributes as $_attribute) { - $s .= $separator; - $s .= $_attribute->getName() . ': ' . Mage::helper('core')->currency($_attribute->getAmount() + $_attribute->getTaxAmount()); + $s .= $separator . $_attribute->getName() . ': '; + $s .= Mage::helper('core')->currency( + $_attribute->getAmount() + $_attribute->getTaxAmount() + ); } $s .= ')'; } @@ -384,10 +497,10 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) if ($_weeeTaxAttributes) { $s .= '('; foreach ($_weeeTaxAttributes as $_attribute) { - $s .= $_attribute->getName() . ': ' . Mage::helper('core')->currency($_attribute->getAmount()); + $s .= $_attribute->getName() . ': '; + $s .= Mage::helper('core')->currency($_attribute->getAmount()); } - $s .= $this->__('Total incl. Tax: %1$s', $_price['formated_price_incl_weee']); - $s .= ')'; + $s .= $this->__('Total incl. Tax: %1$s', $_price['formated_price_incl_weee']) . ')'; } $s .= $this->__('each'); } else { @@ -403,8 +516,8 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) $s .= '('; $separator = ''; foreach ($_weeeTaxAttributes as $_attribute) { - $s .= $separator; - $s .= $_attribute->getName() . ': ' . Mage::helper('core')->currency($_attribute->getAmount()); + $s .= $separator . $_attribute->getName() . ': '; + $s .= Mage::helper('core')->currency($_attribute->getAmount()); $separator = ' + '; } $s .= ')'; @@ -416,8 +529,10 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) $s .= '('; $separator = ''; foreach ($_weeeTaxAttributes as $_attribute) { - $s .= $separator; - $s .= $_attribute->getName() . ': ' . Mage::helper('core')->currency($_attribute->getAmount() + $_attribute->getTaxAmount()); + $s .= $separator . $_attribute->getName() . ': '; + $s .= Mage::helper('core')->currency( + $_attribute->getAmount() + $_attribute->getTaxAmount() + ); $separator = ' + '; } $s .= ')'; @@ -428,10 +543,10 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) if ($_weeeTaxAttributes) { $s .= '('; foreach ($_weeeTaxAttributes as $_attribute) { - $s .= $_attribute->getName() . ': ' . Mage::helper('core')->currency($_attribute->getAmount()); + $s .= $_attribute->getName() . ': '; + $s .= Mage::helper('core')->currency($_attribute->getAmount()); } - $s .= $this->__('Total incl. Tax: %1$s', $_price['formated_price_incl_weee']); - $s .= ')'; + $s .= $this->__('Total incl. Tax: %1$s', $_price['formated_price_incl_weee']) . ')'; } $s .= $this->__('each'); } else { @@ -446,8 +561,8 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) $s .= '('; $separator = ''; foreach ($_weeeTaxAttributes as $_attribute) { - $s .= $separator; - $s .= $_attribute->getName() . ': ' . Mage::helper('core')->currency($_attribute->getAmount()); + $s .= $separator . $_attribute->getName() . ': '; + $s .= Mage::helper('core')->currency($_attribute->getAmount()); $separator = ' + '; } $s .= ')'; @@ -459,8 +574,10 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) $s .= '('; $separator = ''; foreach ($_weeeTaxAttributes as $_attribute) { - $s .= $separator; - $s .= $_attribute->getName() . ': ' . Mage::helper('core')->currency($_attribute->getAmount() + $_attribute->getTaxAmount()); + $s .= $separator . $_attribute->getName() . ': '; + $s .= Mage::helper('core')->currency( + $_attribute->getAmount() + $_attribute->getTaxAmount() + ); $separator = ' + '; } $s .= ')'; @@ -471,10 +588,10 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) if ($_weeeTaxAttributes) { $s .= '('; foreach ($_weeeTaxAttributes as $_attribute) { - $s .= $_attribute->getName() . ': ' . Mage::helper('core')->currency($_attribute->getAmount()); + $s .= $_attribute->getName() . ': '; + $s .= Mage::helper('core')->currency($_attribute->getAmount()); } - $s .= $this->__('Total incl. Tax: %1$s', $_price['formated_price_incl_weee_only']); - $s .= ')'; + $s .= $this->__('Total incl. Tax: %1$s', $_price['formated_price_incl_weee_only']) . ')'; } $s .= $this->__('each'); } else { @@ -483,8 +600,13 @@ protected function _getTierPricesTextArray($_tierPrices, $_product) } } if (!$_product->isGrouped()) { - if (($_product->getPrice() == $_product->getFinalPrice() && $_product->getPrice() > $_price['price']) - || ($_product->getPrice() != $_product->getFinalPrice() && $_product->getFinalPrice() > $_price['price'])) { + $condition1 = ($_product->getPrice() == $_product->getFinalPrice() + && $_product->getPrice() > $_price['price']); + + $condition2 = ($_product->getPrice() != $_product->getFinalPrice() + && $_product->getFinalPrice() > $_price['price']); + + if ($condition1 || $condition2) { $s .= ' ' . $this->__('and') . ' ' . $this->__('save') . ' ' . $_price['savePercent'] . '%'; } } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Giftcard.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Giftcard.php index 3219bf68ef..5924e86c9d 100755 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Giftcard.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Price/Giftcard.php @@ -27,9 +27,9 @@ /** * Giftcard product price xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Catalog_Product_Price_Giftcard extends Mage_Bundle_Block_Catalog_Product_Price { @@ -70,24 +70,19 @@ public function getMaxAmount($product = null) public function collectProductPrices( Mage_Catalog_Model_Product $product, Mage_XmlConnect_Model_Simplexml_Element $item - ) - { + ) { $this->setProduct($product); if ($product->getCanShowPrice() !== false) { $priceXmlObj = $item->addChild('price'); if (($_min = $this->getMinAmount()) && ($_max = $this->getMaxAmount()) && ($_min == $_max)) { - $priceXmlObj->addAttribute( - 'regular', - Mage::helper('core')->currency($_min, true, false) - ); + $priceXmlObj->addAttribute('regular', Mage::helper('core')->currency($_min, true, false)); } elseif (($_min = $this->getMinAmount()) && $_min != 0) { $priceXmlObj->addAttribute( 'regular', - Mage::helper('enterprise_giftcard')->__('From') - . ': ' - . Mage::helper('core')->currency($_min, true, false) + Mage::helper('enterprise_giftcard')->__('From') . ': ' + . Mage::helper('core')->currency($_min, true, false) ); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Related.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Related.php index c57fb3adef..5a15f6d6a0 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Related.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Related.php @@ -41,25 +41,56 @@ class Mage_XmlConnect_Block_Catalog_Product_Related extends Mage_XmlConnect_Bloc */ public function getRelatedProductsXmlObj() { + /** @var $relatedXmlObj Mage_XmlConnect_Model_Simplexml_Element */ $relatedXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); - if ($this->getParentBlock()->getProduct()->getId() > 0) { - $collection = $this->_getProductCollection(); - if (!$collection) { - return $relatedXmlObj; - } - foreach ($collection->getItems() as $product) { - $productXmlObj = $this->productToXmlObject($product); - if ($productXmlObj) { - if ($this->getParentBlock()->getChild('product_price')) { - $this->getParentBlock()->getChild('product_price')->setProduct($product) - ->setProductXmlObj($productXmlObj) - ->collectProductPrices(); - } - $relatedXmlObj->appendChild($productXmlObj); + + $productObj = $this->getParentBlock()->getProduct(); + + if (is_object(Mage::getConfig()->getNode('modules/Enterprise_TargetRule'))) { + Mage::register('product', $productObj); + + $productBlock = $this->getLayout()->addBlock( + 'enterprise_targetrule/catalog_product_list_related', 'relatedProducts' + ); + + $collection = $productBlock->getItemCollection(); + } else { + if ($productObj->getId() > 0) { + $collection = $this->_getProductCollection(); + if (!$collection) { + return $relatedXmlObj; } + $collection = $collection->getItems(); } } + $this->_addProductXmlObj($relatedXmlObj, $collection); + + return $relatedXmlObj; + } + + /** + * Add related products info to xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $relatedXmlObj + * @param array $collection + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + protected function _addProductXmlObj(Mage_XmlConnect_Model_Simplexml_Element $relatedXmlObj, $collection) + { + foreach ($collection as $product) { + $productXmlObj = $this->productToXmlObject($product); + + if (!$productXmlObj) { + continue; + } + + if ($this->getParentBlock()->getChild('product_price')) { + $this->getParentBlock()->getChild('product_price')->setProduct($product) + ->setProductXmlObj($productXmlObj)->collectProductPrices(); + } + $relatedXmlObj->appendChild($productXmlObj); + } return $relatedXmlObj; } @@ -87,7 +118,6 @@ protected function _getProductCollection() * Add rating and review summary, image attribute, apply sort params */ $this->_prepareCollection($collection); - $this->_productCollection = $collection; } return $this->_productCollection; diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Review.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Review.php index 58f067be56..8b196ccbfb 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Review.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Review.php @@ -52,8 +52,8 @@ public function reviewToXmlObject(Mage_Review_Model_Review $review, $itemNodeNam if ($review->getId()) { $item->addChild('review_id', $review->getId()); $item->addChild('created_at', $this->formatDate($review->getCreatedAt())); - $item->addChild('title', $item->xmlentities(strip_tags($review->getTitle()))); - $item->addChild('nickname', $item->xmlentities(strip_tags($review->getNickname()))); + $item->addChild('title', $item->xmlentities($review->getTitle())); + $item->addChild('nickname', $item->xmlentities($review->getNickname())); $detail = $item->xmlentities($review->getDetail()); if ($itemNodeName == 'item') { $remainder = ''; @@ -72,7 +72,6 @@ public function reviewToXmlObject(Mage_Review_Model_Review $review, $itemNodeNam if ($rating) { $item->addChild('rating_votes', $rating); } - } return $item; } @@ -87,5 +86,4 @@ protected function _toHtml() $review = Mage::getModel('review/review')->load((int)$this->getRequest()->getParam('id', 0)); return $this->reviewToXmlObject($review, 'review')->asNiceXml(); } - } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Review/List.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Review/List.php index 03fe02756a..9ed4353766 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Review/List.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Review/List.php @@ -48,7 +48,7 @@ class Mage_XmlConnect_Block_Catalog_Product_Review_List extends Mage_XmlConnect_ public function getReviewsXmlObject() { $reviewsXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); - $collection = $this->_getReviewCollection(); + $collection = $this->_getReviewCollection(); if (!$collection) { return $reviewsXmlObj; @@ -78,10 +78,8 @@ protected function _getReviewCollection() } /** @var $collection Mage_Review_Model_Mysql4_Review_Collection */ $collection = Mage::getResourceModel('review/review_collection') - ->addEntityFilter('product', $product->getId()) - ->addStoreFilter(Mage::app()->getStore()->getId()) - ->addStatusFilter('approved') - ->setDateOrder(); + ->addEntityFilter('product', $product->getId())->addStoreFilter(Mage::app()->getStore()->getId()) + ->addStatusFilter('approved')->setDateOrder(); /** * Apply offset and count @@ -110,5 +108,4 @@ protected function _toHtml() return $this->getReviewsXmlObject()->asNiceXml(); } - } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Search.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Search.php index 10442d6177..a782092bbd 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Search.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Search.php @@ -35,8 +35,8 @@ class Mage_XmlConnect_Block_Catalog_Search extends Mage_XmlConnect_Block_Catalog { /** * Search results xml renderer - * XML also contains filters that can be apply (accorfingly already applyed filters and search query) - * and sort fields + * XML also contains filters that can be apply (accorfingly already applyed filters + * and search query) and sort fields * * @return string */ @@ -48,15 +48,15 @@ protected function _toHtml() $helper = Mage::helper('catalogsearch'); if (method_exists($helper, 'getEngine')) { $engine = Mage::helper('catalogsearch')->getEngine(); - $isLayeredNavigationAllowed = ($engine instanceof Varien_Object) - ? $engine->isLeyeredNavigationAllowed() - : true; + if ($engine instanceof Varien_Object) { + $isLayeredNavigationAllowed = $engine->isLeyeredNavigationAllowed(); + } else { + $isLayeredNavigationAllowed = true; + } } else { $isLayeredNavigationAllowed = true; } - $request = $this->getRequest(); - $requestParams = $request->getParams(); $hasMoreProductItems = 0; /** @@ -66,8 +66,7 @@ protected function _toHtml() if ($productListBlock) { $layer = Mage::getSingleton('catalogsearch/layer'); $productsXmlObj = $productListBlock->setLayer($layer) - ->setNeedBlockApplyingFilters(!$isLayeredNavigationAllowed) - ->getProductsXmlObject(); + ->setNeedBlockApplyingFilters(!$isLayeredNavigationAllowed)->getProductsXmlObject(); $searchXmlObject->appendChild($productsXmlObj); $hasMoreProductItems = (int)$productListBlock->getHasProductItems(); } @@ -78,10 +77,11 @@ protected function _toHtml() * Filters */ $showFiltersAndOrders = (bool) count($productsXmlObj); - $reguest = $this->getRequest(); - foreach ($reguest->getParams() as $key => $value) { - if (0 === strpos($key, parent::REQUEST_SORT_ORDER_PARAM_REFIX) || - 0 === strpos($key, parent::REQUEST_FILTER_PARAM_REFIX)) { + $requestParams = $this->getRequest()->getParams(); + foreach ($requestParams as $key => $value) { + if (0 === strpos($key, parent::REQUEST_SORT_ORDER_PARAM_REFIX) + || 0 === strpos($key, parent::REQUEST_FILTER_PARAM_REFIX) + ) { $showFiltersAndOrders = false; break; } @@ -107,7 +107,9 @@ protected function _toHtml() } $value = $values->addChild('value'); $value->addChild('id', $valueItem->getValueString()); - $value->addChild('label', $searchXmlObject->xmlentities(strip_tags($valueItem->getLabel()))); + $value->addChild( + 'label', $searchXmlObject->xmlentities(strip_tags($valueItem->getLabel())) + ); $value->addChild('count', $count); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Search/Suggest.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Search/Suggest.php index b57cd4bc20..d35c133214 100644 --- a/app/code/core/Mage/XmlConnect/Block/Catalog/Search/Suggest.php +++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Search/Suggest.php @@ -33,6 +33,9 @@ */ class Mage_XmlConnect_Block_Catalog_Search_Suggest extends Mage_CatalogSearch_Block_Autocomplete { + /** + * Suggest item separator + */ const SUGGEST_ITEM_SEPARATOR = '::sep::'; /** @@ -49,16 +52,14 @@ protected function _toHtml() } $suggestData = $this->getSuggestData(); - if (!($count = count($suggestData))) { + if (!count($suggestData)) { return $suggestXmlObj->asNiceXml(); } $items = ''; foreach ($suggestData as $item) { - $items .= $suggestXmlObj->xmlentities(strip_tags($item['title'])) - . self::SUGGEST_ITEM_SEPARATOR - . (int)$item['num_of_results'] - . self::SUGGEST_ITEM_SEPARATOR; + $items .= $suggestXmlObj->xmlentities(strip_tags($item['title'])) . self::SUGGEST_ITEM_SEPARATOR + . (int)$item['num_of_results'] . self::SUGGEST_ITEM_SEPARATOR; } $suggestXmlObj = Mage::getModel('xmlconnect/simplexml_element', '' . $items . ''); diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Billing.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Billing.php index 81b4c065bd..8d5b5c7b7e 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Billing.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Billing.php @@ -54,7 +54,9 @@ protected function _toHtml() $item->addAttribute('selected', 1); } $this->getChild('address_list')->prepareAddressData($address, $item); - $item->addChild('address_line', $billingXmlObj->xmlentities($address->format('oneline'))); + $item->addChild( + 'address_line', $billingXmlObj->xmlentities($address->format('oneline')) + ); } return $billingXmlObj->asNiceXml(); diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Form.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Form.php index 3ced72cc06..8e1cc2d555 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Form.php @@ -27,9 +27,9 @@ /** * Customer address form xml renderer for onepage checkout * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Checkout_Address_Form extends Mage_Core_Block_Template { @@ -45,81 +45,68 @@ protected function _toHtml() $xmlModel->addAttribute('name', 'address_form'); $xmlModel->addAttribute('method', 'post'); - if ($this->getType() == 'shipping' || $this->getType() == 'billing') { - $addressType = $this->getType(); - } else { + $addressType = $this->getType(); + if (!$addressType) { $addressType = 'billing'; } - $isAllowedGuestCheckout = Mage::getSingleton('checkout/session') - ->getQuote() - ->isAllowedGuestCheckout(); + $isAllowedGuestCheckout = Mage::getSingleton('checkout/session')->getQuote()->isAllowedGuestCheckout(); $countries = $this->_getCountryOptions(); - $xmlModel->addField($addressType.'[firstname]', 'text', array( - 'label' => $this->__('First Name'), - 'required' => 'true', - 'value' => '' - ) - ); - - $xmlModel->addField($addressType.'[lastname]', 'text', array( - 'label' => $this->__('Last Name'), - 'required' => 'true', - 'value' => '' - ) - ); - - $xmlModel->addField($addressType.'[company]', 'text', array( - 'label' => $this->__('Company'), - 'required' => 'true', - 'value' => '' - ) - ); - - if ($isAllowedGuestCheckout - && !Mage::getSingleton('customer/session')->isLoggedIn() + $xmlModel->addField($addressType . '[firstname]', 'text', array( + 'label' => $this->__('First Name'), + 'required' => 'true', + 'value' => '' + )); + + $xmlModel->addField($addressType . '[lastname]', 'text', array( + 'label' => $this->__('Last Name'), + 'required' => 'true', + 'value' => '' + )); + + $xmlModel->addField($addressType . '[company]', 'text', array( + 'label' => $this->__('Company'), + 'required' => 'true', + 'value' => '' + )); + + if ($isAllowedGuestCheckout && !Mage::getSingleton('customer/session')->isLoggedIn() && $addressType == 'billing' ) { - $emailField = $xmlModel->addField($addressType.'[email]', 'text', array( - 'label' => $this->__('Email Address'), - 'required' => 'true', - 'value' => '' - ) - ); + $emailField = $xmlModel->addField($addressType . '[email]', 'text', array( + 'label' => $this->__('Email Address'), + 'required' => 'true', + 'value' => '' + )); $emailValidator = $emailField->addChild('validators')->addChild('validator'); $emailValidator->addAttribute('type', 'email'); $emailValidator->addAttribute('message', $this->__('Wrong email format')); } - $xmlModel->addField($addressType.'[street][]', 'text', array( - 'label' => $this->__('Address'), - 'required' => 'true', - 'value' => '' - ) - ); - - $xmlModel->addField($addressType.'[street][]', 'text', array( - 'label' => $this->__('Address 2'), - 'value' => '' - ) - ); - - $xmlModel->addField($addressType.'[city]', 'text', array( - 'label' => $this->__('City'), - 'required' => 'true', - 'value' => '' - ) - ); - - $countryOptionsXml = $xmlModel->addField($addressType.'[country_id]', 'select', array( - 'label' => $this->__('Country'), - 'required' => 'true', - 'value' => '' - ) - ) - ->addChild('values'); + $xmlModel->addField($addressType . '[street][]', 'text', array( + 'label' => $this->__('Address'), + 'required' => 'true', + 'value' => '' + )); + + $xmlModel->addField($addressType . '[street][]', 'text', array( + 'label' => $this->__('Address 2'), + 'value' => '' + )); + + $xmlModel->addField($addressType . '[city]', 'text', array( + 'label' => $this->__('City'), + 'required' => 'true', + 'value' => '' + )); + + $countryOptionsXml = $xmlModel->addField($addressType . '[country_id]', 'select', array( + 'label' => $this->__('Country'), + 'required' => 'true', + 'value' => '' + ))->addChild('values'); foreach ($countries as $data) { $regions = array(); @@ -130,15 +117,11 @@ protected function _toHtml() $regionStr = (!empty($regions) ? 'region_id' : 'region'); - $countryXml = $countryOptionsXml->addCustomChild('item', null, array( - 'relation' => $regionStr - ) - ); + $countryXml = $countryOptionsXml->addCustomChild('item', null, array('relation' => $regionStr)); $countryXml->addCustomChild('label', (string)$data['label']); $countryXml->addCustomChild('value', (string)$data['value']); if (!empty($regions)) { $regionXml = $countryXml->addChild('regions'); - foreach ($regions as $_data) { $regionItemXml = $regionXml->addChild('region_item'); $regionItemXml->addCustomChild('label', (string)$_data['label']); @@ -147,43 +130,37 @@ protected function _toHtml() } } - $xmlModel->addField($addressType.'[region]', 'text', array( - 'label' => $this->__('State/Province'), - 'value' => '' - ) - ); - - $xmlModel->addField($addressType.'[region_id]', 'select', array( - 'label' => $this->__('State/Province'), - 'required' => 'true', - 'value' => '' - ) - ); - - $xmlModel->addField($addressType.'[postcode]', 'text', array( - 'label' => $this->__('Zip/Postal Code'), - 'required' => 'true', - 'value' => '' - ) - ); - - $xmlModel->addField($addressType.'[telephone]', 'text', array( - 'label' => $this->__('Telephone'), - 'required' => 'true', - 'value' => '' - ) - ); - - $xmlModel->addField($addressType.'[fax]', 'text', array( - 'label' => $this->__('Fax'), - 'value' => '' - ) - ); - - $xmlModel->addField($addressType.'[save_in_address_book]', 'checkbox', array( - 'label' => $this->__('Save in address book'), - ) - ); + $xmlModel->addField($addressType . '[region]', 'text', array( + 'label' => $this->__('State/Province'), + 'value' => '' + )); + + $xmlModel->addField($addressType . '[region_id]', 'select', array( + 'label' => $this->__('State/Province'), + 'required' => 'true', + 'value' => '' + )); + + $xmlModel->addField($addressType . '[postcode]', 'text', array( + 'label' => $this->__('Zip/Postal Code'), + 'required' => 'true', + 'value' => '' + )); + + $xmlModel->addField($addressType . '[telephone]', 'text', array( + 'label' => $this->__('Telephone'), + 'required' => 'true', + 'value' => '' + )); + + $xmlModel->addField($addressType . '[fax]', 'text', array( + 'label' => $this->__('Fax'), + 'value' => '' + )); + + $xmlModel->addField($addressType . '[save_in_address_book]', 'checkbox', array( + 'label' => $this->__('Save in address book'), + )); return $xmlModel->asNiceXml(); } @@ -196,12 +173,12 @@ protected function _toHtml() */ protected function _getRegionOptions($countryId) { - $cacheKey = 'DIRECTORY_REGION_SELECT_STORE'.Mage::app()->getStore()->getId().$countryId; - if (Mage::app()->useCache('config') && $cache = Mage::app()->loadCache($cacheKey)) { + $cacheKey = 'DIRECTORY_REGION_SELECT_STORE' . Mage::app()->getStore()->getId() . $countryId; + $cache = Mage::app()->loadCache($cacheKey); + if (Mage::app()->useCache('config') && $cache) { $options = unserialize($cache); } else { - $collection = Mage::getModel('directory/region')->getResourceCollection() - ->addCountryFilter($countryId) + $collection = Mage::getModel('directory/region')->getResourceCollection()->addCountryFilter($countryId) ->load(); $options = $collection->toOptionArray(); if (Mage::app()->useCache('config')) { @@ -218,13 +195,13 @@ protected function _getRegionOptions($countryId) */ protected function _getCountryOptions() { - $cacheKey = 'DIRECTORY_COUNTRY_SELECT_STORE_'.Mage::app()->getStore()->getCode(); - if (Mage::app()->useCache('config') && $cache = Mage::app()->loadCache($cacheKey)) { + $cacheKey = 'DIRECTORY_COUNTRY_SELECT_STORE_' . Mage::app()->getStore()->getCode(); + $cache = Mage::app()->loadCache($cacheKey); + if (Mage::app()->useCache('config') && $cache) { $options = unserialize($cache); } else { /** @var $collection Mage_Directory_Model_Mysql4_Country_Collection */ - $collection = Mage::getModel('directory/country')->getResourceCollection() - ->loadByStore(); + $collection = Mage::getModel('directory/country')->getResourceCollection()->loadByStore(); $options = $collection->toOptionArray(false); if (Mage::app()->useCache('config')) { Mage::app()->saveCache(serialize($options), $cacheKey, array('config')); diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Agreements.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Agreements.php index ae42a039b9..c5f667e6d9 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Agreements.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Agreements.php @@ -48,7 +48,7 @@ protected function _toHtml() if (!$agreement->getIsHtml()) { $content = nl2br(strip_tags($content)); } - $agreementText = $agreementsXmlObj->xmlentities(strip_tags($agreement->getCheckboxText())); + $agreementText = $agreementsXmlObj->xmlentities($agreement->getCheckboxText()); $itemXmlObj->addChild('label', $agreementText); $itemXmlObj->addChild('content', $content); $itemXmlObj->addChild('code', 'agreement[' . $agreement->getId() . ']'); diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Order/Review/Info.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Order/Review/Info.php index 543718ecd6..cab02fc13b 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Order/Review/Info.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Order/Review/Info.php @@ -55,7 +55,7 @@ protected function _toHtml() $itemXml->addChild('entity_id', $item->getProduct()->getId()); $itemXml->addChild('entity_type', $type); $itemXml->addChild('item_id', $item->getId()); - $itemXml->addChild('name', $itemsXmlObj->xmlentities(strip_tags($renderer->getProductName()))); + $itemXml->addChild('name', $itemsXmlObj->xmlentities($renderer->getProductName())); $itemXml->addChild('qty', $renderer->getQty()); $icon = $renderer->getProductThumbnail()->resize( Mage::helper('xmlconnect/image')->getImageSizeForContent('product_small') @@ -73,8 +73,7 @@ protected function _toHtml() if ($this->helper('tax')->displayCartPriceExclTax() || $this->helper('tax')->displayCartBothPrices()) { $typeOfDisplay = Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales'); if ($typeOfDisplay && $item->getWeeeTaxAppliedAmount()) { - $exclPrice = $item->getCalculationPrice() - + $item->getWeeeTaxAppliedAmount() + $exclPrice = $item->getCalculationPrice() + $item->getWeeeTaxAppliedAmount() + $item->getWeeeTaxDisposition(); } else { $exclPrice = $item->getCalculationPrice(); @@ -92,28 +91,28 @@ protected function _toHtml() } $exclPrice = Mage::helper('xmlconnect')->formatPriceForXml($exclPrice); - $formatedExclPrice = $quote->getStore()->formatPrice($exclPrice, false); + $formattedExclPrice = $quote->getStore()->formatPrice($exclPrice, false); $inclPrice = Mage::helper('xmlconnect')->formatPriceForXml($inclPrice); - $formatedInclPrice = $quote->getStore()->formatPrice($inclPrice, false); + $formattedInclPrice = $quote->getStore()->formatPrice($inclPrice, false); $priceXmlObj = $itemXml->addChild('price'); - $formatedPriceXmlObj = $itemXml->addChild('formated_price'); + $formattedPriceXmlObj = $itemXml->addChild('formated_price'); if ($this->helper('tax')->displayCartBothPrices()) { $priceXmlObj->addAttribute('excluding_tax', $exclPrice); $priceXmlObj->addAttribute('including_tax', $inclPrice); - $formatedPriceXmlObj->addAttribute('excluding_tax', $formatedExclPrice); - $formatedPriceXmlObj->addAttribute('including_tax', $formatedInclPrice); + $formattedPriceXmlObj->addAttribute('excluding_tax', $formattedExclPrice); + $formattedPriceXmlObj->addAttribute('including_tax', $formattedInclPrice); } else { if ($this->helper('tax')->displayCartPriceExclTax()) { $priceXmlObj->addAttribute('regular', $exclPrice); - $formatedPriceXmlObj->addAttribute('regular', $formatedExclPrice); + $formattedPriceXmlObj->addAttribute('regular', $formattedExclPrice); } if ($this->helper('tax')->displayCartPriceInclTax()) { $priceXmlObj->addAttribute('regular', $inclPrice); - $formatedPriceXmlObj->addAttribute('regular', $formatedInclPrice); + $formattedPriceXmlObj->addAttribute('regular', $formattedInclPrice); } } @@ -124,8 +123,7 @@ protected function _toHtml() if ($this->helper('tax')->displayCartPriceExclTax() || $this->helper('tax')->displayCartBothPrices()) { $typeOfDisplay = Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales'); if ($typeOfDisplay && $item->getWeeeTaxAppliedAmount()) { - $exclPrice = $item->getRowTotal() - + $item->getWeeeTaxAppliedRowAmount() + $exclPrice = $item->getRowTotal() + $item->getWeeeTaxAppliedRowAmount() + $item->getWeeeTaxRowDisposition(); } else { $exclPrice = $item->getRowTotal(); @@ -143,28 +141,28 @@ protected function _toHtml() } $exclPrice = Mage::helper('xmlconnect')->formatPriceForXml($exclPrice); - $formatedExclPrice = $quote->getStore()->formatPrice($exclPrice, false); + $formattedExclPrice = $quote->getStore()->formatPrice($exclPrice, false); $inclPrice = Mage::helper('xmlconnect')->formatPriceForXml($inclPrice); - $formatedInclPrice = $quote->getStore()->formatPrice($inclPrice, false); + $formattedInclPrice = $quote->getStore()->formatPrice($inclPrice, false); $subtotalPriceXmlObj = $itemXml->addChild('subtotal'); - $subtotalFormatedPriceXmlObj = $itemXml->addChild('formated_subtotal'); + $subtotalFormattedPriceXmlObj = $itemXml->addChild('formated_subtotal'); if ($this->helper('tax')->displayCartBothPrices()) { $subtotalPriceXmlObj->addAttribute('excluding_tax', $exclPrice); $subtotalPriceXmlObj->addAttribute('including_tax', $inclPrice); - $subtotalFormatedPriceXmlObj->addAttribute('excluding_tax', $formatedExclPrice); - $subtotalFormatedPriceXmlObj->addAttribute('including_tax', $formatedInclPrice); + $subtotalFormattedPriceXmlObj->addAttribute('excluding_tax', $formattedExclPrice); + $subtotalFormattedPriceXmlObj->addAttribute('including_tax', $formattedInclPrice); } else { if ($this->helper('tax')->displayCartPriceExclTax()) { $subtotalPriceXmlObj->addAttribute('regular', $exclPrice); - $subtotalFormatedPriceXmlObj->addAttribute('regular', $formatedExclPrice); + $subtotalFormattedPriceXmlObj->addAttribute('regular', $formattedExclPrice); } if ($this->helper('tax')->displayCartPriceInclTax()) { $subtotalPriceXmlObj->addAttribute('regular', $inclPrice); - $subtotalFormatedPriceXmlObj->addAttribute('regular', $formatedInclPrice); + $subtotalFormattedPriceXmlObj->addAttribute('regular', $formattedInclPrice); } } @@ -174,16 +172,14 @@ protected function _toHtml() if ($_options = $renderer->getOptionList()) { $itemOptionsXml = $itemXml->addChild('options'); foreach ($_options as $_option) { - $_formatedOptionValue = $renderer->getFormatedOptionValue($_option); + $_formattedOptionValue = $renderer->getFormatedOptionValue($_option); $optionXml = $itemOptionsXml->addChild('option'); - $labelValue = $itemsXmlObj->xmlentities(strip_tags($_option['label'])); + $labelValue = $itemsXmlObj->xmlentities($_option['label']); $optionXml->addAttribute('label', $labelValue); - $textValue = $itemsXmlObj->xmlentities(strip_tags($_formatedOptionValue['value'])); + $textValue = $itemsXmlObj->xmlentities( + strip_tags($_formattedOptionValue['value']) + ); $optionXml->addAttribute('text', $textValue); -// if (isset($_formatedOptionValue['full_view'])) { -// $label = strip_tags($_option['label']); -// $value = strip_tags($_formatedOptionValue['full_view']); -// } } } } diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Authorizenet.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Authorizenet.php index 01684092f3..11a06acec3 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Authorizenet.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Authorizenet.php @@ -87,7 +87,7 @@ public function addPaymentFormToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $ $cvnText = $this->__('Card Verification Number'); $cvnValidationText = $this->__('Card verification number is wrong'); $verification = - ' + ' @@ -98,29 +98,29 @@ public function addPaymentFormToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $ $expMonthText = $this->__('Expiration Date - Month'); $expYearText = $this->__('Expiration Date - Year'); $xml = << - - - {$ccTypes} - - - - - - - - - - {$ccMonths} - - - - - {$ccYears} - - - {$verification} - +
+ + + {$ccTypes} + + + + + + + + + + {$ccMonths} + + + + + {$ccYears} + + + {$verification} +
EOT; $fieldsetXmlObj = Mage::getModel('xmlconnect/simplexml_element', $xml); $formXmlObj->appendChild($fieldsetXmlObj); diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Checkmo.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Checkmo.php index c5c6032fbd..937646312f 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Checkmo.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Checkmo.php @@ -27,9 +27,9 @@ /** * Check / Money order Payment method xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Checkout_Payment_Method_Checkmo extends Mage_Payment_Block_Form_Checkmo { diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Authorizenet.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Authorizenet.php index 993d574675..5cc6f656f6 100755 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Authorizenet.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Authorizenet.php @@ -31,8 +31,7 @@ * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Authorizenet - extends Mage_Paygate_Block_Authorizenet_Info_Cc +class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Authorizenet extends Mage_Paygate_Block_Authorizenet_Info_Cc { /** * Add Authorizenet info to order XML object @@ -44,31 +43,20 @@ public function addPaymentInfoToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $ { $orderItemXmlObj->addAttribute('type', $this->getMethod()->getCode()); if (!$this->getHideTitle()) { - $orderItemXmlObj->addAttribute( - 'title', - $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle()) - ); + $orderItemXmlObj->addAttribute('title', $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle())); } $cards = $this->getCards(); $showCount = count($cards) > 1; foreach ($cards as $key => $card) { - $creditCard = $orderItemXmlObj->addCustomChild( - 'item', - null, - array( - 'label' => $showCount ? $this->__('Credit Card %s', $key + 1) : $this->__('Credit Card') - ) - ); + $creditCard = $orderItemXmlObj->addCustomChild('item', null, array( + 'label' => $showCount ? $this->__('Credit Card %s', $key + 1) : $this->__('Credit Card') + )); foreach ($card as $label => $value) { - $creditCard->addCustomChild( - 'item', - implode($this->getValueAsArray($value, true), PHP_EOL), - array( - 'label' => $label - ) - ); + $creditCard->addCustomChild('item', implode($this->getValueAsArray($value, true), '\n'), array( + 'label' => $label + )); } } } diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Ccsave.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Ccsave.php index e8264a56a6..5b49907254 100755 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Ccsave.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Ccsave.php @@ -42,20 +42,13 @@ class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Ccsave extends Mage_Pay public function addPaymentInfoToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) { $orderItemXmlObj->addAttribute('type', $this->getMethod()->getCode()); - $orderItemXmlObj->addAttribute( - 'title', - $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle()) - ); + $orderItemXmlObj->addAttribute('title', $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle())); if ($_specificInfo = $this->getSpecificInformation()) { foreach ($_specificInfo as $label => $value) { - $orderItemXmlObj->addCustomChild( - 'item', - implode($this->getValueAsArray($value, true), PHP_EOL), - array( - 'label' => $label - ) - ); + $orderItemXmlObj->addCustomChild('item', implode($this->getValueAsArray($value, true), '\n'), array( + 'label' => $label + )); } } } diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Checkmo.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Checkmo.php index c7984ea6df..71527a7105 100755 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Checkmo.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Checkmo.php @@ -43,28 +43,19 @@ public function addPaymentInfoToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $ { $orderItemXmlObj->addAttribute('type', $this->getMethod()->getCode()); $orderItemXmlObj->addAttribute( - 'title', - $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle()) + 'title', $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle()) ); if ($this->getInfo()->getAdditionalData()) { if ($this->getPayableTo()) { - $orderItemXmlObj->addCustomChild( - 'item', - $this->getPayableTo(), - array( - 'label' => Mage::helper('sales')->__('Make Check payable to:') - ) - ); + $orderItemXmlObj->addCustomChild('item', $this->getPayableTo(), array( + 'label' => Mage::helper('sales')->__('Make Check payable to:') + )); } if ($this->getMailingAddress()) { - $orderItemXmlObj->addCustomChild( - 'item', - $this->getMailingAddress(), - array( - 'label' => Mage::helper('payment')->__('Send Check to:') - ) - ); + $orderItemXmlObj->addCustomChild('item', $this->getMailingAddress(), array( + 'label' => Mage::helper('payment')->__('Send Check to:') + )); } } } diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Free.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Free.php new file mode 100644 index 0000000000..82a9ec85eb --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Free.php @@ -0,0 +1,47 @@ + + */ +class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Free extends Mage_Payment_Block_Info +{ + /** + * Add Check / Money order info to order XML object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function addPaymentInfoToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) + { + $orderItemXmlObj->addAttribute('type', $this->getMethod()->getCode()); + $orderItemXmlObj->addAttribute('title', $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle())); + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Paypal/Abstract.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Paypal/Abstract.php new file mode 100644 index 0000000000..807ef7d069 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Paypal/Abstract.php @@ -0,0 +1,58 @@ + + */ +abstract class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Paypal_Abstract + extends Mage_Paypal_Block_Payment_Info +{ + /** + * Add CC Save Payment info to order XML object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function addPaymentInfoToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) + { + $orderItemXmlObj->addAttribute('type', $this->getMethod()->getCode()); + $orderItemXmlObj->addAttribute( + 'title', $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle()) + ); + + if ($_specificInfo = $this->getSpecificInformation()) { + foreach ($_specificInfo as $label => $value) { + $orderItemXmlObj->addCustomChild('item', implode($this->getValueAsArray($value, true), '\n'), array( + 'label' => $label + )); + } + } + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Paypal/Express.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Paypal/Express.php new file mode 100644 index 0000000000..1979debbd7 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Paypal/Express.php @@ -0,0 +1,37 @@ + + */ +class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Paypal_Express + extends Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Paypal_Abstract +{ +} diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Paypal/Mecl.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Paypal/Mecl.php new file mode 100644 index 0000000000..ea2eec0dbb --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Paypal/Mecl.php @@ -0,0 +1,37 @@ + + */ +class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Paypal_Mecl + extends Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Paypal_Abstract +{ +} diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Authorizenet.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Authorizenet.php new file mode 100644 index 0000000000..d0f6362706 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Authorizenet.php @@ -0,0 +1,37 @@ + + */ +class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Pbridge_Authorizenet + extends Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Authorizenet +{ +} diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Paypal/Direct.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Paypal/Direct.php new file mode 100644 index 0000000000..dd5080b97f --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Paypal/Direct.php @@ -0,0 +1,37 @@ + + */ +class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Pbridge_Paypal_Direct + extends Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Paypal_Abstract +{ +} diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Paypaluk/Direct.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Paypaluk/Direct.php new file mode 100644 index 0000000000..3b885046dc --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Paypaluk/Direct.php @@ -0,0 +1,37 @@ + + */ +class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Pbridge_Paypaluk_Direct + extends Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Paypal_Abstract +{ +} diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Verisign.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Verisign.php new file mode 100644 index 0000000000..d614df0d69 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Pbridge/Verisign.php @@ -0,0 +1,57 @@ + + */ +class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Pbridge_Verisign extends Mage_Payment_Block_Info_Cc +{ + /** + * Add CC Save Payment info to order XML object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function addPaymentInfoToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) + { + $orderItemXmlObj->addAttribute('type', $this->getMethod()->getCode()); + $orderItemXmlObj->addAttribute( + 'title', $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle()) + ); + + if ($_specificInfo = $this->getSpecificInformation()) { + foreach ($_specificInfo as $label => $value) { + $orderItemXmlObj->addCustomChild('item', implode($this->getValueAsArray($value, true), '\n'), array( + 'label' => $label + )); + } + } + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Purchaseorder.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Purchaseorder.php index f2b9c038cb..b238223924 100755 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Purchaseorder.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Info/Purchaseorder.php @@ -42,17 +42,10 @@ class Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Purchaseorder extends M public function addPaymentInfoToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) { $orderItemXmlObj->addAttribute('type', $this->getMethod()->getCode()); - $orderItemXmlObj->addAttribute( - 'title', - $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle()) - ); + $orderItemXmlObj->addAttribute('title', $orderItemXmlObj->xmlAttribute($this->getMethod()->getTitle())); - $orderItemXmlObj->addCustomChild( - 'item', - $this->getInfo()->getPoNumber(), - array( - 'label' => Mage::helper('sales')->__('Purchase Order Number:') - ) - ); + $orderItemXmlObj->addCustomChild('item', $this->getInfo()->getPoNumber(), array( + 'label' => Mage::helper('sales')->__('Purchase Order Number:') + )); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/List.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/List.php index ffda4976be..36c201aa5d 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/List.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/List.php @@ -33,6 +33,32 @@ */ class Mage_XmlConnect_Block_Checkout_Payment_Method_List extends Mage_Payment_Block_Form_Container { + /** + * Pre-defined array of methods that we are going to render + * + * @var array + */ + protected $_methodArray = array( + 'payment_ccsave' => 'Mage_Payment_Model_Method_Cc', + 'payment_checkmo' => 'Mage_Payment_Model_Method_Checkmo', + 'payment_purchaseorder' => 'Mage_Payment_Model_Method_Purchaseorder', + ); + + /** + * Payment bridge methods array + * + * Core block renderer by method code + * - 'pbridge_authorizenet' => 'Enterprise_Pbridge_Model_Payment_Method_Authorizenet', + * - 'pbridge_paypal' => 'Enterprise_Pbridge_Model_Payment_Method_Paypal', + * - 'pbridge_verisign' => 'Enterprise_Pbridge_Model_Payment_Method_Payflow_Pro', + * - 'pbridge_paypaluk' => 'Enterprise_Pbridge_Model_Payment_Method_Paypaluk', + * + * @var array + */ + protected $_pbridgeMethodArray = array( + 'pbridge_authorizenet', 'pbridge_paypal', 'pbridge_verisign', 'pbridge_paypaluk' + ); + /** * Prevent parent set children * @@ -54,54 +80,128 @@ public function getQuote() } /** - * Render payment methods xml + * Add customer balance details to XML object * - * @return string - * @throw Mage_Core_Exception + * @param Mage_XmlConnect_Model_Simplexml_Element $methodsXmlObj */ - protected function _toHtml() + public function addCustomerBalanceToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $methodsXmlObj) { - /** @var $methodsXmlObj Mage_XmlConnect_Model_Simplexml_Element */ - $methodsXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); + /** @var $customerBalanceBlock Enterprise_CustomerBalance_Block_Checkout_Onepage_Payment_Additional */ + $customerBalanceBlock = $this->getLayout() + ->addBlock('enterprise_customerbalance/checkout_onepage_payment_additional', 'customer_balance'); + $storeCreditFlag = (int) Mage::getStoreConfig(Enterprise_CustomerBalance_Helper_Data::XML_PATH_ENABLED); + if ($storeCreditFlag && $customerBalanceBlock->isDisplayContainer()) { + $balance = $this->getQuote()->getStore()->formatPrice($customerBalanceBlock->getBalance(), false); + $methodsXmlObj->addCustomChild('customer_balance', null, array( + 'post_name' => 'payment[use_customer_balance]', + 'code' => 1, + 'label' => $this->__('Use Store Credit (%s available)', $balance), + 'is_cover_a_quote' => intval($customerBalanceBlock->isFullyPaidAfterApplication()), + 'selected' => intval($customerBalanceBlock->isCustomerBalanceUsed()) + )); + } + } - /** - * Pre-defined array of methods that we are going to render - */ - $methodArray = array( - 'payment_ccsave' => 'Mage_Payment_Model_Method_Cc', - 'payment_checkmo' => 'Mage_Payment_Model_Method_Checkmo', - 'payment_purchaseorder' => 'Mage_Payment_Model_Method_Purchaseorder', + /** + * Add gift card details to XML object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $methodsXmlObj + */ + public function addGiftcardToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $methodsXmlObj) + { + $giftcardInfoBlock = $this->getLayout()->addBlock( + 'enterprise_giftcardaccount/checkout_onepage_payment_additional', 'giftcard_info' ); + if (intval($giftcardInfoBlock->getAppliedGiftCardAmount())) { + $amount = $this->getQuote()->getStore()->formatPrice($giftcardInfoBlock->getAppliedGiftCardAmount(), false); + $amount = $this->__('Gift Card amount applied to order: %s', $amount); + + $methodsXmlObj->addCustomChild('information', null, array('label' => $amount, 'disabled' => '1')); + + if ($this->_isPaymentRequired()) { + $methodsXmlObj->addCustomChild('method', null, array( + 'post_name' => 'payment[method]', + 'code' => 'free', + 'label' => $this->__('No Payment Information Required'), + 'selected' => '1', + 'disabled' => '1' + )); + } + $this->setIsUsedGiftCard(true); + } + } + + /** + * Check is payment required for a quote + * + * @return bool + */ + protected function _isPaymentRequired() + { + $this->getQuote()->collectTotals(); + return !intval($this->getQuote()->getGrandTotal()) && !$this->getQuote()->hasNominalItems(); + } + + /** + * Get payment methods array as code => renderer and set payment blocks to layout + * + * @return array + */ + protected function _getPaymentMethodArray() + { + $methodArray = $this->_methodArray; + /** * Check is available Payment Bridge and add methods for rendering */ if (is_object(Mage::getConfig()->getNode('modules/Enterprise_Pbridge'))) { - $pbridgeMethodArray = array( - 'pbridge_authorizenet' => 'Enterprise_Pbridge_Model_Payment_Method_Authorizenet', - 'pbridge_paypal' => 'Enterprise_Pbridge_Model_Payment_Method_Paypal', - 'pbridge_verisign' => 'Enterprise_Pbridge_Model_Payment_Method_Payflow_Pro', - 'pbridge_paypaluk' => 'Enterprise_Pbridge_Model_Payment_Method_Paypaluk', - ); $pbBlockRenderer = 'xmlconnect/checkout_payment_method_'; $pbBlockName = 'xmlconnect.checkout.payment.method.'; - foreach ($pbridgeMethodArray as $block => $class) { + foreach ($this->_pbridgeMethodArray as $block) { $currentBlockRenderer = $pbBlockRenderer . $block; $currentBlockName = $pbBlockName . $block; $this->getLayout()->addBlock($currentBlockRenderer, $currentBlockName); $this->setChild($block, $currentBlockName); } - $methodArray = $methodArray + $pbridgeMethodArray; + $methodArray = $methodArray + $this->_pbridgeMethodArray; + } + return $methodArray; + } + + /** + * Render payment methods xml + * + * @return string + * @throw Mage_Core_Exception + */ + protected function _toHtml() + { + /** @var $methodsXmlObj Mage_XmlConnect_Model_Simplexml_Element */ + $methodsXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); + + if (is_object(Mage::getConfig()->getNode('modules/Enterprise_GiftCardAccount'))) { + $this->addGiftcardToXmlObj($methodsXmlObj); + if ($this->getIsUsedGiftCard() && $this->_isPaymentRequired()) { + return $methodsXmlObj->asNiceXml(); + } } + if (is_object(Mage::getConfig()->getNode('modules/Enterprise_CustomerBalance'))) { + $this->addCustomerBalanceToXmlObj($methodsXmlObj); + } + + $methodArray = $this->_getPaymentMethodArray(); $usedMethods = $sortedAvailableMethodCodes = $usedCodes = array(); /** * Receive available methods for checkout */ - $allAvailableMethods = Mage::helper('payment')->getStoreMethods(Mage::app()->getStore(), $this->getQuote()); + $allAvailableMethods = Mage::helper('payment')->getStoreMethods( + Mage::app()->getStore(), $this->getQuote() + ); /** * Get sorted codes of available methods diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Paypal/Direct.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Paypal/Direct.php index ceb8f11ced..ace6306a33 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Paypal/Direct.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Paypal/Direct.php @@ -27,9 +27,9 @@ /** * PayPal Direct Payment method xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Checkout_Payment_Method_Paypal_Direct extends Mage_XmlConnect_Block_Checkout_Payment_Method_Paypal_Payflow diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Paypal/Payflow.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Paypal/Payflow.php index 4a53a76491..97b9bb7cc2 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Paypal/Payflow.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Paypal/Payflow.php @@ -119,38 +119,39 @@ public function addPaymentFormToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $ $verification = ''; if ($this->hasVerification()) { - $verification = - ' - - - - '; + $verification = << + + + +
+EOT; } $xml = << - - - $ccTypes - - - - - - - - - - $ccMonthes - - - - - $ccYears - - - $verification - +
+ + + $ccTypes + + + + + + + + + + $ccMonthes + + + + + $ccYears + + + $verification +
EOT; $fieldsetXmlObj = Mage::getModel('xmlconnect/simplexml_element', $xml); $formXmlObj->appendChild($fieldsetXmlObj); diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Authorizenet.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Authorizenet.php index 5fbb893ab6..0315456e42 100755 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Authorizenet.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Authorizenet.php @@ -27,9 +27,9 @@ /** * Authorize.Net through Pbridge Payment method xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Checkout_Payment_Method_Pbridge_Authorizenet extends Mage_XmlConnect_Block_Checkout_Payment_Method_Pbridge_Abstract diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Paypal.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Paypal.php index a06e6a4600..1b7fd0b102 100755 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Paypal.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Paypal.php @@ -27,9 +27,9 @@ /** * PayPal Direct through Pbridge Payment method xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Checkout_Payment_Method_Pbridge_Paypal extends Mage_XmlConnect_Block_Checkout_Payment_Method_Pbridge_Abstract diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Paypaluk.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Paypaluk.php index d02bdaf9a8..6af2fad556 100755 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Paypaluk.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Paypaluk.php @@ -27,9 +27,9 @@ /** * PayPalUK Direct through Pbridge Payment method xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Checkout_Payment_Method_Pbridge_Paypaluk extends Mage_XmlConnect_Block_Checkout_Payment_Method_Pbridge_Abstract diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Verisign.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Verisign.php index 9598488315..2fdbe679ed 100755 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Verisign.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Verisign.php @@ -27,9 +27,9 @@ /** * Payflow Pro through Pbridge Payment method xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Checkout_Payment_Method_Pbridge_Verisign extends Mage_XmlConnect_Block_Checkout_Payment_Method_Pbridge_Abstract diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Shipping/Method/Available.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Shipping/Method/Available.php index 1ed6166a72..ca6bcb1ef6 100644 --- a/app/code/core/Mage/XmlConnect/Block/Checkout/Shipping/Method/Available.php +++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Shipping/Method/Available.php @@ -27,9 +27,9 @@ /** * One page checkout shipping methods xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Checkout_Shipping_Method_Available extends Mage_Checkout_Block_Onepage_Shipping_Method_Available @@ -49,24 +49,16 @@ protected function _toHtml() $_sole = count($_shippingRateGroups) == 1; foreach ($_shippingRateGroups as $code => $_rates) { $methodXmlObj = $methodsXmlObj->addChild('method'); - $methodXmlObj->addAttribute( - 'label', - $methodsXmlObj->xmlentities($this->getCarrierName($code)) - ); + $methodXmlObj->addAttribute('label', $methodsXmlObj->xmlentities($this->getCarrierName($code))); $ratesXmlObj = $methodXmlObj->addChild('rates'); $_sole = $_sole && count($_rates) == 1; foreach ($_rates as $_rate) { $rateXmlObj = $ratesXmlObj->addChild('rate'); - $rateXmlObj->addAttribute( - 'label', - $methodsXmlObj->xmlentities($_rate->getMethodTitle()) - ); + $rateXmlObj->addAttribute('label', $methodsXmlObj->xmlentities($_rate->getMethodTitle())); $rateXmlObj->addAttribute('code', $_rate->getCode()); if ($_rate->getErrorMessage()) { - $rateXmlObj->addChild( - 'error_message', - $methodsXmlObj->xmlentities($_rate->getErrorMessage())); + $rateXmlObj->addChild('error_message', $methodsXmlObj->xmlentities($_rate->getErrorMessage())); } else { $price = Mage::helper('tax')->getShippingPrice( $_rate->getPrice(), @@ -74,12 +66,9 @@ protected function _toHtml() $this->getAddress() ); $formattedPrice = $store->convertPrice($price, true, false); - $rateXmlObj->addAttribute( - 'price', - Mage::helper('xmlconnect')->formatPriceForXml( - $store->convertPrice($price, false, false) - ) - ); + $rateXmlObj->addAttribute('price', Mage::helper('xmlconnect')->formatPriceForXml( + $store->convertPrice($price, false, false) + )); $rateXmlObj->addAttribute('formated_price', $formattedPrice); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Cms/Page.php b/app/code/core/Mage/XmlConnect/Block/Cms/Page.php index 2598c21573..be878e7134 100644 --- a/app/code/core/Mage/XmlConnect/Block/Cms/Page.php +++ b/app/code/core/Mage/XmlConnect/Block/Cms/Page.php @@ -27,11 +27,10 @@ /** * Cms Page xml renderer * - * @category Mage - * @package Mage_XmlConnect + * @category Mage + * @package Mage_XmlConnect * @author Magento Core Team */ - class Mage_XmlConnect_Block_Cms_Page extends Mage_Cms_Block_Page { /** diff --git a/app/code/core/Mage/XmlConnect/Block/Configuration.php b/app/code/core/Mage/XmlConnect/Block/Configuration.php index cc73ace607..6d6ba86331 100644 --- a/app/code/core/Mage/XmlConnect/Block/Configuration.php +++ b/app/code/core/Mage/XmlConnect/Block/Configuration.php @@ -31,7 +31,6 @@ * @package Mage_XmlConnect * @author Magento Core Team */ - class Mage_XmlConnect_Block_Configuration extends Mage_Core_Block_Template { /** @@ -100,7 +99,7 @@ protected function _buildRecursive($section, $subtree) } else { $value = (string)$value; if ($value != '') { - $section->addChild($key, Mage::helper('core')->htmlEscape($value)); + $section->addChild($key, Mage::helper('core')->escapeHtml($value)); } } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Address/Form.php b/app/code/core/Mage/XmlConnect/Block/Customer/Address/Form.php index f204de994d..ab998621c4 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Address/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Address/Form.php @@ -31,8 +31,44 @@ * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_XmlConnect_Block_Customer_Address_Form extends Mage_Core_Block_Template +class Mage_XmlConnect_Block_Customer_Address_Form extends Mage_Customer_Block_Address_Edit { + /** + * Customer name widget block + * + * @var Mage_Customer_Block_Widget_Name + */ + protected $_nameWidgetBlock; + + /** + * Enterprise customer field renderer list as type => renderer block + * + * Original block relations: + * - 'text' => 'enterprise_customer/form_renderer_text', + * - 'textarea' => 'enterprise_customer/form_renderer_textarea', + * - 'multiline' => 'enterprise_customer/form_renderer_multiline', + * - 'date' => 'enterprise_customer/form_renderer_date', + * - 'select' => 'enterprise_customer/form_renderer_select', + * - 'multiselect' => 'enterprise_customer/form_renderer_multiselect', + * - 'boolean' => 'enterprise_customer/form_renderer_boolean', + * - 'file' => 'enterprise_customer/form_renderer_file' + * - 'image' => 'enterprise_customer/form_renderer_image' + * + * @see customer.xml layout customer_form_template_handle node + * @var array + */ + protected $_customerFiledRenderer = array( + 'text' => 'xmlconnect/customer_form_renderer_text', + 'textarea' => 'xmlconnect/customer_form_renderer_textarea', + 'multiline' => 'xmlconnect/customer_form_renderer_multiline', + 'date' => 'xmlconnect/customer_form_renderer_date', + 'select' => 'xmlconnect/customer_form_renderer_select', + 'multiselect' => 'xmlconnect/customer_form_renderer_multiselect', + 'boolean' => 'xmlconnect/customer_form_renderer_boolean', + 'file' => 'xmlconnect/customer_form_renderer_file', + 'image' => 'xmlconnect/customer_form_renderer_image' + ); + /** * Render customer address form xml * @@ -41,140 +77,361 @@ class Mage_XmlConnect_Block_Customer_Address_Form extends Mage_Core_Block_Templa protected function _toHtml() { $address = $this->getAddress(); - $xmlModel = Mage::getModel('xmlconnect/simplexml_element', ''); /** * Init address object and save its data to variables */ $addressId = (int)$this->getRequest()->getParam('id'); + $billingChecked = $shippingChecked = false; + if ($addressId && $address && $address->getId()) { $defaultBillingAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling(); $defaultShippingAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultShipping(); - $billingChecked = $addressId == $defaultBillingAddressId ? ' checked="1"' : ''; - $shippingChecked = $addressId == $defaultShippingAddressId ? ' checked="1"' : ''; - - $firstname = $xmlModel->xmlentities(strip_tags($address->getFirstname())); - $lastname = $xmlModel->xmlentities(strip_tags($address->getLastname())); - $company = $xmlModel->xmlentities(strip_tags($address->getCompany())); - $street1 = $xmlModel->xmlentities(strip_tags($address->getStreet(1))); - $street2 = $xmlModel->xmlentities(strip_tags($address->getStreet(2))); - $city = $xmlModel->xmlentities(strip_tags($address->getCity())); - $regionId = $xmlModel->xmlentities($address->getRegionId()); - $region = Mage::getModel('directory/region')->load($regionId)->getName(); - if (!$region) { - $region = $address->getRegion(); - } - $region = $xmlModel->xmlentities(strip_tags($region)); - $postcode = $xmlModel->xmlentities(strip_tags($address->getPostcode())); - $countryId = $xmlModel->xmlentities($address->getCountryId()); - $telephone = $xmlModel->xmlentities(strip_tags($address->getTelephone())); - $fax = $xmlModel->xmlentities(strip_tags($address->getFax())); - } else { - $firstname = $lastname = $company = $street1 = $street2 = $billingChecked = $shippingChecked = ''; - $city = $region = $postcode = $telephone = $fax = ''; - $countryId = $regionId = null; + $billingChecked = (int)$addressId == $defaultBillingAddressId; + $shippingChecked = (int)$addressId == $defaultShippingAddressId; + + $company = $address->getCompany(); + $street1 = $address->getStreet(1); + $street2 = $address->getStreet(2); + $city = $address->getCity(); + $regionId = $address->getRegionId(); + $region = $address->getRegion(); + $postcode = $address->getPostcode(); + $countryId = $address->getCountryId(); + $telephone = $address->getTelephone(); + $fax = $address->getFax(); } - $countries = $this->_getCountryOptions(); + $action = Mage::helper('xmlconnect')->getActionUrl('xmlconnect/customer/saveaddress'); - $regions = array(); - $countryOptionsXml = ''; - if (is_array($countries)) { - foreach ($countries as $key => $data) { - if ($data['value']) { - $regions = $this->_getRegionOptions($data['value']); - } - $region = is_array($regions) && !empty($regions) ? 'region_id' : 'region'; - $countryOptionsXml .= ' - - - ' . $xmlModel->xmlentities($data['value']) . ''; - if (is_array($regions) && !empty($regions)) { - $countryOptionsXml .= ''; - foreach ($regions as $_key => $regionData) { - $region = $regionId == $regionData['value'] ? ' selected="1"' : ''; - $countryOptionsXml .= ''; - $countryOptionsXml .= - ' - ' . $xmlModel->xmlentities($regionData['value']) . ''; - $countryOptionsXml .= ''; - } - $countryOptionsXml .= ''; - } - $countryOptionsXml .= ''; + /** @var Mage_XmlConnect_Model_Simplexml_Form $fromXmlObj */ + $fromXmlObj = Mage::getModel('xmlconnect/simplexml_form', array( + 'xml_id' => 'address_form', + 'action' => $action, + 'use_container' => true + )); + + $contactInfoFieldset = $fromXmlObj->addFieldset('contact_info', array( + 'legend' => $this->__('Contact Information') + ))->setCustomAttributes(array('legend')); + + $this->_addCustomerContactInfo($contactInfoFieldset); + + $contactInfoFieldset->addField('company', 'text', array( + 'label' => $this->__('Company'), + 'value' => isset($company) ? $company : '' + )); + $contactInfoFieldset->addField('telephone', 'text', array( + 'label' => $this->__('Telephone'), + 'required' => 'true', + 'value' => isset($telephone) ? $telephone : '' + )); + $contactInfoFieldset->addField('fax', 'text', array( + 'label' => $this->__('Fax'), + 'value' => isset($fax) ? $fax : '' + )); + + $addressFieldset = $fromXmlObj->addFieldset('address_info', array('legend' => $this->__('Address'))) + ->setCustomAttributes(array('legend')); + + $addressFieldset->addField('street', 'text', array( + 'name' => 'street[]', + 'label' => $this->__('Street Address'), + 'required' => 'true', + 'value' => isset($street1) ? $street1 : '' + )); + $addressFieldset->addField('street_2', 'text', array( + 'name' => 'street[]', + 'label' => $this->__('Street Address 2'), + 'value' => isset($street2) ? $street2 : '' + )); + $addressFieldset->addField('city', 'text', array( + 'label' => $this->__('City'), + 'required' => 'true', + 'value' => isset($city) ? $city : '' + )); + + $countryId = isset($countryId) ? $countryId : null; + $regionId = isset($regionId) ? $regionId : null; + $region = isset($region) ? $region : null; + + $addressFieldset->addField('country_id', 'countryListSelect', array( + 'label' => $this->__('Country'), + 'required' => 'true', + 'value' => array( + 'country_id' => $countryId, + 'region_id' => $regionId, + 'region' => $region + ), + 'old_format' => true + )); + $addressFieldset->addField('region', 'text', array( + 'label' => $this->__('State/Province'), + 'value' => isset($region) ? $region : '' + )); + $addressFieldset->addField('region_id', 'select', array( + 'label' => $this->__('State/Province'), + 'required' => 'true', + )); + $addressFieldset->addField('postcode', 'text', array( + 'label' => $this->__('Zip/Postal Code'), + 'required' => 'true', + 'value' => isset($postcode) ? $postcode : '' + )); + $addressFieldset->addField('default_billing', 'checkbox', array( + 'label' => $this->__('Use as my default billing address'), + 'value' => $billingChecked ? $billingChecked : 0 + )); + + $addressFieldset->addField('default_shipping', 'checkbox', array( + 'label' => $this->__('Use as my default shipping address'), + 'value' => $shippingChecked ? $shippingChecked : 0 + )); + + $this->_addCustomAddressAttributes($addressFieldset); + + return $fromXmlObj->getXml(); + } + + /** + * Add customer contact attributes + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + * @return Mage_XmlConnect_Block_Customer_Address_Form + */ + protected function _addCustomerContactInfo( + Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + ) { + if (is_object(Mage::getConfig()->getNode('modules/Enterprise_Customer'))) { + $this->setNameWidgetBlock( + $this->getLayout()->createBlock('customer/widget_name')->setObject( + $this->getAddress()->getFirstname() ? $this->getAddress() : $this->getCustomer() + )); + + if ($this->getNameWidgetBlock()->showPrefix()) { + $this->_addPrefix($contactInfoFieldset); + } + + $this->_addFirstName($contactInfoFieldset); + + if ($this->getNameWidgetBlock()->showMiddlename()) { + $this->_addMiddleName($contactInfoFieldset); + } + + $this->_addLastName($contactInfoFieldset); + + if ($this->getNameWidgetBlock()->showSuffix()) { + $this->_addSuffix($contactInfoFieldset); } + } else { + $this->_addFirstName($contactInfoFieldset); + $this->_addLastName($contactInfoFieldset); } - $countryOptionsXml .= ''; - - $xml = << -
- - - - - -
-
- - - - - $countryOptionsXml - - - - - - -
- -EOT; - return $xml; + return $this; } /** - * Retrieve regions by country + * Add customer prefix field * - * @param string $countryId - * @return array + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + * @return Mage_XmlConnect_Block_Customer_Address_Form */ - protected function _getRegionOptions($countryId) + protected function _addPrefix(Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset) { - $cacheKey = 'DIRECTORY_REGION_SELECT_STORE'.Mage::app()->getStore()->getId().$countryId; - if (Mage::app()->useCache('config') && $cache = Mage::app()->loadCache($cacheKey)) { - $options = unserialize($cache); + $attributes = array(); + $attributes += $contactInfoFieldset->checkAttribute( + 'value', $this->getNameWidgetBlock()->getObject()->getPrefix() + ); + + $attributes += $contactInfoFieldset->checkAttribute( + 'required', (int)$this->getNameWidgetBlock()->isPrefixRequired() + ); + + if ($this->getNameWidgetBlock()->getPrefixOptions() === false) { + $contactInfoFieldset->addField($this->getNameWidgetBlock()->getFieldId('prefix'), 'text', array( + 'label' => $this->getNameWidgetBlock()->__('Prefix'), + 'name' => $this->getNameWidgetBlock()->getFieldName('prefix') + ) + $attributes); } else { - $collection = Mage::getModel('directory/region')->getResourceCollection() - ->addCountryFilter($countryId) - ->load(); - $options = $collection->toOptionArray(); - if (Mage::app()->useCache('config')) { - Mage::app()->saveCache(serialize($options), $cacheKey, array('config')); - } + $contactInfoFieldset->addField($this->getNameWidgetBlock()->getFieldId('prefix'), 'select', array( + 'label' => $this->getNameWidgetBlock()->__('Prefix'), + 'name' => $this->getNameWidgetBlock()->getFieldName('prefix'), + 'options' => $this->getNameWidgetBlock()->getPrefixOptions() + ) + $attributes); } - return $options; + return $this; } /** - * Retrieve countries + * Add customer suffix field * - * @return array + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + * @return Mage_XmlConnect_Block_Customer_Address_Form */ - protected function _getCountryOptions() + protected function _addSuffix( + Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + ) { - $cacheKey = 'DIRECTORY_COUNTRY_SELECT_STORE_'.Mage::app()->getStore()->getCode(); - if (Mage::app()->useCache('config') && $cache = Mage::app()->loadCache($cacheKey)) { - $options = unserialize($cache); + $attributes = array(); + $attributes += $contactInfoFieldset->checkAttribute( + 'value', $this->getNameWidgetBlock()->getObject()->getSuffix() + ); + + $attributes += $contactInfoFieldset->checkAttribute( + 'required', (int)$this->getNameWidgetBlock()->isSuffixRequired() + ); + + if ($this->getNameWidgetBlock()->getSuffixOptions() === false) { + $contactInfoFieldset->addField($this->getNameWidgetBlock()->getFieldId('suffix'), 'text', array( + 'label' => $this->getNameWidgetBlock()->__('Suffix'), + 'name' => $this->getNameWidgetBlock()->getFieldName('suffix') + ) + $attributes); } else { - $collection = Mage::getModel('directory/country')->getResourceCollection() - ->loadByStore(); - $options = $collection->toOptionArray(); - if (Mage::app()->useCache('config')) { - Mage::app()->saveCache(serialize($options), $cacheKey, array('config')); + $contactInfoFieldset->addField($this->getNameWidgetBlock()->getFieldId('suffix'), 'select', array( + 'label' => $this->getNameWidgetBlock()->__('Suffix'), + 'name' => $this->getNameWidgetBlock()->getFieldName('suffix'), + 'options' => $this->getNameWidgetBlock()->getSuffixOptions() + ) + $attributes); + } + return $this; + } + + /** + * Add customer middle name field + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + * @return Mage_XmlConnect_Block_Customer_Address_Form + */ + protected function _addMiddleName( + Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + ) + { + $attributes = array(); + $attributes += $contactInfoFieldset->checkAttribute( + 'value', + $this->getNameWidgetBlock()->getObject()->getMiddlename() + ); + + $contactInfoFieldset->addField($this->getNameWidgetBlock()->getFieldId('middlename'), 'text', array( + 'label' => $this->getNameWidgetBlock()->__('M.I.'), + 'name' => $this->getNameWidgetBlock()->getFieldName('middlename') + ) + $attributes); + + return $this; + } + + /** + * Add customer first name field + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + * @return Mage_XmlConnect_Block_Customer_Address_Form + */ + protected function _addFirstName( + Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + ) { + $firstName = $this->getAddress()->getFirstname(); + $contactInfoFieldset->addField('firstname', 'text', array( + 'label' => $this->__('First Name'), + 'required' => 'true', + 'value' => isset($firstName) ? $firstName : '' + )); + return $this; + } + + /** + * Add customer last name field + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + * @return Mage_XmlConnect_Block_Customer_Address_Form + */ + protected function _addLastName( + Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $contactInfoFieldset + ) { + $lastName = $this->getAddress()->getLastname(); + $contactInfoFieldset->addField('lastname', 'text', array( + 'label' => $this->__('Last Name'), + 'required' => 'true', + 'value' => isset($lastName) ? $lastName : '' + )); + return $this; + } + + /** + * Add custom customer attributes + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $addressFieldset + * @return Mage_XmlConnect_Block_Customer_Address_Form + */ + protected function _addCustomAddressAttributes( + Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $addressFieldset + ) { + if (is_object(Mage::getConfig()->getNode('modules/Enterprise_Customer'))) { + /** @var $addressAttrBlock Enterprise_Customer_Block_Form */ + $addressAttrBlock = $this->getLayout() + ->addBlock('enterprise_customer/form', 'customer_address_attr'); + $addressAttrBlock->setFormCode('customer_address_edit'); + $addressAttrBlock->setEntity($this->getAddress()); + + foreach ($this->_customerFiledRenderer as $type => $rendererBlock) { + $addressAttrBlock->addRenderer($type, $rendererBlock, 'customer/form/renderer/text.phtml'); + } + + if ($addressAttrBlock->hasUserDefinedAttributes()) { + foreach ($addressAttrBlock->getUserDefinedAttributes() as $attribute) { + $type = $attribute->getFrontendInput(); + $block = $addressAttrBlock->getRenderer($type); + if ($block) { + $block->setAttributeObject($attribute)->setEntity($addressAttrBlock->getEntity()) + ->addFieldToXmlObj($addressFieldset); + } + } } } - return $options; + return $this; + } + + /** + * Get customer name widget block + * + * @return Mage_Customer_Block_Widget_Name + */ + public function getNameWidgetBlock() + { + return $this->_nameWidgetBlock; + } + + /** + * Set customer name widget block + * + * @param Mage_Customer_Block_Widget_Name $nameWidgetBlock + * @return Mage_XmlConnect_Block_Customer_Address_Form + */ + public function setNameWidgetBlock($nameWidgetBlock) + { + $this->_nameWidgetBlock = $nameWidgetBlock; + return $this; + } + + /** + * Get enterprise customer fields renderer + * + * @return array + */ + public function getCustomerFiledRenderer() + { + return $this->_customerFiledRenderer; + } + + /** + * Set enterprise customer fields renderer + * + * @param array $customerFiledRenderer + * @return Mage_XmlConnect_Block_Customer_Address_Form + */ + public function setCustomerFiledRenderer($customerFiledRenderer) + { + $this->_customerFiledRenderer = $customerFiledRenderer; + return $this; } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Address/List.php b/app/code/core/Mage/XmlConnect/Block/Customer/Address/List.php index aeb1e423f3..b0f2381891 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Address/List.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Address/List.php @@ -92,9 +92,7 @@ public function prepareAddressData( $attributes = Mage::helper('customer/address')->getAttributes(); - $data = array( - 'entity_id' => $address->getId() - ); + $data = array('entity_id' => $address->getId()); foreach ($attributes as $attribute) { /* @var $attribute Mage_Customer_Model_Attribute */ @@ -110,7 +108,7 @@ public function prepareAddressData( $dataModel = Mage_Customer_Model_Attribute_Data::factory($attribute, $address); $value = $dataModel->outputValue(Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_ONELINE); if ($attribute->getFrontendInput() == 'multiline') { - $values = $dataModel->outputValue(Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_ARRAY); + $values = $dataModel->outputValue(Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_ARRAY); // explode lines foreach ($values as $k => $v) { $key = sprintf('%s%d', $attribute->getAttributeCode(), $k + 1); @@ -122,9 +120,10 @@ public function prepareAddressData( } foreach ($data as $key => $value) { - if (!empty($value)) { - $item->addChild($key, $item->xmlentities($value)); + if (empty($value)) { + continue; } + $item->addChild($key, $item->xmlentities($value)); } } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form.php index b82d43db08..24431c1e84 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form.php @@ -42,12 +42,13 @@ protected function _toHtml() { $editFlag = (int)$this->getRequest()->getParam('edit'); $customer = $this->getCustomer(); + /** @var $xmlModel Mage_XmlConnect_Model_Simplexml_Element */ $xmlModel = Mage::getModel('xmlconnect/simplexml_element', ''); - + //Enterprise_Customer if ($editFlag == 1 && $customer && $customer->getId()) { - $firstname = $xmlModel->xmlentities(strip_tags($customer->getFirstname())); - $lastname = $xmlModel->xmlentities(strip_tags($customer->getLastname())); - $email = $xmlModel->xmlentities(strip_tags($customer->getEmail())); + $firstname = $xmlModel->xmlentities($customer->getFirstname()); + $lastname = $xmlModel->xmlentities($customer->getLastname()); + $email = $xmlModel->xmlentities($customer->getEmail()); } else { $firstname = $lastname = $email = ''; } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Boolean.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Boolean.php new file mode 100644 index 0000000000..fa6d20a8fd --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Boolean.php @@ -0,0 +1,49 @@ + + */ +class Mage_XmlConnect_Block_Customer_Form_Renderer_Boolean extends Mage_XmlConnect_Block_Customer_Form_Renderer_Select +{ + /** + * Return array of select options + * + * @return array + */ + public function getOptions() + { + return array( + array('value' => '', 'label' => ''), + array('value' => '0', 'label' => Mage::helper('enterprise_customer')->__('No')), + array('value' => '1', 'label' => Mage::helper('enterprise_customer')->__('Yes')) + ); + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Date.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Date.php new file mode 100644 index 0000000000..b410dc34a0 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Date.php @@ -0,0 +1,97 @@ + + */ +class Mage_XmlConnect_Block_Customer_Form_Renderer_Date extends Enterprise_Customer_Block_Form_Renderer_Date +{ + /** + * Field type + * + * @var string + */ + protected $_filedType = 'date'; + + /** + * Prepare values for renderer + * + * @return array + */ + protected function _prepareValues() + { + return array('day' => array( + 'id' => $this->getHtmlId('day'), + 'title' => $this->__('Day'), + 'label' => $this->__('DD'), + 'value' => $this->getDay() + ), 'month' => array( + 'id' => $this->getHtmlId('month'), + 'title' => $this->__('Month'), + 'label' => $this->__('MM'), + 'value' => $this->getMonth() + ), 'year' => array( + 'id' => $this->getHtmlId('year'), + 'title' => $this->__('Year'), + 'label' => $this->__('YYYY'), + 'value' => $this->getYear() + )); + } + + /** + * Add date field to fieldset xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj + * @return Mage_XmlConnect_Block_Customer_Form_Renderer_Date + */ + public function addFieldToXmlObj(Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj) + { + $attributes = array( + 'label' => $this->getLabel(), + 'name' => $this->getFieldName(), + 'format'=> $this->getDateFormat(), + 'value' => $this->_prepareValues() + ); + + $attributes += Mage::helper('xmlconnect/customer_form_renderer') + ->addTitleAndRequiredAttr($fieldsetXmlObj, $this); + $fieldXmlObj = $fieldsetXmlObj->addField($this->getHtmlId('full'), $this->_filedType, $attributes); + $validateRules = $this->getAttributeObject()->getValidateRules(); + + if (!empty($validateRules)) { + $validatorXmlObj = $fieldXmlObj->addValidator(); + if (!empty($validateRules['input_validation'])) { + $validatorXmlObj->addRule(array('type' => $validateRules['input_validation'])); + } + } + + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/File.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/File.php new file mode 100644 index 0000000000..4cb85354b7 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/File.php @@ -0,0 +1,112 @@ + + */ +class Mage_XmlConnect_Block_Customer_Form_Renderer_File extends Enterprise_Customer_Block_Form_Renderer_File +{ + /** + * Field type + * + * @var string + */ + protected $_filedType = 'file'; + + /** + * Change form post params for file upload compliance + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $fieldsetXmlObj + * @return Mage_XmlConnect_Block_Customer_Form_Renderer_File + */ + protected function _setFormPostParams(Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $fieldsetXmlObj) + { + $fieldsetXmlObj->getForm()->setData('method', 'post'); + $fieldsetXmlObj->getForm()->setData('enctype', 'multipart/form-data'); + return $this; + } + + /** + * Add file field to fieldset xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj + * @return Mage_XmlConnect_Block_Customer_Form_Renderer_File + */ + public function addFieldToXmlObj(Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj) + { + $this->_setFormPostParams($fieldsetXmlObj); + + $attributes = array( + 'label' => $this->getLabel(), 'name' => $this->getFieldName(), 'value' => $this->getEscapedValue() + ); + + $attributes += Mage::helper('xmlconnect/customer_form_renderer') + ->addTitleAndRequiredAttr($fieldsetXmlObj, $this); + + $fieldXmlObj = $fieldsetXmlObj->addField($this->getHtmlId(), $this->_filedType, $attributes); + $this->_addValidator($fieldXmlObj); + + return $this; + } + + /** + * Add validator for file field to fieldset xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $fieldXmlObj + * @return Mage_XmlConnect_Block_Customer_Form_Renderer_File + */ + protected function _addValidator(Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $fieldXmlObj) + { + $validateRules = $this->getAttributeObject()->getValidateRules(); + + if (!empty($validateRules)) { + $validatorXmlObj = $fieldXmlObj->addValidator(); + + if (!empty($validateRules['max_file_size'])) { + $minTextLength = (int) $validateRules['max_file_size']; + $validatorXmlObj->addRule(array( + 'type' => 'max_file_size', + 'value' => $minTextLength, + 'field_label' => $this->getLabel() + )); + } + + if (!empty($validateRules['file_extensions'])) { + $maxTextLength = $validateRules['file_extensions']; + $validatorXmlObj->addRule(array( + 'type' => 'file_extensions', + 'value' => $maxTextLength, + 'field_label' => $this->getLabel() + )); + } + } + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Image.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Image.php new file mode 100644 index 0000000000..784e6f0e6b --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Image.php @@ -0,0 +1,83 @@ + + */ +class Mage_XmlConnect_Block_Customer_Form_Renderer_Image extends Mage_XmlConnect_Block_Customer_Form_Renderer_File +{ + /** + * Field type + * + * @var string + */ + protected $_filedType = 'image'; + + /** + * Add validator for image file field to fieldset xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $fieldXmlObj + * @return Mage_XmlConnect_Block_Customer_Form_Renderer_Image + */ + protected function _addValidator(Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $fieldXmlObj) + { + parent::_addValidator($fieldXmlObj); + + $validateRules = $this->getAttributeObject()->getValidateRules(); + + if (!empty($validateRules)) { + + foreach ($fieldXmlObj->getElements() as $element) { + if ($element->getType() == 'validator') { + $validatorXmlObj = $element; + } + } + + if (!isset($validatorXmlObj)) { + $validatorXmlObj = $fieldXmlObj->addValidator(); + } + + if (!empty($validateRules['max_image_width'])) { + $minTextLength = (int) $validateRules['max_image_width']; + $validatorXmlObj->addRule(array( + 'type' => 'max_image_width', 'value' => $minTextLength, 'field_label' => $this->getLabel() + )); + } + + if (!empty($validateRules['max_image_heght'])) { + $maxTextLength = $validateRules['max_image_heght']; + $validatorXmlObj->addRule(array( + 'type' => 'max_image_height', 'value' => $maxTextLength, 'field_label' => $this->getLabel() + )); + } + } + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Multiline.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Multiline.php new file mode 100644 index 0000000000..5c625721ab --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Multiline.php @@ -0,0 +1,88 @@ + + */ +class Mage_XmlConnect_Block_Customer_Form_Renderer_Multiline extends Enterprise_Customer_Block_Form_Renderer_Multiline +{ + /** + * Field type + * + * @var string + */ + protected $_filedType = 'multiline'; + + /** + * Add multiline field to fieldset xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj + * @return Mage_XmlConnect_Block_Customer_Form_Renderer_Multiline + */ + public function addFieldToXmlObj(Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj) + { + $attributes = array( + 'label' => $this->getLabel(), + 'name' => $this->getFieldName(), + 'line_count' => $this->getLineCount(), + 'attribute_code' => $this->getAttributeObject()->getAttributeCode(), + 'value' => $this->getValues() + ); + + $attributes += Mage::helper('xmlconnect/customer_form_renderer') + ->addTitleAndRequiredAttr($fieldsetXmlObj, $this); + + $fieldXmlObj = $fieldsetXmlObj->addField( + $this->_filedType . '_' . $this->getHtmlId(), $this->_filedType, $attributes + ); + + $validateRules = $this->getAttributeObject()->getValidateRules(); + + if (!empty($validateRules)) { + $validatorXmlObj = $fieldXmlObj->addValidator(); + + if (!empty($validateRules['min_text_length'])) { + $minTextLength = (int) $validateRules['min_text_length']; + $validatorXmlObj->addRule(array('type' => 'min_length', 'value' => $minTextLength)); + } + + if (!empty($validateRules['max_text_length'])) { + $maxTextLength = (int) $validateRules['max_text_length']; + $validatorXmlObj->addRule(array('type' => 'max_length', 'value' => $maxTextLength)); + } + + if (!empty($validateRules['input_validation'])) { + $validatorXmlObj->addRule(array('type' => $validateRules['input_validation'])); + } + } + + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Multiselect.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Multiselect.php new file mode 100644 index 0000000000..f529399c48 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Multiselect.php @@ -0,0 +1,66 @@ + + */ +class Mage_XmlConnect_Block_Customer_Form_Renderer_Multiselect + extends Enterprise_Customer_Block_Form_Renderer_Multiselect +{ + /** + * Field type + * + * @var string + */ + protected $_filedType = 'multiselect'; + + /** + * Add select field to fieldset xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj + * @return Mage_XmlConnect_Block_Customer_Form_Renderer_Select + */ + public function addFieldToXmlObj(Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj) + { + $attributes = array( + 'label' => $this->getLabel(), + 'name' => $this->getFieldName(''), + 'value' => $this->getValues(), + 'options' => $this->getOptions() + ); + + $attributes += Mage::helper('xmlconnect/customer_form_renderer') + ->addTitleAndRequiredAttr($fieldsetXmlObj, $this); + + $fieldsetXmlObj->addField($this->getHtmlId(), $this->_filedType, $attributes); + + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Select.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Select.php new file mode 100644 index 0000000000..8f4af08613 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Select.php @@ -0,0 +1,65 @@ + + */ +class Mage_XmlConnect_Block_Customer_Form_Renderer_Select extends Enterprise_Customer_Block_Form_Renderer_Select +{ + /** + * Field type + * + * @var string + */ + protected $_filedType = 'select'; + + /** + * Add select field to fieldset xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj + * @return Mage_XmlConnect_Block_Customer_Form_Renderer_Select + */ + public function addFieldToXmlObj(Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj) + { + $attributes = array( + 'label' => $this->getLabel(), + 'name' => $this->getFieldName(), + 'value' => $this->getValue(), + 'options' => $this->getOptions() + ); + + $attributes += Mage::helper('xmlconnect/customer_form_renderer') + ->addTitleAndRequiredAttr($fieldsetXmlObj, $this); + + $fieldsetXmlObj->addField($this->getHtmlId(), $this->_filedType, $attributes); + + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Text.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Text.php new file mode 100644 index 0000000000..21cbace073 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Text.php @@ -0,0 +1,82 @@ + + */ +class Mage_XmlConnect_Block_Customer_Form_Renderer_Text extends Enterprise_Customer_Block_Form_Renderer_Text +{ + /** + * Field type + * + * @var string + */ + protected $_filedType = 'text'; + + /** + * Add text field to fieldset xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj + * @return Mage_XmlConnect_Block_Customer_Form_Renderer_Text + */ + public function addFieldToXmlObj(Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset $fieldsetXmlObj) + { + $attributes = array( + 'label' => $this->getLabel(), 'name' => $this->getFieldName(), 'value' => $this->getEscapedValue() + ); + + $attributes += Mage::helper('xmlconnect/customer_form_renderer') + ->addTitleAndRequiredAttr($fieldsetXmlObj, $this); + + $fieldXmlObj = $fieldsetXmlObj->addField($this->getHtmlId(), $this->_filedType, $attributes); + + $validateRules = $this->getAttributeObject()->getValidateRules(); + + if (!empty($validateRules)) { + $validatorXmlObj = $fieldXmlObj->addValidator(); + + if (!empty($validateRules['min_text_length'])) { + $minTextLength = (int) $validateRules['min_text_length']; + $validatorXmlObj->addRule(array('type' => 'min_length', 'value' => $minTextLength)); + } + + if (!empty($validateRules['max_text_length'])) { + $maxTextLength = (int) $validateRules['max_text_length']; + $validatorXmlObj->addRule(array('type' => 'max_length', 'value' => $maxTextLength)); + } + + if (!empty($validateRules['input_validation'])) { + $validatorXmlObj->addRule(array('type' => $validateRules['input_validation'])); + } + } + + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Textarea.php b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Textarea.php new file mode 100644 index 0000000000..ced68edd34 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Form/Renderer/Textarea.php @@ -0,0 +1,42 @@ + + */ +class Mage_XmlConnect_Block_Customer_Form_Renderer_Textarea extends Mage_XmlConnect_Block_Customer_Form_Renderer_Text +{ + /** + * Field type + * + * @var string + */ + protected $_filedType = 'textarea'; +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/GiftcardCheck.php b/app/code/core/Mage/XmlConnect/Block/Customer/GiftcardCheck.php new file mode 100644 index 0000000000..fccd8e5ac8 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/GiftcardCheck.php @@ -0,0 +1,65 @@ + + */ +class Mage_XmlConnect_Block_Customer_GiftcardCheck extends Enterprise_GiftCardAccount_Block_Check +{ + /** + * Render gift card info xml + * + * @return string + */ + protected function _toHtml() + { + $card = $this->getCard(); + if ($card->getId()) { + /** @var $xmlModel Mage_XmlConnect_Model_Simplexml_Element */ + $xmlModel = Mage::getModel('xmlconnect/simplexml_element', ''); + + $balance = Mage::helper('core')->currency($card->getBalance(), true, false); + + $result[] = $this->__("Gift Card: %s", $card->getCode()); + $result[] = $this->__('Current Balance: %s', $balance); + + if ($card->getDateExpires()) { + $result[] = $this->__('Expires: %s', $this->formatDate($card->getDateExpires(), 'short')); + } + $xmlModel->addCustomChild('info', implode(PHP_EOL, $result)); + } else { + $xmlModel = Mage::getModel('xmlconnect/simplexml_element', ''); + $xmlModel->addCustomChild('status', Mage_XmlConnect_Controller_Action::MESSAGE_STATUS_ERROR); + $xmlModel->addCustomChild('text', $this->__('Wrong or expired Gift Card Code.')); + } + + return $xmlModel->asNiceXml(); + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Details.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Details.php index 51f73a472c..5cf64fc278 100755 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Details.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Details.php @@ -33,6 +33,27 @@ */ class Mage_XmlConnect_Block_Customer_Order_Details extends Mage_Payment_Block_Info { + /** + * Pre-defined array of methods that we are going to render + * + * Core renderer list: + * - 'ccsave' => Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Ccsave + * - 'checkmo' => Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Checkmo + * - 'purchaseorder' => Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Purchaseorder + * - 'authorizenet' => Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Authorizenet + * - 'pbridge_authorizenet' => Mage_Paygate_Block_Authorizenet_Info_Cc + * - 'pbridge_verisign' => Mage_Payment_Block_Info_Cc + * - 'paypal_express' => Mage_Paypal_Block_Payment_Info + * - 'paypal_mecl' => Mage_Paypal_Block_Payment_Info + * - 'pbridge_paypal_direct' => Mage_Paypal_Block_Payment_Info + * - 'pbridge_paypaluk_direct' => Mage_Paypal_Block_Payment_Info + * - 'free' => Mage_Payment_Block_Info + */ + protected $_methodArray = array( + 'ccsave', 'checkmo', 'purchaseorder', 'authorizenet', 'pbridge_authorizenet', 'pbridge_verisign', + 'paypal_express', 'paypal_mecl', 'pbridge_paypal_direct', 'pbridge_paypaluk_direct', 'free' + ); + /** * Render customer orders list xml * @@ -42,31 +63,18 @@ protected function _toHtml() { /** @var $orderXmlObj Mage_XmlConnect_Model_Simplexml_Element */ $orderXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); - /** @var $order Mage_Sales_Model_Order */ - $order = Mage::registry('current_order'); - if (!($order instanceof Mage_Sales_Model_Order)) { - Mage::throwException($this->__('Model of order is not loaded.')); - } + + $order = $this->_getOrder(); + $orderDate = $this->formatDate($order->getCreatedAtStoreDate(), 'long'); - $orderXmlObj->addCustomChild( - 'order', - null, - array( - 'label' => Mage::helper('sales')->__('Order #%s - %s', $order->getRealOrderId(), $order->getStatusLabel()), - 'order_date' => Mage::helper('sales')->__('Order Date: %s', $orderDate) - ) - ); + $orderXmlObj->addCustomChild('order', null, array( + 'label' => $this->__('Order #%s - %s', $order->getRealOrderId(), $order->getStatusLabel()), + 'order_date' => $this->__('Order Date: %s', $orderDate) + )); if (!$order->getIsVirtual()) { - $shipping = preg_replace( - array('@\r@', '@\n+@'), - array('', "\n"), - $order->getShippingAddress()->format('text') - ); - $billing = preg_replace( - array('@\r@', '@\n+@'), - array('', "\n"), - $order->getBillingAddress()->format('text') - ); + $shipping = Mage::helper('xmlconnect')->trimLineBreaks($order->getShippingAddress()->format('text')); + $billing = Mage::helper('xmlconnect')->trimLineBreaks($order->getBillingAddress()->format('text')); + $orderXmlObj->addCustomChild('shipping_address', $shipping); $orderXmlObj->addCustomChild('billing_address', $billing); @@ -77,36 +85,43 @@ protected function _toHtml() } $orderXmlObj->addCustomChild('shipping_method', $shippingMethodDescription); } - /** - * Pre-defined array of methods that we are going to render - */ - $methodArray = array( - 'ccsave' => 'Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Ccsave', - 'checkmo' => 'Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Checkmo', - 'purchaseorder' => 'Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Purchaseorder', - 'authorizenet' => 'Mage_XmlConnect_Block_Checkout_Payment_Method_Info_Authorizenet', - ); - // TODO: create info blocks for Payment Bridge methods -// /** -// * Check if the Payment Bridge module is available and add methods for rendering -// */ -// if (is_object(Mage::getConfig()->getNode('modules/Enterprise_Pbridge'))) { -// $pbridgeMethodArray = array( -// 'pbridge_authorizenet' => 'Enterprise_Pbridge_Model_Payment_Method_Authorizenet', -// 'pbridge_paypal' => 'Enterprise_Pbridge_Model_Payment_Method_Paypal', -// 'pbridge_verisign' => 'Enterprise_Pbridge_Model_Payment_Method_Payflow_Pro', -// 'pbridge_paypaluk' => 'Enterprise_Pbridge_Model_Payment_Method_Paypaluk', -// ); -// $methodArray = $methodArray + $pbridgeMethodArray; -// } - // TODO: it's need to create an info blocks for other payment methods (including Enterprise) + $this->_addPaymentMethodInfoToXmlObj($orderXmlObj); + + $itemsBlock = $this->getLayout()->getBlock('xmlconnect.customer.order.items'); + if ($itemsBlock) { + /** @var $itemsBlock Mage_XmlConnect_Block_Customer_Order_Items */ + $itemsBlock->setItems($order->getItemsCollection()); + $itemsBlock->addItemsToXmlObject($orderXmlObj); + $totalsBlock = $this->getLayout()->getBlock('xmlconnect.customer.order.totals'); + if ($totalsBlock) { + $totalsBlock->setOrder($order); + $totalsBlock->addTotalsToXmlObject($orderXmlObj); + } + } else { + $orderXmlObj->addChild('ordered_items'); + } + + return $orderXmlObj->asNiceXml(); + } + /** + * Add payment method info to order xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $orderXmlObj + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + protected function _addPaymentMethodInfoToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $orderXmlObj) + { + $order = $this->_getOrder(); + + // TODO: it's need to create an info blocks for other payment methods (including Enterprise) $method = $this->helper('payment')->getInfoBlock($order->getPayment())->getMethod(); $methodCode = $method->getCode(); $paymentNode = $orderXmlObj->addChild('payment_method'); - if (array_key_exists($methodCode, $methodArray)) { + + if (in_array($methodCode, $this->_methodArray, true)) { $currentBlockRenderer = 'xmlconnect/checkout_payment_method_info_' . $methodCode; $currentBlockName = 'xmlconnect.checkout.payment.method.info.' . $methodCode; $this->getLayout()->addBlock($currentBlockRenderer, $currentBlockName); @@ -126,9 +141,7 @@ protected function _toHtml() if (!empty($specificInfo)) { foreach ($specificInfo as $label => $value) { if ($value) { - $paymentNode->addCustomChild( - 'item', - implode($this->getValueAsArray($value, true), PHP_EOL), + $paymentNode->addCustomChild('item', implode($this->getValueAsArray($value, true), '\n'), array('label' => $label) ); } @@ -136,20 +149,37 @@ protected function _toHtml() } } - $itemsBlock = $this->getLayout()->getBlock('xmlconnect.customer.order.items'); - if ($itemsBlock) { - /** @var $itemsBlock Mage_XmlConnect_Block_Customer_Order_Items */ - $itemsBlock->setItems($order->getItemsCollection()); - $itemsBlock->addItemsToXmlObject($orderXmlObj); - $totalsBlock = $this->getLayout()->getBlock('xmlconnect.customer.order.totals'); - if ($totalsBlock) { - $totalsBlock->setOrder($order); - $totalsBlock->addTotalsToXmlObject($orderXmlObj); - } - } else { - $orderXmlObj->addChild('ordered_items'); + return $orderXmlObj; + } + + /** + * Get order model + * + * @through Mage_Core_Exception + * @return Mage_Sales_Model_Order + */ + protected function _getOrder() + { + $order = Mage::registry('current_order'); + if (!($order instanceof Mage_Sales_Model_Order)) { + Mage::throwException($this->__('Order is not available.')); } + return $order; + } - return $orderXmlObj->asNiceXml(); + /** + * Format address string + * + * @deprecated after 1.6.0.0 + * @param string $address + * @return string + */ + protected function _formatAddress($address) + { + return preg_replace( + array('@\r@', '@\n+@'), + array('', '\n'), + $address + ); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Bundle.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Bundle.php index d5b500f052..6efc33fe0c 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Bundle.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Bundle.php @@ -31,20 +31,19 @@ * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Bundle - extends Mage_Bundle_Block_Sales_Order_Items_Renderer +class Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Bundle extends Mage_Bundle_Block_Sales_Order_Items_Renderer { /** * Add item to XML object + * (get from template: bundle/sales/order/items/renderer.phtml) * * @param Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj - * @return void + * @return null */ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) { /** @var $parentItem Mage_Sales_Model_Order_Item */ $parentItem = $this->getItem(); - $items = array_merge(array($parentItem), $parentItem->getChildrenItems()); $_prevOptionId = ''; @@ -58,21 +57,29 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde /** @var $optionsXml Mage_XmlConnect_Model_Simplexml_Element */ $optionsXml = $itemXml->addChild('related_products'); - $weeeTaxAppliedAmount = (float)$parentItem->getWeeeTaxAppliedAmount(); - $weeeTaxDisposition = (float)$parentItem->getWeeeTaxDisposition(); - $typeOfDisplay1 = $weeeHelper->typeOfDisplay($parentItem, 1, 'sales') - && $weeeTaxAppliedAmount; - $typeOfDisplay2 = $weeeHelper->typeOfDisplay($parentItem, 2, 'sales') - && $weeeTaxAppliedAmount; - $typeOfDisplay4 = $weeeHelper->typeOfDisplay($parentItem, 4, 'sales') - && $weeeTaxAppliedAmount; - $typeOfDisplay014 = $weeeHelper->typeOfDisplay($parentItem, array(0, 1, 4), 'sales') - && $weeeTaxAppliedAmount; - $weeeTaxes = $weeeHelper->getApplied($parentItem); - - /** @var $_item Mage_Sales_Model_Order_Item */ - foreach ($items as $_item) { - $isOption = $_item->getParentItem() ? true : false; + $this->setWeeeTaxAppliedAmount($parentItem->getWeeeTaxAppliedAmount()); + $this->setWeeeTaxDisposition($parentItem->getWeeeTaxDisposition()); + + $typeOfDisplay1 = $weeeHelper->typeOfDisplay($parentItem, 1, 'sales') + && $this->getWeeeTaxAppliedAmount(); + $typeOfDisplay2 = $weeeHelper->typeOfDisplay($parentItem, 2, 'sales') + && $this->getWeeeTaxAppliedAmount(); + $typeOfDisplay4 = $weeeHelper->typeOfDisplay($parentItem, 4, 'sales') + && $this->getWeeeTaxAppliedAmount(); + $typeOfDisplay014 = $weeeHelper->typeOfDisplay($parentItem, array(0, 1, 4), 'sales') + && $this->getWeeeTaxAppliedAmount(); + + $this->setTypesOfDisplay(array( + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_1 => $typeOfDisplay1, + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_2 => $typeOfDisplay2, + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_4 => $typeOfDisplay4, + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_14 => $typeOfDisplay014, + )); + $this->setWeeeTaxes($weeeHelper->getApplied($parentItem)); + + /** @var $item Mage_Sales_Model_Order_Item */ + foreach ($items as $item) { + $isOption = $item->getParentItem() ? true : false; /** @var $objectXml Mage_XmlConnect_Model_Simplexml_Element */ if ($isOption) { @@ -80,23 +87,23 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde } else { $objectXml = $itemXml; } - $objectXml->addAttribute('product_id', $_item->getProductId()); - $objectXml->addCustomChild('entity_type', $_item->getProductType()); + $objectXml->addAttribute('product_id', $item->getProductId()); + $objectXml->addCustomChild('entity_type', $item->getProductType()); if ($isOption) { - $attributes = $this->getSelectionAttributes($_item); + $attributes = $this->getSelectionAttributes($item); if ($_prevOptionId != $attributes['option_id']) { $objectXml->addAttribute('label', $objectXml->xmlAttribute($attributes['option_label'])); $_prevOptionId = $attributes['option_id']; } } - $objectXml->addCustomChild('sku', Mage::helper('core/string')->splitInjection($_item->getSku())); + $objectXml->addCustomChild('sku', Mage::helper('core/string')->splitInjection($item->getSku())); if ($isOption) { - $name = $this->getValueHtml($_item); + $name = $this->getValueHtml($item); } else { - $name = $_item->getName(); + $name = $item->getName(); } $objectXml->addCustomChild('name', $name); @@ -104,129 +111,24 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde if (!$isOption) { /** @var $priceXml Mage_XmlConnect_Model_Simplexml_Element */ $priceXml = $objectXml->addChild('price'); + /** @var $subtotalXml Mage_XmlConnect_Model_Simplexml_Element */ + $subtotalXml = $objectXml->addChild('subtotal'); // Price excluding tax if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceExclTax()) { - - if ($typeOfDisplay014) { - $price = $parentItem->getPrice() + $weeeTaxAppliedAmount + $weeeTaxDisposition; - } else { - $price = $parentItem->getPrice(); - } - - $config = array( - 'value' => $this->_formatPrice($price) + Mage::helper('xmlconnect/customer_order')->addPriceAndSubtotalToXml( + $this, + $parentItem, + $priceXml, + $subtotalXml ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Excl. Tax'); - } - $exclPriceXml = $priceXml->addCustomChild( - 'excluding_tax', - null, - $config - ); - - // TODO: move repeated code into another place - if ($weeeTaxes) { - /** @var $weeeXml Mage_XmlConnect_Model_Simplexml_Element */ - if ($typeOfDisplay1) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount']), - array('label' => $tax['title']) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount_incl_tax']), - array('label' => $tax['title']) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $exclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice( - $parentItem->getPrice() + $weeeTaxAppliedAmount + $weeeTaxDisposition - ), - array('label' => $weeeHelper->__('Total')) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } } // Price including tax if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceInclTax()) { - $incl = $this->helper('checkout')->getPriceInclTax($parentItem); - - if ($typeOfDisplay014) { - $price = $incl + $weeeTaxAppliedAmount; - } else { - $price = $incl - $weeeTaxDisposition; - } - - $config = array( - 'value' => $this->_formatPrice($price) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Incl. Tax'); - } - - $inclPriceXml = $priceXml->addCustomChild( - 'including_tax', - null, - $config + Mage::helper('xmlconnect/customer_order')->addPriceAndSubtotalToXml( + $this, $parentItem, $priceXml, $subtotalXml, true ); - - if ($weeeTaxes) { - if ($typeOfDisplay1) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount']), - array('label' => $tax['title']) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount_incl_tax']), - array('label' => $tax['title']) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $inclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice( - $incl + $weeeTaxAppliedAmount - ), - array('label' => $weeeHelper->__('Total incl. tax')) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } } } @@ -236,205 +138,39 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde || (!$isOption && !$this->isChildCalculated()) ) { $qtyXml = $objectXml->addChild('qty'); - if ($_item->getQtyOrdered() > 0) { - $qtyXml->addCustomChild( - 'value', - $_item->getQtyOrdered() * 1, - array('label' => Mage::helper('sales')->__('Ordered')) - ); + if ($item->getQtyOrdered() > 0) { + $qtyXml->addCustomChild('value', $item->getQtyOrdered() * 1, array( + 'label' => Mage::helper('sales')->__('Ordered') + )); } - if ($_item->getQtyShipped() > 0 && !$this->isShipmentSeparately()) { - $qtyXml->addCustomChild( - 'value', - $_item->getQtyShipped() * 1, - array('label' => Mage::helper('sales')->__('Shipped')) - ); + if ($item->getQtyShipped() > 0 && !$this->isShipmentSeparately()) { + $qtyXml->addCustomChild('value', $item->getQtyShipped() * 1, array( + 'label' => Mage::helper('sales')->__('Shipped') + )); } - if ($_item->getQtyCanceled() > 0) { - $qtyXml->addCustomChild( - 'value', - $_item->getQtyCanceled() * 1, - array('label' => Mage::helper('sales')->__('Canceled')) - ); + if ($item->getQtyCanceled() > 0) { + $qtyXml->addCustomChild('value', $item->getQtyCanceled() * 1, array( + 'label' => Mage::helper('sales')->__('Canceled') + )); } - if ($_item->getQtyRefunded() > 0) { - $qtyXml->addCustomChild( - 'value', - $_item->getQtyRefunded() * 1, - array('label' => Mage::helper('sales')->__('Refunded')) - ); + if ($item->getQtyRefunded() > 0) { + $qtyXml->addCustomChild('value', $item->getQtyRefunded() * 1, array( + 'label' => Mage::helper('sales')->__('Refunded') + )); } - } elseif ($_item->getQtyShipped() > 0 && $isOption && $this->isShipmentSeparately()) { + } elseif ($item->getQtyShipped() > 0 && $isOption && $this->isShipmentSeparately()) { $qtyXml = $objectXml->addChild('qty'); - $qtyXml->addCustomChild( - 'value', - $_item->getQtyShipped() * 1, - array('label' => Mage::helper('sales')->__('Shipped')) - ); - } - - // set subtotals exactly for the Bundle product, but not for related products - if (!$isOption) { - /** @var $subtotalXml Mage_XmlConnect_Model_Simplexml_Element */ - $subtotalXml = $objectXml->addChild('subtotal'); - - // Subtotal excluding tax - if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceExclTax()) { - if ($typeOfDisplay014) { - $subtotal = $parentItem->getRowTotal() - + $parentItem->getWeeeTaxAppliedRowAmount() - + $parentItem->getWeeeTaxRowDisposition(); - } else { - $subtotal = $parentItem->getRowTotal(); - } - - $config = array( - 'value' => $this->_formatPrice($subtotal) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Excl. Tax'); - } - $exclPriceXml = $subtotalXml->addCustomChild( - 'excluding_tax', - null, - $config - ); - - if ($weeeTaxes) { - /** @var $weeeXml Mage_XmlConnect_Model_Simplexml_Element */ - if ($typeOfDisplay1) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount']), - array('label' => $tax['title']) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount_incl_tax']), - array('label' => $tax['title']) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $exclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice( - $parentItem->getRowTotal() - + $parentItem->getWeeeTaxAppliedRowAmount() - + $parentItem->getWeeeTaxRowDisposition() - ), - array('label' => $weeeHelper->__('Total')) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } - } - - // Subtotal including tax - if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceInclTax()) { - $incl = $this->helper('checkout')->getSubtotalInclTax($parentItem); - - if ($typeOfDisplay014) { - $subtotal = $incl + $parentItem->getWeeeTaxAppliedRowAmount(); - } else { - $subtotal = $incl - $parentItem->getWeeeTaxRowDisposition(); - } - - $config = array( - 'value' => $this->_formatPrice($subtotal) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Incl. Tax'); - } - - $inclPriceXml = $subtotalXml->addCustomChild( - 'including_tax', - null, - $config - ); - - if ($weeeTaxes) { - if ($typeOfDisplay1) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount']), - array('label' => $tax['title']) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount_incl_tax']), - array('label' => $tax['title']) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $inclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice( - $incl + $parentItem->getWeeeTaxAppliedRowAmount() - ), - array('label' => $weeeHelper->__('Total incl. tax')) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } - } + $qtyXml->addCustomChild('value', $item->getQtyShipped() * 1, array( + 'label' => Mage::helper('sales')->__('Shipped') + )); } } if ($parentItem->getDescription()) { - $itemXml->addCustomChild( - 'description', - $parentItem->getDescription() - ); + $itemXml->addCustomChild('description', $parentItem->getDescription()); } - if ($options = $this->getItemOptions()) { - /** @var $optionsXml Mage_XmlConnect_Model_Simplexml_Element */ - $optionsXml = $itemXml->addChild('options'); - foreach ($options as $option) { - $formatedOptionValue = $this->getFormatedOptionValue($option); - if (isset($formatedOptionValue['full_view']) && isset($formatedOptionValue['value'])) { - $value = $formatedOptionValue['value']; - } elseif (isset($option['print_value'])) { - $value = $option['print_value']; - } else { - $value = $option['value']; - } - - if ($value) { - $optionsXml->addCustomChild( - 'option', - strip_tags($value), - array('label' => $option['label']) - ); - } - } - } + Mage::helper('xmlconnect/customer_order')->addItemOptionsToXml($this, $itemXml); } /** @@ -447,9 +183,8 @@ public function getValueHtml($item) { $attributes = $this->getSelectionAttributes($item); if ($attributes) { - return sprintf('%d', $attributes['qty']) . ' x ' - . $item->getName() - . ' - ' . $this->_formatPrice($attributes['price']); + return sprintf('%d', $attributes['qty']) . ' x ' . $item->getName() . ' - ' + . $this->_formatPrice($attributes['price']); } else { return $item->getName(); } @@ -463,6 +198,6 @@ public function getValueHtml($item) */ protected function _formatPrice($price) { - return $this->getOrder()->getOrderCurrency()->formatPrecision($price, 2, array(), false); + return Mage::helper('xmlconnect/customer_order')->formatPrice($this, $price); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Default.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Default.php index 7b7a692407..3f6b45d5c8 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Default.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Default.php @@ -31,14 +31,14 @@ * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Default - extends Mage_Sales_Block_Order_Item_Renderer_Default +class Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Default extends Mage_Sales_Block_Order_Item_Renderer_Default { /** * Add item to XML object + * (get from template: sales/order/items/renderer/default.phtml) * * @param Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj - * @return void + * @return null */ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) { @@ -46,13 +46,9 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde $item = $this->getItem(); /** @var $itemXml Mage_XmlConnect_Model_Simplexml_Element */ - $itemXml = $orderItemXmlObj->addCustomChild( - 'item', - null, - array( - 'product_id' => $item->getProductId() - ) - ); + $itemXml = $orderItemXmlObj->addCustomChild('item', null, array( + 'product_id' => $item->getProductId() + )); $itemXml->addCustomChild('name', $item->getName()); /** @var $weeeHelper Mage_Weee_Helper_Data */ @@ -60,347 +56,57 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde /** @var $taxHelper Mage_Tax_Helper_Data */ $taxHelper = $this->helper('tax'); - $options = $this->getItemOptions(); - if ($options) { - /** @var $optionsXml Mage_XmlConnect_Model_Simplexml_Element */ - $optionsXml = $itemXml->addChild('options'); - foreach ($options as $option) { - $value = false; - $formatedOptionValue = $this->getFormatedOptionValue($option); - if (isset($formatedOptionValue['full_view']) && isset($formatedOptionValue['value'])) { - $value = $formatedOptionValue['value']; - } elseif (isset($option['print_value'])) { - $value = $option['print_value']; - } elseif (isset($option['value'])) { - $value = $option['value']; - } - if ($value) { - $optionsXml->addCustomChild( - 'option', - strip_tags($value), - array('label' => $option['label']) - ); - } - } + Mage::helper('xmlconnect/customer_order')->addItemOptionsToXml($this, $itemXml); - $addtInfoBlock = $this->getProductAdditionalInformationBlock(); - if ($addtInfoBlock) { - // TODO: find how to set additional info block - // $addtInfoBlock->setItem($item)->toHtml(); - } + $addtInfoBlock = $this->getProductAdditionalInformationBlock(); + if ($addtInfoBlock) { + // TODO: find how to set additional info block + // $addtInfoBlock->setItem($item)->toHtml(); } $itemXml->addCustomChild('entity_type', $item->getProductType()); $itemXml->addCustomChild('description', $item->getDescription()); $itemXml->addCustomChild('sku', Mage::helper('core/string')->splitInjection($this->getSku())); + $this->setWeeeTaxAppliedAmount($item->getWeeeTaxAppliedAmount()); + $this->setWeeeTaxDisposition($item->getWeeeTaxDisposition()); + + $typeOfDisplay1 = $weeeHelper->typeOfDisplay($item, 1, 'sales') + && $this->getWeeeTaxAppliedAmount(); + $typeOfDisplay2 = $weeeHelper->typeOfDisplay($item, 2, 'sales') + && $this->getWeeeTaxAppliedAmount(); + $typeOfDisplay4 = $weeeHelper->typeOfDisplay($item, 4, 'sales') + && $this->getWeeeTaxAppliedAmount(); + $typeOfDisplay014 = $weeeHelper->typeOfDisplay($item, array(0, 1, 4), 'sales') + && $this->getWeeeTaxAppliedAmount(); + + $this->setTypesOfDisplay(array( + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_1 => $typeOfDisplay1, + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_2 => $typeOfDisplay2, + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_4 => $typeOfDisplay4, + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_14 => $typeOfDisplay014, + )); + $this->setWeeeTaxes($weeeHelper->getApplied($item)); + /** @var $priceXml Mage_XmlConnect_Model_Simplexml_Element */ $priceXml = $itemXml->addChild('price'); - $weeeTaxAppliedAmount = (float)$item->getWeeeTaxAppliedAmount(); - $weeeTaxDisposition = (float)$item->getWeeeTaxDisposition(); - $typeOfDisplay1 = $weeeHelper->typeOfDisplay($item, 1, 'sales') && $weeeTaxAppliedAmount; - $typeOfDisplay2 = $weeeHelper->typeOfDisplay($item, 2, 'sales') && $weeeTaxAppliedAmount; - $typeOfDisplay4 = $weeeHelper->typeOfDisplay($item, 4, 'sales') && $weeeTaxAppliedAmount; - $typeOfDisplay014 = $weeeHelper->typeOfDisplay($item, array(0, 1, 4), 'sales') && $weeeTaxAppliedAmount; - $weeeTaxes = $weeeHelper->getApplied($item); - - // Price excluding tax - if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceExclTax()) { - if ($typeOfDisplay014) { - $price = $item->getPrice() + $weeeTaxAppliedAmount + $weeeTaxDisposition; - } else { - $price = $item->getPrice(); - } - - $config = array( - 'value' => $this->_formatPrice($price) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Excl. Tax'); - } - - /** @var $exclPriceXml Mage_XmlConnect_Model_Simplexml_Element */ - $exclPriceXml = $priceXml->addCustomChild( - 'excluding_tax', - null, - $config - ); - - // TODO: move repeated code into another place - if ($weeeTaxes) { - /** @var $weeeXml Mage_XmlConnect_Model_Simplexml_Element */ - if ($typeOfDisplay1) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount']), - array('label' => $tax['title']) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount_incl_tax']), - array('label' => $tax['title']) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $exclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice( - $item->getPrice() + $weeeTaxAppliedAmount + $weeeTaxDisposition - ), - array('label' => $weeeHelper->__('Total')) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } - } - - // Price including tax - if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceInclTax()) { - $incl = $this->helper('checkout')->getPriceInclTax($item); - - if ($typeOfDisplay014) { - $price = $incl + $weeeTaxAppliedAmount; - } else { - $price = $incl - $weeeTaxDisposition; - } - - $config = array( - 'value' => $this->_formatPrice($price) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Incl. Tax'); - } - - /** @var $inclPriceXml Mage_XmlConnect_Model_Simplexml_Element */ - $inclPriceXml = $priceXml->addCustomChild( - 'including_tax', - null, - $config - ); - - if ($weeeTaxes) { - /** @var $weeeXml Mage_XmlConnect_Model_Simplexml_Element */ - if ($typeOfDisplay1) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount']), - array('label' => $tax['title']) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount_incl_tax']), - array('label' => $tax['title']) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $inclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice($incl + $weeeTaxAppliedAmount), - array('label' => $weeeHelper->__('Total incl. tax')) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } - } // Quantity: Ordered, Shipped, Cancelled, Refunded - /** @var $quantityXml Mage_XmlConnect_Model_Simplexml_Element */ - $quantityXml = $itemXml->addChild('qty'); - $qty = 1 * $item->getQtyOrdered(); - if ($qty > 0) { - $quantityXml->addCustomChild( - 'value', - $qty, - array('label' => $this->__('Ordered')) - ); - } - $qty = 1 * $item->getQtyShipped(); - if ($qty > 0) { - $quantityXml->addCustomChild( - 'value', - $qty, - array('label' => $this->__('Shipped')) - ); - } - $qty = 1 * $item->getQtyCanceled(); - if ($qty > 0) { - $quantityXml->addCustomChild( - 'value', - $qty, - array('label' => $this->__('Canceled')) - ); - } - $qty = 1 * $item->getQtyRefunded(); - if ($qty > 0) { - $quantityXml->addCustomChild( - 'value', - $qty, - array('label' => $this->__('Refunded')) - ); - } + Mage::helper('xmlconnect/customer_order')->addQuantityToXml($this, $itemXml->addChild('qty'), $item); - // Subtotal excluding tax /** @var $subtotalXml Mage_XmlConnect_Model_Simplexml_Element */ $subtotalXml = $itemXml->addChild('subtotal'); + // Price & subtotal - excluding tax if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceExclTax()) { - - if ($typeOfDisplay014) { - $subtotal = $item->getRowTotal() - + $item->getWeeeTaxAppliedRowAmount() - + $item->getWeeeTaxRowDisposition(); - } else { - $subtotal = $item->getRowTotal(); - } - - $config = array( - 'value' => $this->_formatPrice($subtotal) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Excl. Tax'); - } - - /** @var $exclPriceXml Mage_XmlConnect_Model_Simplexml_Element */ - $exclPriceXml = $subtotalXml->addCustomChild( - 'excluding_tax', - null, - $config - ); - - if ($weeeTaxes) { - if ($typeOfDisplay1) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount']), - array('label' => $tax['title']) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount_incl_tax']), - array('label' => $tax['title']) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $exclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice( - $item->getRowTotal() - + $item->getWeeeTaxAppliedRowAmount() - + $item->getWeeeTaxRowDisposition() - ), - array('label' => $weeeHelper->__('Total')) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } + Mage::helper('xmlconnect/customer_order')->addPriceAndSubtotalToXml($this, $item, $priceXml, $subtotalXml); } - // Subtotal including tax + // Price & subtotal - including tax if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceInclTax()) { - $incl = $this->helper('checkout')->getSubtotalInclTax($item); - - if ($typeOfDisplay014) { - $subtotal = $incl + $item->getWeeeTaxAppliedRowAmount(); - } else { - $subtotal = $incl - $item->getWeeeTaxRowDisposition(); - } - - $config = array( - 'value' => $this->_formatPrice($subtotal) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Incl. Tax'); - } - - /** @var $inclPriceXml Mage_XmlConnect_Model_Simplexml_Element */ - $inclPriceXml = $subtotalXml->addCustomChild( - 'including_tax', - null, - $config + Mage::helper('xmlconnect/customer_order')->addPriceAndSubtotalToXml( + $this, $item, $priceXml, $subtotalXml, true ); - - if ($weeeTaxes) { - if ($typeOfDisplay1) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount']), - array('label' => $tax['title']) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount_incl_tax']), - array('label' => $tax['title']) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $inclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice($incl + $item->getWeeeTaxAppliedRowAmount()), - array('label' => $weeeHelper->__('Total incl. tax')) - ); - } - } } } - - /** - * Format price using order currency - * - * @param float $price - * @return string - */ - protected function _formatPrice($price) - { - return $this->getOrder()->getOrderCurrency()->formatPrecision($price, 2, array(), false); - } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Downloadable.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Downloadable.php index 2b9ca910ef..b6f00368e0 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Downloadable.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Downloadable.php @@ -36,9 +36,10 @@ class Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Downloadable { /** * Add item to XML object + * (get from template: downloadable/sales/order/items/renderer/downloadable.phtml) * * @param Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj - * @return void + * @return null */ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) { @@ -46,13 +47,9 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde $item = $this->getItem(); /** @var $itemXml Mage_XmlConnect_Model_Simplexml_Element */ - $itemXml = $orderItemXmlObj->addCustomChild( - 'item', - null, - array( - 'product_id' => $item->getProductId() - ) - ); + $itemXml = $orderItemXmlObj->addCustomChild('item', null, array( + 'product_id' => $item->getProductId() + )); $itemXml->addCustomChild('name', $item->getName()); /** @var $weeeHelper Mage_Weee_Helper_Data */ @@ -60,47 +57,19 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde /** @var $taxHelper Mage_Tax_Helper_Data */ $taxHelper = $this->helper('tax'); - $options = $this->getItemOptions(); - if ($options) { - /** @var $optionsXml Mage_XmlConnect_Model_Simplexml_Element */ - $optionsXml = $itemXml->addChild('options'); - foreach ($options as $option) { - $formatedOptionValue = $this->getFormatedOptionValue($option); - if (isset($formatedOptionValue['full_view']) && isset($formatedOptionValue['value'])) { - $value = $formatedOptionValue['value']; - } elseif (isset($option['print_value'])) { - $value = $option['print_value']; - } else { - $value = $option['value']; - } - $optionsXml->addCustomChild( - 'option', - strip_tags($value), - array( - 'label' => $option['label'] - ) - ); - } + Mage::helper('xmlconnect/customer_order')->addItemOptionsToXml($this, $itemXml); - $addtInfoBlock = $this->getProductAdditionalInformationBlock(); - if ($addtInfoBlock) { - // TODO: find how to set additional info block - // $addtInfoBlock->setItem($item)->toHtml(); - } + $addtInfoBlock = $this->getProductAdditionalInformationBlock(); + if ($addtInfoBlock) { + // TODO: find how to set additional info block + // $addtInfoBlock->setItem($item)->toHtml(); } $links = $this->getLinks(); if ($links) { - $linksXml = $itemXml->addCustomChild( - 'links', - null, - array('label' => $this->getLinksTitle()) - ); + $linksXml = $itemXml->addCustomChild('links', null, array('label' => $this->getLinksTitle())); foreach ($links->getPurchasedItems() as $link) { - $linksXml->addCustomChild( - 'link', - $link->getLinkTitle() - ); + $linksXml->addCustomChild('link', $link->getLinkTitle()); } } @@ -110,342 +79,48 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde /** @var $priceXml Mage_XmlConnect_Model_Simplexml_Element */ $priceXml = $itemXml->addChild('price'); - $weeeTaxAppliedAmount = (float)$item->getWeeeTaxAppliedAmount(); - $weeeTaxDisposition = (float)$item->getWeeeTaxDisposition(); - $typeOfDisplay1 = $weeeHelper->typeOfDisplay($item, 1, 'sales') && $weeeTaxAppliedAmount; - $typeOfDisplay2 = $weeeHelper->typeOfDisplay($item, 2, 'sales') && $weeeTaxAppliedAmount; - $typeOfDisplay4 = $weeeHelper->typeOfDisplay($item, 4, 'sales') && $weeeTaxAppliedAmount; - $typeOfDisplay014 = $weeeHelper->typeOfDisplay($item, array(0, 1, 4), 'sales') && $weeeTaxAppliedAmount; - $weeeTaxes = $weeeHelper->getApplied($item); - - // Price excluding tax - if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceExclTax()) { - if ($typeOfDisplay014) { - $price = $item->getPrice() + $weeeTaxAppliedAmount + $weeeTaxDisposition; - } else { - $price = $item->getPrice(); - } - - $config = array( - 'value' => $this->_formatPrice($price) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Excl. Tax'); - } - - /** @var $exclPriceXml Mage_XmlConnect_Model_Simplexml_Element */ - $exclPriceXml = $priceXml->addCustomChild( - 'excluding_tax', - null, - $config - ); - - if ($weeeTaxes) { - /** @var $weeeXml Mage_XmlConnect_Model_Simplexml_Element */ - if ($typeOfDisplay1) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount']), - array( - 'label' => $tax['title'] - ) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount_incl_tax']), - array( - 'label' => $tax['title'] - ) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $exclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice( - $item->getPrice() + $weeeTaxAppliedAmount + $weeeTaxDisposition - ), - array( - 'label' => $weeeHelper->__('Total') - ) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } - } - - // Price including tax - if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceInclTax()) { - $incl = $this->helper('checkout')->getPriceInclTax($item); - - if ($typeOfDisplay014) { - $price = $incl + $weeeTaxAppliedAmount; - } else { - $price = $incl - $weeeTaxDisposition; - } - - $config = array( - 'value' => $this->_formatPrice($price) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Incl. Tax'); - } - - /** @var $inclPriceXml Mage_XmlConnect_Model_Simplexml_Element */ - $inclPriceXml = $priceXml->addCustomChild( - 'including_tax', - null, - $config - ); - - if ($weeeTaxes) { - /** @var $weeeXml Mage_XmlConnect_Model_Simplexml_Element */ - if ($typeOfDisplay1) { - $weeeXml = $inclPriceXml->tddChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount']), - array( - 'label' => $tax['title'] - ) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $inclPriceXml->tddChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['amount_incl_tax']), - array( - 'label' => $tax['title'] - ) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $inclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice($incl + $weeeTaxAppliedAmount), - array( - 'label' => $weeeHelper->__('Total incl. tax') - ) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } - } // Quantity: Ordered, Shipped, Cancelled, Refunded - /** @var $quantityXml Mage_XmlConnect_Model_Simplexml_Element */ - $quantityXml = $itemXml->addChild('qty'); - $qty = 1 * $item->getQtyOrdered(); - if ($qty > 0) { - $quantityXml->addCustomChild( - 'value', - $qty, - array( - 'label' => $this->__('Ordered') - ) - ); - } - $qty = 1 * $item->getQtyShipped(); - if ($qty > 0) { - $quantityXml->addCustomChild( - 'value', - $qty, - array( - 'label' => $this->__('Shipped') - ) - ); - } - $qty = 1 * $item->getQtyCanceled(); - if ($qty > 0) { - $quantityXml->addCustomChild( - 'value', - $qty, - array( - 'label' => $this->__('Canceled') - ) - ); - } - $qty = 1 * $item->getQtyRefunded(); - if ($qty > 0) { - $quantityXml->addCustomChild( - 'value', - $qty, - array( - 'label' => $this->__('Refunded') - ) - ); - } + Mage::helper('xmlconnect/customer_order')->addQuantityToXml($this, $itemXml->addChild('qty'), $item); - // Subtotal excluding tax /** @var $subtotalXml Mage_XmlConnect_Model_Simplexml_Element */ $subtotalXml = $itemXml->addChild('subtotal'); + $this->setWeeeTaxAppliedAmount($item->getWeeeTaxAppliedAmount()); + $this->setWeeeTaxDisposition($item->getWeeeTaxDisposition()); + + $typeOfDisplay1 = $weeeHelper->typeOfDisplay($item, 1, 'sales') + && $this->getWeeeTaxAppliedAmount(); + $typeOfDisplay2 = $weeeHelper->typeOfDisplay($item, 2, 'sales') + && $this->getWeeeTaxAppliedAmount(); + $typeOfDisplay4 = $weeeHelper->typeOfDisplay($item, 4, 'sales') + && $this->getWeeeTaxAppliedAmount(); + $typeOfDisplay014 = $weeeHelper->typeOfDisplay($item, array(0, 1, 4), 'sales') + && $this->getWeeeTaxAppliedAmount(); + + $this->setTypesOfDisplay(array( + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_1 => $typeOfDisplay1, + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_2 => $typeOfDisplay2, + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_4 => $typeOfDisplay4, + Mage_XmlConnect_Helper_Customer_Order::PRICE_DISPLAY_TYPE_14 => $typeOfDisplay014, + )); + $this->setWeeeTaxes($weeeHelper->getApplied($item)); + + // Price & subtotal - excluding tax if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceExclTax()) { - - if ($typeOfDisplay014) { - $subtotal = $item->getRowTotal() - + $item->getWeeeTaxAppliedRowAmount() - + $item->getWeeeTaxRowDisposition(); - } else { - $subtotal = $item->getRowTotal(); - } - - $config = array( - 'value' => $this->_formatPrice($subtotal) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Excl. Tax'); - } - - /** @var $exclPriceXml Mage_XmlConnect_Model_Simplexml_Element */ - $exclPriceXml = $subtotalXml->addCustomChild( - 'excluding_tax', - null, - $config + Mage::helper('xmlconnect/customer_order')->addPriceAndSubtotalToXml( + $this, + $item, + $priceXml, + $subtotalXml ); - - if ($weeeTaxes) { - if ($typeOfDisplay1) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount']), - array( - 'label' => $tax['title'] - ) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $exclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount_incl_tax']), - array( - 'label' => $tax['title'] - ) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $exclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice( - $item->getRowTotal() - + $item->getWeeeTaxAppliedRowAmount() - + $item->getWeeeTaxRowDisposition() - ), - array( - 'label' => $weeeHelper->__('Total') - ) - ); - } - if (isset($weeeXml)) { - unset($weeeXml); - } - } } - // Subtotal including tax + // Price & subtotal - including tax if ($taxHelper->displaySalesBothPrices() || $taxHelper->displaySalesPriceInclTax()) { - $incl = $this->helper('checkout')->getSubtotalInclTax($item); - - if ($typeOfDisplay014) { - $subtotal = $incl + $item->getWeeeTaxAppliedRowAmount(); - } else { - $subtotal = $incl - $item->getWeeeTaxRowDisposition(); - } - - $config = array( - 'value' => $this->_formatPrice($subtotal) - ); - if ($taxHelper->displaySalesBothPrices()) { - $config['label'] = $this->__('Incl. Tax'); - } - - /** @var $inclPriceXml Mage_XmlConnect_Model_Simplexml_Element */ - $inclPriceXml = $subtotalXml->addCustomChild( - 'including_tax', - null, - $config + Mage::helper('xmlconnect/customer_order')->addPriceAndSubtotalToXml( + $this, $item, $priceXml, $subtotalXml, true ); - - if ($weeeHelper->getApplied($item)) { - if ($typeOfDisplay1) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount']), - array( - 'label' => $tax['title'] - ) - ); - } - } elseif ($typeOfDisplay2 || $typeOfDisplay4) { - $weeeXml = $inclPriceXml->addChild('weee'); - foreach ($weeeTaxes as $tax) { - $weeeXml->addCustomChild( - 'tax', - $this->_formatPrice($tax['row_amount_incl_tax']), - array( - 'label' => $tax['title'] - ) - ); - } - } - - if ($typeOfDisplay2) { - if (!isset($weeeXml)) { - $weeeXml = $inclPriceXml->addChild('weee'); - } - $weeeXml->addCustomChild( - 'total', - $this->_formatPrice($incl + $item->getWeeeTaxAppliedRowAmount()), - array( - 'label' => $weeeHelper->__('Total incl. tax') - ) - ); - } - } } } - - /** - * Format price using order currency - * - * @param float $price - * @return string - */ - protected function _formatPrice($price) - { - return $this->getOrder()->getOrderCurrency()->formatPrecision($price, 2, array(), false); - } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Giftcard.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Giftcard.php index b635e7e374..0b700a2d12 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Giftcard.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Giftcard.php @@ -62,16 +62,17 @@ protected function _getNameEmailString($name, $email) /** * Add item to XML object + * (get from template: sales/order/items/renderer/default.phtml) * * @param Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj - * @return void + * @return null */ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) { $item = $this->getOrderItem(); $item->setProductOptions(array('additional_options' => $this->getItemOptions())); - $defaultRenderer = $this->getLayout()->getBlock('xmlconnect.customer.order.items')->getItemRenderer(); + $defaultRenderer = $this->getLayout()->getBlock('xmlconnect.customer.order.items')->getItemRenderer(null); $defaultRenderer->setItem($item); $defaultRenderer->addItemToXmlObject($orderItemXmlObj); } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Grouped.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Grouped.php index 4cbce05dc5..d7fe114c3b 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Grouped.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Item/Renderer/Grouped.php @@ -31,8 +31,7 @@ * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Grouped - extends Mage_Sales_Block_Order_Item_Renderer_Grouped +class Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Grouped extends Mage_Sales_Block_Order_Item_Renderer_Grouped { /** * Default product type @@ -41,9 +40,10 @@ class Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Grouped /** * Add item to XML object + * (get from template: sales/order/items/renderer/default.phtml) * * @param Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj - * @return void + * @return null */ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orderItemXmlObj) { @@ -55,7 +55,6 @@ public function addItemToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orde } $renderer = $this->getRenderedBlock()->getItemRenderer($productType); $renderer->setItem($this->getItem()); - $renderer->addItemToXmlObject($orderItemXmlObj); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Items.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Items.php index c34a128482..536d420611 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Items.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Items.php @@ -39,25 +39,7 @@ class Mage_XmlConnect_Block_Customer_Order_Items extends Mage_Sales_Block_Order_ protected function _construct() { parent::_construct(); - $this->addItemRender('default', 'xmlconnect/customer_order_item_renderer_default'); - } - - /** - * Add renderer for item product type - * - * @param string $type - * @param string $block - * @param string $template - * @return Mage_Checkout_Block_Cart_Abstract - */ - public function addItemRender($type, $block, $template = '') - { - $this->_itemRenders[$type] = array( - 'block' => $block, - 'renderer' => null - ); - - return $this; + $this->addItemRender('default', 'xmlconnect/customer_order_item_renderer_default', null); } /** @@ -66,25 +48,25 @@ public function addItemRender($type, $block, $template = '') * @param string $type * @return Mage_Core_Block_Abstract */ - public function getItemRenderer($type = 'default') + public function getItemRenderer($type) { - if (!isset($this->_itemRenders[$type])) { + if (empty($type) || !isset($this->_itemRenders[$type])) { $type = 'default'; } if (is_null($this->_itemRenders[$type]['renderer'])) { $this->_itemRenders[$type]['renderer'] = $this->getLayout() - ->createBlock($this->_itemRenders[$type]['block']) - ->setRenderedBlock($this); + ->createBlock($this->_itemRenders[$type]['block'])->setRenderedBlock($this); } return $this->_itemRenders[$type]['renderer']; } /** * Render XML for items + * (get from template: sales/order/items.phtml) * * @param Mage_XmlConnect_Model_Simplexml_Element $orderXmlObj - * @return void + * @return null */ public function addItemsToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orderXmlObj) { diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/List.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/List.php index 27e12330be..90734f5fe9 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/List.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/List.php @@ -47,19 +47,13 @@ protected function _toHtml() { $ordersXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); - $orders = Mage::getResourceModel('sales/order_collection') - ->addFieldToSelect('*') - ->addFieldToFilter( - 'customer_id', - Mage::getSingleton('customer/session')->getCustomer()->getId() - ) - ->addFieldToFilter( - 'state', - array( - 'in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates() - ) - ) - ->setOrder('created_at', 'desc'); + $orders = Mage::getResourceModel('sales/order_collection')->addFieldToSelect('*')->addFieldToFilter( + 'customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId() + ) + ->addFieldToFilter( + 'state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()) + ) + ->setOrder('created_at', 'desc'); $orders->getSelect()->limit(self::ORDERS_LIST_LIMIT, 0); $orders->load(); @@ -71,21 +65,11 @@ protected function _toHtml() $item->addChild('number', $_order->getRealOrderId()); $item->addChild('date', $this->formatDate($_order->getCreatedAtStoreDate())); if ($_order->getShippingAddress()) { - $item->addChild( - 'ship_to', - $ordersXmlObj->xmlentities($_order->getShippingAddress()->getName()) - ); + $item->addChild('ship_to', $ordersXmlObj->xmlentities($_order->getShippingAddress()->getName())); } - $item->addChild( - 'total', - $_order->getOrderCurrency()->formatPrecision( - $_order->getGrandTotal(), - 2, - array(), - false, - false - ) - ); + $item->addChild('total', $_order->getOrderCurrency()->formatPrecision( + $_order->getGrandTotal(), 2, array(), false, false + )); $item->addChild('status', $_order->getStatusLabel()); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals.php index 55684e9a5b..5f0a980e68 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals.php @@ -35,9 +35,10 @@ class Mage_XmlConnect_Block_Customer_Order_Totals extends Mage_Sales_Block_Order { /** * Add order totals rendered to XML object + * (get from template: sales/order/totals.phtml) * * @param Mage_XmlConnect_Model_Simplexml_Element $orderXmlObj - * @return void + * @return null */ public function addTotalsToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $orderXmlObj) { @@ -112,20 +113,13 @@ public function addTotalsToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $or * * @param Varien_Object $total * @param Mage_XmlConnect_Model_Simplexml_Element $totalsXml - * @return void + * @return null */ private function _addTotalToXml($total, Mage_XmlConnect_Model_Simplexml_Element $totalsXml) { - if ( - $total instanceof Varien_Object - && $total->getCode() - && $total->getLabel() - && $total->hasData('value') - ) { - $totalsXml->addCustomChild( - preg_replace('@[\W]+@', '_', trim($total->getCode())), - $this->_formatPrice($total), - array('label' => strip_tags($total->getLabel())) + if ($total instanceof Varien_Object && $total->getCode() && $total->getLabel() && $total->hasData('value')) { + $totalsXml->addCustomChild(preg_replace('@[\W]+@', '_', trim($total->getCode())), + $this->_formatPrice($total), array('label' => strip_tags($total->getLabel())) ); } } @@ -139,7 +133,7 @@ private function _addTotalToXml($total, Mage_XmlConnect_Model_Simplexml_Element protected function _formatPrice($total) { if (!$total->getIsFormated()) { - return $this->getOrder()->getOrderCurrency()->formatPrecision($total->getValue(), 2, array(), false); + return Mage::helper('xmlconnect/customer_order')->formatPrice($this, $total->getValue()); } return $total->getValue(); } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Customerbalance.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Customerbalance.php index 53ade18541..7bed9048b3 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Customerbalance.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Customerbalance.php @@ -38,15 +38,13 @@ class Mage_XmlConnect_Block_Customer_Order_Totals_Customerbalance * Add order total rendered to XML object * * @param $totalsXml Mage_XmlConnect_Model_Simplexml_Element - * @return void + * @return null */ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXml) { $balance = $this->getSource()->getCustomerBalanceAmount(); if ($balance) { - $totalsXml->addCustomChild( - $this->getTotal()->getCode(), - '-' . $this->_formatPrice($balance), + $totalsXml->addCustomChild($this->getTotal()->getCode(), '-' . $this->_formatPrice($balance), array('label' => Mage::helper('enterprise_giftcardaccount')->__('Store Credit')) ); } @@ -60,6 +58,6 @@ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXm */ protected function _formatPrice($amount) { - return $this->getOrder()->getOrderCurrency()->formatPrecision($amount, 2, array(), false); + return Mage::helper('xmlconnect/customer_order')->formatPrice($this, $amount); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Customerbalance/Refunded.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Customerbalance/Refunded.php index 3843036ba6..4faca89b0a 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Customerbalance/Refunded.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Customerbalance/Refunded.php @@ -38,15 +38,13 @@ class Mage_XmlConnect_Block_Customer_Order_Totals_Customerbalance_Refunded * Add order total rendered to XML object * * @param $totalsXml Mage_XmlConnect_Model_Simplexml_Element - * @return void + * @return null */ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXml) { $balance = $this->getSource()->getCustomerBalanceTotalRefunded(); if ($balance) { - $totalsXml->addCustomChild( - $this->getTotal()->getCode(), - $this->_formatPrice($balance), + $totalsXml->addCustomChild($this->getTotal()->getCode(), $this->_formatPrice($balance), array('label' => Mage::helper('enterprise_giftcardaccount')->__('Refunded to Store Credit')) ); } @@ -60,6 +58,6 @@ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXm */ protected function _formatPrice($amount) { - return $this->getOrder()->getOrderCurrency()->formatPrecision($amount, 2, array(), false); + return Mage::helper('xmlconnect/customer_order')->formatPrice($this, $amount); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Giftcards.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Giftcards.php index 12af538af5..68d24a0206 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Giftcards.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Giftcards.php @@ -38,7 +38,7 @@ class Mage_XmlConnect_Block_Customer_Order_Totals_Giftcards * Add order total rendered to XML object * * @param $totalsXml Mage_XmlConnect_Model_Simplexml_Element - * @return void + * @return null */ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXml) { @@ -46,18 +46,14 @@ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXm if ($cards) { foreach ($cards as $card) { $label = Mage::helper('enterprise_giftcardaccount')->__('Gift Card (%s)', $card->getCode()); - $totalsXml->addCustomChild( - $this->getTotal()->getCode(), - '-' . $this->_formatPrice($card->getAmount()), + $totalsXml->addCustomChild($this->getTotal()->getCode(), '-' . $this->_formatPrice($card->getAmount()), array('label' => $label) ); } } else { $cardsAmount = $this->getSource()->getGiftCardsAmount(); if ($cardsAmount > 0) { - $totalsXml->addCustomChild( - $this->getTotal()->getCode(), - '-' . $this->_formatPrice($cardsAmount), + $totalsXml->addCustomChild($this->getTotal()->getCode(), '-' . $this->_formatPrice($cardsAmount), array('label' => Mage::helper('enterprise_giftcardaccount')->__('Gift Card')) ); } @@ -72,6 +68,6 @@ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXm */ protected function _formatPrice($amount) { - return $this->getOrder()->getOrderCurrency()->formatPrecision($amount, 2, array(), false); + return Mage::helper('xmlconnect/customer_order')->formatPrice($this, $amount); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Tax.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Tax.php index 563a2fa301..328aaad6a0 100644 --- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Tax.php +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Totals/Tax.php @@ -37,7 +37,7 @@ class Mage_XmlConnect_Block_Customer_Order_Totals_Tax extends Mage_Tax_Block_Sal * Add order taxes rendered to XML object * * @param Mage_XmlConnect_Model_Simplexml_Element $totalsXmlObj - * @return void + * @return null */ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXmlObj) { @@ -54,16 +54,12 @@ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXm foreach ((array)$info['rates'] as $rate) { if (isset($info['amount'])) { - $config = array( - 'label' => $rate['title'] - ); + $config = array('label' => $rate['title']); if (!is_null($rate['percent'])) { - $config['percent'] = '(' . (float)$rate['percent'] . '%)'; + $config['percent'] = sprintf('(%0.2f%%)', $rate['percent']); } $taxesXmlObj->addCustomChild( - 'item', - is_null($rate['percent']) ? '' : $this->_formatPrice($info['amount']), - $config + 'item', is_null($rate['percent']) ? '' : $this->_formatPrice($info['amount']), $config ); } } @@ -71,11 +67,7 @@ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXm } $taxesXmlObj->addCustomChild( - 'summary', - $this->_formatPrice($this->getSource()->getTaxAmount()), - array( - 'label' => $this->__('Tax') - ) + 'summary', $this->_formatPrice($this->getSource()->getTaxAmount()), array('label' => $this->__('Tax')) ); } @@ -87,6 +79,6 @@ public function addToXmlObject(Mage_XmlConnect_Model_Simplexml_Element $totalsXm */ protected function _formatPrice($amount) { - return $this->getOrder()->getOrderCurrency()->formatPrecision($amount, 2, array(), false); + return Mage::helper('xmlconnect/customer_order')->formatPrice($this, $amount); } } diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Storecredit.php b/app/code/core/Mage/XmlConnect/Block/Customer/Storecredit.php new file mode 100644 index 0000000000..2412011ac0 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Block/Customer/Storecredit.php @@ -0,0 +1,91 @@ + + */ +class Mage_XmlConnect_Block_Customer_Storecredit extends Mage_Core_Block_Template +{ + /** + * Render customer store credits xml + * + * @return string + */ + protected function _toHtml() + { + /** @var $xmlModel Mage_XmlConnect_Model_Simplexml_Element */ + $xmlModel = Mage::getModel('xmlconnect/simplexml_element', ''); + + $accountBalance = $this->getLayout() + ->addBlock('enterprise_customerbalance/account_balance', 'account_balance'); + + $customerBalanceHelper = Mage::helper('enterprise_customerbalance'); + + $xmlModel->addCustomChild('balance', null, array( + 'label' => $customerBalanceHelper->__('Your current balance is:'), + 'value' => $accountBalance->getBalance(), + 'formatted_value' => Mage::helper('core')->currency($accountBalance->getBalance(), true, false) + )); + + $accountHistory = $this->getLayout() + ->addBlock('enterprise_customerbalance/account_history', 'account_history'); + + if ($accountHistory->canShow() && $accountHistory->getEvents() && count($accountHistory->getEvents())) { + $balanceHistory = $xmlModel->addCustomChild('balance_history', null, array( + 'label' => $customerBalanceHelper->__('Balance History'), + 'action_label' => $customerBalanceHelper->__('Action'), + 'balance_change_label' => $customerBalanceHelper->__('Balance Change'), + 'balance_label' => $customerBalanceHelper->__('Balance'), + 'date_label' => $customerBalanceHelper->__('Date') + )); + + foreach ($accountHistory->getEvents() as $event) { + $item = $balanceHistory->addCustomChild('item'); + $item->addCustomChild('action', null, array( + 'value' => $accountHistory->getActionLabel($event->getAction()) + )); + + $item->addCustomChild('balance_change', null, array( + 'value' => Mage::helper('core')->currency($event->getBalanceDelta(), true, false) + )); + + $item->addCustomChild('balance', null, array( + 'value' => Mage::helper('core')->currency($event->getBalanceAmount(), true, false) + )); + + $item->addCustomChild('date', null, array( + 'value' => Mage::helper('core')->formatDate($event->getUpdatedAt(), 'short', true) + )); + } + } + + return $xmlModel->asNiceXml(); + } +} diff --git a/app/code/core/Mage/XmlConnect/Block/Home.php b/app/code/core/Mage/XmlConnect/Block/Home.php index f2f4aa48d6..af9a7d34ae 100644 --- a/app/code/core/Mage/XmlConnect/Block/Home.php +++ b/app/code/core/Mage/XmlConnect/Block/Home.php @@ -50,13 +50,13 @@ protected function _toHtml() $categoryCollection = array(); $helper = Mage::helper('catalog/category'); - $i = 0; + $categoryCount = 0; foreach ($helper->getStoreCategories() as $child) { if ($child->getIsActive()) { $categoryCollection[] = $child; - $i++; + $categoryCount++; } - if ($i == self::HOME_PAGE_CATEGORIES_COUNT) { + if ($categoryCount == self::HOME_PAGE_CATEGORIES_COUNT) { break; } } @@ -69,16 +69,14 @@ protected function _toHtml() /** @var $item Mage_Catalog_Model_Category */ $item = Mage::getModel('catalog/category')->load($item->getId()); $itemXmlObj = $itemsXmlObj->addChild('item'); - $itemXmlObj->addChild('label', $homeXmlObj->xmlentities(strip_tags($item->getName()))); + $itemXmlObj->addChild('label', $homeXmlObj->xmlentities($item->getName())); $itemXmlObj->addChild('entity_id', $item->getId()); $itemXmlObj->addChild('content_type', $item->hasChildren() ? 'categories' : 'products'); $icon = Mage::helper('xmlconnect/catalog_category_image')->initialize($item, 'thumbnail') ->resize(Mage::helper('xmlconnect/image')->getImageSizeForContent('category')); $iconXml = $itemXmlObj->addChild('icon', $icon); - $file = Mage::helper('xmlconnect')->urlToPath($icon); - $iconXml->addAttribute('modification_time', filemtime($file)); } $homeXmlObj->addChild('home_banner', '/current/media/catalog/category/banner_home.png'); diff --git a/app/code/core/Mage/XmlConnect/Block/Review/Form.php b/app/code/core/Mage/XmlConnect/Block/Review/Form.php index 21dfdaee5e..5e55d76826 100644 --- a/app/code/core/Mage/XmlConnect/Block/Review/Form.php +++ b/app/code/core/Mage/XmlConnect/Block/Review/Form.php @@ -27,9 +27,9 @@ /** * Product review form xml renderer * - * @category Mage - * @package Mage_XmlConnect - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Block_Review_Form extends Mage_Core_Block_Template { @@ -55,27 +55,19 @@ protected function _toHtml() $nickname = ''; if ($customer->getId()) { - $nickname = strip_tags($customer->getFirstname()); + $nickname = $xmlReview->xmlentities($customer->getFirstname()); } if ($this->getRatings()) { - $ratingsFieldset = $xmlReview->addCustomChild( - 'fieldset', - null, - array( - 'label' => $this->__('How do you rate this product?') - ) - ); + $ratingsFieldset = $xmlReview->addCustomChild('fieldset', null, array( + 'label' => $this->__('How do you rate this product?') + )); foreach ($this->getRatings() as $rating) { - $ratingField = $ratingsFieldset->addField( - 'ratings[' . $rating->getId() . ']', - 'radio', - array( - 'label' => $rating->getRatingCode(), - 'required' => 'true' - ) - ); + $ratingField = $ratingsFieldset->addField('ratings[' . $rating->getId() . ']', 'radio', array( + 'label' => $rating->getRatingCode(), + 'required' => 'true' + )); foreach ($rating->getOptions() as $option) { $ratingField->addCustomChild('value', $option->getId()); } @@ -83,31 +75,19 @@ protected function _toHtml() } $reviewFieldset = $xmlReview->addCustomChild('fieldset'); - $reviewFieldset->addField( - 'nickname', - 'text', - array( - 'label' => $this->__('Nickname'), - 'required' => 'true', - 'value' => $nickname - ) - ); - $reviewFieldset->addField( - 'title', - 'text', - array( - 'label' => $this->__('Summary of Your Review'), - 'required' => 'true' - ) - ); - $reviewFieldset->addField( - 'detail', - 'textarea', - array( - 'label' => $this->__('Review'), - 'required' => 'true' - ) - ); + $reviewFieldset->addField('nickname', 'text', array( + 'label' => $this->__('Nickname'), + 'required' => 'true', + 'value' => $nickname + )); + $reviewFieldset->addField('title', 'text', array( + 'label' => $this->__('Summary of Your Review'), + 'required' => 'true' + )); + $reviewFieldset->addField('detail', 'textarea', array( + 'label' => $this->__('Review'), + 'required' => 'true' + )); return $xmlReview->asNiceXml(); } @@ -120,14 +100,9 @@ protected function _toHtml() public function getRatings() { if (is_null($this->_ratings)) { - $this->_ratings = Mage::getModel('rating/rating') - ->getResourceCollection() - ->addEntityFilter('product') - ->setPositionOrder() - ->addRatingPerStoreName(Mage::app()->getStore()->getId()) - ->setStoreFilter(Mage::app()->getStore()->getId()) - ->load() - ->addOptionToItems(); + $this->_ratings = Mage::getModel('rating/rating')->getResourceCollection()->addEntityFilter('product') + ->setPositionOrder()->addRatingPerStoreName(Mage::app()->getStore()->getId()) + ->setStoreFilter(Mage::app()->getStore()->getId())->load()->addOptionToItems(); if (!$this->_ratings->getSize()) { $this->_ratings = false; diff --git a/app/code/core/Mage/XmlConnect/Block/Wishlist.php b/app/code/core/Mage/XmlConnect/Block/Wishlist.php index c8866a0804..f2ca53bf46 100644 --- a/app/code/core/Mage/XmlConnect/Block/Wishlist.php +++ b/app/code/core/Mage/XmlConnect/Block/Wishlist.php @@ -40,8 +40,8 @@ class Mage_XmlConnect_Block_Wishlist extends Mage_Wishlist_Block_Customer_Wishli */ protected function _toHtml() { + /** @var Mage_XmlConnect_Model_Simplexml_Element $wishlistXmlObj */ $wishlistXmlObj = Mage::getModel('xmlconnect/simplexml_element', ''); - $hasMoreItems = 0; /** * Apply offset and count */ @@ -50,6 +50,7 @@ protected function _toHtml() $count = (int)$request->getParam('count', 0); $offset = $offset < 0 ? 0 : $offset; $count = $count <= 0 ? 1 : $count; + $hasMoreItems = 0; if ($offset + $count < $this->getWishlistItems()->getSize()) { $hasMoreItems = 1; } @@ -67,12 +68,11 @@ protected function _toHtml() $itemXmlObj = $wishlistXmlObj->addChild('item'); $itemXmlObj->addChild('item_id', $item->getWishlistItemId()); - $itemXmlObj->addChild('entity_id', $item->getProductId()); $itemXmlObj->addChild('entity_type_id', $item->getProduct()->getTypeId()); - $itemXmlObj->addChild('name', $wishlistXmlObj->xmlentities(strip_tags($item->getName()))); - $itemXmlObj->addChild('in_stock', (int)$item->getProduct()->isInStock()); - $itemXmlObj->addChild('is_salable', (int)$item->getProduct()->getIsSalable()); + $itemXmlObj->addChild('name', $wishlistXmlObj->xmlentities($item->getName())); + $itemXmlObj->addChild('in_stock', (int)$item->getProduct()->getIsInStock()); + $itemXmlObj->addChild('is_salable', (int)$item->getProduct()->isSalable()); /** * If product type is grouped than it has options as its grouped items */ @@ -96,8 +96,7 @@ protected function _toHtml() $itemXmlObj->addChild('added_date', $addedDate); if ($this->getChild('product_price')) { - $this->getChild('product_price')->setProduct($item->getProduct()) - ->setProductXmlObj($itemXmlObj) + $this->getChild('product_price')->setProduct($item->getProduct())->setProductXmlObj($itemXmlObj) ->collectProductPrices(); } diff --git a/app/code/core/Mage/XmlConnect/Controller/Action.php b/app/code/core/Mage/XmlConnect/Controller/Action.php index fdf5625d18..670aeb9cb3 100644 --- a/app/code/core/Mage/XmlConnect/Controller/Action.php +++ b/app/code/core/Mage/XmlConnect/Controller/Action.php @@ -62,7 +62,7 @@ abstract class Mage_XmlConnect_Controller_Action extends Mage_Core_Controller_Fr * Declare content type header * Validate current application * - * @return void + * @return null */ public function preDispatch() { @@ -78,8 +78,7 @@ public function preDispatch() $screenSize = isset($_COOKIE[$screenSizeCookieName]) ? (string) $_COOKIE[$screenSizeCookieName] : ''; if (!$appCode) { $this->_message( - Mage::helper('xmlconnect')->__('Specified invalid app code.'), - self::MESSAGE_STATUS_ERROR + Mage::helper('xmlconnect')->__('Specified invalid app code.'), self::MESSAGE_STATUS_ERROR ); $this->setFlag('', self::FLAG_NO_DISPATCH, true); return; @@ -91,8 +90,7 @@ public function preDispatch() && (int)Mage::getStoreConfig('general/restriction/mode') == 0 ) { $this->_message( - Mage::helper('xmlconnect')->__('Website is offline.'), - self::MESSAGE_STATUS_SUCCESS + Mage::helper('xmlconnect')->__('Website is offline.'), self::MESSAGE_STATUS_SUCCESS ); $this->setFlag('', self::FLAG_NO_DISPATCH, true); return; @@ -108,8 +106,7 @@ public function preDispatch() Mage::register('current_app', $appModel); } else { $this->_message( - Mage::helper('xmlconnect')->__('Specified invalid app code.'), - self::MESSAGE_STATUS_ERROR + Mage::helper('xmlconnect')->__('Specified invalid app code.'), self::MESSAGE_STATUS_ERROR ); $this->setFlag('', self::FLAG_NO_DISPATCH, true); return; @@ -119,7 +116,7 @@ public function preDispatch() /** * Validate response body * - * @return void + * @return null */ public function postDispatch() { @@ -138,16 +135,20 @@ public function postDispatch() * * @param string $text * @param string $status - * @param string $type - * @param string $action - * @return void + * @param array $children + * @return null */ - protected function _message($text, $status, $type='', $action='') + protected function _message($text, $status, $children = array()) { /** @var $message Mage_XmlConnect_Model_Simplexml_Element */ $message = Mage::getModel('xmlconnect/simplexml_element', ''); - $message->addChild('status', $status); - $message->addChild('text', $text); + $message->addCustomChild('status', $status); + $message->addCustomChild('text', $text); + + foreach ($children as $node => $value) { + $message->addCustomChild($node, $value); + } + $this->getResponse()->setBody($message->asNiceXml()); } } diff --git a/app/code/core/Mage/XmlConnect/Helper/Android.php b/app/code/core/Mage/XmlConnect/Helper/Android.php index 17ad43f06b..961612bd39 100755 --- a/app/code/core/Mage/XmlConnect/Helper/Android.php +++ b/app/code/core/Mage/XmlConnect/Helper/Android.php @@ -141,7 +141,6 @@ public function getSubmitImages() /** * Get default application tabs * - * @param string * @return array */ public function getDefaultDesignTabs() @@ -196,74 +195,74 @@ public function getDefaultDesignTabs() */ public function getDefaultConfiguration() { - return array( - 'native' => array( - 'body' => array( - 'backgroundColor' => '#ABABAB', - 'scrollBackgroundColor' => '#EDEDED', - ), - 'itemActions' => array( - 'relatedProductBackgroundColor' => '#404040', - ), - 'fonts' => array( - 'Title1' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '14', - 'color' => '#FEFEFE', - ), - 'Title2' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '12', - 'color' => '#222222', - ), - 'Title3' => array( - 'name' => 'HelveticaNeue', - 'size' => '13', - 'color' => '#000000', - ), - 'Title4' => array( - 'name' => 'HelveticaNeue', - 'size' => '12', - 'color' => '#FFFFFF', - ), - 'Title5' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '13', - 'color' => '#dc5f02', - ), - 'Title6' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '16', - 'color' => '#222222', - ), - 'Title7' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '13', - 'color' => '#000000', - ), - 'Title8' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '11', - 'color' => '#FFFFFF', - ), - 'Title9' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '12', - 'color' => '#FFFFFF', - ), - 'Text1' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '12', - 'color' => '#777777', - ), - 'Text2' => array( - 'name' => 'HelveticaNeue', - 'size' => '10', - 'color' => '#555555', - ), - ), - ), - ); + return array( + 'native' => array( + 'body' => array( + 'backgroundColor' => '#ABABAB', + 'scrollBackgroundColor' => '#EDEDED', + ), + 'itemActions' => array( + 'relatedProductBackgroundColor' => '#404040', + ), + 'fonts' => array( + 'Title1' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '14', + 'color' => '#FEFEFE', + ), + 'Title2' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '12', + 'color' => '#222222', + ), + 'Title3' => array( + 'name' => 'HelveticaNeue', + 'size' => '13', + 'color' => '#000000', + ), + 'Title4' => array( + 'name' => 'HelveticaNeue', + 'size' => '12', + 'color' => '#FFFFFF', + ), + 'Title5' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '13', + 'color' => '#dc5f02', + ), + 'Title6' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '16', + 'color' => '#222222', + ), + 'Title7' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '13', + 'color' => '#000000', + ), + 'Title8' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '11', + 'color' => '#FFFFFF', + ), + 'Title9' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '12', + 'color' => '#FFFFFF', + ), + 'Text1' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '12', + 'color' => '#777777', + ), + 'Text2' => array( + 'name' => 'HelveticaNeue', + 'size' => '10', + 'color' => '#555555', + ), + ), + ), + ); } /** @@ -492,7 +491,7 @@ public function getFontList() */ public function getFontSizes() { - $result = array( ); + $result = array(); for ($i = 6; $i < 32; $i++) { $result[] = array( 'value' => $i, @@ -560,14 +559,14 @@ public function validateSubmit($params) if (!Zend_Validate::is($resubmissionKey, 'NotEmpty')) { $errors[] = Mage::helper('xmlconnect')->__('Please enter the Resubmission Key.'); - } else if (!Zend_Validate::is($resubmissionKey, 'StringLength', array(1, $keyLenght))) { + } elseif (!Zend_Validate::is($resubmissionKey, 'StringLength', array(1, $keyLenght))) { $errors[] = Mage::helper('xmlconnect')->__('Submit App failure. Invalid activation key provided'); } } else { $key = isset($params['key']) ? $params['key'] : null; if (!Zend_Validate::is($key, 'NotEmpty')) { $errors[] = Mage::helper('xmlconnect')->__('Please enter the Activation Key.'); - } else if (!Zend_Validate::is($key, 'StringLength', array(1, $keyLenght))) { + } elseif (!Zend_Validate::is($key, 'StringLength', array(1, $keyLenght))) { $errors[] = Mage::helper('xmlconnect')->__('Submit App failure. Invalid activation key provided'); } } @@ -583,10 +582,9 @@ public function validateSubmit($params) public function validateConfig($native) { $errors = array(); - if ( ($native === false) - || (!isset($native['navigationBar']) || !is_array($native['navigationBar']) - || !isset($native['navigationBar']['icon']) - || !Zend_Validate::is($native['navigationBar']['icon'], 'NotEmpty'))) { + if ($native === false || !isset($native['navigationBar']['icon']) + || !Zend_Validate::is($native['navigationBar']['icon'], 'NotEmpty') + ) { $errors[] = Mage::helper('xmlconnect')->__('Please upload an image for "Logo in Header" field from Design Tab.'); } @@ -672,16 +670,18 @@ public function getAndroidMarketCountriesArray() */ public function checkImages(array $data) { - if (isset($data['conf']['native']['navigationBar']['icon']) && - !file_exists($data['conf']['native']['navigationBar']['icon']) - ) { - $data['conf']['native']['navigationBar']['icon'] = ''; + /** @var $helper Mage_XmlConnect_Helper_Image */ + $helper = Mage::helper('xmlconnect/image'); + + $icon =& $data['conf']['native']['navigationBar']['icon']; + + if (!empty($icon) && !$helper->checkAndGetImagePath($icon)) { + $icon = ''; } - if (isset($data['conf']['native']['body']['bannerAndroidImage']) && - !file_exists($data['conf']['native']['body']['bannerAndroidImage']) - ) { - $data['conf']['native']['body']['bannerAndroidImage'] = ''; + $banner =& $data['conf']['native']['body']['bannerAndroidImage']; + if (!empty($banner) && !$helper->checkAndGetImagePath($banner)) { + $banner = ''; } return $data; } @@ -691,7 +691,7 @@ public function checkImages(array $data) * * @throws Mage_Core_Exception * @param array $data - * @return void + * @return null */ public function checkRequiredConfigFields($data) { @@ -699,19 +699,22 @@ public function checkRequiredConfigFields($data) return; } - if (isset($data['navigationBar']['icon']) - && empty($data['navigationBar']['icon']) - ) { - Mage::throwException( - Mage::helper('xmlconnect')->__('Logo in Header image missing.') - ); + if (isset($data['navigationBar']['icon']) && empty($data['navigationBar']['icon'])) { + Mage::throwException(Mage::helper('xmlconnect')->__('Logo in Header image missing.')); } - if (isset($data['body']['bannerAndroidImage']) - && empty($data['body']['bannerAndroidImage']) - ) { - Mage::throwException( - Mage::helper('xmlconnect')->__('Banner on Home Screen image missing.') - ); + + if (isset($data['body']['bannerAndroidImage']) && empty($data['body']['bannerAndroidImage'])) { + Mage::throwException(Mage::helper('xmlconnect')->__('Banner on Home Screen image missing.')); } } + + /** + * Check the notifications are allowed for current type of application + * + * @return bool + */ + public function isNotificationsAllowed() + { + return true; + } } diff --git a/app/code/core/Mage/GoogleOptimizer/Model/Code/Category.php b/app/code/core/Mage/XmlConnect/Helper/Customer/Form/Renderer.php similarity index 52% rename from app/code/core/Mage/GoogleOptimizer/Model/Code/Category.php rename to app/code/core/Mage/XmlConnect/Helper/Customer/Form/Renderer.php index 3240a51d6b..ea40a65c31 100644 --- a/app/code/core/Mage/GoogleOptimizer/Model/Code/Category.php +++ b/app/code/core/Mage/XmlConnect/Helper/Customer/Form/Renderer.php @@ -19,46 +19,40 @@ * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_XmlConnect * @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 + * Customer form renderer helper * * @category Mage - * @package Mage_GoogleOptimizer + * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_GoogleOptimizer_Model_Code_Category extends Mage_GoogleOptimizer_Model_Code +class Mage_XmlConnect_Helper_Customer_Form_Renderer extends Mage_Core_Helper_Abstract { - - protected $_entityType = 'category'; - /** - * Removing scripts assigned to entity + * Get title and required attributes for a field * - * @param integer $storeId - * @return Mage_GoogleOptimizer_Model_Code + * @param Mage_XmlConnect_Model_Simplexml_Form_Abstract $fieldsetXmlObj + * @param Enterprise_Customer_Block_Form_Renderer_Abstract $blockObject + * @return array */ - public function deleteScripts($storeId) - { - $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); + public function addTitleAndRequiredAttr(Mage_XmlConnect_Model_Simplexml_Form_Abstract $fieldsetXmlObj, + Enterprise_Customer_Block_Form_Renderer_Abstract $blockObject + ) { + $attributes = array(); + + if ($blockObject->isRequired()) { + $attributes += $fieldsetXmlObj->checkAttribute('required', (int)$blockObject->isRequired()); + } + + if ($blockObject->getAdditionalDescription()) { + $attributes += $fieldsetXmlObj->checkAttribute('title', $blockObject->getAdditionalDescription()); } - return parent::deleteScripts($storeId); - } + return $attributes; + } } diff --git a/app/code/core/Mage/XmlConnect/Helper/Customer/Order.php b/app/code/core/Mage/XmlConnect/Helper/Customer/Order.php new file mode 100644 index 0000000000..b588441280 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Helper/Customer/Order.php @@ -0,0 +1,251 @@ + + */ +class Mage_XmlConnect_Helper_Customer_Order extends Mage_Core_Helper_Abstract +{ + /**#@+ + * Price display type + * @see Mage_Weee_Helper_Data::typeOfDisplay(...); + */ + const PRICE_DISPLAY_TYPE_1 = 1; + const PRICE_DISPLAY_TYPE_2 = 2; + const PRICE_DISPLAY_TYPE_4 = 4; + const PRICE_DISPLAY_TYPE_14 = 14; + /**#@-*/ + + /** + * Add Weee taxes child to the XML + * + * @param Mage_Core_Block_Template $renderer Product renderer + * @param Mage_Sales_Model_Order_Item $item + * @param Mage_XmlConnect_Model_Simplexml_Element $priceXml + * @param Mage_XmlConnect_Model_Simplexml_Element $subtotalXml + * @param bool $isIncludeTax + * @return null + */ + public function addPriceAndSubtotalToXml(Mage_Core_Block_Template $renderer, Mage_Sales_Model_Order_Item $item, + Mage_XmlConnect_Model_Simplexml_Element $priceXml, Mage_XmlConnect_Model_Simplexml_Element $subtotalXml, + $isIncludeTax = false + ) { + $weeeParams = array(); + + $typesOfDisplay = $renderer->getTypesOfDisplay(); + if ($isIncludeTax) { + $nodeName = 'including_tax'; + $nodeLabel = $renderer->__('Incl. Tax'); + + $inclPrice = $renderer->helper('checkout')->getPriceInclTax($item); + $inclSubtotal = $renderer->helper('checkout')->getSubtotalInclTax($item); + + if ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_14]) { + $price = $inclPrice + $renderer->getWeeeTaxAppliedAmount(); + $subtotal = $inclSubtotal + $item->getWeeeTaxAppliedRowAmount(); + } else { + $price = $inclPrice - $renderer->getWeeeTaxDisposition(); + $subtotal = $inclSubtotal - $item->getWeeeTaxRowDisposition(); + } + $weeeParams['include'] = $inclPrice; + } else { + $nodeName = 'excluding_tax'; + $nodeLabel = $renderer->__('Excl. Tax'); + + if ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_14]) { + $price = $item->getPrice() + $renderer->getWeeeTaxAppliedAmount() + + $renderer->getWeeeTaxDisposition(); + $subtotal = $item->getRowTotal() + $item->getWeeeTaxAppliedRowAmount() + + $item->getWeeeTaxRowDisposition(); + } else { + $price = $item->getPrice(); + $subtotal = $item->getRowTotal(); + } + } + + $configNode = array( + 'value' => $this->formatPrice($renderer, $price) + ); + if ($renderer->helper('tax')->displaySalesBothPrices()) { + $configNode['label'] = $nodeLabel; + } + + $this->addWeeeTaxesToPriceXml( + $renderer, $item, $priceXml->addCustomChild($nodeName, null, $configNode), $weeeParams + ); + + $configNode['value'] = $this->formatPrice($renderer, $subtotal); + $weeeParams['include'] = $isIncludeTax ? $inclSubtotal : null; + $weeeParams['is_subtotal'] = true; + $this->addWeeeTaxesToPriceXml( + $renderer, $item, $subtotalXml->addCustomChild($nodeName, null, $configNode), $weeeParams + ); + } + + /** + * Add Product options to XML + * + * @param Mage_Core_Block_Template $renderer Product renderer + * @param Mage_XmlConnect_Model_Simplexml_Element $itemXml + * @return null + */ + public function addItemOptionsToXml(Mage_Core_Block_Template $renderer, + Mage_XmlConnect_Model_Simplexml_Element $itemXml + ) { + $options = $renderer->getItemOptions(); + if (!empty($options)) { + $optionsXml = $itemXml->addChild('options'); + + foreach ($options as $option) { + $value = false; + $formatedOptionValue = $renderer->getFormatedOptionValue($option); + if (isset($formatedOptionValue['full_view']) && isset($formatedOptionValue['value'])) { + $value = $formatedOptionValue['value']; + } elseif (isset($option['print_value'])) { + $value = $option['print_value']; + } elseif (isset($option['value'])) { + $value = $option['value']; + } + if ($value) { + $optionsXml->addCustomChild('option', strip_tags($value), array('label' => $option['label'])); + } + } + } + } + + /** + * Add Weee taxes child to the XML + * + * @param Mage_Core_Block_Template $renderer Product renderer + * @param Mage_Sales_Model_Order_Item $item + * @param Mage_XmlConnect_Model_Simplexml_Element $parentXml + * @param array $params Params for Weee taxes: 'include' - Price including tax, 'is_subtotal' - Flag of subtotal + * @return null + */ + public function addWeeeTaxesToPriceXml(Mage_Core_Block_Template $renderer, Mage_Sales_Model_Order_Item $item, + Mage_XmlConnect_Model_Simplexml_Element $parentXml, $params = array() + ) { + $weeTaxes = $renderer->getWeeeTaxes(); + if (empty($weeTaxes)) { + return; + } + + $typesOfDisplay = $renderer->getTypesOfDisplay(); + + $row = isset($params['is_subtotal']) && $params['is_subtotal'] ? 'row_' : ''; + + /** @var $weeeXml Mage_XmlConnect_Model_Simplexml_Element */ + if ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_1]) { + $weeeXml = $parentXml->addChild('weee'); + foreach ($weeTaxes as $tax) { + $weeeXml->addCustomChild('tax', $this->formatPrice($renderer, $tax[$row . 'amount']), + array('label' => $tax['title']) + ); + } + } elseif ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_2] || $typesOfDisplay[self::PRICE_DISPLAY_TYPE_4]) { + $weeeXml = $parentXml->addChild('weee'); + foreach ($weeTaxes as $tax) { + $weeeXml->addCustomChild('tax', $this->formatPrice($renderer, $tax[$row . 'amount_incl_tax']), + array('label' => $tax['title']) + ); + } + } + + if ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_2]) { + if (!is_null($params['include'])) { + // including tax + if (isset($params['is_subtotal'])) { + $total = $params['include'] + $item->getWeeeTaxAppliedRowAmount(); + } else { + $total = $params['include'] + $renderer->getWeeeTaxAppliedAmount(); + } + } else { + // excluding tax + if ($params['is_subtotal']) { + $total = $item->getRowTotal() + $item->getWeeeTaxAppliedRowAmount() + + $item->getWeeeTaxRowDisposition(); + } else { + $total = $item->getPrice() + $renderer->getWeeeTaxAppliedAmount() + + $renderer->getWeeeTaxDisposition(); + } + } + + if (!isset($weeeXml)) { + $weeeXml = $parentXml->addChild('weee'); + } + $weeeXml->addCustomChild( + 'total', + $this->formatPrice($renderer, $total), + array('label' => $renderer->helper('weee')->__('Total')) + ); + } + } + + /** + * Add item quantities to the XML + * + * @param Mage_Core_Block_Template $renderer Product renderer + * @param Mage_XmlConnect_Model_Simplexml_Element $quantityXml + * @param Mage_Sales_Model_Order_Item $item + * @return null + */ + public function addQuantityToXml(Mage_Core_Block_Template $renderer, + Mage_XmlConnect_Model_Simplexml_Element $quantityXml, Mage_Sales_Model_Order_Item $item + ) { + $qty = 1 * $item->getQtyOrdered(); + if ($qty > 0) { + $quantityXml->addCustomChild('value', $qty, array('label' => $renderer->__('Ordered'))); + } + $qty = 1 * $item->getQtyShipped(); + if ($qty > 0) { + $quantityXml->addCustomChild('value', $qty, array('label' => $renderer->__('Shipped'))); + } + $qty = 1 * $item->getQtyCanceled(); + if ($qty > 0) { + $quantityXml->addCustomChild('value', $qty, array('label' => $renderer->__('Canceled'))); + } + $qty = 1 * $item->getQtyRefunded(); + if ($qty > 0) { + $quantityXml->addCustomChild('value', $qty, array('label' => $renderer->__('Refunded'))); + } + } + + /** + * Format price using order currency + * + * @param Mage_Core_Block_Template $renderer Product renderer + * @param float $price + * @return string + */ + public function formatPrice(Mage_Core_Block_Template $renderer, $price) + { + return $renderer->getOrder()->getOrderCurrency()->formatPrecision($price, 2, array(), false); + } +} diff --git a/app/code/core/Mage/XmlConnect/Helper/Data.php b/app/code/core/Mage/XmlConnect/Helper/Data.php index c90994cb7a..daf287f808 100644 --- a/app/code/core/Mage/XmlConnect/Helper/Data.php +++ b/app/code/core/Mage/XmlConnect/Helper/Data.php @@ -48,9 +48,7 @@ class Mage_XmlConnect_Helper_Data extends Mage_Core_Helper_Abstract * * @var array */ - protected $_excludedXmlConfigKeys = array( - 'notifications/applicationMasterSecret', - ); + protected $_excludedXmlConfigKeys = array('notifications/applicationMasterSecret'); /** * Application names array @@ -194,10 +192,14 @@ public function getApplication() } /** - * Create filter object by key + * Create array with filter model and filter block by key + * + * Create array with: + * - Mage_Catalog_Model_Layer_Filter_Abstract + * - Mage_Catalog_Block_Layer_Filter_Abstract * * @param string $key - * @return Mage_Catalog_Model_Layer_Filter_Abstract + * @return array */ public function getFilterByKey($key) { @@ -215,7 +217,7 @@ public function getFilterByKey($key) $filterModelName = 'catalog/layer_filter_attribute'; break; } - return Mage::getModel($filterModelName); + return array(Mage::getModel($filterModelName), $this->getLayout()->createBlock($filterModelName)); } /** @@ -234,7 +236,7 @@ public function getUrl($route, $params = array()) * Retrieve device specific country options array * * @throws Mage_Core_Exception - * @param bool $isItunes + * @param bool $isItunes deprecated after 1.6.0.0 * @return array */ public function getCountryOptionsArray($isItunes = false) @@ -262,10 +264,8 @@ public function getCountryOptionsArray($isItunes = false) $options = unserialize($cache); } else { if (isset($deviceCountries)) { - $options = Mage::getModel('directory/country') - ->getResourceCollection() - ->addFieldToFilter('country_id', array('in' => $deviceCountries)) - ->loadByStore() + $options = Mage::getModel('directory/country')->getResourceCollection() + ->addFieldToFilter('country_id', array('in' => $deviceCountries))->loadByStore() ->toOptionArray(false); } if (Mage::app()->useCache('config')) { @@ -275,10 +275,7 @@ public function getCountryOptionsArray($isItunes = false) Varien_Profiler::stop('TEST: ' . __METHOD__); if (count($options)) { - $options[] = array( - 'value' => 'NEW_COUNTRIES', - 'label' => 'New Territories As Added' - ); + $options[] = array('value' => 'NEW_COUNTRIES', 'label' => 'New Territories As Added'); } return $options; @@ -333,7 +330,6 @@ public function getDeviceTypeOptions() /** * Get default application tabs * - * @param string * @return array */ public function getDefaultApplicationDesignTabs() @@ -439,8 +435,8 @@ public function htmlize($body) /** * Return select options for xml from array * - * @param array $dataArray - source array - * @param string $info - selected item + * @param array $dataArray source array + * @param string $selected selected item * @return string */ public function getArrayAsXmlItemValues($dataArray, $selected) @@ -570,13 +566,14 @@ public function getMessageTitleLength() public function getApplicationOptions() { $options = array(); + /** @var $app Mage_XmlConnect_Model_Application */ foreach (Mage::getModel('xmlconnect/application')->getCollection() as $app) { - if (self::isTemplateAllowedForApplication($app)) { - $options[] = array('value' => $app->getId(), 'label' => $app->getName()); - } + $options[] = array('value' => $app->getId(), 'label' => $app->getName()); } if (count($options) > 1) { - $options[] = array('value' => '', 'label' => Mage::helper('xmlconnect')->__('Please Select Application')); + array_unshift($options, array( + 'value' => '', 'label' => Mage::helper('xmlconnect')->__('Please Select Application') + )); } return $options; } @@ -584,7 +581,7 @@ public function getApplicationOptions() /** * Get applications array like `code` as `name` * - * @staticvar array $apps + * @static array $apps * @return array */ public function getApplications() @@ -603,13 +600,12 @@ public function getApplications() * Check if creating AirMail template for the application is allowed * * @param Mage_XmlConnect_Model_Application $application + * @deprecated after 1.6.0.0 * @return boolean */ public static function isTemplateAllowedForApplication($application = null) { - return $application instanceof Mage_XmlConnect_Model_Application - ? in_array($application->getType(), array(self::DEVICE_TYPE_IPHONE)) - : false; + return true; } /** @@ -626,7 +622,8 @@ public function sendBroadcastMessage(Mage_XmlConnect_Model_Queue $queue) try { $appCode = $queue->getAppCode(); - $app = Mage::getModel('xmlconnect/application')->load($appCode, 'code'); + /** @var $app Mage_XmlConnect_Model_Application */ + $app = Mage::getModel('xmlconnect/application')->loadByCode($appCode); if (!$app->getId()) { Mage::throwException( @@ -634,41 +631,44 @@ public function sendBroadcastMessage(Mage_XmlConnect_Model_Queue $queue) ); } + if (!$app->isNotificationsActive()) { + $queue->setStatus(Mage_XmlConnect_Model_Queue::STATUS_CANCELED); + return; + } + $userpwd = $app->getUserpwd(); $sendType = $queue->getData('type'); switch ($sendType) { case Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL: $configPath = 'xmlconnect/' . Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL . '/broadcast_url'; - $broadcastUrl = Mage::getStoreConfig($configPath); $params = $queue->getAirmailBroadcastParams(); break; case Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_PUSH: default: $configPath = 'xmlconnect/' . Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_PUSH . '/broadcast_url'; - $broadcastUrl = Mage::getStoreConfig($configPath); $params = $queue->getPushBroadcastParams(); break; } - $ch = curl_init($broadcastUrl); + $curlHandler = curl_init(Mage::getStoreConfig($configPath)); $httpHeaders = $this->getHttpHeaders(); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders); - curl_setopt($ch, CURLOPT_POSTFIELDS, $params); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_USERPWD, $userpwd); - curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($curlHandler, CURLOPT_POST, 1); + curl_setopt($curlHandler, CURLOPT_HTTPHEADER, $httpHeaders); + curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $params); + curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curlHandler, CURLOPT_USERPWD, $userpwd); + curl_setopt($curlHandler, CURLOPT_TIMEOUT, 60); // Execute the request. - $result = curl_exec($ch); - $succeeded = curl_errno($ch) == 0 ? true : false; + $result = curl_exec($curlHandler); + $succeeded = curl_errno($curlHandler) == 0 ? true : false; // close cURL resource, and free up system resources - curl_close($ch); + curl_close($curlHandler); if ($succeeded && (is_null($result) || strtolower($result) == 'null')) { $queue->setStatus(Mage_XmlConnect_Model_Queue::STATUS_COMPLETED); @@ -743,7 +743,7 @@ public function getExcludedXmlConfigKeys() /** * Returns Application name by it's code - * @param string $appCode + * @param string $appCode * @return string */ public function getApplicationName($appCode = null) @@ -764,7 +764,7 @@ public function getApplicationName($appCode = null) /** * Returns Application name by it's code - * @param string $appCode + * @param string $templateId * @return string */ public function getTemplateName($templateId = null) @@ -786,10 +786,10 @@ public function getTemplateName($templateId = null) /** * Set value into multidimensional array 'conf/native/navigationBar/icon' * - * @param &array $target // pointer to target array - * @param string $fieldPath // 'conf/native/navigationBar/icon' - * @param mixed $fieldValue // 'Some Value' || 12345 || array(1=>3, 'aa'=>43) - * @param string $delimiter // path delimiter + * @param array &$target pointer to target array + * @param string $fieldPath 'conf/native/navigationBar/icon' + * @param mixed $fieldValue 'Some Value' || 12345 || array(1=>3, 'aa'=>43) + * @param string $delimiter path delimiter * @return null */ public function _injectFieldToArray(&$target, $fieldPath, $fieldValue, $delimiter = '/') @@ -829,13 +829,51 @@ public function urlToPath($icon) */ public function validateConfFieldNotEmpty($field, $native) { - if ( ($native === false) - || (!isset($native['body']) || !is_array($native['body']) - || !isset($native['body'][$field]) - || !Zend_Validate::is($native['body'][$field], 'NotEmpty')) + if (($native === false) || (!isset($native['body']) || !is_array($native['body']) + || !isset($native['body'][$field]) || !Zend_Validate::is($native['body'][$field], 'NotEmpty')) ) { return false; } return true; } + + /** + * Check the notifications are allowed for current type of application + * + * @param Mage_XmlConnect_Model_Application $application + * @return bool + */ + public function isNotificationsAllowed($application = null) + { + return $this->getDeviceHelper($application)->isNotificationsAllowed(); + } + + /** + * Get front url for action + * + * @param string $action + * @param array $params + * @return string url + */ + public function getActionUrl($action, $params = array()) + { + $defaultParams = array( + '_store' => $this->getApplication()->getStoreId(), + '_nosid' => true, + '_secure' => $this->getApplication()->getUseSecureURLInFrontend() + ); + $params = array_merge($defaultParams, $params); + return Mage::getUrl($action, $params); + } + + /** + * Remove trilling line breaks + * + * @param string $string + * @return string + */ + public function trimLineBreaks($string) + { + return preg_replace(array('@\r@', '@\n+@'), array('', PHP_EOL), $string); + } } diff --git a/app/code/core/Mage/XmlConnect/Helper/Image.php b/app/code/core/Mage/XmlConnect/Helper/Image.php index a76cb536cf..7d94289c51 100644 --- a/app/code/core/Mage/XmlConnect/Helper/Image.php +++ b/app/code/core/Mage/XmlConnect/Helper/Image.php @@ -78,10 +78,9 @@ class Mage_XmlConnect_Helper_Image extends Mage_Core_Helper_Abstract * setup file names to the configuration * * @param string $field - * @param mixed &$target * @retun string */ - public function handleUpload($field, &$target) + public function handleUpload($field) { $uploadedFilename = ''; $uploadDir = $this->getOriginalSizeUploadDir(); @@ -111,7 +110,7 @@ public function handleUpload($field, &$target) Mage::logException($e); } } - return $uploadedFilename; + return basename($uploadedFilename); } /** @@ -130,7 +129,7 @@ protected function _getScreenSize() * @throws Mage_Core_Exception * @param string $fieldPath * @param string $fileName - * @param string $default + * @param bool $default * @return string */ protected function _getResizedFilename($fieldPath, $fileName, $default = false) @@ -143,7 +142,7 @@ protected function _getResizedFilename($fieldPath, $fileName, $default = false) } $customSizeFileName = $dir . DS . $fileName; $originalSizeFileName = $this->getOriginalSizeUploadDir(). DS . $fileName; - $error = false; + /** * Compatibility with old versions of XmlConnect */ @@ -151,9 +150,8 @@ protected function _getResizedFilename($fieldPath, $fileName, $default = false) $oldFileName = $this->getOldUploadDir() . DS . $fileName; if (file_exists($oldFileName)) { if (!(copy($oldFileName, $originalSizeFileName) - && (is_readable($customSizeFileName) - || chmod($customSizeFileName, 0644))) - ) { + && (is_readable($customSizeFileName) || chmod($customSizeFileName, 0644)) + )) { Mage::throwException( Mage::helper('xmlconnect')->__('Error while processing file "%s".', $fileName) ); @@ -163,11 +161,9 @@ protected function _getResizedFilename($fieldPath, $fileName, $default = false) } } - if (!$error - && copy($originalSizeFileName, $customSizeFileName) - && (is_readable($customSizeFileName) - || chmod($customSizeFileName, 0644)) - ) { + $isCopied = copy($originalSizeFileName, $customSizeFileName); + clearstatcache(); + if ($isCopied && (is_readable($customSizeFileName) || chmod($customSizeFileName, 0644))) { $this->_handleResize($fieldPath, $customSizeFileName); } else { $fileName = ''; @@ -184,7 +180,7 @@ protected function _getResizedFilename($fieldPath, $fileName, $default = false) * * @param string $fieldPath * @param string $file - * @return void + * @return null */ protected function _handleResize($fieldPath, $file) { @@ -219,9 +215,7 @@ protected function _handleResize($fieldPath, $file) $height = $conf['height']; } - if (($width != $image->getOriginalWidth()) - || ($height != $image->getOriginalHeight()) - ) { + if (($width != $image->getOriginalWidth()) || ($height != $image->getOriginalHeight())) { $image->keepTransparency(true); $image->keepFrame(true); $image->keepAspectRatio(true); @@ -246,11 +240,17 @@ protected function _forcedConvertPng($field) } $file['name'] .= '.png'; - $fileType = exif_imagetype($file['tmp_name']); +// We can't use exif extension, because magento doesn't require it. +// $fileType = exif_imagetype($file['tmp_name']); + list($unnecessaryVar, $unnecessaryVar, $fileType) = getimagesize($file['tmp_name']); + unset($unnecessaryVar); + if ($fileType != IMAGETYPE_PNG) { switch ($fileType) { case IMAGETYPE_GIF: $img = imagecreatefromgif($file['tmp_name']); + imagealphablending($img, false); + imagesavealpha($img, true); break; case IMAGETYPE_JPEG: $img = imagecreatefromjpeg($file['tmp_name']); @@ -264,8 +264,6 @@ protected function _forcedConvertPng($field) default: return; } - imagealphablending($img, false); - imagesavealpha($img, true); imagepng($img, $file['tmp_name']); imagedestroy($img); } @@ -441,7 +439,9 @@ public function getDefaultDesignSuffixAsUrl($image = '') /** * Retrieve thumbnail image url * + * @param string $imageUrl * @param int $width + * @param int $height * @return string|null */ public function getCustomSizeImageUrl($imageUrl, $width = 100, $height = 100) @@ -614,9 +614,9 @@ public function getImageLimits($screenSize = Mage_XmlConnect_Model_Application:: /** * Return reference to the $path in $array * - * @param array $array + * @param array &$array * @param string $path - * @return &mixed //(reference) + * @return mixed reference */ public function &findPath(&$array, $path) { @@ -639,9 +639,9 @@ public function &findPath(&$array, $path) * Multiply given $item by $value if non array * * @param mixed $item (argument to change) - * @param mixed $key (not used) + * @param mixed $key (used with array_walk_recursive function as a key of given array) * @param string $value (contains float) - * @return void + * @return null */ protected function _zoom(&$item, $key, $value) { @@ -658,8 +658,12 @@ protected function _zoom(&$item, $key, $value) */ protected function _verifyDirExist($dir) { - $io = new Varien_Io_File(); - $io->checkAndCreateFolder($dir); + try { + $ioFile = new Varien_Io_File(); + $ioFile->checkAndCreateFolder($dir); + } catch (Exception $e) { + Mage::throwException($e->getMessage()); + } } /** @@ -718,11 +722,13 @@ public function getDefaultSizeUploadDir() public function getInterfaceImagesPathsConf() { if (!isset($this->_confPaths)) { - $paths = $this->getInterfaceImagesPaths(); $this->_confPaths = array(); - $len = strlen('conf/native/'); - foreach ($paths as $path => $defaultFileName) { - $this->_confPaths[$path] = substr($path, $len); + $paths = $this->getInterfaceImagesPaths(); + if (is_array($paths)) { + $len = strlen('conf/native/'); + while (list($path,) = each($paths)) { + $this->_confPaths[$path] = substr($path, $len); + } } } return $this->_confPaths; @@ -758,4 +764,20 @@ public function getInterfaceImagesPaths($imagePath = null) return null; } } + + /** + * Check image and get full file path + * + * @param string &$icon + * @return bool + */ + public function checkAndGetImagePath(&$icon) + { + $icon = basename($icon); + if (is_file($this->getDefaultSizeUploadDir() . DS . $icon)) { + $icon = $this->getDefaultSizeUploadDir() . DS . $icon; + return true; + } + return false; + } } diff --git a/app/code/core/Mage/XmlConnect/Helper/Ipad.php b/app/code/core/Mage/XmlConnect/Helper/Ipad.php index f7d60ed6ef..a128537611 100755 --- a/app/code/core/Mage/XmlConnect/Helper/Ipad.php +++ b/app/code/core/Mage/XmlConnect/Helper/Ipad.php @@ -98,11 +98,8 @@ class Mage_XmlConnect_Helper_Ipad extends Mage_Core_Helper_Abstract * * @var array */ - protected $_imageIds = array('icon', - 'ipad_loader_portrait_image', - 'ipad_loader_landscape_image', - 'ipad_logo', - 'big_logo' + protected $_imageIds = array( + 'icon', 'ipad_loader_portrait_image', 'ipad_loader_landscape_image', 'ipad_logo', 'big_logo' ); /** @@ -125,7 +122,6 @@ public function getSubmitImages() /** * Get default application tabs * - * @param string * @return array */ public function getDefaultDesignTabs() @@ -164,74 +160,74 @@ public function getDefaultDesignTabs() */ public function getDefaultConfiguration() { - return array( - 'native' => array( - 'body' => array( - 'backgroundColor' => '#ABABAB', - 'scrollBackgroundColor' => '#EDEDED', - ), - 'itemActions' => array( - 'relatedProductBackgroundColor' => '#404040', - ), - 'fonts' => array( - 'Title1' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '20', - 'color' => '#FEFEFE', - ), - 'Title2' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '15', - 'color' => '#222222', - ), - 'Title3' => array( - 'name' => 'HelveticaNeue', - 'size' => '14', - 'color' => '#222222', - ), - 'Title4' => array( - 'name' => 'HelveticaNeue', - 'size' => '12', - 'color' => '#FFFFFF', - ), - 'Title5' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '18', - 'color' => '#d55000', - ), - 'Title6' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '16', - 'color' => '#FFFFFF', - ), - 'Title7' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '13', - 'color' => '#222222', - ), - 'Title8' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '13', - 'color' => '#FFFFFF', - ), - 'Title9' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '18', - 'color' => '#FFFFFF', - ), - 'Text1' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '14', - 'color' => '#222222', - ), - 'Text2' => array( - 'name' => 'HelveticaNeue', - 'size' => '12', - 'color' => '#222222', - ), - ), - ), - ); + return array( + 'native' => array( + 'body' => array( + 'backgroundColor' => '#ABABAB', + 'scrollBackgroundColor' => '#EDEDED', + ), + 'itemActions' => array( + 'relatedProductBackgroundColor' => '#404040', + ), + 'fonts' => array( + 'Title1' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '20', + 'color' => '#FEFEFE', + ), + 'Title2' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '15', + 'color' => '#222222', + ), + 'Title3' => array( + 'name' => 'HelveticaNeue', + 'size' => '14', + 'color' => '#222222', + ), + 'Title4' => array( + 'name' => 'HelveticaNeue', + 'size' => '12', + 'color' => '#FFFFFF', + ), + 'Title5' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '18', + 'color' => '#d55000', + ), + 'Title6' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '16', + 'color' => '#FFFFFF', + ), + 'Title7' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '13', + 'color' => '#222222', + ), + 'Title8' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '13', + 'color' => '#FFFFFF', + ), + 'Title9' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '18', + 'color' => '#FFFFFF', + ), + 'Text1' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '14', + 'color' => '#222222', + ), + 'Text2' => array( + 'name' => 'HelveticaNeue', + 'size' => '12', + 'color' => '#222222', + ), + ), + ), + ); } /** @@ -460,7 +456,7 @@ public function getFontList() */ public function getFontSizes() { - $result = array( ); + $result = array(); for ($i = 6; $i < 32; $i++) { $result[] = array( 'value' => $i, @@ -538,14 +534,14 @@ public function validateSubmit($params) } if (!Zend_Validate::is($resubmissionKey, 'NotEmpty')) { $errors[] = Mage::helper('xmlconnect')->__('Please enter the Resubmission Key.'); - } else if (!Zend_Validate::is($resubmissionKey, 'StringLength', array(1, $keyLenght))) { + } elseif (!Zend_Validate::is($resubmissionKey, 'StringLength', array(1, $keyLenght))) { $errors[] = Mage::helper('xmlconnect')->__('Submit App failure. Invalid activation key provided'); } } else { $key = isset($params['key']) ? $params['key'] : null; if (!Zend_Validate::is($key, 'NotEmpty')) { $errors[] = Mage::helper('xmlconnect')->__('Please enter the Activation Key.'); - } else if (!Zend_Validate::is($key, 'StringLength', array(1, $keyLenght))) { + } elseif (!Zend_Validate::is($key, 'StringLength', array(1, $keyLenght))) { $errors[] = Mage::helper('xmlconnect')->__('Submit App failure. Invalid activation key provided'); } } @@ -561,10 +557,11 @@ public function validateSubmit($params) public function validateConfig($native) { $errors = array(); - if ( ($native === false) - || (!isset($native['navigationBar']) || !is_array($native['navigationBar']) - || !isset($native['navigationBar']['icon']) - || !Zend_Validate::is($native['navigationBar']['icon'], 'NotEmpty'))) { + if ($native === false + || (!isset($native['navigationBar']['icon']) + || !Zend_Validate::is($native['navigationBar']['icon'], 'NotEmpty') + ) + ) { $errors[] = Mage::helper('xmlconnect')->__('Please upload an image for "Logo in Header" field from Design Tab.'); } @@ -652,34 +649,39 @@ public function getCountryClass() */ public function checkImages(array $data) { - if (isset($data['conf']['native']['navigationBar']['icon']) - && !file_exists($data['conf']['native']['navigationBar']['icon']) - ) { - $data['conf']['native']['navigationBar']['icon'] = ''; + /** @var $helper Mage_XmlConnect_Helper_Image */ + $helper = Mage::helper('xmlconnect/image'); + + $icon =& $data['conf']['native']['navigationBar']['icon']; + + if (!empty($icon) && !$helper->checkAndGetImagePath($icon)) { + $icon = ''; } - if (isset($data['conf']['native']['body']['bannerIpadLandscapeImage']) - && !file_exists($data['conf']['native']['body']['bannerIpadLandscapeImage']) - ) { - $data['conf']['native']['body']['bannerIpadLandscapeImage'] = ''; + $bannerLand =& $data['conf']['native']['body']['bannerIpadLandscapeImage']; + + if (!empty($bannerLand) && !$helper->checkAndGetImagePath($bannerLand)) { + $bannerLand = ''; } - if (isset($data['conf']['native']['body']['bannerIpadImage']) - && !file_exists($data['conf']['native']['body']['bannerIpadImage']) - ) { - $data['conf']['native']['body']['bannerIpadImage'] = ''; + $banner =& $data['conf']['native']['body']['bannerIpadImage']; + + if (!empty($banner) && !$helper->checkAndGetImagePath($banner)) { + $banner = ''; } - if (isset($data['conf']['native']['body']['backgroundIpadLandscapeImage']) - && !file_exists($data['conf']['native']['body']['backgroundIpadLandscapeImage']) - ) { - $data['conf']['native']['body']['backgroundIpadLandscapeImage'] = ''; + $backgroundLand =& $data['conf']['native']['body']['backgroundIpadLandscapeImage']; + + if (!empty($backgroundLand) && !$helper->checkAndGetImagePath($backgroundLand)) { + $backgroundLand = ''; } - if (isset($data['conf']['native']['body']['backgroundIpadPortraitImage']) - && !file_exists($data['conf']['native']['body']['backgroundIpadPortraitImage']) - ) { - $data['conf']['native']['body']['backgroundIpadPortraitImage'] = ''; + + $background =& $data['conf']['native']['body']['backgroundIpadPortraitImage']; + + if (!empty($background) && !$helper->checkAndGetImagePath($background)) { + $background = ''; } + return $data; } @@ -688,7 +690,7 @@ public function checkImages(array $data) * * @throws Mage_Core_Exception * @param array $data - * @return void + * @return null */ public function checkRequiredConfigFields($data) { @@ -696,23 +698,17 @@ public function checkRequiredConfigFields($data) return; } - if (isset($data['navigationBar']['icon']) - && empty($data['navigationBar']['icon']) - ) { + if (isset($data['navigationBar']['icon']) && empty($data['navigationBar']['icon'])) { Mage::throwException( Mage::helper('xmlconnect')->__('Logo in Header image missing.') ); } - if (isset($data['body']['bannerIpadImage']) - && empty($data['body']['bannerIpadImage']) - ) { + if (isset($data['body']['bannerIpadImage']) && empty($data['body']['bannerIpadImage'])) { Mage::throwException( Mage::helper('xmlconnect')->__('Banner on Home Screen (portrait mode) image missing.') ); } - if (isset($data['body']['bannerIpadLandscapeImage']) - && empty($data['body']['bannerIpadLandscapeImage']) - ) { + if (isset($data['body']['bannerIpadLandscapeImage']) && empty($data['body']['bannerIpadLandscapeImage'])) { Mage::throwException( Mage::helper('xmlconnect')->__('Banner on Home Screen (landscape mode) image missing.') ); @@ -732,4 +728,14 @@ public function checkRequiredConfigFields($data) ); } } + + /** + * Check the notifications are allowed for current type of application + * + * @return bool + */ + public function isNotificationsAllowed() + { + return true; + } } diff --git a/app/code/core/Mage/XmlConnect/Helper/Iphone.php b/app/code/core/Mage/XmlConnect/Helper/Iphone.php index 9f81f57858..73f8954ac2 100644 --- a/app/code/core/Mage/XmlConnect/Helper/Iphone.php +++ b/app/code/core/Mage/XmlConnect/Helper/Iphone.php @@ -59,13 +59,7 @@ class Mage_XmlConnect_Helper_Iphone extends Mage_Core_Helper_Abstract * @var array */ protected $_imageIds = array( - 'icon', - 'loader_image', - 'loader_image_i4', - 'logo', - 'logo_i4', - 'big_logo', - 'big_logo_i4' + 'icon', 'loader_image', 'loader_image_i4', 'logo', 'logo_i4', 'big_logo', 'big_logo_i4' ); /** @@ -190,7 +184,6 @@ public function getSubmitImages() /** * Get default application tabs * - * @param string * @return array */ public function getDefaultDesignTabs() @@ -244,74 +237,74 @@ public function getDefaultDesignTabs() */ public function getDefaultConfiguration() { - return array( - 'native' => array( - 'body' => array( - 'backgroundColor' => '#ABABAB', - 'scrollBackgroundColor' => '#EDEDED', - ), - 'itemActions' => array( - 'relatedProductBackgroundColor' => '#404040', - ), - 'fonts' => array( - 'Title1' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '14', - 'color' => '#FEFEFE', - ), - 'Title2' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '12', - 'color' => '#222222', - ), - 'Title3' => array( - 'name' => 'HelveticaNeue', - 'size' => '13', - 'color' => '#000000', - ), - 'Title4' => array( - 'name' => 'HelveticaNeue', - 'size' => '12', - 'color' => '#FFFFFF', - ), - 'Title5' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '13', - 'color' => '#dc5f02', - ), - 'Title6' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '16', - 'color' => '#222222', - ), - 'Title7' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '13', - 'color' => '#000000', - ), - 'Title8' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '11', - 'color' => '#FFFFFF', - ), - 'Title9' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '12', - 'color' => '#FFFFFF', - ), - 'Text1' => array( - 'name' => 'HelveticaNeue-Bold', - 'size' => '12', - 'color' => '#777777', - ), - 'Text2' => array( - 'name' => 'HelveticaNeue', - 'size' => '10', - 'color' => '#555555', - ), - ), - ), - ); + return array( + 'native' => array( + 'body' => array( + 'backgroundColor' => '#ABABAB', + 'scrollBackgroundColor' => '#EDEDED', + ), + 'itemActions' => array( + 'relatedProductBackgroundColor' => '#404040', + ), + 'fonts' => array( + 'Title1' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '14', + 'color' => '#FEFEFE', + ), + 'Title2' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '12', + 'color' => '#222222', + ), + 'Title3' => array( + 'name' => 'HelveticaNeue', + 'size' => '13', + 'color' => '#000000', + ), + 'Title4' => array( + 'name' => 'HelveticaNeue', + 'size' => '12', + 'color' => '#FFFFFF', + ), + 'Title5' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '13', + 'color' => '#dc5f02', + ), + 'Title6' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '16', + 'color' => '#222222', + ), + 'Title7' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '13', + 'color' => '#000000', + ), + 'Title8' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '11', + 'color' => '#FFFFFF', + ), + 'Title9' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '12', + 'color' => '#FFFFFF', + ), + 'Text1' => array( + 'name' => 'HelveticaNeue-Bold', + 'size' => '12', + 'color' => '#777777', + ), + 'Text2' => array( + 'name' => 'HelveticaNeue', + 'size' => '10', + 'color' => '#555555', + ), + ), + ), + ); } /** @@ -540,7 +533,7 @@ public function getFontList() */ public function getFontSizes() { - $result = array( ); + $result = array(); for ($i = 6; $i < 32; $i++) { $result[] = array( 'value' => $i, @@ -618,14 +611,14 @@ public function validateSubmit($params) if (!Zend_Validate::is($resubmissionKey, 'NotEmpty')) { $errors[] = Mage::helper('xmlconnect')->__('Please enter the Resubmission Key.'); - } else if (!Zend_Validate::is($resubmissionKey, 'StringLength', array(1, $keyLenght))) { + } elseif (!Zend_Validate::is($resubmissionKey, 'StringLength', array(1, $keyLenght))) { $errors[] = Mage::helper('xmlconnect')->__('Submit App failure. Invalid activation key provided'); } } else { $key = isset($params['key']) ? $params['key'] : null; if (!Zend_Validate::is($key, 'NotEmpty')) { $errors[] = Mage::helper('xmlconnect')->__('Please enter the Activation Key.'); - } else if (!Zend_Validate::is($key, 'StringLength', array(1, $keyLenght))) { + } elseif (!Zend_Validate::is($key, 'StringLength', array(1, $keyLenght))) { $errors[] = Mage::helper('xmlconnect')->__('Submit App failure. Invalid activation key provided'); } } @@ -642,10 +635,9 @@ public function validateConfig($native) { $errors = array(); - if ( ($native === false) - || (!isset($native['navigationBar']) || !is_array($native['navigationBar']) - || !isset($native['navigationBar']['icon']) - || !Zend_Validate::is($native['navigationBar']['icon'], 'NotEmpty'))) { + if ($native === false || (!isset($native['navigationBar']['icon']) + || !Zend_Validate::is($native['navigationBar']['icon'], 'NotEmpty')) + ) { $errors[] = Mage::helper('xmlconnect')->__('Please upload an image for "Logo in Header" field from Design Tab.'); } @@ -725,23 +717,27 @@ public function getCountryClass() */ public function checkImages(array $data) { - if (isset($data['conf']['native']['navigationBar']['icon']) && - !file_exists($data['conf']['native']['navigationBar']['icon']) - ) { - $data['conf']['native']['navigationBar']['icon'] = ''; + /** @var $helper Mage_XmlConnect_Helper_Image */ + $helper = Mage::helper('xmlconnect/image'); + + $icon =& $data['conf']['native']['navigationBar']['icon']; + + if (!empty($icon) && !$helper->checkAndGetImagePath($icon)) { + $icon = ''; } - if (isset($data['conf']['native']['body']['bannerImage']) && - !file_exists($data['conf']['native']['body']['bannerImage']) - ) { - $data['conf']['native']['body']['bannerImage'] = ''; + $banner =& $data['conf']['native']['body']['bannerImage']; + + if (!empty($banner) && !$helper->checkAndGetImagePath($banner)) { + $banner = ''; } - if (isset($data['conf']['native']['body']['backgroundImage']) && - !file_exists($data['conf']['native']['body']['backgroundImage']) - ) { - $data['conf']['native']['body']['backgroundImage'] = ''; + $background =& $data['conf']['native']['body']['backgroundImage']; + + if (!empty($background) && !$helper->checkAndGetImagePath($background)) { + $background = ''; } + return $data; } @@ -750,7 +746,7 @@ public function checkImages(array $data) * * @throws Mage_Core_Exception * @param array $data - * @return void + * @return null */ public function checkRequiredConfigFields($data) { @@ -758,26 +754,24 @@ public function checkRequiredConfigFields($data) return; } - if (isset($data['navigationBar']['icon']) - && empty($data['navigationBar']['icon']) - ) { - Mage::throwException( - Mage::helper('xmlconnect')->__('Logo in Header image missing.') - ); + if (isset($data['navigationBar']['icon']) && empty($data['navigationBar']['icon'])) { + Mage::throwException(Mage::helper('xmlconnect')->__('Logo in Header image missing.')); } - if (isset($data['body']['bannerImage']) && - empty($data['body']['bannerImage']) - ) { - Mage::throwException( - Mage::helper('xmlconnect')->__('Banner on Home Screen image missing.') - ); + if (isset($data['body']['bannerImage']) && empty($data['body']['bannerImage'])) { + Mage::throwException(Mage::helper('xmlconnect')->__('Banner on Home Screen image missing.')); } - if (isset($data['body']['backgroundImage']) - && empty($data['body']['backgroundImage']) - ) { - Mage::throwException( - Mage::helper('xmlconnect')->__('App Background image missing.') - ); + if (isset($data['body']['backgroundImage']) && empty($data['body']['backgroundImage'])) { + Mage::throwException(Mage::helper('xmlconnect')->__('App Background image missing.')); } } + + /** + * Check the notifications are allowed for current type of application + * + * @return bool + */ + public function isNotificationsAllowed() + { + return true; + } } diff --git a/app/code/core/Mage/XmlConnect/Helper/Payment.php b/app/code/core/Mage/XmlConnect/Helper/Payment.php index ca4938fdb4..4a1df2f794 100644 --- a/app/code/core/Mage/XmlConnect/Helper/Payment.php +++ b/app/code/core/Mage/XmlConnect/Helper/Payment.php @@ -31,7 +31,7 @@ class Mage_XmlConnect_Helper_Payment extends Mage_Core_Helper_Abstract { /** * Return paymentMethod => methodCode array - * + * * @deprecated after 1.4.2.0 * @return array */ diff --git a/app/code/core/Mage/XmlConnect/Helper/Theme.php b/app/code/core/Mage/XmlConnect/Helper/Theme.php index 2414d0a2b5..bb69bc374b 100644 --- a/app/code/core/Mage/XmlConnect/Helper/Theme.php +++ b/app/code/core/Mage/XmlConnect/Helper/Theme.php @@ -81,7 +81,7 @@ public function getThemeAjaxParameters() /** * Returns JSON ready Themes array * - * @param bool $flushCache - load defaults + * @param bool $flushCache load defaults * @return array */ public function getAllThemesArray($flushCache = false) @@ -128,6 +128,12 @@ public function getThemesSelector($themeId = '') $currentTheme = $this->getThemeByName($themeId); } + if (!($currentTheme instanceof Mage_XmlConnect_Model_Theme)) { + Mage::throwException( + Mage::helper('xmlconnect')->__('Can\'t load selected theme. Please check your media folder permissions.') + ); + } + $themeList = ''; foreach ($this->getAllThemes(true) as $theme) { $themeList .= '
  • '; @@ -168,11 +174,11 @@ public function getAllThemes($flushCache = false) $saveLibxmlErrors = libxml_use_internal_errors(true); $this->_themeArray = array(); $themeDir = $this->getMediaThemePath(); - $io = new Varien_Io_File(); - $io->checkAndCreateFolder($themeDir); - $io->open(array('path' => $themeDir)); + $ioFile = new Varien_Io_File(); + $ioFile->checkAndCreateFolder($themeDir); + $ioFile->open(array('path' => $themeDir)); try { - $fileList = $io->ls(Varien_Io_File::GREP_FILES); + $fileList = $ioFile->ls(Varien_Io_File::GREP_FILES); if (!count($fileList)) { $this->resetTheme(); $this->getAllThemes(true); @@ -204,10 +210,10 @@ public function getDefaultThemes() $saveLibxmlErrors = libxml_use_internal_errors(true); $defaultThemeArray = array(); $themeDir = $this->_getDefaultThemePath(); - $io = new Varien_Io_File(); - $io->open(array('path' => $themeDir)); + $ioFile = new Varien_Io_File(); + $ioFile->open(array('path' => $themeDir)); try { - $fileList = $io->ls(Varien_Io_File::GREP_FILES); + $fileList = $ioFile->ls(Varien_Io_File::GREP_FILES); foreach ($fileList as $file) { $src = $themeDir . DS . $file['text']; if (is_readable($src)) { @@ -220,9 +226,7 @@ public function getDefaultThemes() Mage::logException($e); } if (!count($defaultThemeArray)) { - Mage::throwException( - Mage::helper('xmlconnect')->__('Can\'t load default themes.') - ); + Mage::throwException(Mage::helper('xmlconnect')->__('Can\'t load default themes.')); } return $defaultThemeArray; } @@ -267,16 +271,16 @@ public function getMediaThemePath() * * @throws Mage_Core_Exception * @param null $theme - * @return void + * @return null */ public function resetTheme($theme = null) { $themeDir = $this->getMediaThemePath(); $defaultThemeDir = $this->_getDefaultThemePath(); - $io = new Varien_Io_File(); - $io->open(array('path' => $defaultThemeDir)); - $fileList = $io->ls(Varien_Io_File::GREP_FILES); + $ioFile = new Varien_Io_File(); + $ioFile->open(array('path' => $defaultThemeDir)); + $fileList = $ioFile->ls(Varien_Io_File::GREP_FILES); foreach ($fileList as $file) { $f = $file['text']; $src = $defaultThemeDir . DS . $f; @@ -286,12 +290,10 @@ public function resetTheme($theme = null) continue; } - if (!$io->cp($src, $dst)) { - Mage::throwException( - Mage::helper('xmlconnect')->__('Can\'t copy file "%s" to "%s".', $src, $dst) - ); + if (!$ioFile->cp($src, $dst)) { + Mage::throwException(Mage::helper('xmlconnect')->__('Can\'t copy file "%s" to "%s".', $src, $dst)); } else { - $io->chmod($dst, 0755); + $ioFile->chmod($dst, 0755); } } } @@ -378,11 +380,11 @@ public function getThemeLabel(array $themes, $themeId = false) public function deleteTheme($themeId) { $result = false; - $io = new Varien_Io_File(); - $io->cd($this->getMediaThemePath()); + $ioFile = new Varien_Io_File(); + $ioFile->cd($this->getMediaThemePath()); $themeFile = $themeId . '.xml'; - if ($io->fileExists($themeFile)) { - $result = $io->rm($themeFile); + if ($ioFile->fileExists($themeFile)) { + $result = $ioFile->rm($themeFile); } return $result; } diff --git a/app/code/core/Mage/XmlConnect/Model/Adminhtml/System/Config/Backend/Baseurl.php b/app/code/core/Mage/XmlConnect/Model/Adminhtml/System/Config/Backend/Baseurl.php index bfeb9dd081..e1a658cb99 100644 --- a/app/code/core/Mage/XmlConnect/Model/Adminhtml/System/Config/Backend/Baseurl.php +++ b/app/code/core/Mage/XmlConnect/Model/Adminhtml/System/Config/Backend/Baseurl.php @@ -24,12 +24,20 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Model_Adminhtml_System_Config_Backend_Baseurl extends Mage_Adminhtml_Model_System_Config_Backend_Baseurl +/** + * Xmlconnect system config base url model + * + * @category Mage + * @package Mage_Xmlconnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Model_Adminhtml_System_Config_Backend_Baseurl + extends Mage_Adminhtml_Model_System_Config_Backend_Baseurl { /** * Update all applications "updated at" parameter with current date * - * @return this + * @return Mage_XmlConnect_Model_Adminhtml_System_Config_Backend_Baseurl */ protected function _afterSave() { diff --git a/app/code/core/Mage/XmlConnect/Model/Adminhtml/System/Config/Backend/Currency/Default.php b/app/code/core/Mage/XmlConnect/Model/Adminhtml/System/Config/Backend/Currency/Default.php index 7d1c69861a..f8ae325735 100644 --- a/app/code/core/Mage/XmlConnect/Model/Adminhtml/System/Config/Backend/Currency/Default.php +++ b/app/code/core/Mage/XmlConnect/Model/Adminhtml/System/Config/Backend/Currency/Default.php @@ -24,7 +24,15 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Mage_XmlConnect_Model_Adminhtml_System_Config_Backend_Currency_Default extends Mage_Adminhtml_Model_System_Config_Backend_Currency_Default +/** + * Xmlconnect system config currency model + * + * @category Mage + * @package Mage_Xmlconnect + * @author Magento Core Team + */ +class Mage_XmlConnect_Model_Adminhtml_System_Config_Backend_Currency_Default + extends Mage_Adminhtml_Model_System_Config_Backend_Currency_Default { /** * Update all applications "updated at" parameter with current date diff --git a/app/code/core/Mage/XmlConnect/Model/Application.php b/app/code/core/Mage/XmlConnect/Model/Application.php index acfe8712a1..fe57afaccd 100644 --- a/app/code/core/Mage/XmlConnect/Model/Application.php +++ b/app/code/core/Mage/XmlConnect/Model/Application.php @@ -25,7 +25,7 @@ */ /** - * XmlConnect Model Application + * Xmlconnect Application model * * @method Mage_XmlConnect_Model_Resource_Application _getResource() * @method Mage_XmlConnect_Model_Resource_Application getResource() @@ -56,17 +56,17 @@ class Mage_XmlConnect_Model_Application extends Mage_Core_Model_Abstract /** * Application code cookie name */ - const APP_CODE_COOKIE_NAME = 'app_code'; + const APP_CODE_COOKIE_NAME = 'app_code'; /** * Device screen size name */ - const APP_SCREEN_SIZE_NAME = 'screen_size'; + const APP_SCREEN_SIZE_NAME = 'screen_size'; /** * Device screen size name */ - const APP_SCREEN_SIZE_DEFAULT = '320x480'; + const APP_SCREEN_SIZE_DEFAULT = '320x480'; /** * Device screen size source name @@ -76,12 +76,12 @@ class Mage_XmlConnect_Model_Application extends Mage_Core_Model_Abstract /** * Application status "submitted" value */ - const APP_STATUS_SUCCESS = 1; + const APP_STATUS_SUCCESS = 1; /** * Application status "not submitted" value */ - const APP_STATUS_INACTIVE = 0; + const APP_STATUS_INACTIVE = 0; /** * Application prefix length of cutted part of deviceType and storeCode @@ -131,6 +131,13 @@ class Mage_XmlConnect_Model_Application extends Mage_Core_Model_Abstract */ protected $_configModel; + /** + * Flag of loaded configuration + * + * @var bool + */ + protected $_isConfigurationLoaded = false; + /** * Social networking validation array * @@ -157,103 +164,106 @@ class Mage_XmlConnect_Model_Application extends Mage_Core_Model_Abstract * for contact to receive credentials * of Urban Airship notifications */ - const XML_PATH_CONTACT_CREDENTIALS_EMAIL = 'xmlconnect/mobile_application/urbanairship_credentials_email'; + const XML_PATH_CONTACT_CREDENTIALS_EMAIL = 'xmlconnect/mobile_application/urbanairship_credentials_email'; /** * XML path to config with Urban Airship Terms of Service URL */ - const XML_PATH_URBAN_AIRSHIP_TOS_URL = 'xmlconnect/mobile_application/urbanairship_terms_of_service_url'; + const XML_PATH_URBAN_AIRSHIP_TOS_URL = 'xmlconnect/mobile_application/urbanairship_terms_of_service_url'; /** * XML path to config with Urban Airship partner's login URL */ - const XML_PATH_URBAN_AIRSHIP_PARTNER_LOGIN_URL = 'xmlconnect/mobile_application/urbanairship_login_url'; + const XML_PATH_URBAN_AIRSHIP_PARTNER_LOGIN_URL = 'xmlconnect/mobile_application/urbanairship_login_url'; /** * XML path to config with Urban Airship Push notifications product URL */ - const XML_PATH_URBAN_AIRSHIP_ABOUT_PUSH_URL = 'xmlconnect/mobile_application/urbanairship_push_url'; + const XML_PATH_URBAN_AIRSHIP_ABOUT_PUSH_URL = 'xmlconnect/mobile_application/urbanairship_push_url'; /** * XML path to config with Urban Airship Rich Push notifications product URL */ - const XML_PATH_URBAN_AIRSHIP_ABOUT_RICH_PUSH_URL = 'xmlconnect/mobile_application/urbanairship_rich_push_url'; + const XML_PATH_URBAN_AIRSHIP_ABOUT_RICH_PUSH_URL = 'xmlconnect/mobile_application/urbanairship_rich_push_url'; /** * XML path to config copyright data */ - const XML_PATH_DESIGN_FOOTER_COPYRIGHT = 'design/footer/copyright'; + const XML_PATH_DESIGN_FOOTER_COPYRIGHT = 'design/footer/copyright'; /** * XML path to config restriction status * (EE module) */ - const XML_PATH_GENERAL_RESTRICTION_IS_ACTIVE = 'general/restriction/is_active'; + const XML_PATH_GENERAL_RESTRICTION_IS_ACTIVE = 'general/restriction/is_active'; /** * XML path to config restriction mode * (EE module) */ - const XML_PATH_GENERAL_RESTRICTION_MODE = 'general/restriction/mode'; + const XML_PATH_GENERAL_RESTRICTION_MODE = 'general/restriction/mode'; /** * XML path to config secure base link URL */ - const XML_PATH_SECURE_BASE_LINK_URL = 'web/secure/base_link_url'; + const XML_PATH_SECURE_BASE_LINK_URL = 'web/secure/base_link_url'; /** * XML path to config for paypal business account */ - const XML_PATH_PAYPAL_BUSINESS_ACCOUNT = 'paypal/general/business_account'; + const XML_PATH_PAYPAL_BUSINESS_ACCOUNT = 'paypal/general/business_account'; /** * XML path to config for default cache time */ - const XML_PATH_DEFAULT_CACHE_LIFETIME = 'xmlconnect/mobile_application/cache_lifetime'; + const XML_PATH_DEFAULT_CACHE_LIFETIME = 'xmlconnect/mobile_application/cache_lifetime'; /** * XML path to How-To URL for twitter */ - const XML_PATH_HOWTO_TWITTER_URL = 'xmlconnect/social_networking/howto_twitter_url'; + const XML_PATH_HOWTO_TWITTER_URL = 'xmlconnect/social_networking/howto_twitter_url'; /** * XML path to How-To URL for facebook */ - const XML_PATH_HOWTO_FACEBOOK_URL = 'xmlconnect/social_networking/howto_facebook_url'; + const XML_PATH_HOWTO_FACEBOOK_URL = 'xmlconnect/social_networking/howto_facebook_url'; /** * XML path to How-To URL for linkedin */ - const XML_PATH_HOWTO_LINKEDIN_URL = 'xmlconnect/social_networking/howto_linkedin_url'; + const XML_PATH_HOWTO_LINKEDIN_URL = 'xmlconnect/social_networking/howto_linkedin_url'; + + /** + * XML path to XmlConnect module version + */ + const XML_PATH_MODULE_VERSION = 'modules/Mage_XmlConnect/innerVersion'; /** * Deprecated config flag * * @deprecated Serialized config storage has been removed */ - const DEPRECATED_CONFIG_FLAG = 'deprecated'; + const DEPRECATED_CONFIG_FLAG = 'deprecated'; /** * Delete on update paths for config data * * @var array */ - protected $_deleteOnUpdateConfig = array( + protected $_deleteOnUpdateConfig = array( self::DEPRECATED_CONFIG_FLAG => 'native/pages' ); /** * Initialize application * - * @return void + * @return null */ protected function _construct() { $this->_init('xmlconnect/application'); $this->_configModel = Mage::getModel('xmlconnect/configData'); - $this->_configModel->setDeleteOnUpdate( - $this->getDeleteOnUpdateConfig() - ); + $this->_configModel->setDeleteOnUpdate($this->getDeleteOnUpdateConfig()); } /** @@ -306,25 +316,25 @@ protected function _flatArray($subtree, $prefix=null) } /** - * Like array_merge_recursive(), but string values is replaced + * Like array_merge_recursive(), but string values will be replaced * - * @param array $a - * @param array $b + * @param array $array1 + * @param array $array2 * @return array */ - protected function _configMerge(array $a, array $b) + protected function _configMerge(array $array1, array $array2) { $result = array(); - $keys = array_unique(array_merge(array_keys($a), array_keys($b))); + $keys = array_unique(array_merge(array_keys($array1), array_keys($array2))); foreach ($keys as $key) { - if (!isset($a[$key])) { - $result[$key] = $b[$key]; - } elseif (!isset($b[$key])) { - $result[$key] = $a[$key]; - } elseif (is_scalar($a[$key]) || is_scalar($b[$key])) { - $result[$key] = $b[$key]; + if (!isset($array1[$key])) { + $result[$key] = $array2[$key]; + } elseif (!isset($array2[$key])) { + $result[$key] = $array1[$key]; + } elseif (is_scalar($array1[$key]) || is_scalar($array2[$key])) { + $result[$key] = $array2[$key]; } else { - $result[$key] = $this->_configMerge($a[$key], $b[$key]); + $result[$key] = $this->_configMerge($array1[$key], $array2[$key]); } } return $result; @@ -333,7 +343,7 @@ protected function _configMerge(array $a, array $b) /** * Set default configuration data * - * @return void + * @return null */ public function loadDefaultConfiguration() { @@ -383,7 +393,7 @@ public function getRenderConf() { $result = Mage::helper('xmlconnect')->getDeviceHelper()->getDefaultConfiguration(); $result = $result['native']; - $extra = array(); + if (isset($this->_data['conf'])) { if (isset($this->_data['conf']['native'])) { $result = $this->_configMerge($result, $this->_data['conf']['native']); @@ -401,8 +411,8 @@ public function getRenderConf() if (!empty($extra['fontColors']['primary'])) { $result['fonts']['Title2']['color'] = $extra['fontColors']['primary']; $result['fonts']['Title3']['color'] = $extra['fontColors']['primary']; - $result['fonts']['Text1']['color'] = $extra['fontColors']['primary']; - $result['fonts']['Text2']['color'] = $extra['fontColors']['primary']; + $result['fonts']['Text1']['color'] = $extra['fontColors']['primary']; + $result['fonts']['Text2']['color'] = $extra['fontColors']['primary']; $result['fonts']['Title7']['color'] = $extra['fontColors']['primary']; } if (!empty($extra['fontColors']['secondary'])) { @@ -417,23 +427,24 @@ public function getRenderConf() } } } + /** @var $helperImage Mage_XmlConnect_Helper_Image */ $helperImage = Mage::helper('xmlconnect/image'); $paths = $helperImage->getInterfaceImagesPathsConf(); + foreach ($paths as $confPath => $dataPath) { $imageNodeValue =& $helperImage->findPath($result, $dataPath); - if ($imageNodeValue) { - if (!file_exists($imageNodeValue)) { - /** - * We set empty string to get default image if original was missing in some reason - */ - $imageNodeValue = ''; - } else { - /** - * Creating file ending (some_inner/some_dir/filename.png) For url - */ - $imageNodeValue = $helperImage->getFileCustomDirSuffixAsUrl($confPath, $imageNodeValue); - } + + if (!$helperImage->checkAndGetImagePath($imageNodeValue)) { + /** + * We set empty string to get default image if original was missing in some reason + */ + $imageNodeValue = ''; + } else { + /** + * Creating file ending (some_inner/some_dir/filename.png) For url + */ + $imageNodeValue = $helperImage->getFileCustomDirSuffixAsUrl($confPath, $imageNodeValue); } } $result = $this->_absPath($result); @@ -444,10 +455,7 @@ public function getRenderConf() $result['general']['updateTimeUTC'] = strtotime($this->getUpdatedAt()); $result['general']['browsingMode'] = $this->getBrowsingMode(); $result['general']['currencyCode'] = Mage::app()->getStore($this->getStoreId())->getDefaultCurrencyCode(); - $result['general']['secureBaseUrl'] = Mage::getStoreConfig( - self::XML_PATH_SECURE_BASE_LINK_URL, - $this->getStoreId() - ); + $result['general']['secureBaseUrl'] = $this->getSecureBaseUrl(); $maxRecipients = 0; $allowGuest = 0; @@ -461,11 +469,11 @@ public function getRenderConf() ->getStore($this->getStoreId())->getConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE); $result['general']['magentoVersion'] = Mage::getVersion(); $result['general']['copyright'] = Mage::getStoreConfig( - self::XML_PATH_DESIGN_FOOTER_COPYRIGHT, - $this->getStoreId() + self::XML_PATH_DESIGN_FOOTER_COPYRIGHT, $this->getStoreId() ); + $result['general']['xmlconnectVersion'] = Mage::getConfig()->getNode(self::XML_PATH_MODULE_VERSION); - $result['general']['isAllowedGuestCheckout'] = Mage::getSingleton('checkout/session') + $result['general']['isAllowedGuestCheckout'] = (int)Mage::getSingleton('checkout/session') ->getQuote()->isAllowedGuestCheckout(); /** @@ -489,8 +497,28 @@ public function getRenderConf() /** * "Use Secure URLs in Frontend" flag */ - $result['general']['useSecureURLInFrontend'] = (int)Mage::getStoreConfigFlag( - Mage_Core_Model_Store::XML_PATH_SECURE_IN_FRONTEND + $result['general']['useSecureURLInFrontend'] = $this->getUseSecureURLInFrontend(); + + /** + * Is enabled Store credit functionality + */ + if (is_object(Mage::getConfig()->getNode('modules/Enterprise_CustomerBalance'))) { + $storeCreditFlag = Mage::getStoreConfig(Enterprise_CustomerBalance_Helper_Data::XML_PATH_ENABLED); + $isStoreCreditEnable = (int)$storeCreditFlag; + $canShowHistoryFlag = (int) Mage::getStoreConfigFlag( + 'customer/enterprise_customerbalance/show_history' + ); + } else { + $isStoreCreditEnable = $canShowHistoryFlag = 0; + } + $result['general']['isStoreCreditEnabled'] = $isStoreCreditEnable; + $result['general']['isStoreCreditHistoryEnabled'] = $canShowHistoryFlag; + + /** + * Is available Gift Card functionality + */ + $result['general']['isGiftcardEnabled'] = (int) is_object( + Mage::getConfig()->getNode('modules/Enterprise_GiftCard') ); /** @@ -500,21 +528,52 @@ public function getRenderConf() $result['paypal']['merchantLabel'] = $this->getData('conf/special/merchantLabel'); $isActive = 0; - if (isset($result['paypal']) && isset($result['paypal']['isActive'])) { - $paypalMep = Mage::getModel('xmlconnect/payment_method_paypal_mep'); - $isActive = (int)($result['paypal']['isActive'] && $paypalMep->isAvailable(null)); + $paypalMepIsAvailable = Mage::getModel('xmlconnect/payment_method_paypal_mep')->isAvailable(null); + if ($paypalMepIsAvailable && isset($result['paypal']['isActive'])) { + $isActive = (int) $result['paypal']['isActive']; } $result['paypal']['isActive'] = $isActive; + $paypalMeclIsAvailable = Mage::getModel('xmlconnect/payment_method_paypal_mecl')->isAvailable(null); + + /** + * PayPal Mobile Express Library Checkout + */ + $result['paypalMecl']['isActive'] = (int) ( + $paypalMeclIsAvailable + && $this->getData('config_data/payment/paypalmecl_is_active') + ); + if ((int)Mage::getStoreConfig(self::XML_PATH_GENERAL_RESTRICTION_IS_ACTIVE)) { $result['website_restrictions']['mode'] = (int)Mage::getStoreConfig( self::XML_PATH_GENERAL_RESTRICTION_MODE ); } + ksort($result); return $result; } + /** + * Get secure base url + * + * @return string + */ + public function getSecureBaseUrl() + { + return Mage::getStoreConfig(self::XML_PATH_SECURE_BASE_LINK_URL, $this->getStoreId()); + } + + /** + * Is forced front secure url + * + * @return int + */ + public function getUseSecureURLInFrontend() + { + return (int) Mage::getStoreConfigFlag(Mage_Core_Model_Store::XML_PATH_SECURE_IN_FRONTEND); + } + /** * Return current screen_size parameter * @@ -566,9 +625,7 @@ protected function _absPath($subtree) if (!empty($value)) { if (is_array($value)) { $subtree[$key] = $this->_absPath($value); - } elseif ((substr($key, -4) == 'icon') || - (substr($key, -4) == 'Icon') || - (substr($key, -5) == 'Image')) { + } elseif (strtolower(substr($key, -4)) == 'icon' || strtolower(substr($key, -5)) == 'image') { $subtree[$key] = Mage::getBaseUrl('media') . 'xmlconnect/' . $value; } } @@ -606,9 +663,7 @@ public function getConfigModel() */ protected function _beforeSave() { - $this->setUpdatedAt( - Mage::getSingleton('core/date')->gmtDate() - ); + $this->setUpdatedAt(Mage::getSingleton('core/date')->gmtDate()); return $this; } @@ -634,9 +689,7 @@ protected function _saveConfigData() { $configuration = $this->getData('config_data'); if (is_array($configuration)) { - $this->getConfigModel() - ->setConfigData($this->getId(), $configuration) - ->initSaveConfig(); + $this->getConfigModel()->setConfigData($this->getId(), $configuration)->initSaveConfig(); } return $this; } @@ -652,9 +705,7 @@ private function _saveDeprecatedConfig() $deprecatedConfig = $this->getData('conf'); if (is_array($deprecatedConfig)) { $this->getConfigModel()->saveConfig( - $this->getId(), - $this->convertOldConfing($deprecatedConfig), - self::DEPRECATED_CONFIG_FLAG + $this->getId(), $this->convertOldConfing($deprecatedConfig), self::DEPRECATED_CONFIG_FLAG ); } return $this; @@ -689,12 +740,10 @@ public function convertOldConfing(array $conf, $path = false) */ public function loadConfiguration() { - static $isConfigurationLoaded = null; - if (is_null($isConfigurationLoaded)) { + if (!$this->_isConfigurationLoaded) { if ($this->getId()) { - $this->_loadDeprecatedConfig() - ->_loadConfigData(); - $isConfigurationLoaded = true; + $this->_loadDeprecatedConfig()->_loadConfigData(); + $this->_isConfigurationLoaded = true; } } return $this; @@ -708,15 +757,11 @@ public function loadConfiguration() */ protected function _loadConfigData() { - $configuration = $this->getConfigModel() - ->getCollection() - ->addArrayFilter( - array( - 'application_id' => $this->getId(), - 'category' => 'payment' - ) - ) - ->toOptionArray(); + $configuration = $this->getConfigModel()->getCollection()->addArrayFilter(array( + 'application_id' => $this->getId(), + 'category' => 'payment' + ))->toOptionArray(); + $this->setData('config_data', $configuration); return $this; } @@ -730,15 +775,10 @@ protected function _loadConfigData() private function _loadDeprecatedConfig() { $configuration = $this->_convertConfig( - $this->getConfigModel() - ->getCollection() - ->addArrayFilter( - array( - 'application_id' => $this->getId(), - 'category' => self::DEPRECATED_CONFIG_FLAG - ) - ) - ->toOptionArray() + $this->getConfigModel()->getCollection()->addArrayFilter(array( + 'application_id' => $this->getId(), + 'category' => self::DEPRECATED_CONFIG_FLAG + ))->toOptionArray() ); $this->setData('conf', $configuration); return $this; @@ -801,9 +841,7 @@ public function loadSubmit() $conf['submit_restore'] = array(); } foreach ($params as $id => $value) { - $deviceImages = Mage::helper('xmlconnect') - ->getDeviceHelper() - ->getSubmitImages(); + $deviceImages = Mage::helper('xmlconnect')->getDeviceHelper()->getSubmitImages(); if (!in_array($id, $deviceImages)) { $conf['submit_text'][$id] = $value; @@ -839,7 +877,7 @@ public function getImages() * Fetching data from session restored array */ $basename = basename($path); - } else if (isset($params[$id])) { + } elseif (isset($params[$id])) { /** * Fetching data from submission history table record * @@ -849,7 +887,7 @@ public function getImages() $basename = basename($params[$id]); } if (!empty($basename)) { - $images['conf/submit/'.$id] = Mage::getBaseUrl('media').'xmlconnect/' + $images['conf/submit/'.$id] = Mage::getBaseUrl('media') . 'xmlconnect/' . Mage::helper('xmlconnect/image')->getFileDefaultSizeSuffixAsUrl($basename); } } @@ -925,7 +963,7 @@ public function validateSubmit($params) */ protected function _validateConf() { - $conf = $this->getConf(); + $conf = $this->getConf(); $native = isset($conf['native']) && is_array($conf['native']) ? $conf['native'] : false; $errors = Mage::helper('xmlconnect')->getDeviceHelper($this)->validateConfig($native); @@ -981,9 +1019,7 @@ public function prepareSubmitParams($data) $params['code'] = $this->getCode(); $params['type'] = $this->getType(); $params['url'] = Mage::getUrl('xmlconnect/configuration/index', array( - '_store' => $this->getStoreId(), - '_nosid' => true, - 'app_code' => $this->getCode() + '_store' => $this->getStoreId(), '_nosid' => true, 'app_code' => $this->getCode() )); $params['magentoversion'] = Mage::getVersion(); @@ -1001,7 +1037,8 @@ public function prepareSubmitParams($data) } else { $params['key'] = isset($params['key']) ? trim($params['key']) : ''; } - // processing files : + + // processing files $submit = array(); if (isset($this->_data['conf']['submit']) && is_array($this->_data['conf']['submit'])) { $submit = $this->_data['conf']['submit']; @@ -1012,14 +1049,13 @@ public function prepareSubmitParams($data) $submitRestore = $this->_data['conf']['submit_restore']; } - $deviceImages = Mage::helper('xmlconnect') - ->getDeviceHelper() - ->getSubmitImages(); + $deviceImages = Mage::helper('xmlconnect')->getDeviceHelper()->getSubmitImages(); foreach ($deviceImages as $id) { if (isset($submit[$id])) { - $params[$id] = '@' . $submit[$id]; - } else if (isset($submitRestore[$id])) { + $params[$id] = '@' . Mage::helper('xmlconnect/image')->getDefaultSizeUploadDir() . DS + . $submit[$id]; + } elseif (isset($submitRestore[$id])) { $params[$id] = $submitRestore[$id]; } } @@ -1049,9 +1085,7 @@ public function getStoreId() public function getActivationKey() { $key = null; - if (isset($this->_data['conf']) && is_array($this->_data['conf']) && - isset($this->_data['conf']['submit_text']) && is_array($this->_data['conf']['submit_text']) && - isset($this->_data['conf']['submit_text']['key'])) { + if (isset($this->_data['conf']['submit_text']['key'])) { $key = $this->_data['conf']['submit_text']['key']; } return $key; @@ -1068,6 +1102,16 @@ public function updateAllAppsUpdatedAtParameter() return $this; } + /** + * Checks if notifications is active + * + * @return boolean + */ + public function isNotificationsActive() + { + return (boolean)$this->loadConfiguration()->getData('conf/native/notifications/isActive'); + } + /** * Getter return concatenated user and password * diff --git a/app/code/core/Mage/XmlConnect/Model/Catalog/Category/Image.php b/app/code/core/Mage/XmlConnect/Model/Catalog/Category/Image.php index 66bfa13255..3e801a346a 100644 --- a/app/code/core/Mage/XmlConnect/Model/Catalog/Category/Image.php +++ b/app/code/core/Mage/XmlConnect/Model/Catalog/Category/Image.php @@ -27,9 +27,9 @@ /** * Catalog category link model * - * @category Mage - * @package Mage_Catalog - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Model_Catalog_Category_Image extends Mage_Catalog_Model_Product_Image { @@ -58,21 +58,26 @@ public function setBaseFile($file) } if (!$file) { // check if placeholder defined in config - $isConfigPlaceholder = Mage::getStoreConfig("catalog/placeholder/{$this->getDestinationSubdir()}_placeholder"); + $isConfigPlaceholder = Mage::getStoreConfig( + 'catalog/placeholder/' . $this->getDestinationSubdir() . '_placeholder' + ); $configPlaceholder = '/placeholder/' . $isConfigPlaceholder; if ($isConfigPlaceholder && file_exists($baseDir . $configPlaceholder)) { $file = $configPlaceholder; } else { // replace file with skin or default skin placeholder $skinBaseDir = Mage::getDesign()->getSkinBaseDir(); - $skinPlaceholder = "/images/xmlconnect/catalog/category/placeholder/{$this->getDestinationSubdir()}.jpg"; + $skinPlaceholder = '/images/xmlconnect/catalog/category/placeholder/' . $this->getDestinationSubdir() + . '.jpg'; + $file = $skinPlaceholder; if (file_exists($skinBaseDir . $file)) { $baseDir = $skinBaseDir; } else { $baseDir = Mage::getDesign()->getSkinBaseDir(array('_theme' => 'default')); if (!file_exists($baseDir . $file)) { - $baseDir = Mage::getDesign()->getSkinBaseDir(array('_theme' => 'default', '_package' => 'base')); + $baseDir = Mage::getDesign() + ->getSkinBaseDir(array('_theme' => 'default', '_package' => 'base')); } } } @@ -82,30 +87,24 @@ public function setBaseFile($file) $baseFile = $baseDir . $file; if ((!$file) || (!file_exists($baseFile))) { - throw new Exception(Mage::helper('xmlconnect')->__('Image file was not found.')); + Mage::throwException(Mage::helper('xmlconnect')->__('Image file was not found.')); } $this->_baseFile = $baseFile; // build new filename (most important params) - $path = array( - Mage::getSingleton('xmlconnect/catalog_category_media_config')->getBaseMediaPath(), - 'cache', - Mage::app()->getStore()->getId(), - $path[] = $this->getDestinationSubdir() + $path = array(Mage::getSingleton('xmlconnect/catalog_category_media_config')->getBaseMediaPath(), 'cache', + Mage::app()->getStore()->getId(), $path[] = $this->getDestinationSubdir() ); - if ((!empty($this->_width)) || (!empty($this->_height))) + if ((!empty($this->_width)) || (!empty($this->_height))) { $path[] = "{$this->_width}x{$this->_height}"; + } // add misk params as a hash - $miscParams = array( - ($this->_keepAspectRatio ? '' : 'non') . 'proportional', - ($this->_keepFrame ? '' : 'no') . 'frame', - ($this->_keepTransparency ? '' : 'no') . 'transparency', - ($this->_constrainOnly ? 'do' : 'not') . 'constrainonly', - $this->_rgbToString($this->_backgroundColor), - 'angle' . $this->_angle, - 'quality' . $this->_quality + $miscParams = array(($this->_keepAspectRatio ? '' : 'non') . 'proportional', + ($this->_keepFrame ? '' : 'no') . 'frame', ($this->_keepTransparency ? '' : 'no') . 'transparency', + ($this->_constrainOnly ? 'do' : 'not') . 'constrainonly', $this->_rgbToString($this->_backgroundColor), + 'angle' . $this->_angle, 'quality' . $this->_quality ); // if has watermark add watermark params to hash @@ -141,17 +140,17 @@ protected function _getWatermarkFilePath() $baseDir = Mage::getSingleton('xmlconnect/catalog_category_media_config')->getBaseMediaPath(); - if ( file_exists($baseDir . '/watermark/stores/' . Mage::app()->getStore()->getId() . $file) ) { + if (file_exists($baseDir . '/watermark/stores/' . Mage::app()->getStore()->getId() . $file)) { $filePath = $baseDir . '/watermark/stores/' . Mage::app()->getStore()->getId() . $file; - } elseif ( file_exists($baseDir . '/watermark/websites/' . Mage::app()->getWebsite()->getId() . $file) ) { + } elseif (file_exists($baseDir . '/watermark/websites/' . Mage::app()->getWebsite()->getId() . $file)) { $filePath = $baseDir . '/watermark/websites/' . Mage::app()->getWebsite()->getId() . $file; - } elseif ( file_exists($baseDir . '/watermark/default/' . $file) ) { + } elseif (file_exists($baseDir . '/watermark/default/' . $file)) { $filePath = $baseDir . '/watermark/default/' . $file; - } elseif ( file_exists($baseDir . '/watermark/' . $file) ) { + } elseif (file_exists($baseDir . '/watermark/' . $file)) { $filePath = $baseDir . '/watermark/' . $file; } else { $baseDir = Mage::getDesign()->getSkinBaseDir(); - if ( file_exists($baseDir . $file) ) { + if (file_exists($baseDir . $file)) { $filePath = $baseDir . $file; } } @@ -162,13 +161,13 @@ protected function _getWatermarkFilePath() /** * Clear catalog cache * - * @return void + * @return null */ public function clearCache() { - $directory = Mage::getBaseDir('media') . DS.'catalog'.DS.'category'.DS.'cache'.DS; - $io = new Varien_Io_File(); - $io->rmdir($directory, true); + $directory = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS . 'cache' . DS; + $ioFile = new Varien_Io_File(); + $ioFile->rmdir($directory, true); } /** diff --git a/app/code/core/Mage/XmlConnect/Model/Catalog/Category/Media/Config.php b/app/code/core/Mage/XmlConnect/Model/Catalog/Category/Media/Config.php index a68fce610f..f4b47d32c5 100644 --- a/app/code/core/Mage/XmlConnect/Model/Catalog/Category/Media/Config.php +++ b/app/code/core/Mage/XmlConnect/Model/Catalog/Category/Media/Config.php @@ -45,7 +45,7 @@ public function getBaseMediaPath() /** * Getter, return catalog baseMediaUrl - * + * * @return string */ public function getBaseMediaUrl() diff --git a/app/code/core/Mage/XmlConnect/Model/ConfigData.php b/app/code/core/Mage/XmlConnect/Model/ConfigData.php index 3f0949cde7..486ff1c137 100644 --- a/app/code/core/Mage/XmlConnect/Model/ConfigData.php +++ b/app/code/core/Mage/XmlConnect/Model/ConfigData.php @@ -60,7 +60,7 @@ class Mage_XmlConnect_Model_ConfigData extends Mage_Core_Model_Abstract /** * Initialize configuration data * - * @return void + * @return null */ protected function _construct() { @@ -154,11 +154,7 @@ public function initSaveConfig() $applicationId = str_ireplace(self::CONFIG_PREFIX, '', $application); $this->_deleteOnUpdate($applicationId); foreach ($data as $category => $config) { - $this->saveConfig( - $applicationId, - $config, - $category - ); + $this->saveConfig($applicationId, $config, $category); } } return $this; @@ -176,9 +172,7 @@ public function saveConfig($applicationId, array $configData, $category = self:: { foreach ($configData as $path => $value) { if (!is_scalar($value)) { - Mage::throwException( - Mage::helper('xmlconnect')->__('Unsupported value type received') - ); + Mage::throwException(Mage::helper('xmlconnect')->__('Unsupported value type received')); } $this->getResource()->saveConfig($applicationId, $category, $path, $value); } diff --git a/app/code/core/Mage/XmlConnect/Model/History.php b/app/code/core/Mage/XmlConnect/Model/History.php index 3ac634eca2..0a84cc8398 100644 --- a/app/code/core/Mage/XmlConnect/Model/History.php +++ b/app/code/core/Mage/XmlConnect/Model/History.php @@ -24,9 +24,8 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ - /** - * XmlConnect Model History + * Xmlconnect history model * * @method Mage_XmlConnect_Model_Resource_History _getResource() * @method Mage_XmlConnect_Model_Resource_History getResource() @@ -54,7 +53,7 @@ class Mage_XmlConnect_Model_History extends Mage_Core_Model_Abstract /** * Initialize application * - * @return void + * @return null */ protected function _construct() { @@ -64,7 +63,7 @@ protected function _construct() /** * Get array of existing images * - * @param int $id application instance Id + * @param int $id Application instance Id * @return array */ public function getLastParams($id) diff --git a/app/code/core/Mage/XmlConnect/Model/Observer.php b/app/code/core/Mage/XmlConnect/Model/Observer.php index d9ae7c2255..5bf0b4de8f 100644 --- a/app/code/core/Mage/XmlConnect/Model/Observer.php +++ b/app/code/core/Mage/XmlConnect/Model/Observer.php @@ -25,10 +25,10 @@ */ /** - * XmlConnect Model Observer + * XmlConnect module observer * * @category Mage - * @package Mage_XmlConnect + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_Model_Observer @@ -70,11 +70,9 @@ public function restrictWebsite($observer) public function changeUpdatedAtParamOnConfigSave($observer) { $configData = $observer->getEvent()->getConfigData(); - if ($configData - && (int)$configData->isValueChanged() + if ($configData && (int)$configData->isValueChanged() && in_array($configData->getPath(), $this->_appDependOnConfigFieldPathes) - ) - { + ) { Mage::getModel('xmlconnect/application')->updateAllAppsUpdatedAtParameter(); } } @@ -83,16 +81,14 @@ public function changeUpdatedAtParamOnConfigSave($observer) * Send a message if Start Date (Queue Date) is empty * * @param Varien_Event_Observer $observer + * @return bool */ public function sendMessageImmediately($observer) { $message = $observer->getEvent()->getData('queueMessage'); - if ($message instanceof Mage_XmlConnect_Model_Queue - && (strtolower($message->getExecTime()) == 'null' - || !$message->getExecTime() - ) - ) - { + if ($message instanceof Mage_XmlConnect_Model_Queue && (strtolower($message->getExecTime()) == 'null' + || !$message->getExecTime()) + ) { $message->setExecTime(Mage::getSingleton('core/date')->gmtDate()); Mage::helper('xmlconnect')->sendBroadcastMessage($message); return true; @@ -102,19 +98,16 @@ public function sendMessageImmediately($observer) } /** - * Send sheduled messages + * Send scheduled messages * - * @param mixed $schedule + * @return null */ - public function scheduledSend($schedule = null) + public function scheduledSend() { $countOfQueue = Mage::getStoreConfig(Mage_XmlConnect_Model_Queue::XML_PATH_CRON_MESSAGES_COUNT); - $collection = Mage::getModel('xmlconnect/queue')->getCollection() - ->addOnlyForSendingFilter() - ->setPageSize($countOfQueue) - ->setCurPage(1) - ->load(); + $collection = Mage::getModel('xmlconnect/queue')->getCollection()->addOnlyForSendingFilter() + ->setPageSize($countOfQueue)->setCurPage(1)->load(); foreach ($collection as $message) { if ($message->getId()) { diff --git a/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Config.php b/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Config.php new file mode 100644 index 0000000000..30ff9fab3e --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Config.php @@ -0,0 +1,51 @@ + + */ +class Mage_XmlConnect_Model_Payment_Method_Paypal_Config extends Mage_Paypal_Model_Config +{ + /** + * PayPal Website Payments Pro - PayPal Mobile Express Checkout Library + */ + const METHOD_WPP_MECL = 'paypal_mecl'; + + /** + * Get url for dispatching customer to express checkout start + * + * @param string $token + * @return string + */ + public function getExpressCheckoutStartUrl($token) + { + return $this->getPaypalUrl(array('cmd' => '_express-checkout-mobile', 'token' => $token)); + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Mecl.php b/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Mecl.php new file mode 100644 index 0000000000..e22886200f --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Mecl.php @@ -0,0 +1,101 @@ + + */ +class Mage_XmlConnect_Model_Payment_Method_Paypal_Mecl extends Mage_Paypal_Model_Express +{ + /** + * Store MECL payment method code + */ + const MECL_METHOD_CODE = 'paypal_mecl'; + + /** + * Payment method code + * + * @var string + */ + protected $_code = self::MECL_METHOD_CODE; + + /** + * Can use method for a frontend checkout + * + * @var bool + */ + protected $_canUseCheckout = false; + + /** + * Can method be used for multishipping checkout type + * + * @var bool + */ + protected $_canUseForMultishipping = false; + + /** + * Can method manage recurring profiles + * + * @var bool + */ + protected $_canManageRecurringProfiles = false; + + /** + * Check whether payment method can be used + * + * @param Mage_Sales_Model_Quote $quote + * @return bool + */ + public function isAvailable($quote = null) + { + $storeId = false; + $model = Mage::registry('current_app'); + + if ($model instanceof Mage_XmlConnect_Model_Application) { + $storeId = $model->getStoreId(); + } + + if (!$storeId) { + $storeId = $quote ? $quote->getStoreId() : Mage::app()->getStore()->getId(); + } + + return (bool) Mage::getModel('paypal/config')->setStoreId($storeId) + ->isMethodAvailable(Mage_Paypal_Model_Config::METHOD_WPP_EXPRESS); + } + + /** + * Return title of the PayPal Mobile Express Checkout Payment method + * + * @return string + */ + public function getTitle() + { + return Mage::helper('xmlconnect')->__('PayPal Mobile Express Checkout'); + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Mep.php b/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Mep.php index 249a23d465..f527565154 100644 --- a/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Mep.php +++ b/app/code/core/Mage/XmlConnect/Model/Payment/Method/Paypal/Mep.php @@ -81,8 +81,7 @@ public function isAvailable($quote = null) $storeId = $quote ? $quote->getStoreId() : Mage::app()->getStore()->getId(); } - return Mage::getModel('paypal/config') - ->setStoreId($storeId) + return (bool) Mage::getModel('paypal/config')->setStoreId($storeId) ->isMethodAvailable(Mage_Paypal_Model_Config::METHOD_WPP_EXPRESS); } diff --git a/app/code/core/Mage/XmlConnect/Model/Paypal/Mecl/Checkout.php b/app/code/core/Mage/XmlConnect/Model/Paypal/Mecl/Checkout.php new file mode 100644 index 0000000000..02ce8c2ead --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Paypal/Mecl/Checkout.php @@ -0,0 +1,42 @@ + + */ +class Mage_XmlConnect_Model_Paypal_Mecl_Checkout extends Mage_Paypal_Model_Express_Checkout +{ + /** + * Payment method type + * + * @var string + */ + protected $_methodType = Mage_XmlConnect_Model_Payment_Method_Paypal_Config::METHOD_WPP_MECL; +} diff --git a/app/code/core/Mage/XmlConnect/Model/Paypal/Mep/Checkout.php b/app/code/core/Mage/XmlConnect/Model/Paypal/Mep/Checkout.php index 38d05eb318..111b28b99d 100644 --- a/app/code/core/Mage/XmlConnect/Model/Paypal/Mep/Checkout.php +++ b/app/code/core/Mage/XmlConnect/Model/Paypal/Mep/Checkout.php @@ -74,7 +74,6 @@ class Mage_XmlConnect_Model_Paypal_Mep_Checkout * * @throws Mage_Core_Exception * @param array $params - * @return void */ public function __construct($params = array()) { @@ -82,7 +81,9 @@ public function __construct($params = array()) if (isset($params['quote']) && $params['quote'] instanceof Mage_Sales_Model_Quote) { $this->_quote = $params['quote']; } else { - Mage::throwException(Mage::helper('xmlconnect')->__('Quote instance is required.')); + Mage::throwException( + Mage::helper('xmlconnect')->__('Quote instance is required.') + ); } } @@ -113,7 +114,8 @@ public function initCheckout() $this->_quote->assignCustomer($customer); } if (!Mage::getSingleton('customer/session')->isLoggedIn() - && Mage::getSingleton('checkout/session')->getQuote()->isAllowedGuestCheckout()) { + && Mage::getSingleton('checkout/session')->getQuote()->isAllowedGuestCheckout() + ) { $this->_prepareGuestQuote(); } return $this->_quote->getReservedOrderId(); @@ -173,9 +175,7 @@ public function saveShipping($data) $billing->unsAddressId()->unsAddressType(); $shipping = $this->_quote->getShippingAddress(); $shippingMethod = $shipping->getShippingMethod(); - $shipping->addData($billing->getData()) - ->setSameAsBilling(1) - ->setShippingMethod($shippingMethod) + $shipping->addData($billing->getData())->setSameAsBilling(1)->setShippingMethod($shippingMethod) ->setCollectShippingRates(true); } @@ -204,10 +204,8 @@ public function saveShippingMethod($shippingMethod) if (!$this->_quote->getIsVirtual() && $shippingAddress) { if ($shippingMethod != $shippingAddress->getShippingMethod()) { $this->_ignoreAddressValidation(); - $this->_quote->getShippingAddress() - ->setShippingMethod($shippingMethod); - $this->_quote->collectTotals() - ->save(); + $this->_quote->getShippingAddress()->setShippingMethod($shippingMethod); + $this->_quote->collectTotals()->save(); } } @@ -235,8 +233,7 @@ public function savePayment($data) $email = isset($data['payer']) ? $data['payer'] : null; $payment->setAdditionalInformation(self::PAYMENT_INFO_PAYER_EMAIL, $email); $payment->setAdditionalInformation( - self::PAYMENT_INFO_TRANSACTION_ID, - isset($data['transaction_id']) ? $data['transaction_id'] : null + self::PAYMENT_INFO_TRANSACTION_ID, isset($data['transaction_id']) ? $data['transaction_id'] : null ); $this->_quote->setCustomerEmail($email); @@ -258,15 +255,14 @@ public function saveOrder() $order = Mage::getModel('sales/service_quote', $this->_quote)->submit(); $this->_quote->save(); + $this->_getCheckoutSession()->clear(); + /** * Prepare session to success or cancellation page */ $quoteId = $this->_quote->getId(); - $this->_getCheckoutSession() - ->setLastQuoteId($quoteId) - ->setLastSuccessQuoteId($quoteId) - ->setLastOrderId($order->getId()) - ->setLastRealOrderId($order->getIncrementId()); + $this->_getCheckoutSession()->setLastQuoteId($quoteId)->setLastSuccessQuoteId($quoteId) + ->setLastOrderId($order->getId())->setLastRealOrderId($order->getIncrementId()); if ($order->getState() == Mage_Sales_Model_Order::STATE_PROCESSING && Mage::getSingleton('customer/session')->isLoggedIn() @@ -301,7 +297,7 @@ public function getLastOrderId() /** * Make sure addresses will be saved without validation errors * - * @return void + * @return null */ protected function _ignoreAddressValidation() { @@ -329,8 +325,7 @@ protected function _getCheckoutSession() protected function _prepareGuestQuote() { $quote = $this->_quote; - $quote->setCustomerId(null) - ->setCustomerIsGuest(true) + $quote->setCustomerId(null)->setCustomerIsGuest(true) ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID); return $this; } @@ -339,7 +334,7 @@ protected function _prepareGuestQuote() * Adopt specified request array from PayPal * * @param array $request - * @return void + * @return null */ protected function _applyCountryWorkarounds(&$request) { diff --git a/app/code/core/Mage/XmlConnect/Model/Preview/Abstract.php b/app/code/core/Mage/XmlConnect/Model/Preview/Abstract.php index 24365f9781..34794c2b8a 100755 --- a/app/code/core/Mage/XmlConnect/Model/Preview/Abstract.php +++ b/app/code/core/Mage/XmlConnect/Model/Preview/Abstract.php @@ -58,7 +58,7 @@ abstract class Mage_XmlConnect_Model_Preview_Abstract extends Varien_Object * Internal constructor not depended on params. * It's used for application object initialization * - * @return void + * @return null */ final function _construct() { @@ -67,9 +67,9 @@ final function _construct() } /** - * Getter for current loaded application model + * Setter for current loaded application model * - * @return Mage_XmlConnect_Model_Application + * @return Mage_XmlConnect_Model_Preview_Abstract */ protected function setApplicationModel() { @@ -79,6 +79,12 @@ protected function setApplicationModel() return $this; } + + /** + * Getter for current loaded application model + * + * @return Mage_XmlConnect_Model_Application + */ public function getApplicationModel() { return $this->setApplicationModel()->_appModel; @@ -145,7 +151,7 @@ public function setConf($conf) if (!is_array($conf)) { $conf = array(); } - $tabs = isset($conf['tabBar']) && isset($conf['tabBar']['tabs']) ? $conf['tabBar']['tabs'] : false; + $tabs = isset($conf['tabBar']['tabs']) ? $conf['tabBar']['tabs'] : false; if ($tabs !== false) { foreach ($tabs->getEnabledTabs() as $tab) { $tab = (array) $tab; @@ -215,45 +221,44 @@ public function getLogoUrl() public function getCategoryItemTintColor() { if (!strlen($this->_categoryItemTintColor)) { - $percent = .4; - $mask = 255; + $percent = 0.4; + $mask = 255; - $hex = str_replace('#','',$this->getData('conf/categoryItem/tintColor')); - $hex2 = ''; - $_rgb = array(); + $hex = str_replace('#', '', $this->getData('conf/categoryItem/tintColor')); + $hex2 = ''; + $_rgb = array(); - $d = '[a-fA-F0-9]'; + $hexChars = '[a-fA-F0-9]'; - if (preg_match("/^($d$d)($d$d)($d$d)\$/", $hex, $rgb)) { + if (preg_match("/^($hexChars{2})($hexChars{2})($hexChars{2})$/", $hex, $rgb)) { $_rgb = array(hexdec($rgb[1]), hexdec($rgb[2]), hexdec($rgb[3])); - } - if (preg_match("/^($d)($d)($d)$/", $hex, $rgb)) { + } elseif (preg_match("/^($hexChars)($hexChars)($hexChars)$/", $hex, $rgb)) { $_rgb = array(hexdec($rgb[1] . $rgb[1]), hexdec($rgb[2] . $rgb[2]), hexdec($rgb[3] . $rgb[3])); } - for ($i=0; $i<3; $i++) { - $_rgb[$i] = round($_rgb[$i] * $percent) + round($mask * (1-$percent)); + for ($i = 0; $i < 3; $i++) { + $_rgb[$i] = round($_rgb[$i] * $percent) + round($mask * (1 - $percent)); if ($_rgb[$i] > 255) { $_rgb[$i] = 255; } - } - - for($i=0; $i < 3; $i++) { $hex_digit = dechex($_rgb[$i]); - if(strlen($hex_digit) == 1) { + if (strlen($hex_digit) == 1) { $hex_digit = "0" . $hex_digit; } $hex2 .= $hex_digit; } - if($hex && $hex2){ + + if ($hex && $hex2) { // for IE $this->_categoryItemTintColor .= "filter: progid:DXImageTransform.Microsoft.gradient"; - $this->_categoryItemTintColor .= "(startColorstr='#".$hex2."', endColorstr='#".$hex."');"; + $this->_categoryItemTintColor .= "(startColorstr='#" . $hex2 . "', endColorstr='#" . $hex . "');"; // for webkit browsers $this->_categoryItemTintColor .= "background:-webkit-gradient"; - $this->_categoryItemTintColor .= "(linear, left top, left bottom, from(#".$hex2."), to(#".$hex."));"; + $this->_categoryItemTintColor .= "(linear, left top, left bottom,"; + $this->_categoryItemTintColor .= " from(#" . $hex2 . "), to(#" . $hex . "));"; // for firefox - $this->_categoryItemTintColor .= "background:-moz-linear-gradient(top, #".$hex2.", #".$hex.");"; + $this->_categoryItemTintColor .= "background:-moz-linear-gradient"; + $this->_categoryItemTintColor .= "(top, #" . $hex2 . ", #" . $hex . ");"; } } return $this->_categoryItemTintColor; diff --git a/app/code/core/Mage/XmlConnect/Model/Preview/Iphone.php b/app/code/core/Mage/XmlConnect/Model/Preview/Iphone.php index 639bfe6cd2..9a946e12e5 100755 --- a/app/code/core/Mage/XmlConnect/Model/Preview/Iphone.php +++ b/app/code/core/Mage/XmlConnect/Model/Preview/Iphone.php @@ -57,13 +57,12 @@ public function getBannerImage() */ public function getBackgroundImage() { - $backgroundImage = ''; $configPath = 'conf/body/backgroundImage'; $imageUrlOrig = $this->getData($configPath); if ($imageUrlOrig) { $backgroundImage = $imageUrlOrig; } else { - $backgroundImage = $this->getPreviewImagesUrl('banner.png'); + $backgroundImage = $this->getPreviewImagesUrl('background.png'); } return $backgroundImage; } diff --git a/app/code/core/Mage/XmlConnect/Model/Queue.php b/app/code/core/Mage/XmlConnect/Model/Queue.php index 329199428e..343b1bec06 100755 --- a/app/code/core/Mage/XmlConnect/Model/Queue.php +++ b/app/code/core/Mage/XmlConnect/Model/Queue.php @@ -25,10 +25,10 @@ */ /** - * XmlConnect Model Queue + * XmlConnect Queue model * * @category Mage - * @package Mage_XmlConnect + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_Model_Queue extends Mage_Core_Model_Template @@ -84,7 +84,7 @@ class Mage_XmlConnect_Model_Queue extends Mage_Core_Model_Template /** * Initialize queue message * - * @return void + * @return null */ protected function _construct() { @@ -94,17 +94,16 @@ protected function _construct() /** * Load object data * - * @param integer $id - * @return Mage_Core_Model_Abstract + * @param int $id + * @param string $field + * @return Mage_XmlConnect_Model_Queue */ - public function load($id, $field=null) + public function load($id, $field = null) { parent::load($id, $field); if ($this->getTemplateId()) { - $this->setName( - Mage::getModel('xmlconnect/template')->load($this->getTemplateId())->getName() - ); + $this->setName(Mage::getModel('xmlconnect/template')->load($this->getTemplateId())->getName()); } return $this; } @@ -187,16 +186,16 @@ public function getProcessedTemplate(array $variables = array()) switch ($this->getData('type')) { case Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL: $html = sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Push title')) - . $this->getPushTitle(); - $html .= sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Message title')) - . $this->getMessageTitle(); - $html .= sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Message content')) - . $processor->filter($this->getContent()); + . $this->getPushTitle() + . sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Message title')) + . $this->getMessageTitle() + . sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Message content')) + . $processor->filter($this->getContent()); break; case Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_PUSH: default: $html = sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Push title')) - . $this->getPushTitle(); + . $this->getPushTitle(); break; } return $html; @@ -241,11 +240,7 @@ public function getAirmailBroadcastParams() ); $payload = array( - 'push' => array( - $notificationType => array( - 'alert' => $this->getPushTitle(), - ) - ), + 'push' => array($notificationType => array('alert' => $this->getPushTitle())), 'title' => $this->getMessageTitle(), 'message' => $this->getContent(), ); diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/Application.php b/app/code/core/Mage/XmlConnect/Model/Resource/Application.php index f5cc05038a..7e78710983 100755 --- a/app/code/core/Mage/XmlConnect/Model/Resource/Application.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/Application.php @@ -36,7 +36,7 @@ class Mage_XmlConnect_Model_Resource_Application extends Mage_Core_Model_Resourc /** * Constructor, setting table and index field * - * @return void + * @return null */ protected function _construct() { @@ -55,9 +55,7 @@ public function updateApplicationStatus($applicationId, $status) $this->_getWriteAdapter()->update( $this->getMainTable(), array('status' => $status), - $this->_getWriteAdapter()->quoteInto( - $this->getIdFieldName() . '=?', $applicationId - ) + $this->_getWriteAdapter()->quoteInto($this->getIdFieldName() . '=?', $applicationId) ); return $this; } @@ -92,9 +90,7 @@ protected function _afterSave(Mage_Core_Model_Abstract $object) $this->_getWriteAdapter()->update( $this->getMainTable(), array('code' => $appCode . $object->getId()), - $this->_getWriteAdapter()->quoteInto( - $this->getIdFieldName() . '=?', $object->getId() - ) + $this->_getWriteAdapter()->quoteInto($this->getIdFieldName() . '=?', $object->getId()) ); } return parent::_afterSave($object); @@ -107,10 +103,8 @@ protected function _afterSave(Mage_Core_Model_Abstract $object) */ public function getExistingStoreDeviceType() { - $select = $this->_getWriteAdapter()->select() - ->from($this->getMainTable(), array('store_id', 'type')) - ->group(array('store_id', 'type')) - ->order(array('store_id', 'type')); + $select = $this->_getWriteAdapter()->select()->from($this->getMainTable(), array('store_id', 'type')) + ->group(array('store_id', 'type'))->order(array('store_id', 'type')); return $this->_getReadAdapter()->fetchAll($select, array('store_id', 'type')); } @@ -121,10 +115,7 @@ public function getExistingStoreDeviceType() */ public function updateAllAppsUpdatedAtParameter() { - $this->_getWriteAdapter()->update( - $this->getMainTable(), - array('updated_at' => date('Y-m-d H:i:s')) - ); + $this->_getWriteAdapter()->update($this->getMainTable(), array('updated_at' => date('Y-m-d H:i:s'))); return $this; } } diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/Application/Collection.php b/app/code/core/Mage/XmlConnect/Model/Resource/Application/Collection.php index 4f4da73be8..8bcde33208 100755 --- a/app/code/core/Mage/XmlConnect/Model/Resource/Application/Collection.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/Application/Collection.php @@ -36,7 +36,7 @@ class Mage_XmlConnect_Model_Resource_Application_Collection extends Mage_Core_Mo /** * Constructor, setting table * - * @return void + * @return null */ protected function _construct() { diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/ConfigData.php b/app/code/core/Mage/XmlConnect/Model/Resource/ConfigData.php index a4878549c5..37801f09b4 100644 --- a/app/code/core/Mage/XmlConnect/Model/Resource/ConfigData.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/ConfigData.php @@ -36,7 +36,7 @@ class Mage_XmlConnect_Model_Resource_ConfigData extends Mage_Core_Model_Mysql4_A /** * Initialize configuration data * - * @return void + * @return null */ protected function _construct() { @@ -61,11 +61,7 @@ public function saveConfig($applicationId, $category, $path, $value) 'value' => $value ); - $this->_getWriteAdapter()->insertOnDuplicate( - $this->getMainTable(), - $newData, - array('value') - ); + $this->_getWriteAdapter()->insertOnDuplicate($this->getMainTable(), $newData, array('value')); return $this; } @@ -88,8 +84,7 @@ public function deleteConfig($applicationId, $category = false, $path = false, $ $deleteWhere[] = $writeAdapter->quoteInto('category=?', $category); } if ($path) { - $deleteWhere[] = $pathLike - ? $writeAdapter->quoteInto('path like ?', $path . '/%') + $deleteWhere[] = $pathLike ? $writeAdapter->quoteInto('path like ?', $path . '/%') : $writeAdapter->quoteInto('path=?', $path); } $writeAdapter->delete($this->getMainTable(), $deleteWhere); diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/ConfigData/Collection.php b/app/code/core/Mage/XmlConnect/Model/Resource/ConfigData/Collection.php index 2001503570..13705353a9 100644 --- a/app/code/core/Mage/XmlConnect/Model/Resource/ConfigData/Collection.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/ConfigData/Collection.php @@ -31,8 +31,7 @@ * @package Mage_Xmlconnect * @author Magento Core Team */ -class Mage_XmlConnect_Model_Resource_ConfigData_Collection - extends Mage_Core_Model_Mysql4_Collection_Abstract +class Mage_XmlConnect_Model_Resource_ConfigData_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract { /** * Is application filter applied @@ -58,8 +57,7 @@ protected function _construct() public function addApplicationIdFilter($applicationId) { $this->_applicationFilter = true; - $this->getSelect() - ->where('application_id=?', $applicationId); + $this->getSelect()->where('application_id=?', $applicationId); return $this; } @@ -73,11 +71,9 @@ public function addApplicationIdFilter($applicationId) public function addPathFilter($path, $like = true) { if ($like) { - $this->getSelect() - ->where('path like ?', $path . '/%'); + $this->getSelect()->where('path like ?', $path . '/%'); } else { - $this->getSelect() - ->where('path=?', $path); + $this->getSelect()->where('path=?', $path); } return $this; } diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/History.php b/app/code/core/Mage/XmlConnect/Model/Resource/History.php index 355bed4aed..b538fe7ff8 100755 --- a/app/code/core/Mage/XmlConnect/Model/Resource/History.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/History.php @@ -36,7 +36,7 @@ class Mage_XmlConnect_Model_Resource_History extends Mage_Core_Model_Resource_Db /** * Constructor, setting table and index field * - * @return void + * @return null */ protected function _construct() { @@ -77,10 +77,8 @@ public function getLastParams($id) { $paramArray = array(); $idFieldName = Mage::getModel('xmlconnect/application')->getIdFieldName(); - $select = $this->_getReadAdapter()->select() - ->from($this->getMainTable(), 'params') - ->where($idFieldName . '=?', $id) - ->order(array('created_at ' . Zend_Db_Select::SQL_DESC)); + $select = $this->_getReadAdapter()->select()->from($this->getMainTable(), 'params') + ->where($idFieldName . '=?', $id)->order(array('created_at ' . Zend_Db_Select::SQL_DESC)); $params = $this->_getReadAdapter()->fetchOne($select); diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/History/Collection.php b/app/code/core/Mage/XmlConnect/Model/Resource/History/Collection.php index a33349e517..889f7b9159 100755 --- a/app/code/core/Mage/XmlConnect/Model/Resource/History/Collection.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/History/Collection.php @@ -31,8 +31,7 @@ * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_XmlConnect_Model_Resource_History_Collection - extends Mage_Core_Model_Resource_Db_Collection_Abstract +class Mage_XmlConnect_Model_Resource_History_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract { /** * Internal constructor diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/Queue.php b/app/code/core/Mage/XmlConnect/Model/Resource/Queue.php index c04108b179..21d483d3a9 100755 --- a/app/code/core/Mage/XmlConnect/Model/Resource/Queue.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/Queue.php @@ -36,7 +36,7 @@ class Mage_XmlConnect_Model_Resource_Queue extends Mage_Core_Model_Resource_Db_A /** * Constructor, setting table and index field * - * @return void + * @return null */ protected function _construct() { diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/Queue/Collection.php b/app/code/core/Mage/XmlConnect/Model/Resource/Queue/Collection.php index 7d97e8101d..c9fb3bc50c 100755 --- a/app/code/core/Mage/XmlConnect/Model/Resource/Queue/Collection.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/Queue/Collection.php @@ -31,13 +31,12 @@ * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_XmlConnect_Model_Resource_Queue_Collection - extends Mage_Core_Model_Resource_Db_Collection_Abstract +class Mage_XmlConnect_Model_Resource_Queue_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract { /** * Internal constructor * - * @return void + * @return null */ protected function _construct() { @@ -75,11 +74,10 @@ protected function _joinNames() */ protected function _joinTemplateName() { - $this->getSelect() - ->joinLeft( - array('t' => $this->getTable('xmlconnect/template')), - 't.template_id = main_table.template_id', - array('template_name' => 't.name') + $this->getSelect()->joinLeft( + array('t' => $this->getTable('xmlconnect/template')), + 't.template_id = main_table.template_id', + array('template_name' => 't.name') ); return $this; } @@ -91,11 +89,10 @@ protected function _joinTemplateName() */ protected function _joinApplicationName() { - $this->getSelect() - ->joinLeft( - array('app' => $this->getTable('xmlconnect/application')), - 'app.application_id = t.application_id', - array('application_name' => 'app.name') + $this->getSelect()->joinLeft( + array('app' => $this->getTable('xmlconnect/application')), + 'app.application_id = t.application_id', + array('application_name' => 'app.name') ); return $this; } @@ -107,8 +104,7 @@ protected function _joinApplicationName() */ public function addOnlyForSendingFilter() { - $this->getSelect() - ->where('main_table.status in (?)', array(Mage_XmlConnect_Model_Queue::STATUS_IN_QUEUE)) + $this->getSelect()->where('main_table.status in (?)', array(Mage_XmlConnect_Model_Queue::STATUS_IN_QUEUE)) ->where('main_table.exec_time < ?', Mage::getSingleton('core/date')->gmtDate()) ->order(new Zend_Db_Expr('main_table.exec_time ' . Zend_Db_Select::SQL_ASC) ); diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/Template.php b/app/code/core/Mage/XmlConnect/Model/Resource/Template.php index ae02a4cf6d..03dae7d771 100755 --- a/app/code/core/Mage/XmlConnect/Model/Resource/Template.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/Template.php @@ -36,7 +36,7 @@ class Mage_XmlConnect_Model_Resource_Template extends Mage_Core_Model_Resource_D /** * Constructor, setting table and index field * - * @return void + * @return null */ protected function _construct() { diff --git a/app/code/core/Mage/XmlConnect/Model/Resource/Template/Collection.php b/app/code/core/Mage/XmlConnect/Model/Resource/Template/Collection.php index 077fb210ec..f0f00699dd 100755 --- a/app/code/core/Mage/XmlConnect/Model/Resource/Template/Collection.php +++ b/app/code/core/Mage/XmlConnect/Model/Resource/Template/Collection.php @@ -31,13 +31,12 @@ * @package Mage_XmlConnect * @author Magento Core Team */ -class Mage_XmlConnect_Model_Resource_Template_Collection - extends Mage_Core_Model_Resource_Db_Collection_Abstract +class Mage_XmlConnect_Model_Resource_Template_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract { /** * Internal constructor * - * @return void + * @return null */ protected function _construct() { @@ -63,11 +62,10 @@ protected function _initSelect() */ protected function _joinApplicationName() { - $this->getSelect() - ->joinLeft( - array('app' => $this->getTable('xmlconnect/application')), - 'app.application_id = main_table.application_id', - array('app_name' => 'app.name', 'app_code' => 'app.code') + $this->getSelect()->joinLeft( + array('app' => $this->getTable('xmlconnect/application')), + 'app.application_id = main_table.application_id', + array('app_name' => 'app.name', 'app_code' => 'app.code') ); return $this; } diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Element.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Element.php index d253ed12bc..67aea94c7a 100644 --- a/app/code/core/Mage/XmlConnect/Model/Simplexml/Element.php +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Element.php @@ -25,10 +25,11 @@ */ /** - * * XmlConnect fixed Varien SimpleXML Element class * - * @author Magento Core Team + * @category Mage + * @package Mage_XmlConnect + * @author Magento Core Team */ class Mage_XmlConnect_Model_Simplexml_Element extends Varien_Simplexml_Element { @@ -41,14 +42,7 @@ class Mage_XmlConnect_Model_Simplexml_Element extends Varien_Simplexml_Element public function appendChild($source) { if (sizeof($source->children())) { - /** - * @link http://bugs.php.net/bug.php?id=41867 , fixed in 5.2.4 - */ - if (version_compare(phpversion(), '5.2.4', '<')===true) { - $name = $source->children()->getName(); - } else { - $name = $source->getName(); - } + $name = $source->getName(); $child = $this->addChild($name); } else { $child = $this->addChild($source->getName(), $this->xmlentities($source)); diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form.php new file mode 100644 index 0000000000..7af540c994 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form.php @@ -0,0 +1,388 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form extends Mage_XmlConnect_Model_Simplexml_Form_Abstract +{ + /** + * All form elements collection + * + * @var Mage_XmlConnect_Model_Simplexml_Form_Element_Collection + */ + protected $_allElements; + + /** + * form elements index + * + * @var array + */ + protected $_elementsIndex; + + /**#@+ + * Custom form components renderer + * + * @var object + */ + static protected $_defaultElementRenderer; + static protected $_defaultFieldsetRenderer; + static protected $_defaultValidatorRenderer; + static protected $_defaultValidatorRuleRenderer; + static protected $_defaultFieldsetElementRenderer; + /**#@-*/ + + /** + * Init simple xml form + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->setType('form'); + $this->_allElements = Mage::getModel('xmlconnect/simplexml_form_element_collection', $this); + } + + /** + * Set element renderer + * + * @static $_defaultElementRenderer + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + * @return null + */ + public static function setElementRenderer( + Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + ) { + self::$_defaultElementRenderer = $renderer; + } + + /** + * Set validator renderer + * + * @static $_defaultValidatorRenderer + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + * @return null + */ + public static function setValidatorRenderer( + Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + ) { + self::$_defaultValidatorRenderer = $renderer; + } + + /** + * Set validator rule renderer + * + * @static $_defaultValidatorRuleRenderer + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + * @return null + */ + public static function setValidatorRuleRenderer( + Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + ) { + self::$_defaultValidatorRuleRenderer = $renderer; + } + + /** + * Set fieldset renderer + * + * @static $_defaultFieldsetRenderer + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + * @return null + */ + public static function setFieldsetRenderer( + Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + ) { + self::$_defaultFieldsetRenderer = $renderer; + } + + /** + * Set fieldset element renderer + * + * @static $_defaultFieldsetElementRenderer + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + * @return null + */ + public static function setFieldsetElementRenderer( + Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + ) { + self::$_defaultFieldsetElementRenderer = $renderer; + } + + /** + * Get element renderer + * + * @static $_defaultElementRenderer + * @return object + */ + public static function getElementRenderer() + { + return self::$_defaultElementRenderer; + } + + /** + * Get validator renderer + * + * @static $_defaultValidatorRenderer + * @return object + */ + public static function getValidatorRenderer() + { + return self::$_defaultValidatorRenderer; + } + + /** + * Get validator rule renderer + * + * @static $_defaultValidatorRuleRenderer + * @return object + */ + public static function getValidatorRuleRenderer() + { + return self::$_defaultValidatorRuleRenderer; + } + + /** + * Get fieldset renderer + * + * @static $_defaultFieldsetRenderer + * @return object + */ + public static function getFieldsetRenderer() + { + return self::$_defaultFieldsetRenderer; + } + + /** + * Get fieldset element renderer + * + * @static $_defaultFieldsetElementRenderer + * @return object + */ + public static function getFieldsetElementRenderer() + { + return self::$_defaultFieldsetElementRenderer; + } + + /** + * Add form element + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element + * @param bool $after + * @return Mage_XmlConnect_Model_Simplexml_Form + */ + public function addElement(Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element, $after = false) + { + $this->checkElementId($element->getId()); + parent::addElement($element, $after); + $this->addElementToCollection($element); + return $this; + } + + /** + * Check existing element + * + * @param string $elementId + * @return bool + */ + protected function _elementIdExists($elementId) + { + return isset($this->_elementsIndex[$elementId]); + } + + /** + * Add form element to collection + * + * @param $element + * @return Mage_XmlConnect_Model_Simplexml_Form + */ + public function addElementToCollection($element) + { + $this->_elementsIndex[$element->getId()] = $element; + $this->_allElements->add($element); + return $this; + } + + /** + * Insure existing element + * + * @throws Exception + * @param $elementId + * @return bool + */ + public function checkElementId($elementId) + { + if ($this->_elementIdExists($elementId)) { + throw new Exception(Mage::helper('xmlconnect')->__('Element with id %s already exists', $elementId)); + } + return true; + } + + /** + * Get form object + * + * @return Mage_XmlConnect_Model_Simplexml_Form + */ + public function getForm() + { + return $this; + } + + /** + * Get element object + * + * @param $elementId + * @return null|Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + public function getElement($elementId) + { + if ($this->_elementIdExists($elementId)) { + return $this->_elementsIndex[$elementId]; + } + return null; + } + + /** + * Set values to the form elements + * + * @param array $values + * @return Mage_XmlConnect_Model_Simplexml_Form + */ + public function setValues($values) + { + foreach ($this->_allElements as $element) { + if (isset($values[$element->getId()])) { + $element->setValue($values[$element->getId()]); + } else { + $element->setValue(null); + } + } + return $this; + } + + /** + * Add values to the form elements + * + * @param array $values + * @return Mage_XmlConnect_Model_Simplexml_Form + */ + public function addValues($values) + { + if (!is_array($values)) { + return $this; + } + + foreach ($values as $elementId => $value) { + $element = $this->getElement($elementId); + if ($element) { + $element->setValue($value); + } + } + return $this; + } + + /** + * Remove field from collection + * + * @param string $elementId + * @return Mage_XmlConnect_Model_Simplexml_Form + */ + public function removeField($elementId) + { + if ($this->_elementIdExists($elementId)) { + unset($this->_elementsIndex[$elementId]); + } + return $this; + } + + /** + * Set field id prefix + * + * @param string $prefix + * @return Mage_XmlConnect_Model_Simplexml_Form + */ + public function setFieldContainerIdPrefix($prefix) + { + $this->setData('field_container_id_prefix', $prefix); + return $this; + } + + /** + * Get field container id prefix + * + * @return mixed + */ + public function getFieldContainerIdPrefix() + { + return $this->getData('field_container_id_prefix'); + } + + /** + * Retrieve form xml object or an array of Simplexml elements + * + * @return array|Mage_XmlConnect_Model_Simplexml_Element + */ + public function toXmlObject() + { + $xmlObj = $this->getXmlObject(); + if ($useContainer = $this->getUseContainer()) { + $this->_addRequiredAttributes($xmlObj); + foreach ($this->getAttributes() as $key => $val) { + $xmlObj->addAttribute($key, $xmlObj->xmlAttribute($val)); + } + } + + foreach ($this->getElements() as $element) { + $xmlObj->appendChild($element->toXmlObject()); + } + + if (!$useContainer) { + $result = array(); + foreach ($xmlObj->children() as $child) { + $result[] = $child; + } + } + return isset($result) ? $result : $xmlObj; + } + + /** + * Get from xml as string + * + * @throws Mage_Core_Exception + * @return string + */ + public function getXml() + { + if ($this->getUseContainer()) { + return $this->toXmlObject()->asNiceXml(); + } + Mage::throwException(Mage::helper('xmlconnect')->__('Container is not defined.')); + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Abstract.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Abstract.php new file mode 100644 index 0000000000..7608e9068d --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Abstract.php @@ -0,0 +1,524 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Abstract extends Varien_Object +{ + /** + * Element unique id + * + * @var string + */ + protected $_id; + + /** + * Form level elements collection + * + * @var Mage_XmlConnect_Model_Simplexml_Form_Element_Collection + */ + protected $_elements; + + /** + * Element type classes + * + * @var array + */ + protected $_types = array(); + + /** + * From Simplexml object + * + * @var Mage_XmlConnect_Model_Simplexml_Element + */ + protected $_xml; + + /** + * Main element node + * + * @var string + */ + protected $_mainNode = 'form'; + + /** + * Is name attribute required + * + * @var bool + */ + protected $_nameRequired = true; + + /** + * Custom attributes array + * + * @var array + */ + protected $_customAttributes = array(); + + /** + * Init form model + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->_prepareXmlObject(); + } + + /** + * Init form parent Simplexml object + * + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + protected function _prepareXmlObject() + { + $this->setXmlObject( + Mage::getModel('xmlconnect/simplexml_element', '<' . $this->_mainNode . '>_mainNode . '>') + ); + return $this; + } + + /** + * Get base simple xml object + * + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function getXmlObject() + { + return $this->_xml; + } + + /** + * Set simple xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xml + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function setXmlObject(Mage_XmlConnect_Model_Simplexml_Element $xml) + { + $this->_xml = $xml; + return $this; + } + + /** + * Get element id + * + * @return string + */ + public function getId() + { + return $this->_id; + } + + /** + * Set element id + * + * @param $id + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function setId($id) + { + $this->_id = $id; + $this->setData('xml_id', $id); + return $this; + } + + /** + * Get element id + * + * @return string + */ + public function getXmlId() + { + return $this->getXmlIdPrefix() . $this->getData('xml_id') . $this->getXmlIdSuffix(); + } + + /** + * Add form element type + * + * @param string $type + * @param string $className + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function addType($type, $className) + { + $this->_types[$type] = $className; + return $this; + } + + /** + * Get elements collection + * + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Collection + */ + public function getElements() + { + if (empty($this->_elements)) { + $this->_elements = Mage::getModel('xmlconnect/simplexml_form_element_collection'); + } + return $this->_elements; + } + + /** + * Add form element + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element + * @param bool|string $after + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function addElement(Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element, $after = false) + { + $element->setForm($this); + $this->getElements()->add($element, $after); + return $this; + } + + /** + * Add child element + * + * if $after parameter is false - add element to the end of a collection + * if $after parameter is ^ - prepend element to the beginning of a collection + * if $after parameter is string - add element after the element with some id + * + * @param string $elementId + * @param string $type + * @param array $config + * @param mixed $after + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function addField($elementId, $type, $config, $after = false) + { + if (isset($this->_types[$type])) { + $className = $this->_types[$type]; + } else { + $className = 'Mage_XmlConnect_Model_Simplexml_Form_Element_' . uc_words($type); + } + + $element = Mage::getModel($className, $config); + $element->setId($elementId); + $this->addElement($element, $after); + return $element; + } + + /** + * Remove element from collection + * + * @param string $elementId + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function removeField($elementId) + { + $this->getElements()->remove($elementId); + return $this; + } + + /** + * Add fieldset element + * + * @param string $elementId + * @param array $config + * @param bool|string $after + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset + */ + public function addFieldset($elementId, $config = array(), $after = false) + { + $element = Mage::getModel('xmlconnect/simplexml_form_element_fieldset', $config); + $element->setId($elementId); + $this->addElement($element, $after); + return $element; + } + + /** + * Add validator element + * + * @param array $config + * @param bool|string $after + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Validator + */ + public function addValidator($config = array(), $after = false) + { + $element = Mage::getModel('xmlconnect/simplexml_form_element_validator', $config); + $element->setId($this->getXmlId()); + $this->addElement($element, $after); + return $element; + } + + /** + * Get array of existing elements + * + * @param array $arrAttributes + * @return array + */ + public function __toArray(array $arrAttributes = array()) + { + $res = array(); + $res['config'] = $this->getData(); + $res['formElements']= array(); + foreach ($this->getElements() as $element) { + $res['formElements'][] = $element->toArray(); + } + return $res; + } + + /** + * Return allowed xml form attributes + * + * @return array + */ + public function getXmlAttributes() + { + return array('enctype'); + } + + /** + * Required form attribute array + * + * @return array + */ + public function getRequiredXmlAttributes() + { + return array('action' => null, 'method' => 'post'); + } + + /** + * Get after element xml + * + * @return array|Mage_XmlConnect_Model_Simplexml_Element + */ + public function getAfterElementXml() + { + return $this->getData('after_element_xml'); + } + + /** + * Get xml object attributes + * + * @param array $attributes + * @return array + */ + public function getXmlObjAttributes($attributes = array()) + { + $data = array(); + if (empty($attributes)) { + $attributes = array_keys($this->_data); + } + + foreach ($this->_data as $key => $value) { + if (in_array($key, $attributes)) { + $data[$key] = $value; + } + } + ksort($data); + return $data; + } + + /** + * Get object attributes array + * + * @return array + */ + public function getAttributes() + { + $attributes = array_merge($this->getXmlAttributes(), $this->getCustomAttributes()); + return $this->getXmlObjAttributes($attributes); + } + + /** + * Add after element xml to object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function addAfterXmlElementToObj(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + if ($this->_checkXmlInstance($this->getAfterElementXml())) { + $xmlObj->appendChild($this->getAfterElementXml()); + } elseif (is_array($this->getAfterElementXml())) { + foreach ($this->getAfterElementXml() as $afterElement) { + if (!$this->_checkXmlInstance($afterElement)) { + continue; + } + $xmlObj->appendChild($afterElement); + } + } + return $this; + } + + /** + * Add required attributes to element + * + * @throws Mage_Core_Exception + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + protected function _addRequiredAttributes(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + $this->_addId($xmlObj); + $this->_addName($xmlObj); + + foreach ($this->getRequiredXmlAttributes() as $attribute => $defValue) { + $data = $this->getData($this->_underscore($attribute)); + if ($data) { + $xmlObj->addAttribute($attribute, $xmlObj->xmlAttribute($data)); + } elseif(null !== $defValue){ + $xmlObj->addAttribute($attribute, $xmlObj->xmlAttribute($defValue)); + } else { + Mage::throwException(Mage::helper('xmlconnect')->__('%s attribute is required.', $attribute)); + } + } + return $this; + } + + /** + * Add validator to element xml object + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + protected function _addValidator(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + return $this; + } + + /** + * Add form id to element + * + * @throws Mage_Core_Exception + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + protected function _addId(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + if ($this->getXmlId()) { + $xmlObj->addAttribute('id', $xmlObj->xmlAttribute($this->getXmlId())); + } else { + Mage::throwException( + Mage::helper('xmlconnect')->__('"id" attribute is required for a "%s" field.', $this->getType()) + ); + } + return $this; + } + + /** + * Add form name to element + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + protected function _addName(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + if ($this->getName()) { + $name = $this->getName(); + } elseif($this->getNameRequired()) { + $name = $this->getXmlId(); + } + + if (isset($name)) { + $xmlObj->addAttribute('name', $xmlObj->xmlAttribute($name)); + } + + return $this; + } + + /** + * Is object instance of Simplexml object + * + * @param $object + * @return bool + */ + protected function _checkXmlInstance($object) + { + return $object instanceof Mage_XmlConnect_Model_Simplexml_Element; + } + + /** + * Get is name required attribute + * + * @return boolean + */ + public function getNameRequired() + { + return $this->_nameRequired; + } + + /** + * Set is name required attribute + * + * @param boolean $nameRequired + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function setNameRequired($nameRequired) + { + $this->_nameRequired = $nameRequired; + return $this; + } + + /** + * Get custom attributes + * + * @return array + */ + public function getCustomAttributes() + { + return $this->_customAttributes; + } + + /** + * Set custom attributes + * + * @param array $customAttributes + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function setCustomAttributes(array $customAttributes) + { + $this->_customAttributes = $customAttributes; + return $this; + } + + /** + * Check value and return as array - attribute => value + * + * @param string $attribute + * @param mixed $value + * @return array + */ + public function checkAttribute($attribute, $value = null) + { + if (null === $value) { + $value = $this->getData($attribute); + } + + if (null !== $value) { + return array($attribute => $value); + } + return array(); + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Abstract.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Abstract.php new file mode 100644 index 0000000000..2aed90b334 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Abstract.php @@ -0,0 +1,325 @@ + + */ +abstract class Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + extends Mage_XmlConnect_Model_Simplexml_Form_Abstract +{ + /** + * Element type + * + * @var string + */ + protected $_type; + + /** + * From element object + * + * @var Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + protected $_form; + + /** + * Main element node + * + * @var string + */ + protected $_mainNode = 'field'; + + /** + * Element renderer object + * + * @var object + */ + protected $_renderer; + + /** + * Init element object abstract + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->_renderer = Mage_XmlConnect_Model_Simplexml_Form::getElementRenderer(); + } + + /** + * Add form element + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element + * @param bool $after + * @return Mage_XmlConnect_Model_Simplexml_Form + */ + public function addElement(Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element, $after = false) + { + if ($this->getForm()) { + $this->getForm()->checkElementId($element->getId()); + $this->getForm()->addElementToCollection($element); + } + + parent::addElement($element, $after); + return $this; + } + + /** + * Get element type + * + * @return string + */ + public function getType() + { + return $this->_type; + } + + /** + * Get form object + * + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function getForm() + { + return $this->_form; + } + + /** + * Get element id + * + * @return string + */ + public function getXmlId() + { + return $this->getForm()->getXmlIdPrefix() . $this->getData('xml_id') . $this->getForm()->getXmlIdSuffix(); + } + + /** + * Get element name + * + * @return string + */ + public function getName() + { + $name = $this->getData('name'); + if ($suffix = $this->getForm()->getFieldNameSuffix()) { + $name = $this->getForm()->addSuffixToName($name, $suffix); + } + return $name; + } + + /** + * Set element type + * + * @param $type + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + public function setType($type) + { + $this->_type = $type; + $this->setData('type', $type); + return $this; + } + + /** + * Set form object + * + * @param $form + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + public function setForm($form) + { + $this->_form = $form; + return $this; + } + + /** + * Remove field from a form + * + * @param $elementId + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function removeField($elementId) + { + $this->getForm()->removeField($elementId); + return parent::removeField($elementId); + } + + /** + * Element attributes array + * + * @return array + */ + public function getXmlAttributes() + { + return array('title', 'required', 'disabled', 'visible', 'relation'); + } + + /** + * Required element attribute array + * + * @return array + */ + public function getRequiredXmlAttributes() + { + return array('label' => null, 'type' => null); + } + + /** + * Retrieve element xml object + * + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function getElementXml() + { + $xmlObj = $this->getXmlObject(); + $this->_addRequiredAttributes($xmlObj); + foreach ($this->getAttributes() as $key => $val) { + $xmlObj->addAttribute($key, $xmlObj->xmlAttribute($val)); + } + $this->_addValue($xmlObj); + + foreach ($this->getElements() as $element) { + if ($element->getType() == 'validator') { + $xmlObj->appendChild($element->toXmlObject()); + } + } + + $this->addAfterXmlElementToObj($xmlObj); + + return $xmlObj; + } + + /** + * Get escaped value + * + * @param string $index + * @return string|null + */ + public function getEscapedValue($index = null) + { + $value = $this->getValue($index); + + if ($filter = $this->getValueFilter()) { + $value = $filter->filter($value); + } + + return $value; + } + + /** + * Set element renderer + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + public function setRenderer(Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface $renderer) + { + $this->_renderer = $renderer; + return $this; + } + + /** + * Get element renderer + * + * @return object + */ + public function getRenderer() + { + return $this->_renderer; + } + + /** + * Add value to element + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + protected function _addValue(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + if ($this->getEscapedValue()) { + $xmlObj->addAttribute('value', $xmlObj->xmlAttribute($this->getEscapedValue())); + } + return $this; + } + + /** + * Retrieve default form xml object + * + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function getDefaultXml() + { + $xml = $this->getData('default_xml'); + if (null === $xml) { + $xml = $this->getElementXml(); + } + return $xml; + } + + /** + * Get element xml as string + * + * @return string + */ + public function getXml() + { + return $this->toXmlObject->asNiceXml(); + } + + /** + * Retrieve form xml object + * + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function toXmlObject() + { + if ($this->_renderer) { + return $this->_renderer->render($this); + } else { + return $this->getDefaultXml(); + } + } + + /** + * Get xml container id + * + * @return string + */ + public function getXmlContainerId() + { + if ($this->hasData('container_id')) { + return $this->getData('container_id'); + } elseif ($idPrefix = $this->getForm()->getFieldContainerIdPrefix()) { + return $idPrefix . $this->getId(); + } + return ''; + } +} diff --git a/app/code/community/Find/Feed/Block/Adminhtml/List/Codes.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Checkbox.php similarity index 55% rename from app/code/community/Find/Feed/Block/Adminhtml/List/Codes.php rename to app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Checkbox.php index b75aa6ced5..62bf94a76b 100644 --- a/app/code/community/Find/Feed/Block/Adminhtml/List/Codes.php +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Checkbox.php @@ -18,36 +18,42 @@ * 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_XmlConnect * @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 + * Xmlconnect form checkbox element * - * @category Find - * @package Find_Feed + * @category Mage + * @package Mage_XmlConnect * @author Magento Core Team */ -class Find_Feed_Block_Adminhtml_List_Codes extends Mage_Adminhtml_Block_Widget_Grid_Container +class Mage_XmlConnect_Model_Simplexml_Form_Element_Checkbox + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract { /** - * Initialize grid container settings + * Init checkbox element * + * @param array $attributes */ - public function __construct() + public function __construct($attributes = array()) { - $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(); + parent::__construct($attributes); + $this->setType('checkbox'); + } - $url = $this->getUrl('*/codes_grid/editForm'); - $this->_updateButton('add', 'onclick', 'openNewImportWindow(\''.$url.'\');'); + /** + * Add value to element + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + protected function _addValue(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + $xmlObj->addAttribute('value', (int)$this->getValue()); + return $this; } } diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Collection.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Collection.php new file mode 100644 index 0000000000..0694dd4d9a --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Collection.php @@ -0,0 +1,202 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Collection implements ArrayAccess, IteratorAggregate +{ + /** + * Elements storage + * + * @var array + */ + private $_elements; + + /** + * Elements container + * + * @var Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + private $_container; + + /** + * Class constructor + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Abstract $container + */ + public function __construct($container) + { + $this->_elements = array(); + $this->_container = $container; + } + + /** + * Implementation of IteratorAggregate::getIterator() + * + * @return ArrayIterator + */ + public function getIterator() + { + return new ArrayIterator($this->_elements); + } + + /** + * Implementation of ArrayAccess:offsetSet() + * + * @param mixed $key + * @param mixed $value + */ + public function offsetSet($key, $value) + { + $this->_elements[$key] = $value; + } + + /** + * Implementation of ArrayAccess:offsetGet() + * + * @param mixed $key + */ + public function offsetGet($key) + { + return $this->_elements[$key]; + } + + /** + * Implementation of ArrayAccess:offsetUnset() + * + * @param mixed $key + */ + public function offsetUnset($key) + { + unset($this->_elements[$key]); + } + + /** + * Implementation of ArrayAccess:offsetExists() + * + * @param mixed $key + * @return bool + */ + public function offsetExists($key) + { + return isset($this->_elements[$key]); + } + + /** + * Add element to collection + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Abstract $element + * @param bool|string $after + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function add(Mage_XmlConnect_Model_Simplexml_Form_Abstract $element, $after = false) + { + // Set the Form for the node + if ($this->_container->getForm() instanceof Mage_XmlConnect_Model_Simplexml_Form) { + $element->setContainer($this->_container); + $element->setForm($this->_container->getForm()); + } + + if ($after === false) { + $this->_elements[] = $element; + } elseif ($after === '^') { + array_unshift($this->_elements, $element); + } elseif (is_string($after)) { + $newOrderElements = array(); + foreach ($this->_elements as $index => $currElement) { + if ($currElement->getId() == $after) { + $newOrderElements[] = $currElement; + $newOrderElements[] = $element; + $this->_elements = array_merge($newOrderElements, array_slice($this->_elements, ++$index)); + return $element; + } + $newOrderElements[] = $currElement; + } + $this->_elements[] = $element; + } + + return $element; + } + + /** + * Sort elements by values using a user-defined comparison function + * + * @param mixed $callback + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Collection + */ + public function usort($callback) + { + usort($this->_elements, $callback); + return $this; + } + + /** + * Remove element from collection + * + * @param mixed $elementId + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Collection + */ + public function remove($elementId) + { + foreach ($this->_elements as $index => $element) { + if ($elementId == $element->getId()) { + unset($this->_elements[$index]); + } + } + return $this; + } + + /** + * Count elements in collection + * + * @return int + */ + public function count() + { + return count($this->_elements); + } + + /** + * Find element by ID + * + * @param mixed $elementId + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract|null + */ + public function searchById($elementId) + { + foreach ($this->_elements as $element) { + if ($element->getId() == $elementId) { + return $element; + } + } + return null; + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/CountryListSelect.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/CountryListSelect.php new file mode 100644 index 0000000000..9872e45779 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/CountryListSelect.php @@ -0,0 +1,240 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_CountryListSelect + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Select +{ + /** + * Country list values array + * + * @var array + */ + protected $_countryListValues = array('country_id', 'region_id', 'region'); + + /** + * Init country list select element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + } + + /** + * Set country list values 'country_id' and 'region_id' + * + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_CountryListSelect + */ + protected function _setValues() + { + $value = $this->getValue(); + + foreach ($this->_countryListValues as $param) { + if (isset($value[$param])) { + $this->setData($param, $value[$param]); + } + } + + return $this; + } + + /** + * Get values using old standard + * + * @deprecated old output standard + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_CountryListSelect + */ + protected function _addOldStandardValue(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + $countries = $this->_getCountryOptions(); + + if (is_array($countries)) { + $valuesXmlObj = $xmlObj->addCustomChild('values'); + foreach ($countries as $data) { + $regions = array(); + + if ($data['value']) { + $regions = $this->_getRegionOptions($data['value']); + } + + $relationType = is_array($regions) && !empty($regions) ? 'region_id' : 'region'; + + $selectedCountry = array(); + if ($this->getCountryId() == $data['value']) { + $selectedCountry = array('selected' => 1); + } + + $item = $valuesXmlObj->addCustomChild('item', null, + array('relation' => $relationType) + $selectedCountry + ); + + $item->addCustomChild('label', (string)$data['label']); + $item->addCustomChild('value', $data['value']); + + if ($relationType == 'region_id') { + $regionsXmlObj = $item->addCustomChild('regions'); + foreach ($regions as $regionData) { + $selectedRegion = array(); + + if (!empty($selectedCountry) && $this->getRegionId() == $regionData['value']) { + $selectedRegion = array('selected' => 1); + } + + $regionItem = $regionsXmlObj->addCustomChild('region_item', null, $selectedRegion); + $regionItem->addCustomChild('label', (string)$regionData['label']); + $regionItem->addCustomChild('value', (string)$regionData['value']); + } + } + } + } + + return $this; + } + + /** + * Add value to element + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + protected function _addValue(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + $this->_setValues(); + + if ($this->getOldFormat()) { + $this->_addOldStandardValue($xmlObj); + return $this; + } + + if ($this->getCountryId()) { + $xmlObj->addAttribute('value', $xmlObj->xmlAttribute($this->getCountryId())); + } + $countries = $this->_getCountryOptions(); + + if (is_array($countries)) { + $values = $xmlObj->addCustomChild('values'); + foreach ($countries as $data) { + $regions = array(); + + if ($data['value']) { + $regions = $this->_getRegionOptions($data['value']); + } + + if (is_array($regions) && !empty($regions)) { + $relationType = 'region_id'; + } else { + $relationType = 'region'; + } + + $item = $values->addCustomChild('item', null, array( + 'relation' => $relationType, 'label' => (string)$data['label'], 'value' => $data['value'] + )); + + if ($relationType !== 'region') { + + $selectedRegion = array(); + if ($this->getCountryId() == $data['value']) { + $selectedRegion = array('value' => $this->getRegionId()); + } + + $regionsXmlObj = $item->addCustomChild('field', null, array( + 'id' => 'region_list_' . $data['value'], 'name' => 'region_id', + 'label' => Mage::helper('xmlconnect')->__('State/Province'), 'type' => 'select', + 'required' => 1 + ) + $selectedRegion); + + $regionValues = $regionsXmlObj->addCustomChild('values'); + + foreach ($regions as $regionData) { + $regionValues->addCustomChild('item', null, array( + 'label' => (string)$regionData['label'], 'value' => (string)$regionData['value'] + )); + } + } elseif ($this->getCountryId() == $data['value']) { + $item->addCustomChild('field', null, array( + 'id' => 'region_' . $data['value'], 'name' => 'region', + 'label' => Mage::helper('xmlconnect')->__('State/Province'), 'type' => 'text', + 'value' => $this->getRegion(), 'required' => 1 + )); + } + } + } + return $this; + } + + /** + * Retrieve regions by country + * + * @param string $countryId + * @return array + */ + protected function _getRegionOptions($countryId) + { + $cacheKey = 'DIRECTORY_REGION_SELECT_STORE' . Mage::app()->getStore()->getId() . $countryId; + $cache = Mage::app()->loadCache($cacheKey); + if (Mage::app()->useCache('config') && $cache) { + $options = unserialize($cache); + } else { + $collection = Mage::getModel('directory/region')->getResourceCollection()->addCountryFilter($countryId) + ->load(); + $options = $collection->toOptionArray(); + if (Mage::app()->useCache('config')) { + Mage::app()->saveCache(serialize($options), $cacheKey, array('config')); + } + } + return $options; + } + + /** + * Retrieve countries + * + * @return array + */ + protected function _getCountryOptions() + { + $cacheKey = 'DIRECTORY_COUNTRY_SELECT_STORE_' . Mage::app()->getStore()->getCode(); + $cache = Mage::app()->loadCache($cacheKey); + if (Mage::app()->useCache('config') && $cache) { + $options = unserialize($cache); + } else { + $collection = Mage::getModel('directory/country')->getResourceCollection()->loadByStore(); + $options = $collection->toOptionArray(false); + if (Mage::app()->useCache('config')) { + Mage::app()->saveCache(serialize($options), $cacheKey, array('config')); + } + } + return $options; + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Date.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Date.php new file mode 100644 index 0000000000..921364960f --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Date.php @@ -0,0 +1,85 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Date + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract +{ + /** + * Init multiline element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->setType('date'); + } + + /** + * Required element attribute array + * + * @return array + */ + public function getRequiredXmlAttributes() + { + return array( + 'label' => null, + 'type' => null, + 'format' => null + ); + } + + /** + * Add value to element + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + protected function _addValue(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + $values = $this->getEscapedValue(); + if (!empty($values)) { + $valuesXmlObj = $xmlObj->addCustomChild('values'); + foreach ($values as $element => $config) { + $valuesXmlObj->addCustomChild('item', null, array( + 'id' => $config['id'], + 'title' => $config['title'], + 'label' => $config['label'], + 'type' => $element, + 'value' => $config['value'] + )); + } + } + return $this; + } +} diff --git a/app/code/community/Find/Feed/Block/Adminhtml/List/Items.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Email.php similarity index 65% rename from app/code/community/Find/Feed/Block/Adminhtml/List/Items.php rename to app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Email.php index d295a4a735..382b75fdcc 100644 --- a/app/code/community/Find/Feed/Block/Adminhtml/List/Items.php +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Email.php @@ -18,34 +18,30 @@ * 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_XmlConnect * @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 product grid container + * Xmlconnect form email element * - * @category Find - * @package Find_Feed + * @category Mage + * @package Mage_XmlConnect * @author Magento Core Team */ -class Find_Feed_Block_Adminhtml_List_Items extends Mage_Adminhtml_Block_Widget_Grid_Container +class Mage_XmlConnect_Model_Simplexml_Form_Element_Email + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract { /** - * Initialize grid container settings + * Init email element * + * @param array $attributes */ - public function __construct() + public function __construct($attributes = array()) { - $this->_blockGroup = 'find_feed'; - $this->_controller = 'adminhtml_list_items'; - $this->_headerText = Mage::helper('find_feed')->__('Product import'); - - parent::__construct(); - - $this->_removeButton('add'); + parent::__construct($attributes); + $this->setType('email'); } } diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Fieldset.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Fieldset.php new file mode 100644 index 0000000000..aa6fa3c0e0 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Fieldset.php @@ -0,0 +1,219 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract +{ + /** + * Sort child elements by specified data key + * + * @var string + */ + protected $_sortChildrenByKey = ''; + + /** + * Children sort direction + * + * @var int + */ + protected $_sortChildrenDirection = SORT_ASC; + + /** + * Main element node + * + * @var string + */ + protected $_mainNode = 'fieldset'; + + /** + * Is name attribute required + * + * @var bool + */ + protected $_nameRequired = false; + + /** + * Init fieldset object + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->_renderer = Mage_XmlConnect_Model_Simplexml_Form::getFieldsetRenderer(); + $this->setType('fieldset'); + } + + /** + * Get fieldset element object + * + * @return Mage_XmlConnect_Model_Simplexml_Element + */ + public function getElementXml() + { + $xmlObj = $this->getXmlObject(); + $this->_addRequiredAttributes($xmlObj); + foreach ($this->getAttributes() as $key => $val) { + $xmlObj->addAttribute($key, $xmlObj->xmlAttribute($val)); + } + foreach ($this->getChildrenXml(false) as $element) { + $xmlObj->appendChild($element); + } + foreach ($this->getChildrenXml(true) as $fieldset) { + $xmlObj->appendChild($fieldset); + } + $this->addAfterXmlElementToObj($xmlObj); + return $xmlObj; + } + + /** + * Default element attribute array + * + * @return array + */ + public function getXmlAttributes() + { + return array('title', 'disabled'); + } + + /** + * Required element attribute array + * + * @return array + */ + public function getRequiredXmlAttributes() + { + return array(); + } + + /** + * Get children array of elements + * + * @param bool $isFieldset + * @return array + */ + public function getChildrenXml($isFieldset = false) + { + $result = array(); + foreach ($this->getSortedElements() as $element) { + if ($this->_checkFieldset($element, $isFieldset)) { + $result[] = $element->toXmlObject(); + } + } + return $result; + } + + /** + * Check weather is element a fieldset + * + * @param Mage_XmlConnect_Model_Simplexml_Form_Abstract $element + * @param bool $equal + * @return bool + */ + protected function _checkFieldset($element, $equal = true) { + if ($equal) { + return $element->getType() == 'fieldset'; + } else { + return $element->getType() != 'fieldset'; + } + } + + /** + * Add field element to fieldset + * + * @param string $elementId + * @param string $type + * @param array $config + * @param boolean $after + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + public function addField($elementId, $type, $config, $after = false) + { + $element = parent::addField($elementId, $type, $config, $after); + if ($renderer = Mage_XmlConnect_Model_Simplexml_Form::getFieldsetElementRenderer()) { + $element->setRenderer($renderer); + } + return $element; + } + + /** + * Commence sorting elements by values by specified data key + * + * @param string $key + * @param int $direction + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset + */ + public function setSortElementsByAttribute($key, $direction = SORT_ASC) + { + $this->_sortChildrenByKey = $key; + $this->_sortDirection = $direction; + return $this; + } + + /** + * Get sorted elements as array + * + * @return array + */ + public function getSortedElements() + { + $elements = array(); + // sort children by value by specified key + if ($this->_sortChildrenByKey) { + $sortKey = $this->_sortChildrenByKey; + $uniqueIncrement = 0; // in case if there are elements with same values + /** @var Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element */ + foreach ($this->getElements() as $element) { + $key = '_' . $uniqueIncrement; + if ($element->hasData($sortKey)) { + $key = $element->getDataUsingMethod($sortKey) . $key; + } + $elements[$key] = $element; + $uniqueIncrement++; + } + + if ($this->_sortDirection == SORT_ASC) { + ksort($elements, $this->_sortChildrenDirection); + } else { + krsort($elements, $this->_sortChildrenDirection); + } + + $elements = array_values($elements); + } else { + foreach ($this->getElements() as $element) { + $elements[] = $element; + } + } + return $elements; + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/File.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/File.php new file mode 100644 index 0000000000..286b8ef8f4 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/File.php @@ -0,0 +1,47 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_File + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract +{ + /** + * Init text element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->setType('file'); + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Image.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Image.php new file mode 100644 index 0000000000..ca7570af62 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Image.php @@ -0,0 +1,47 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Image + extends Mage_XmlConnect_Model_Simplexml_Form_Element_File +{ + /** + * Init text element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->setType('image'); + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Multiline.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Multiline.php new file mode 100644 index 0000000000..efb68d98bb --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Multiline.php @@ -0,0 +1,132 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Multiline + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract +{ + /** + * Format for Xml elements id attribute + * + * @var string + */ + protected $_fieldIdFormat = '%1$s'; + + /** + * Format for Xml elements name attribute + * + * @var string + */ + protected $_fieldNameFormat = '%1$s'; + + /** + * Init multiline element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + if (!isset($attributes['line_count'])) { + Mage::throwException( + Mage::helper('xmlconnect')->__('"line_count" attribute is required for "multiline" element.') + ); + } + parent::__construct($attributes); + $this->setType('multiline'); + } + + /** + * Required element attribute array + * + * @return array + */ + public function getRequiredXmlAttributes() + { + return array( + 'label' => null, + 'type' => null + ); + } + + /** + * Return Xml id for element + * + * @param null|string $index + * @return string + */ + public function getXmlId($index = null) + { + $format = $this->_fieldIdFormat; + if (!is_null($index)) { + $format .= '_%2$s'; + } + return sprintf($format, $this->getData('attribute_code'), $index); + } + + /** + * Return Xml id for element + * + * @param null|string $index + * @return string + */ + public function getFieldName($index = null) + { + $format = $this->_fieldNameFormat; + if (!is_null($index)) { + $format .= '[%2$s]'; + } + return sprintf($format, $this->getData('attribute_code'), $index); + } + + /** + * Add value to element + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + protected function _addValue(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + $values = $this->getEscapedValue(); + if (!empty($values)) { + $valuesXmlObj = $xmlObj->addCustomChild('values'); + for ($i = 0; $i < $this->getData('line_count'); $i++) { + $value = !empty($values[$i]) ? array('value' => $values[$i]) : array(); + + $valuesXmlObj->addCustomChild('item', null, array( + 'id' => $this->getXmlId($i), + 'name' => $this->getFieldName($i) + ) + $value); + } + } + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Multiselect.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Multiselect.php new file mode 100644 index 0000000000..7349989dca --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Multiselect.php @@ -0,0 +1,81 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Multiselect + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Select +{ + /** + * Init text element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->setType('multiselect'); + } + + /** + * Add value to element + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Multiselect + */ + protected function _addValue(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + $values = array(); + if (is_array($this->getEscapedValue())) { + $values = $this->getEscapedValue(); + } + + $valuesXmlObj = $xmlObj->addCustomChild('values'); + foreach ($this->getOptions() as $option) { + + if (empty($option['value'])) { + continue; + } + + $selected = array(); + if (in_array($option['value'], $values)) { + $selected = array('selected' => 1); + } + + $valuesXmlObj->addCustomChild('item', null, array( + 'label' => $option['label'], + 'value' => $option['value'] + ) + $selected); + } + + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Renderer/Interface.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Renderer/Interface.php new file mode 100644 index 0000000000..c71fd3795a --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Renderer/Interface.php @@ -0,0 +1,37 @@ + + */ +interface Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface +{ + public function render(Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element); +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Select.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Select.php new file mode 100644 index 0000000000..7eda8e14d2 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Select.php @@ -0,0 +1,91 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Select + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract +{ + /** + * Init text element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->setType('select'); + } + + /** + * Add value and options to select + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Select + */ + protected function _addValue(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + $value = $this->getEscapedValue(); + if ($value !== null) { + $xmlObj->addAttribute( + 'value', + $xmlObj->xmlAttribute($value) + ); + } + $this->_addOptions($xmlObj); + + return $this; + } + + /** + * Add options to select + * + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Select + */ + protected function _addOptions(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + if ($this->getOptions() && is_array($this->getOptions())) { + $valuesXmlObj = $xmlObj->addCustomChild('values'); + foreach ($this->getOptions() as $option) { + + if (!isset($option['value']) || $option['value'] == '') { + continue; + } + + $valuesXmlObj->addCustomChild('item', null, array( + 'label' => $option['label'], + 'value' => $option['value'] + )); + } + } + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Text.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Text.php new file mode 100644 index 0000000000..c664e9c4e0 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Text.php @@ -0,0 +1,47 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Text + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract +{ + /** + * Init text element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->setType('text'); + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Textarea.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Textarea.php new file mode 100644 index 0000000000..92e1b3c9da --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Textarea.php @@ -0,0 +1,47 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Textarea + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract +{ + /** + * Init textarea element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->setType('textarea'); + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Validator.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Validator.php new file mode 100644 index 0000000000..5449685a94 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Validator.php @@ -0,0 +1,193 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Validator + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Fieldset +{ + /** + * Main element node + * + * @var string + */ + protected $_mainNode = 'validators'; + + /** + * Validator id prefix + * + * @var string + */ + protected $_validatorIdPrefix = 'validator_'; + + /** + * Rule type block renderer + * + * @var string + */ + protected $_ruleTypeBlock = 'validator_rule'; + + /** + * Init validator container + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->_renderer = Mage_XmlConnect_Model_Simplexml_Form::getValidatorRenderer(); + $this->setType('validator'); + } + + /** + * Skip name attribute for validator + * + * @todo re-factor required attributes logic to make it easy to replace them + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + protected function _addName(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + return $this; + } + + /** + * Default element attribute array + * + * @return array + */ + public function getXmlAttributes() + { + return array(); + } + + /** + * Required element attribute array + * + * @return array + */ + public function getRequiredXmlAttributes() + { + return array(); + } + + /** + * Set element id + * + * @param $id + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + public function setId($id) + { + parent::setId($this->getValidatorIdPrefix() . $id); + return $this; + } + + /** + * Get validator prefix + * + * @return string + */ + public function getValidatorIdPrefix() + { + return $this->_validatorIdPrefix; + } + + /** + * Set validator prefix + * + * @param string $validatorIdPrefix + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Validator + */ + public function setValidatorIdPrefix($validatorIdPrefix) + { + $this->_validatorIdPrefix = $validatorIdPrefix; + return $this; + } + + /** + * Get object attributes array + * + * @return array + */ + public function getAttributes() + { + $attributes = array_merge($this->getXmlAttributes(), $this->getCustomAttributes()); + if (!empty($attributes)) { + return $this->getXmlObjAttributes($attributes); + } else { + return $attributes; + } + } + + /** + * Add rule element to validator container + * + * @param array $config + * @param boolean $after + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract + */ + public function addRule(array $config, $after = false) + { + if (isset($config['type'])) { + $ruleType = $config['type']; + } + + $elementId = $this->getXmlId() . '_' . $ruleType; + $element = parent::addField($elementId, $this->getRuleTypeBlock(), $config, $after); + if ($renderer = Mage_XmlConnect_Model_Simplexml_Form::getValidatorRuleRenderer()) { + $element->setRenderer($renderer); + } + return $element; + } + + /** + * Get rule type block renderer + * + * @return string + */ + public function getRuleTypeBlock() + { + return $this->_ruleTypeBlock; + } + + /** + * Set rule type block renderer + * + * @param string $ruleTypeBlock + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Validator + */ + public function setRuleTypeBlock($ruleTypeBlock) + { + $this->_ruleTypeBlock = $ruleTypeBlock; + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Validator/Abstract.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Validator/Abstract.php new file mode 100644 index 0000000000..91eb1c1e4d --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Validator/Abstract.php @@ -0,0 +1,184 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Validator_Abstract + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract +{ + /** + * Array of the messages for default validator types + * + * @var array + */ + protected $_validatorTypeMessages = array(); + + /** + * Main element node + * + * @var string + */ + protected $_mainNode = 'validator'; + + /** + * Init validator rule element abstract + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + $this->_renderer = Mage_XmlConnect_Model_Simplexml_Form::getValidatorRuleRenderer(); + $this->_setDefaultValidatorTypeMessages(); + if (isset($attributes['type'])) { + $this->setType($attributes['type']); + } + } + + /** + * Set default validator messages + * + * @see Mage_Core_Helper_Js->_getTranslateData() and validation.js + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Validator_Abstract + */ + protected function _setDefaultValidatorTypeMessages() + { + $helper = Mage::helper('xmlconnect'); + $this->_validatorTypeMessages = array( + 'min_length' => $helper->__('Text length does not satisfy specified min text range.'), + 'max_length' => $helper->__('Text length does not satisfy specified max text range.'), + 'alphanumeric' => $helper->__('Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed.'), + 'email' => $helper->__('Please enter a valid email address. For example johndoe@domain.com.'), + 'required' => $helper->__('This is a required field.'), + 'required_select' => $helper->__('Please select an option.'), + 'numeric' => $helper->__('Please use numbers only in this field. Please avoid spaces or other characters such as dots or commas.'), + 'alpha' => $helper->__('Please use letters only (a-z or A-Z) in this field.'), + 'url' => $helper->__('Please enter a valid URL. Protocol is required (http://, https:// or ftp://)'), + 'date' => $helper->__('Please enter a valid date.'), + 'max_file_size' => $helper->__('\'%s\' exceeds the allowed file size: %d (bytes)', $this->getFieldLabel(), $this->getValue()), + 'file_extensions' => $helper->__('\'%s\' is not a valid file extension. Allowed extensions: %s', $this->getFieldLabel(), $this->getValue()), + 'max_image_width' => $helper->__('\'%s\' width exceeds allowed value of %d px', $this->getFieldLabel(), $this->getValue()), + 'max_image_height' => $helper->__('\'%s\' height exceeds allowed value of %d px', $this->getFieldLabel(), $this->getValue()) + ); + return $this; + } + + /** + * Add required attributes to validator rule + * + * @todo re-factor required attributes logic to make it easy to replace them + * @throws Mage_Core_Exception + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + protected function _addRequiredAttributes(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + $this->_addId($xmlObj); + + foreach ($this->getRequiredXmlAttributes() as $attribute => $defValue) { + $data = $this->getData($this->_underscore($attribute)); + + if ($data) { + $xmlObj->addAttribute($attribute, $xmlObj->xmlAttribute($data)); + } elseif(null !== $defValue){ + $xmlObj->addAttribute($attribute, $xmlObj->xmlAttribute($defValue)); + } else { + Mage::throwException(Mage::helper('xmlconnect')->__('%s attribute is required.', $attribute)); + } + } + $this->_addMessage($xmlObj); + return $this; + } + + /** + * Add validator message for validator rule + * + * @throws Mage_Core_Exception + * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj + * @return Mage_XmlConnect_Model_Simplexml_Form_Abstract + */ + protected function _addMessage(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) + { + if ($this->getMessage()) { + $message = $this->getMessage(); + } elseif (array_key_exists($this->getType(), $this->getValidatorTypeMessages())) { + $message = $this->_validatorTypeMessages[$this->getType()]; + } else { + Mage::throwException( + Mage::helper('xmlconnect')->__('"message" attribute is required for "%s" validator rule.', $this->getType()) + ); + } + $xmlObj->addAttribute('message', $xmlObj->xmlAttribute($message)); + return $this; + } + + /** + * Default validator rule attribute array + * + * @return array + */ + public function getXmlAttributes() + { + return array('relation'); + } + + /** + * Required validator rule attribute array + * + * @return array + */ + public function getRequiredXmlAttributes() + { + return array('type' => null); + } + + /** + * Get validator type messages + * + * @return array + */ + public function getValidatorTypeMessages() + { + return $this->_validatorTypeMessages; + } + + /** + * Set validator type messages + * + * @param array $validatorTypeMessages + * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Validator_Abstract + */ + public function addValidatorTypeMessages(array $validatorTypeMessages) + { + $this->_validatorTypeMessages = array_merge($this->_validatorTypeMessages, $validatorTypeMessages); + return $this; + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Validator/Rule.php b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Validator/Rule.php new file mode 100644 index 0000000000..bd47829a6f --- /dev/null +++ b/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Validator/Rule.php @@ -0,0 +1,46 @@ + + */ +class Mage_XmlConnect_Model_Simplexml_Form_Element_Validator_Rule + extends Mage_XmlConnect_Model_Simplexml_Form_Element_Validator_Abstract +{ + /** + * Init validator rule element + * + * @param array $attributes + */ + public function __construct($attributes = array()) + { + parent::__construct($attributes); + } +} diff --git a/app/code/core/Mage/XmlConnect/Model/Tabs.php b/app/code/core/Mage/XmlConnect/Model/Tabs.php index 2f18d3b18f..58da61abe6 100644 --- a/app/code/core/Mage/XmlConnect/Model/Tabs.php +++ b/app/code/core/Mage/XmlConnect/Model/Tabs.php @@ -25,10 +25,10 @@ */ /** - * XmlConnect Model Tabs + * XmlConnect Tabs model * * @category Mage - * @package Mage_XmlConnect + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_Model_Tabs @@ -69,8 +69,8 @@ public function __construct($data) /** * Translate Label fields * - * @param &array $tabItems - * @return this + * @param array &$tabItems + * @return Mage_XmlConnect_Model_Tabs */ protected function _translateLabel(&$tabItems) { diff --git a/app/code/core/Mage/XmlConnect/Model/Template.php b/app/code/core/Mage/XmlConnect/Model/Template.php index 3f7a0690c4..95998f3a52 100755 --- a/app/code/core/Mage/XmlConnect/Model/Template.php +++ b/app/code/core/Mage/XmlConnect/Model/Template.php @@ -25,10 +25,10 @@ */ /** - * XmlConnect Model Template + * XmlConnect Template model * * @category Mage - * @package Mage_XmlConnect + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_Model_Template extends Mage_Core_Model_Template @@ -36,7 +36,7 @@ class Mage_XmlConnect_Model_Template extends Mage_Core_Model_Template /** * Model constructor * - * @return void + * @return null */ protected function _construct() { @@ -94,8 +94,6 @@ public function getProcessedTemplate(array $variables = array()) $htmlDescription = <<%s: EOT; - /** @var $coreHelper Mage_Core_Helper_Data */ - $coreHelper = Mage::helper('core'); $html = sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Push title')) . $this->getPushTitle(); $html .= sprintf($htmlDescription, Mage::helper('xmlconnect')->__('Message title')) diff --git a/app/code/core/Mage/XmlConnect/Model/Theme.php b/app/code/core/Mage/XmlConnect/Model/Theme.php index 674356bf51..00acf46e23 100644 --- a/app/code/core/Mage/XmlConnect/Model/Theme.php +++ b/app/code/core/Mage/XmlConnect/Model/Theme.php @@ -25,10 +25,10 @@ */ /** - * XmlConnect Model Theme + * XmlConnect Theme model * * @category Mage - * @package Mage_XmlConnect + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_Model_Theme @@ -172,14 +172,8 @@ protected function _createThemeName() /** @var $coreHelper Mage_Core_Helper_Data */ $coreHelper = Mage::helper('core'); - $themeFileName = $themesHelper->getMediaThemePath() - . DS - .$themesHelper->getCustomThemeName() - . '_' - . time() - . '_' - . $coreHelper->getRandomString(10, 'abcdefghijklmnopqrstuvwxyz0123456789') - . '.xml'; + $themeFileName = $themesHelper->getMediaThemePath() . DS .$themesHelper->getCustomThemeName() . '_' . time() + . '_' . $coreHelper->getRandomString(10, 'abcdefghijklmnopqrstuvwxyz0123456789') . '.xml'; return $themeFileName; } @@ -193,13 +187,13 @@ protected function _createCopy($filePath) { $currentThemeFileName = $this->_getThemeFile(); - $io = new Varien_Io_File(); - if (!$io->cp($currentThemeFileName, $filePath)) { + $ioFile = new Varien_Io_File(); + if (!$ioFile->cp($currentThemeFileName, $filePath)) { Mage::throwException( Mage::helper('xmlconnect')->__('Can\'t copy file "%s" to "%s".', $currentThemeFileName, $filePath) ); } else { - $io->chmod($filePath, 0755); + $ioFile->chmod($filePath, 0755); } return $filePath; @@ -221,7 +215,7 @@ public function createNewTheme($themeName, $data) $themeFileName = Mage::getModel('xmlconnect/theme', $filePath); $themeFileName->setLabel($themeName); $fileName = basename($filePath); - $themeFileName->setName(substr($fileName, 0, strlen($fileName)-4)); + $themeFileName->setName(substr($fileName, 0, -4)); $themeFileName->importAndSaveData($data); return $themeFileName; } @@ -243,7 +237,7 @@ public function getFormData() * @param string $prefix * @return array */ - protected function _flatArray($subtree, $prefix=null) + protected function _flatArray($subtree, $prefix = null) { $result = array(); foreach ($subtree as $key => $value) { @@ -269,7 +263,7 @@ protected function _flatArray($subtree, $prefix=null) * @param array $xml * @return array */ - protected function _validateFormInput($data, $xml=NULL) + protected function _validateFormInput($data, $xml = null) { $root = false; $result = array(); @@ -298,7 +292,7 @@ protected function _validateFormInput($data, $xml=NULL) * * @param SimpleXMLElement $parent * @param array $data - * @return void + * @return null */ protected function _buildRecursive($parent, $data) { @@ -315,7 +309,7 @@ protected function _buildRecursive($parent, $data) * Import data into theme form $data array, and save XML to file * * @param array $data - * @return void + * @return null */ public function importAndSaveData($data) { @@ -325,9 +319,7 @@ public function importAndSaveData($data) if (is_writeable($this->_file)) { file_put_contents($this->_file, $xml->asXML()); } else { - Mage::throwException( - Mage::helper('xmlconnect')->__('Can\'t write to file "%s".', $this->_file) - ); + Mage::throwException(Mage::helper('xmlconnect')->__('Can\'t write to file "%s".', $this->_file)); } } } diff --git a/app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php b/app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php index 9287cf7ebe..8b81bca344 100644 --- a/app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php +++ b/app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php @@ -83,7 +83,7 @@ protected function _restoreSessionFilesFormData($data) /** * Mobile applications management * - * @return void + * @return null */ public function indexAction() { @@ -95,7 +95,7 @@ public function indexAction() /** * Create new app * - * @return void + * @return null */ public function newAction() { @@ -108,7 +108,7 @@ public function newAction() /** * Submission Action, loads application data * - * @return void + * @return null */ public function submissionAction() { @@ -152,7 +152,7 @@ public function submissionAction() /** * Edit app form * - * @return void + * @return null */ public function editAction() { @@ -209,7 +209,7 @@ public function editAction() /** * Submit POST application action * - * @return void + * @return null */ public function submissionPostAction() { @@ -238,20 +238,16 @@ public function submissionPostAction() $this->_processPostRequest(); $history = Mage::getModel('xmlconnect/history'); $history->setData(array( - 'params' => $params, - 'application_id' => $app->getId(), - 'created_at' => Mage::getModel('core/date')->date(), - 'store_id' => $app->getStoreId(), - 'title' => isset($params['title']) ? $params['title'] : '', - 'name' => $app->getName(), - 'code' => $app->getCode(), - 'activation_key' => isset($params['resubmission_activation_key']) - ? $params['resubmission_activation_key'] - : $params['key'], + 'params' => $params, 'application_id' => $app->getId(), + 'created_at' => Mage::getModel('core/date')->date(), 'store_id' => $app->getStoreId(), + 'title' => isset($params['title']) ? $params['title'] : '', 'name' => $app->getName(), + 'code' => $app->getCode(), 'activation_key' => isset($params['resubmission_activation_key']) + ? $params['resubmission_activation_key'] : $params['key'], )); $history->save(); - $app->getResource()->updateApplicationStatus($app->getId(), - Mage_XmlConnect_Model_Application::APP_STATUS_SUCCESS); + $app->getResource()->updateApplicationStatus( + $app->getId(), Mage_XmlConnect_Model_Application::APP_STATUS_SUCCESS + ); $this->_getSession()->addSuccess($this->__('App has been submitted.')); $this->_clearSessionData(); $this->_redirect('*/*/edit', array('application_id' => $app->getId())); @@ -316,7 +312,7 @@ protected function _clearSessionData() /** * Send HTTP POST request to magentocommerce.com * - * @return void + * @return null */ protected function _processPostRequest() { @@ -325,28 +321,27 @@ protected function _processPostRequest() $params = $app->getSubmitParams(); $appConnectorUrl = Mage::getStoreConfig('xmlconnect/mobile_application/magentocommerce_url'); - $ch = curl_init($appConnectorUrl . $params['key']); + $curlHandler = curl_init($appConnectorUrl . $params['key']); // set URL and other appropriate options - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $params); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($curlHandler, CURLOPT_POST, 1); + curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $params); + curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($curlHandler, CURLOPT_TIMEOUT, 60); // Execute the request. - $result = curl_exec($ch); - $succeeded = curl_errno($ch) == 0 ? true : false; + $result = curl_exec($curlHandler); // close cURL resource, and free up system resources - curl_close($ch); + curl_close($curlHandler); // Assert that we received an expected message in reponse. $resultArray = json_decode($result, true); $app->setResult($result); - $success = (isset($resultArray['success'])) && ($resultArray['success'] === true); + $success = isset($resultArray['success']) && $resultArray['success'] === true; $app->setSuccess($success); if (!$app->getSuccess()) { @@ -364,7 +359,7 @@ protected function _processPostRequest() /** * Save action * - * @return void + * @return null */ public function saveAction() { @@ -470,8 +465,6 @@ protected function _saveThemeAction($data, $paramId = 'saveTheme') 'selectedTheme' => $themeName ); } - } elseif ($newThemeName) { - $response = array('error' => true, 'message' => $this->__('Cannot load theme "%s".', $themeName)); } else { $response = array('error' => true, 'message' => $this->__('Cannot load theme "%s".', $themeName)); } @@ -479,22 +472,16 @@ protected function _saveThemeAction($data, $paramId = 'saveTheme') $convertedConf = $this->_convertPost($data); $newTheme = $themesHelper->createNewTheme($themeName, $convertedConf); $response = array( - 'message' => $this->__('Theme has been created.'), - 'themes' => $themesHelper->getAllThemesArray(true), + 'message' => $this->__('Theme has been created.'), + 'themes' => $themesHelper->getAllThemesArray(true), 'themeSelector' => $themesHelper->getThemesSelector($newTheme->getName()), 'selectedTheme' => $newTheme->getName() ); } } catch (Mage_Core_Exception $e) { - $response = array( - 'error' => true, - 'message' => $e->getMessage(), - ); + $response = array('error' => true, 'message' => $e->getMessage()); } catch (Exception $e) { - $response = array( - 'error' => true, - 'message' => $this->__('Can\'t save theme.') - ); + $response = array('error' => true, 'message' => $this->__('Can\'t save theme.')); } } else { $response = array('error' => true, 'message' => $this->__('Theme name is not set.')); @@ -519,15 +506,15 @@ protected function _convertPost($data) foreach ($data as $key => $val) { $parts = explode('_', $key); // "4" - is number of expected params conf_native_bar_tintcolor in correct data - if (is_array($parts) && (count($parts) == 4)) { - @list($key0, $key1, $key2, $key3) = $parts; + if (is_array($parts) && count($parts) == 4) { + list(, $key1, $key2, $key3) = $parts; if (!isset($conf[$key1])) { $conf[$key1] = array(); } if (!isset($conf[$key1][$key2])) { $conf[$key1][$key2] = array(); } - $conf[$key1][$key2][$key3] = $val; + $conf[$key1][$key2][$key3] = $val; } } return $conf; @@ -536,7 +523,7 @@ protected function _convertPost($data) /** * Delete theme action * - * @return void + * @return null */ public function deleteThemeAction() { @@ -560,10 +547,7 @@ public function deleteThemeAction() ); } } catch (Mage_Core_Exception $e) { - $response = array( - 'error' => true, - 'message' => $e->getMessage(), - ); + $response = array('error' => true, 'message' => $e->getMessage()); } catch (Exception $e) { $response = array( 'error' => true, @@ -582,7 +566,7 @@ public function deleteThemeAction() /** * Save Theme action * - * @return void + * @return null */ public function saveThemeAction() { @@ -593,7 +577,7 @@ public function saveThemeAction() /** * Save Theme action * - * @return void + * @return null */ public function resetThemeAction() { @@ -602,15 +586,9 @@ public function resetThemeAction() Mage::helper('xmlconnect/theme')->resetTheme($theme); $response = Mage::helper('xmlconnect/theme')->getAllThemesArray(true); } catch (Mage_Core_Exception $e) { - $response = array( - 'error' => true, - 'message' => $e->getMessage(), - ); + $response = array('error' => true, 'message' => $e->getMessage()); } catch (Exception $e) { - $response = array( - 'error' => true, - 'message' => $this->__('Can\'t reset theme.') - ); + $response = array('error' => true, 'message' => $this->__('Can\'t reset theme.')); } if (is_array($response)) { $response = Mage::helper('core')->jsonEncode($response); @@ -621,7 +599,7 @@ public function resetThemeAction() /** * Preview Home action handler * - * @return void + * @return null */ public function previewHomeAction() { @@ -639,7 +617,7 @@ public function previewHomeHorAction() /** * Preview Catalog action handler * - * @return void + * @return null */ public function previewCatalogAction() { @@ -737,7 +715,7 @@ protected function _previewAction($block) /** * Delete app action * - * @return void + * @return null */ public function deleteAction() { @@ -769,9 +747,7 @@ public function deleteTemplateAction() Mage::getModel('xmlconnect/template')->load($id)->delete(); // display success message - Mage::getSingleton('adminhtml/session')->addSuccess( - $this->__('Template has been deleted.') - ); + Mage::getSingleton('adminhtml/session')->addSuccess($this->__('Template has been deleted.')); // go to grid $this->_redirect('*/*/template'); @@ -787,9 +763,7 @@ public function deleteTemplateAction() } // display error message - Mage::getSingleton('adminhtml/session')->addError( - $this->__('Unable to find template to delete.') - ); + Mage::getSingleton('adminhtml/session')->addError($this->__('Unable to find template to delete.')); } /** @@ -815,7 +789,7 @@ public function historyAction() /** * Render apps grid * - * @return void + * @return null */ public function gridAction() { @@ -826,7 +800,7 @@ public function gridAction() /** * Process all uploaded files - * setup filenames to the configuration return array + * setup file names to the configuration return array * * @param array $data * @param bool $restore @@ -844,13 +818,14 @@ protected function _processUploadedFiles($data, $restore = false) if (!empty($_FILES)) { foreach ($_FILES as $field => $file) { if (!empty($file['name']) && is_scalar($file['name'])) { - $uploadedFileName = Mage::helper('xmlconnect/image')->handleUpload($field, $data); + $uploadedFileName = Mage::helper('xmlconnect/image')->handleUpload($field); if (!empty($uploadedFileName)) { $this->_uploadedFiles[$field] = $uploadedFileName; } } } } + foreach ($this->_uploadedFiles as $fieldPath => $fileName) { Mage::helper('xmlconnect')->_injectFieldToArray($data, $fieldPath, $fileName); } @@ -973,7 +948,7 @@ protected function _initTemplate($paramName = 'id') /** * List AirMail message queue grid * - * @return void + * @return null */ public function queueAction() { @@ -985,7 +960,7 @@ public function queueAction() /** * Edit message action * - * @return void + * @return null */ public function editQueueAction() { @@ -1000,7 +975,7 @@ public function editQueueAction() /** * Filtering posted data. Converting localized data if needed * - * @param array + * @param array $data * @return array */ protected function _filterPostData($data) @@ -1012,7 +987,7 @@ protected function _filterPostData($data) /** * Cancel queue action * - * @return void + * @return null */ public function cancelQueueAction() { @@ -1039,7 +1014,7 @@ public function cancelQueueAction() /** * Delete queue action * - * @return void + * @return null */ public function deleteQueueAction() { @@ -1066,7 +1041,7 @@ public function deleteQueueAction() /** * Cancel selected queue action * - * @return void + * @return null */ public function massCancelQueueAction() { @@ -1077,9 +1052,7 @@ public function massCancelQueueAction() try { $queue = Mage::getModel('xmlconnect/queue'); foreach ($queueIds as $queueId) { - $queue->reset() - ->load((int)$queueId) - ->setStatus(Mage_XmlConnect_Model_Queue::STATUS_CANCELED) + $queue->reset()->load((int)$queueId)->setStatus(Mage_XmlConnect_Model_Queue::STATUS_CANCELED) ->save(); } Mage::getSingleton('adminhtml/session')->addSuccess( @@ -1096,7 +1069,7 @@ public function massCancelQueueAction() /** * Delete selected queue action * - * @return void + * @return null */ public function massDeleteQueueAction() { @@ -1107,15 +1080,10 @@ public function massDeleteQueueAction() try { $queue = Mage::getModel('xmlconnect/queue'); foreach ($queueIds as $queueId) { - $queue->reset() - ->load($queueId) - ->setStatus(Mage_XmlConnect_Model_Queue::STATUS_DELETED) - ->save(); + $queue->reset()->load($queueId)->setStatus(Mage_XmlConnect_Model_Queue::STATUS_DELETED)->save(); } Mage::getSingleton('adminhtml/session')->addSuccess( - Mage::helper('adminhtml')->__( - 'Total of %d record(s) were deleted.', count($queueIds) - ) + Mage::helper('adminhtml')->__('Total of %d record(s) were deleted.', count($queueIds)) ); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); @@ -1128,7 +1096,7 @@ public function massDeleteQueueAction() /** * Save AirMail message action * - * @return void + * @return null */ public function saveMessageAction() { @@ -1143,12 +1111,25 @@ public function saveMessageAction() $message = $this->_initMessage(); if (!$template->getId() && !$message->getTemplateId()) { - $this->_getSession()->addError( - $this->__('Template for new AirMail Message does not exist.') - ); + $this->_getSession()->addError($this->__('Template for new AirMail Message does not exist.')); $this->_redirect('*/*/queue'); return; } + + /** @var $app Mage_XmlConnect_Model_Application */ + $app = Mage::getModel('xmlconnect/application')->loadByCode($template->getAppCode()); + $deviceType = Mage::helper('xmlconnect')->getDeviceType($app); + + if ($deviceType == Mage_XmlConnect_Helper_Data::DEVICE_TYPE_ANDROID + && $data['type'] == Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL + ) { + $this->_getSession()->addError($this->__('Android doesn\'t support AirMail message type.')); + $redirectParams = $this->_getQueueMessageParams($message); + $action = $message->getId() ? 'editQueue' : 'queueMessage'; + $this->_redirect('*/*/' . $action, $redirectParams); + return; + } + $temporaryObject = new Varien_Object(); $temporaryObject->setData($data); @@ -1163,7 +1144,7 @@ public function saveMessageAction() $message->setStatus(Mage_XmlConnect_Model_Queue::STATUS_IN_QUEUE); } elseif ($message->getStatus() != Mage_XmlConnect_Model_Queue::STATUS_IN_QUEUE) { $this->_getSession()->addError( - $this->__('Message can be edited when status of the message is "IN QUEUE" only.') + $this->__('Message can be edited when status of the message is "In Queue" only.') ); $this->_redirect('*/*/queue'); return; @@ -1207,22 +1188,34 @@ public function saveMessageAction() if ($isError) { Mage::getSingleton('adminhtml/session')->setLoadSessionFlag(true); } - $redirectParams = array(); - if ($message && $message->getId()) { - $redirectParams['id'] = $message->getId(); - } else { - $redirectParams['template_id'] = (int) $this->getRequest()->getParam('template_id'); - } + $redirectParams = $this->_getQueueMessageParams($message); $this->_redirect('*/*/queueMessage', $redirectParams); } else { $this->_redirect('*/*/queue'); } } + /** + * Get queue message action params + * + * @param Mage_XmlConnect_Model_Queue $message + * @return array + */ + protected function _getQueueMessageParams(Mage_XmlConnect_Model_Queue $message) + { + $redirectParams = array(); + if ($message && $message->getId()) { + $redirectParams['id'] = $message->getId(); + } else { + $redirectParams['template_id'] = (int) $this->getRequest()->getParam('template_id'); + } + return $redirectParams; + } + /** * Temlate grid * - * @return void + * @return null */ public function templateAction() { @@ -1234,7 +1227,7 @@ public function templateAction() /** * Create new template action * - * @return void + * @return null */ public function newTemplateAction() { @@ -1244,7 +1237,7 @@ public function newTemplateAction() /** * Edit template action * - * @return void + * @return null */ public function editTemplateAction() { @@ -1252,9 +1245,7 @@ public function editTemplateAction() $applicationsFound = Mage::helper('xmlconnect')->getApplicationOptions(); if (!$template->getId() && empty($applicationsFound)) { - $this->_getSession()->addError( - $this->__('Template creation is allowed only for applications which have device type iPhone, but this kind of applications has not been found.') - ); + $this->_getSession()->addError($this->__('At last one application has to be created.')); $this->_redirect('*/*/template'); return; } @@ -1267,7 +1258,7 @@ public function editTemplateAction() /** * Save template action * - * @return void + * @return null */ public function saveTemplateAction() { @@ -1276,7 +1267,7 @@ public function saveTemplateAction() $isError = false; if ($data) { $data = Mage::getModel('core/input_filter_maliciousCode')->filter($data); - Mage::getSingleton('adminhtml/session')->setFormData($data); + Mage::getSingleton('adminhtml/session')->setTemplateFormData($data); try { $id = $this->getRequest()->getParam('id'); $template = $this->_initTemplate(); @@ -1308,7 +1299,7 @@ public function saveTemplateAction() /** * Add message to queue action * - * @return void + * @return null */ public function queueMessageAction() { @@ -1316,22 +1307,36 @@ public function queueMessageAction() if (!$message->getId()) { $template = $this->_initTemplate('template_id'); if (!$template->getId()) { - $this->_getSession()->addError( - $this->__('Template for new AirMail Message does not exist.') - ); + $this->_getSession()->addError($this->__('Template for new AirMail Message does not exist.')); $this->_redirect('*/*/template'); } } + if (isset($template)) { + $appCode = $template->getAppCode(); + } else { + $appCode = Mage::getModel('xmlconnect/template')->load($message->getTemplateId())->getAppCode(); + } + + /** @var $app Mage_XmlConnect_Model_Application */ + $app = Mage::getModel('xmlconnect/application')->loadByCode($appCode); + + if(!$app->isNotificationsActive()) { + $this->_getSession()->addError( + $this->__('Queue is allowed only for applications with enabled Push Notification.') + ); + $action = $message->getId() ? 'queue' : 'template'; + $this->_redirect('*/*/' . $action); + return; + } + $this->loadLayout(); if ($message->getId()) { $title = $this->__('Edit AirMail Message'); } else { $title = $this->__('New AirMail Message'); } - $this->_addBreadcrumb( - $this->__('AirMail Message Queue'), - $this->__('AirMail Message Queue'), + $this->_addBreadcrumb($this->__('AirMail Message Queue'), $this->__('AirMail Message Queue'), $this->getUrl('*/*/queue') ); $this->_addBreadcrumb($title, $title); @@ -1343,7 +1348,7 @@ public function queueMessageAction() /** * Edit queue message action * - * @return void + * @return null */ public function editMessageAction() { diff --git a/app/code/core/Mage/XmlConnect/controllers/CartController.php b/app/code/core/Mage/XmlConnect/controllers/CartController.php index c8a3588fc0..b48bfe6457 100644 --- a/app/code/core/Mage/XmlConnect/controllers/CartController.php +++ b/app/code/core/Mage/XmlConnect/controllers/CartController.php @@ -36,42 +36,48 @@ class Mage_XmlConnect_CartController extends Mage_XmlConnect_Controller_Action /** * Shopping cart display action * - * @return void + * @return null */ public function indexAction() { - $messages = array(); - $cart = $this->_getCart(); - if ($cart->getQuote()->getItemsCount()) { - $cart->init(); - $cart->save(); - - if (!$this->_getQuote()->validateMinimumAmount()) { - $warning = Mage::getStoreConfig('sales/minimum_order/description'); - $messages[parent::MESSAGE_STATUS_WARNING][] = $warning; + try { + $messages = array(); + $cart = $this->_getCart(); + if ($cart->getQuote()->getItemsCount()) { + $cart->init(); + $cart->save(); + + if (!$this->_getQuote()->validateMinimumAmount()) { + $warning = Mage::getStoreConfig('sales/minimum_order/description'); + $messages[parent::MESSAGE_STATUS_WARNING][] = $warning; + } } - } - foreach ($cart->getQuote()->getMessages() as $message) { - if ($message) { - $messages[$message->getType()][] = $message->getText(); + foreach ($cart->getQuote()->getMessages() as $message) { + if ($message) { + $messages[$message->getType()][] = $message->getText(); + } } - } - - /** - * if customer enters shopping cart we should mark quote - * as modified bc he can has checkout page in another window. - */ - $this->_getSession()->setCartWasUpdated(true); - $this->loadLayout(false)->getLayout()->getBlock('xmlconnect.cart')->setMessages($messages); - $this->renderLayout(); + /** + * if customer enters shopping cart we should mark quote + * as modified bc he can has checkout page in another window. + */ + $this->_getSession()->setCartWasUpdated(true); + $this->loadLayout(false)->getLayout()->getBlock('xmlconnect.cart')->setMessages($messages); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + Mage::logException($e); + $this->_message($this->__('Can\'t load cart.'), self::MESSAGE_STATUS_ERROR); + } } /** * Update shoping cart data action * - * @return void + * @return null */ public function updateAction() { @@ -87,17 +93,17 @@ public function updateAction() } } $cart = $this->_getCart(); - if (! $cart->getCustomerSession()->getCustomer()->getId() && $cart->getQuote()->getCustomerId()) { + if (!$cart->getCustomerSession()->getCustomer()->getId() && $cart->getQuote()->getCustomerId()) { $cart->getQuote()->setCustomerId(null); } - $cart->updateItems($cartData) - ->save(); + $cart->updateItems($cartData)->save(); } $this->_getSession()->setCartWasUpdated(true); $this->_message($this->__('Cart has been updated.'), parent::MESSAGE_STATUS_SUCCESS); } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); } catch (Exception $e) { + Mage::logException($e); $this->_message($this->__('Can\'t update cart.'), self::MESSAGE_STATUS_ERROR); } } @@ -128,7 +134,7 @@ protected function _getProductRequest($requestInfo) /** * Add product to shopping cart action * - * @return void + * @return null */ public function addAction() { @@ -145,8 +151,7 @@ public function addAction() $product = null; $productId = (int) $this->getRequest()->getParam('product'); if ($productId) { - $_product = Mage::getModel('catalog/product') - ->setStoreId(Mage::app()->getStore()->getId()) + $_product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId()) ->load($productId); if ($_product->getId()) { $product = $_product; @@ -165,7 +170,6 @@ public function addAction() if ($product->isConfigurable()) { $request = $this->_getProductRequest($params); - /** * Hardcoded Configurable product default * Set min required qty for a product if it's need @@ -190,7 +194,6 @@ public function addAction() } $cart->save(); - $this->_getSession()->setCartWasUpdated(true); if (isset($params['whishlist_id'])) { @@ -227,7 +230,7 @@ public function addAction() if (isset($wishlistMessage)) { $this->_message($wishlistMessage, self::MESSAGE_STATUS_ERROR); } else { - $productName = Mage::helper('core')->htmlEscape($product->getName()); + $productName = Mage::helper('core')->escapeHtml($product->getName()); $message = $this->__('%s has been added to your cart.', $productName); if ($cart->getQuote()->getHasError()) { $message .= $this->__(' But cart has some errors.'); @@ -243,6 +246,7 @@ public function addAction() $this->_message($messageText, parent::MESSAGE_STATUS_ERROR); } } catch (Exception $e) { + Mage::logException($e); $this->_message($this->__('Can\'t add item to shopping cart.'), self::MESSAGE_STATUS_ERROR); } } @@ -250,7 +254,7 @@ public function addAction() /** * Delete shoping cart item action * - * @return void + * @return null */ public function deleteAction() { @@ -262,6 +266,7 @@ public function deleteAction() } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), parent::MESSAGE_STATUS_ERROR); } catch (Exception $e) { + Mage::logException($e); $this->_message($this->__('Can\'t remove the item.'), self::MESSAGE_STATUS_ERROR); } } @@ -270,7 +275,7 @@ public function deleteAction() /** * Initialize coupon * - * @return void + * @return null */ public function couponAction() { @@ -295,15 +300,19 @@ public function couponAction() try { $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true); - $this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '') - ->collectTotals() - ->save(); + $this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '')->collectTotals()->save(); if ($couponCode) { if ($couponCode == $this->_getQuote()->getCouponCode()) { - $this->_message($this->__('Coupon code %s was applied.', strip_tags($couponCode)), parent::MESSAGE_STATUS_SUCCESS); + $this->_message( + $this->__('Coupon code %s was applied.', strip_tags($couponCode)), + parent::MESSAGE_STATUS_SUCCESS + ); } else { - $this->_message($this->__('Coupon code %s is not valid.', strip_tags($couponCode)), self::MESSAGE_STATUS_ERROR); + $this->_message( + $this->__('Coupon code %s is not valid.', strip_tags($couponCode)), + self::MESSAGE_STATUS_ERROR + ); } } else { $this->_message($this->__('Coupon code was canceled.'), parent::MESSAGE_STATUS_SUCCESS); @@ -312,20 +321,123 @@ public function couponAction() } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); } catch (Exception $e) { + Mage::logException($e); $this->_message($this->__('Can\'t apply the coupon code.'), self::MESSAGE_STATUS_ERROR); } } + /** + * Add Gift Card action + * + * @return null + */ + public function addGiftcardAction() + { + /** + * No reason continue with empty shopping cart + */ + if (!$this->_getQuote()->getItemsCount()) { + $this->_message($this->__('Shopping cart is empty.'), self::MESSAGE_STATUS_ERROR); + return; + } + + $data = $this->getRequest()->getPost(); + if (!empty($data['giftcard_code'])) { + $code = $data['giftcard_code']; + try { + Mage::getModel('enterprise_giftcardaccount/giftcardaccount')->loadByCode($code)->addToCart(); + $this->_message( + $this->__('Gift Card "%s" was added.', Mage::helper('core')->escapeHtml($code)), + self::MESSAGE_STATUS_SUCCESS + ); + return; + } catch (Mage_Core_Exception $e) { + Mage::dispatchEvent('enterprise_giftcardaccount_add', array('status' => 'fail', 'code' => $code)); + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Cannot apply gift card.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } else { + $this->_message($this->__('Gift Card code is empty.'), self::MESSAGE_STATUS_ERROR); + return; + } + } + + /** + * Remove Gift Card action + * + * @return null + */ + public function removeGiftcardAction() + { + $code = $this->getRequest()->getParam('giftcard_code'); + if ($code) { + try { + Mage::getModel('enterprise_giftcardaccount/giftcardaccount')->loadByCode($code)->removeFromCart(); + $this->_message( + $this->__('Gift Card "%s" was removed.', Mage::helper('core')->escapeHtml($code)), + self::MESSAGE_STATUS_SUCCESS + ); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Cannot remove gift card.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } else { + $this->_message($this->__('Gift Card code is empty.'), self::MESSAGE_STATUS_ERROR); + return; + } + } + + /** + * Remove Store Credit action + * + * @return null + */ + public function removeStoreCreditAction() + { + if (!Mage::helper('enterprise_customerbalance')->isEnabled()) { + $this->_message($this->__('Customer balance is disabled for current store'), self::MESSAGE_STATUS_ERROR); + return; + } + + $quote = $this->_getQuote(); + + if ($quote->getUseCustomerBalance()) { + $this->_message( + $this->__('The store credit payment has been removed from shopping cart.'), + self::MESSAGE_STATUS_SUCCESS + ); + $quote->setUseCustomerBalance(false)->collectTotals()->save(); + return; + } else { + $this->_message( + $this->__('Store Credit payment is not being used in your shopping cart.'), + self::MESSAGE_STATUS_ERROR + ); + return; + } + } + /** * Get shopping cart summary and flag is_virtual * - * @return void + * @return null */ public function infoAction() { - $this->_getQuote()->collectTotals()->save(); - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->_getQuote()->collectTotals()->save(); + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + Mage::logException($e); + $this->_message($this->__('Can\'t load cart info.'), self::MESSAGE_STATUS_ERROR); + } } /** diff --git a/app/code/core/Mage/XmlConnect/controllers/CatalogController.php b/app/code/core/Mage/XmlConnect/controllers/CatalogController.php index e512bba80e..9b1381c2e8 100644 --- a/app/code/core/Mage/XmlConnect/controllers/CatalogController.php +++ b/app/code/core/Mage/XmlConnect/controllers/CatalogController.php @@ -36,22 +36,32 @@ class Mage_XmlConnect_CatalogController extends Mage_XmlConnect_Controller_Actio /** * Category list * - * @return void + * @return null */ public function categoryAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + Mage::logException($e); + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + Mage::logException($e); + $this->_message( + $this->__('An error occurred while loading categories.'), self::MESSAGE_STATUS_ERROR + ); + } } /** * Filter product list * - * @return void + * @return null */ public function filtersAction() { - try{ + try { $this->loadLayout(false); $this->renderLayout(); } catch (Mage_Core_Exception $e) { @@ -59,8 +69,7 @@ public function filtersAction() } catch (Exception $e) { Mage::logException($e); $this->_message( - $this->__('An error occurred while loading category filters.'), - self::MESSAGE_STATUS_ERROR + $this->__('An error occurred while loading category filters.'), self::MESSAGE_STATUS_ERROR ); } } @@ -68,7 +77,7 @@ public function filtersAction() /** * Product information * - * @return void + * @return null */ public function productAction() { @@ -87,51 +96,79 @@ public function productAction() /** * Product options list * - * @return void + * @return null */ public function productOptionsAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load product options.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Product gallery images list * - * @return void + * @return null */ public function productGalleryAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load product gallery.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Product reviews list * - * @return void + * @return null */ public function productReviewsAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load product reviews.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Add new review * - * @return void + * @return null */ public function productReviewAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load product review.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Perform search products * - * @return void + * @return null */ public function searchAction() { @@ -176,20 +213,34 @@ public function searchAction() } } - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load search.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Retrieve suggestions based on search query * - * @return void + * @return null */ public function searchSuggestAction() { $this->getRequest()->setParam('q', $this->getRequest()->getParam('query')); - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load search.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** @@ -210,7 +261,11 @@ public function sendEmailAction() } if (!$helper->isAllowForGuest() && !$session->isLoggedIn()) { - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); + $this->_message( + $this->__('Customer not logged in.'), + self::MESSAGE_STATUS_ERROR, + array('logged_in' => '0') + ); return $this; } @@ -266,8 +321,7 @@ public function sendEmailAction() */ $categoryId = $this->getRequest()->getParam('category_id', null); if ($categoryId) { - $category = Mage::getModel('catalog/category') - ->load($categoryId); + $category = Mage::getModel('catalog/category')->load($categoryId); $product->setCategory($category); Mage::register('current_category', $category); } diff --git a/app/code/core/Mage/XmlConnect/controllers/CheckoutController.php b/app/code/core/Mage/XmlConnect/controllers/CheckoutController.php index 5e89b941f6..4cc97dbcb5 100644 --- a/app/code/core/Mage/XmlConnect/controllers/CheckoutController.php +++ b/app/code/core/Mage/XmlConnect/controllers/CheckoutController.php @@ -28,7 +28,7 @@ * XmlConnect checkout controller * * @category Mage - * @package Mage_Checkout + * @package Mage_Xmlconnect * @author Magento Core Team */ class Mage_XmlConnect_CheckoutController extends Mage_XmlConnect_Controller_Action @@ -36,7 +36,7 @@ class Mage_XmlConnect_CheckoutController extends Mage_XmlConnect_Controller_Acti /** * Make sure customer is logged in * - * @return void + * @return null */ public function preDispatch() { @@ -45,7 +45,11 @@ public function preDispatch() && !Mage::getSingleton('checkout/session')->getQuote()->isAllowedGuestCheckout() ) { $this->setFlag('', self::FLAG_NO_DISPATCH, true); - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); + $this->_message( + $this->__('Customer not logged in.'), + self::MESSAGE_STATUS_ERROR, + array('logged_in' => '0') + ); return ; } } @@ -63,7 +67,7 @@ public function getOnepage() /** * Onepage Checkout page * - * @return void + * @return null */ public function indexAction() { @@ -87,47 +91,75 @@ public function indexAction() Mage::getSingleton('checkout/session')->setCartWasUpdated(false); $this->getOnepage()->initCheckout(); - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load checkout.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Display customer new billing addrress form * - * @return void + * @return null */ public function newBillingAddressFormAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load billing address form.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Display customer new shipping addrress form * - * @return void + * @return null */ public function newShippingAddressFormAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load shipping address form.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Billing addresses list action * - * @return void + * @return null */ public function billingAddressAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load billing address.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Save billing address to current quote using onepage model * - * @return void + * @return null */ public function saveBillingAddressAction() { @@ -155,18 +187,25 @@ public function saveBillingAddressAction() /** * Shipping addresses list action * - * @return void + * @return null */ public function shippingAddressAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load billing address.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Save shipping address to current quote using onepage model * - * @return void + * @return null */ public function saveShippingAddressAction() { @@ -259,7 +298,7 @@ protected function _checkUseForShipping(array $data, $billingAddress, $shippingA /** * Get shipping methods for current quote * - * @return void + * @return null */ public function shippingMethodsAction() { @@ -279,7 +318,7 @@ public function shippingMethodsAction() /** * Shipping method save action * - * @return void + * @return null */ public function saveShippingMethodAction() { @@ -290,9 +329,16 @@ public function saveShippingMethodAction() $data = $this->getRequest()->getPost('shipping_method', ''); $result = $this->getOnepage()->saveShippingMethod($data); - if (!isset($result['error'])) { + if (!$result) { + + Mage::dispatchEvent('checkout_controller_onepage_save_shipping_method', array( + 'request' => $this->getRequest(), + 'quote' => $this->getOnepage()->getQuote() + )); + $this->getOnepage()->getQuote()->collectTotals()->save(); + $this->_message($this->__('Shipping method has been set.'), self::MESSAGE_STATUS_SUCCESS); - } else { + } elseif(isset($result['error'])) { if (!is_array($result['message'])) { $result['message'] = array($result['message']); } @@ -300,6 +346,7 @@ public function saveShippingMethodAction() 'request' => $this->getRequest(), 'quote' => $this->getOnepage()->getQuote() )); + $this->getOnepage()->getQuote()->collectTotals()->save(); $this->_message(implode('. ', $result['message']), self::MESSAGE_STATUS_ERROR); } } @@ -308,7 +355,7 @@ public function saveShippingMethodAction() /** * Save checkout method * - * @return void + * @return null */ public function saveMethodAction() { @@ -329,7 +376,7 @@ public function saveMethodAction() /** * Get payment methods action * - * @return void + * @return null */ public function paymentMethodsAction() { @@ -346,7 +393,7 @@ public function paymentMethodsAction() /** * Save payment action * - * @return void + * @return null */ public function savePaymentAction() { @@ -375,19 +422,26 @@ public function savePaymentAction() /** * Order summary info action * - * @return void + * @return null */ public function orderReviewAction() { $this->getOnepage()->getQuote()->collectTotals()->save(); - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load order review.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Create order action * - * @return void + * @return null */ public function saveOrderAction() { diff --git a/app/code/core/Mage/XmlConnect/controllers/CmsController.php b/app/code/core/Mage/XmlConnect/controllers/CmsController.php index 9103c06f33..0ea582df1e 100644 --- a/app/code/core/Mage/XmlConnect/controllers/CmsController.php +++ b/app/code/core/Mage/XmlConnect/controllers/CmsController.php @@ -27,14 +27,16 @@ /** * XmlConnect cms page controller * - * @author Magento Core Team + * @category Mage + * @package Mage_Xmlconnect + * @author Magento Core Team */ class Mage_XmlConnect_CmsController extends Mage_XmlConnect_Controller_Action { /** * Declare content type header * - * @return void + * @return null */ public function preDispatch() { @@ -45,7 +47,7 @@ public function preDispatch() /** * Category list * - * @return void + * @return null */ public function pageAction() { diff --git a/app/code/core/Mage/XmlConnect/controllers/ConfigurationController.php b/app/code/core/Mage/XmlConnect/controllers/ConfigurationController.php index a757a13131..68c24a2e7e 100644 --- a/app/code/core/Mage/XmlConnect/controllers/ConfigurationController.php +++ b/app/code/core/Mage/XmlConnect/controllers/ConfigurationController.php @@ -36,7 +36,7 @@ class Mage_XmlConnect_ConfigurationController extends Mage_Core_Controller_Front /** * Declare content type header * - * @return void + * @return null */ public function preDispatch() { @@ -52,7 +52,6 @@ public function preDispatch() */ protected function _initApp() { - $cookieName = Mage_XmlConnect_Model_Application::APP_CODE_COOKIE_NAME; $code = $this->getRequest()->getParam($cookieName); $screenSize = (string) $this->getRequest()->getParam( @@ -62,12 +61,16 @@ protected function _initApp() $app = Mage::getModel('xmlconnect/application'); if ($app) { $app->loadByCode($code); - Mage::app()->setCurrentStore(Mage::app()->getStore($app->getStoreId())->getCode()); + Mage::app()->setCurrentStore( + Mage::app()->getStore($app->getStoreId())->getCode() + ); Mage::getSingleton('core/locale')->emulate($app->getStoreId()); $app->setScreenSize($screenSize); + if (!$app->getId()) { Mage::throwException($this->__('App with specified code does not exist.')); } + $app->loadConfiguration(); } else { Mage::throwException($this->__('App code required.')); @@ -82,20 +85,22 @@ protected function _initApp() * Set application coolies: application code and device screen size. * * @param Mage_XmlConnect_Model_Application $app - * @return void + * @return null */ protected function _initCookies(Mage_XmlConnect_Model_Application $app) { - $cookieToSetArray = array ( + $cookieToSetArray = array( array( 'cookieName' => Mage_XmlConnect_Model_Application::APP_CODE_COOKIE_NAME, 'paramName' => Mage_XmlConnect_Model_Application::APP_CODE_COOKIE_NAME, - 'value' => $app->getCode()), + 'value' => $app->getCode() + ), array( 'cookieName' => Mage_XmlConnect_Model_Application::APP_SCREEN_SIZE_NAME, 'paramName' => Mage_XmlConnect_Model_Application::APP_SCREEN_SIZE_NAME, - 'value' => $app->getScreenSize()) - ); + 'value' => $app->getScreenSize() + )); + foreach ($cookieToSetArray as $item) { if (!isset($_COOKIE[$item['cookieName']]) || $_COOKIE[$item['cookieName']] != $this->getRequest()->getParam($item['paramName']) @@ -105,13 +110,7 @@ protected function _initCookies(Mage_XmlConnect_Model_Application $app) */ $cookieExpireOffset = 3600 * 24 * 30; Mage::getSingleton('core/cookie')->set( - $item['cookieName'], - $item['value'], - $cookieExpireOffset, - '/', - null, - null, - true + $item['cookieName'], $item['value'], $cookieExpireOffset, '/', null, null, true ); } } @@ -120,7 +119,7 @@ protected function _initCookies(Mage_XmlConnect_Model_Application $app) /** * Default action * - * @return void + * @return null */ public function indexAction() { @@ -143,14 +142,10 @@ public function indexAction() $this->loadLayout(false); $this->renderLayout(); } catch (Mage_Core_Exception $e) { - $this->_message( - $e->getMessage(), - Mage_XmlConnect_Controller_Action::MESSAGE_STATUS_ERROR - ); + $this->_message($e->getMessage(), Mage_XmlConnect_Controller_Action::MESSAGE_STATUS_ERROR); } catch (Exception $e) { $this->_message( - $this->__('Can\'t show configuration.'), - Mage_XmlConnect_Controller_Action::MESSAGE_STATUS_ERROR + $this->__('Can\'t show configuration.'), Mage_XmlConnect_Controller_Action::MESSAGE_STATUS_ERROR ); Mage::logException($e); } @@ -161,15 +156,14 @@ public function indexAction() * * @param string $text * @param string $status - * @param string $type - * @param string $action - * @return void + * @return null */ - protected function _message($text, $status, $type='', $action='') + protected function _message($text, $status) { + /** @var $message Mage_XmlConnect_Model_Simplexml_Element */ $message = Mage::getModel('xmlconnect/simplexml_element', ''); - $message->addChild('status', $status); - $message->addChild('text', $text); + $message->addCustomChild('status', $status); + $message->addCustomChild('text', $text); $this->getResponse()->setBody($message->asNiceXml()); } } diff --git a/app/code/core/Mage/XmlConnect/controllers/CustomerController.php b/app/code/core/Mage/XmlConnect/controllers/CustomerController.php index 12591cdbc2..35ce112d60 100644 --- a/app/code/core/Mage/XmlConnect/controllers/CustomerController.php +++ b/app/code/core/Mage/XmlConnect/controllers/CustomerController.php @@ -34,9 +34,9 @@ class Mage_XmlConnect_CustomerController extends Mage_XmlConnect_Controller_Action { /** - * Customer authentification action + * Customer authentication action * - * @return void + * @return null */ public function loginAction() { @@ -63,6 +63,7 @@ public function loginAction() switch ($e->getCode()) { case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED: // TODO: resend confirmation email message with action + $message = $e->getMessage(); break; case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD: $message = $e->getMessage(); @@ -82,7 +83,7 @@ public function loginAction() /** * Customer logout * - * @return void + * @return null */ public function logoutAction() { @@ -92,6 +93,7 @@ public function logoutAction() } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); } catch (Exception $e) { + Mage::logException($e); $this->_message($this->__('Customer logout problem.'), self::MESSAGE_STATUS_ERROR); } } @@ -99,42 +101,52 @@ public function logoutAction() /** * Customer registration/edit account form * - * @return void + * @return null */ public function formAction() { - $customer = null; - $editFlag = (int)$this->getRequest()->getParam('edit'); - if ($editFlag == 1) { - if (!$this->_getSession()->isLoggedIn()) { - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); - return; + try { + $customer = null; + $editFlag = (int)$this->getRequest()->getParam('edit'); + if ($editFlag == 1) { + if (!$this->_getSession()->isLoggedIn()) { + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); + return; + } + $customer = $this->_getSession()->getCustomer(); } - $customer = $this->_getSession()->getCustomer(); - } - $this->loadLayout(false)->getLayout()->getBlock('xmlconnect.customer.form')->setCustomer($customer); - $this->renderLayout(); + $this->loadLayout(false)->getLayout()->getBlock('xmlconnect.customer.form')->setCustomer($customer); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + Mage::logException($e); + $this->_message($this->__('Can\'t load customer form.'), self::MESSAGE_STATUS_ERROR); + } } /** * Change customer data action * - * @return void + * @return null */ public function editAction() { if (!$this->_getSession()->isLoggedIn()) { - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); - return ; + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); + return; } if ($this->getRequest()->isPost()) { $customer = $this->_getSession()->getCustomer(); /* @var $customerForm Mage_Customer_Model_Form */ $customerForm = Mage::getModel('customer/form'); - $customerForm->setFormCode('customer_account_edit') - ->setEntity($customer); + $customerForm->setFormCode('customer_account_edit')->setEntity($customer); $customerData = $customerForm->extractData($this->getRequest()); @@ -165,7 +177,7 @@ public function editAction() $oldPass = $this->_getSession()->getCustomer()->getPasswordHash(); if (strpos($oldPass, ':')) { - list($_salt, $salt) = explode(':', $oldPass); + list(, $salt) = explode(':', $oldPass); } else { $salt = false; } @@ -208,7 +220,7 @@ public function editAction() /** * Save customer account * - * @return void + * @return null */ public function saveAction() { @@ -231,8 +243,7 @@ public function saveAction() /* @var $customerForm Mage_Customer_Model_Form */ $customerForm = Mage::getModel('customer/form'); - $customerForm->setFormCode('customer_account_create') - ->setEntity($customer); + $customerForm->setFormCode('customer_account_create')->setEntity($customer); $customerData = $customerForm->extractData($this->getRequest()); @@ -290,7 +301,7 @@ public function saveAction() $message = $this->__('Invalid customer data.'); } $this->_message($message, self::MESSAGE_STATUS_ERROR); - return ; + return; } } catch (Mage_Core_Exception $e) { if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) { @@ -309,7 +320,7 @@ public function saveAction() /** * Send new password to customer by specified email * - * @return void + * @return null */ public function forgotPasswordAction() { @@ -319,8 +330,7 @@ public function forgotPasswordAction() $this->_message($this->__('Invalid email address.'), self::MESSAGE_STATUS_ERROR); return; } - $customer = Mage::getModel('customer/customer') - ->setWebsiteId(Mage::app()->getStore()->getWebsiteId()) + $customer = Mage::getModel('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId()) ->loadByEmail($email); if ($customer->getId()) { @@ -329,22 +339,19 @@ public function forgotPasswordAction() $customer->changePassword($newPassword, false); $customer->sendPasswordReminderEmail(); $this->_message( - $this->__('A new password has been sent.'), - self::MESSAGE_STATUS_SUCCESS + $this->__('A new password has been sent.'), self::MESSAGE_STATUS_SUCCESS ); return; } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); } catch (Exception $e) { $this->_message( - $this->__('Problem changing or sending password.'), - self::MESSAGE_STATUS_ERROR + $this->__('Problem changing or sending password.'), self::MESSAGE_STATUS_ERROR ); } } else { $this->_message( - $this->__('This email address was not found in our records.'), - self::MESSAGE_STATUS_ERROR + $this->__('This email address was not found in our records.'), self::MESSAGE_STATUS_ERROR ); } } else { @@ -355,18 +362,28 @@ public function forgotPasswordAction() /** * Customer addresses list * - * @return void + * @return null */ public function addressAction() { if (!$this->_getSession()->isLoggedIn()) { - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); - return ; + Mage::log('address:'.$this->_getSession()->getSessionId()); + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); + return; } if (count($this->_getSession()->getCustomer()->getAddresses())) { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load addresses.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } else { /** @var $message Mage_XmlConnect_Model_Simplexml_Element */ $message = Mage::getModel('xmlconnect/simplexml_element', ''); @@ -379,43 +396,56 @@ public function addressAction() /** * Customer add/edit address form * - * @return void + * @return null */ public function addressFormAction() { - if (!$this->_getSession()->isLoggedIn()) { - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); - return ; - } + try { + if (!$this->_getSession()->isLoggedIn()) { + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); + return; + } - $address = Mage::getModel('customer/address'); + $address = Mage::getModel('customer/address'); - /** - * Init address object - */ - $addressId = (int)$this->getRequest()->getParam('id'); - if ($addressId) { - $address->load($addressId); - if ($address->getCustomerId() != $this->_getSession()->getCustomerId()) { - $this->_message($this->__('Specified address does not exist.'), self::MESSAGE_STATUS_ERROR); - return ; + /** + * Init address object + */ + $addressId = (int)$this->getRequest()->getParam('id'); + if ($addressId) { + $address->load($addressId); + if ($address->getCustomerId() != $this->_getSession()->getCustomerId()) { + $this->_message($this->__('Specified address does not exist.'), self::MESSAGE_STATUS_ERROR); + return; + } } - } - $this->loadLayout(false)->getLayout()->getBlock('xmlconnect.customer.address.form')->setAddress($address); - $this->renderLayout(); + $this->loadLayout(false)->getLayout()->getBlock('xmlconnect.customer.address.form')->setAddress($address); + + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } catch (Exception $e) { + Mage::logException($e); + $this->_message($this->__('Can\'t load customer form.'), self::MESSAGE_STATUS_ERROR); + } } /** * Remove customer address * - * @return void + * @return null */ public function deleteAddressAction() { if (!$this->_getSession()->isLoggedIn()) { - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); - return ; + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); + return; } $addressId = $this->getRequest()->getParam('id', false); @@ -442,12 +472,14 @@ public function deleteAddressAction() /** * Add/Save customer address * - * @return void + * @return null */ public function saveAddressAction() { if (!$this->_getSession()->isLoggedIn()) { - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); return; } @@ -491,7 +523,7 @@ public function saveAddressAction() if (true === $addressValidation) { $address->save(); - + /** @var $message Mage_XmlConnect_Model_Simplexml_Element */ $message = Mage::getModel('xmlconnect/simplexml_element', ''); $message->addChild('status', self::MESSAGE_STATUS_SUCCESS); $message->addChild('text', $this->__('Address has been saved.')); @@ -519,35 +551,46 @@ public function saveAddressAction() /** * Customer orders list * - * @return void + * @return null */ public function orderListAction() { if (!$this->_getSession()->isLoggedIn()) { - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); - return ; + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); + return; } - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load order list.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Customer order details * - * @return void + * @return null */ public function orderDetailsAction() { try { if (!$this->_getSession()->isLoggedIn()) { - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); return; } $orderId = (int) $this->getRequest()->getParam('order_id'); if (!$orderId) { - $this->_message($this->__('Order id not specified.'), self::MESSAGE_STATUS_ERROR); + $this->_message($this->__('Order id is not specified.'), self::MESSAGE_STATUS_ERROR); return; } @@ -580,9 +623,7 @@ protected function _canViewOrder($order) { $customerId = Mage::getSingleton('customer/session')->getCustomerId(); $availableStates = Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates(); - if ($order->getId() - && $order->getCustomerId() - && ($order->getCustomerId() == $customerId) + if ($order->getId() && $order->getCustomerId() && ($order->getCustomerId() == $customerId) && in_array($order->getState(), $availableStates, true) ) { return true; @@ -593,7 +634,7 @@ protected function _canViewOrder($order) /** * Check if customer is loggined * - * @return void + * @return null */ public function isLogginedAction() { @@ -624,4 +665,114 @@ protected function _getSession() { return Mage::getSingleton('customer/session'); } + + /** + * Store Credit info + * + * @return null + */ + public function storeCreditAction() + { + try { + /** + * Check is available Customer Balance + */ + if (!is_object(Mage::getConfig()->getNode('modules/Enterprise_CustomerBalance'))) { + $this->_message( + $this->__('Customer balance available in enterprise version of Magento only.'), + self::MESSAGE_STATUS_ERROR + ); + return; + } + $this->loadLayout(false); + $this->renderLayout(); + return; + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to render the store credits.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } + + /** + * Check Gift card action + * + * @return null + */ + public function giftcardCheckAction() + { + try { + /** + * Check is available Customer Balance + */ + if (!is_object(Mage::getConfig()->getNode('modules/Enterprise_GiftCardAccount'))) { + $this->_message( + $this->__('Gift card account available in enterprise version of Magento only.'), + self::MESSAGE_STATUS_ERROR + ); + return; + } + /* @var $card Enterprise_GiftCardAccount_Model_Giftcardaccount */ + $card = Mage::getModel('enterprise_giftcardaccount/giftcardaccount') + ->loadByCode($this->getRequest()->getParam('giftcard_code', '')); + Mage::register('current_giftcardaccount', $card); + + $card->isValid(true, true, true, false); + + $this->loadLayout(false); + $this->renderLayout(); + return; + } catch (Mage_Core_Exception $e) { + $card->unsetData(); + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to render a gift card account.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } + + /** + * Redeem Gift card action + * + * @return null + */ + public function giftcardRedeemAction() + { + try { + /** + * Check is available Customer Balance + */ + if (!is_object(Mage::getConfig()->getNode('modules/Enterprise_GiftCardAccount'))) { + $this->_message( + $this->__('Gift card account available in enterprise version of Magento only.'), + self::MESSAGE_STATUS_ERROR + ); + return; + } + + $code = $this->getRequest()->getParam('giftcard_code', ''); + if ($code) { + if (!Mage::helper('enterprise_customerbalance')->isEnabled()) { + Mage::throwException($this->__('Redemption functionality is disabled.')); + } + Mage::getModel('enterprise_giftcardaccount/giftcardaccount')->loadByCode($code) + ->setIsRedeemed(true)->redeem(); + + $this->_message( + $this->__('Gift Card "%s" was redeemed.', Mage::helper('core')->escapeHtml($code)), + self::MESSAGE_STATUS_SUCCESS + ); + } + return; + } catch (Mage_Core_Exception $e) { + if (isset($card) && is_object($card)) { + $card->unsetData(); + } + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Cannot redeem Gift Card.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } } diff --git a/app/code/core/Mage/XmlConnect/controllers/IndexController.php b/app/code/core/Mage/XmlConnect/controllers/IndexController.php index 8bbc928b3f..f4c8c2281b 100644 --- a/app/code/core/Mage/XmlConnect/controllers/IndexController.php +++ b/app/code/core/Mage/XmlConnect/controllers/IndexController.php @@ -27,18 +27,27 @@ /** * XmlConnect index controller * - * @author Magento Core Team + * @category Mage + * @package Mage_Xmlconnect + * @author Magento Core Team */ class Mage_XmlConnect_IndexController extends Mage_XmlConnect_Controller_Action { /** * Default action * - * @return void + * @return null */ public function indexAction() { - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load categories.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } } diff --git a/app/code/core/Mage/XmlConnect/controllers/Paypal/MeclController.php b/app/code/core/Mage/XmlConnect/controllers/Paypal/MeclController.php new file mode 100644 index 0000000000..9fa4427ca7 --- /dev/null +++ b/app/code/core/Mage/XmlConnect/controllers/Paypal/MeclController.php @@ -0,0 +1,410 @@ + + */ +class Mage_XmlConnect_Paypal_MeclController extends Mage_XmlConnect_Controller_Action +{ + /** + * Config mode type + * + * @var string + */ + protected $_configType = 'xmlconnect/payment_method_paypal_config'; + + /** + * Config method type + * + * @var string + */ + protected $_configMethod = Mage_XmlConnect_Model_Payment_Method_Paypal_Mecl::MECL_METHOD_CODE; + + /** + * Checkout mode type + * + * @var string + */ + protected $_checkoutType = 'xmlconnect/paypal_mecl_checkout'; + + /** + * Paypal Mobile Express Checkout Library + * + * @var Mage_XmlConnect_Model_Payment_Method_Paypal_Mecl + */ + protected $_checkout = null; + + /** + * PayPal Mobile Express Checkout Library config model + * + * @var Mage_XmlConnect_Model_Payment_Method_Paypal_Config + */ + protected $_config = null; + + /** + * Checkout Quote + * + * @var Mage_Sales_Model_Quote + */ + protected $_quote = false; + + /** + * Instantiate config + */ + protected function _construct() + { + parent::_construct(); + $this->_config = Mage::getModel($this->_configType, array($this->_configMethod)); + } + + /** + * Make sure customer is logged in + * + * @return null + */ + public function preDispatch() + { + parent::preDispatch(); + if (!Mage::getSingleton('customer/session')->isLoggedIn() + && !Mage::getSingleton('checkout/session')->getQuote()->isAllowedGuestCheckout() + ) { + $this->setFlag('', self::FLAG_NO_DISPATCH, true); + $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, + array('logged_in' => '0') + ); + return; + } + } + + /** + * Start Mobile Express Checkout by requesting initial token and dispatching customer to PayPal + */ + public function startAction() + { + try { + $this->_initCheckout(); + + $customer = Mage::getSingleton('customer/session')->getCustomer(); + if ($customer && $customer->getId()) { + $this->_checkout->setCustomerWithAddressChange( + $customer, null, $this->_getQuote()->getShippingAddress() + ); + } + + $token = $this->_checkout->start(Mage::getUrl('*/*/return'), Mage::getUrl('*/*/cancel')); + + if ($token) { + $this->_initToken($token); + /** @var $message Mage_XmlConnect_Model_Simplexml_Element */ + $message = Mage::getModel('xmlconnect/simplexml_element', ''); + $message->addChild('status', self::MESSAGE_STATUS_SUCCESS); + $message->addChild('token', $token); + $this->getResponse()->setBody($message->asNiceXml()); + } else { + $this->_message($this->__('Token has not been set.'), self::MESSAGE_STATUS_ERROR); + } + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to start Mobile Express Checkout.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } + + /** + * Return from PayPal and dispatch customer to order review page + * (GetExpressCheckoutDetails method call) + */ + public function returnAction() + { + try { + $this->_initCheckout(); + $this->_checkout->returnFromPaypal($this->_initToken()); + $this->_message($this->__('Mobile Express Checkout processed successfully.'), self::MESSAGE_STATUS_SUCCESS); + return; + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + Mage::logException($e); + $this->_message($this->__('Unable to initialize return action.'), self::MESSAGE_STATUS_ERROR); + } + } + + /** + * Review order after returning from PayPal + */ + public function reviewAction() + { + try { + $this->_initCheckout(); + $this->_checkout->prepareOrderReview($this->_initToken()); + $this->loadLayout(false); + $this->_initLayoutMessages('paypal/session'); + + $messages = $this->_getSession()->getMessages(true); + $messageArray = array(); + foreach ($messages->getItems() as $message) { + $messageArray[] = $message; + } + + $detailsBlock = $this->getLayout()->getBlock('xmlconnect.cart.paypal.mecl.review'); + if (count($messageArray)) { + $detailsBlock->setPaypalMessages($messageArray); + } + + $detailsBlock->setQuote($this->_getQuote())->getChild('details')->setQuote($this->_getQuote()) + ->getChild('totals')->setQuote($this->_getQuote()); + $this->renderLayout(); + return; + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to initialize express checkout review.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } + + /** + * Get shipping method list for PayPal + */ + public function shippingMethodsAction() + { + try { + $this->_initCheckout(); + $this->_checkout->prepareOrderReview($this->_initToken()); + $this->loadLayout(false); + + $this->getLayout()->getBlock('xmlconnect.cart.paypal.mecl.shippingmethods')->setQuote($this->_getQuote()); + $this->renderLayout(); + return; + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message( + $this->__('Unable to initialize express checkout shipping method list.'), + self::MESSAGE_STATUS_ERROR + ); + Mage::logException($e); + } + } + + /** + * Update shipping method (combined action for ajax and regular request) + */ + public function saveShippingMethodAction() + { + try { + $this->_initCheckout(); + if ($this->getRequest()->getParam('shipping_method', false)) { + $this->_checkout->updateShippingMethod($this->getRequest()->getParam('shipping_method')); + $this->_message($this->__('Shipping method successfully updated'), self::MESSAGE_STATUS_SUCCESS); + } else { + $this->_message($this->__('Shipping method is required'), self::MESSAGE_STATUS_ERROR); + } + return; + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to update shipping method.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } + + /** + * Submit the order + */ + public function placeOrderAction() + { + try { + $this->_initCheckout(); + $this->_checkout->place($this->_initToken()); + + // prepare session to success or cancellation page + $session = $this->_getCheckoutSession(); + $session->clearHelperData(); + + // "last successful quote" + $quoteId = $this->_getQuote()->getId(); + $session->setLastQuoteId($quoteId)->setLastSuccessQuoteId($quoteId); + + // an order may be created + $order = $this->_checkout->getOrder(); + if ($order) { + $orderId = $order->getId(); + $realOrderId = $order->getIncrementId(); + $session->setLastOrderId($order->getId())->setLastRealOrderId($order->getIncrementId()); + } + + // recurring profiles may be created along with the order or without it + $profiles = $this->_checkout->getRecurringPaymentProfiles(); + if ($profiles) { + $ids = array(); + foreach($profiles as $profile) { + $ids[] = $profile->getId(); + } + $session->setLastRecurringProfileIds($ids); + } + + $this->_initToken(false); // no need in token anymore + + /** @var $message Mage_XmlConnect_Model_Simplexml_Element */ + $message = Mage::getModel('xmlconnect/simplexml_element', ''); + $message->addChild('status', self::MESSAGE_STATUS_SUCCESS); + + $text = $this->__('Thank you for your purchase! '); + $text .= $this->__('Your order # is: %s. ', $realOrderId); + $text .= $this->__('You will receive an order confirmation email with details of your order and a link to track its progress.'); + $message->addChild('text', $text); + $message->addChild('order_id', $orderId); + $this->getResponse()->setBody($message->asNiceXml()); + return; + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to place the order.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } + + /** + * Cancel Mobile Express Checkout + */ + public function cancelAction() + { + try { + $this->_initToken(false); + // if there is an order - cancel it + $orderId = $this->_getCheckoutSession()->getLastOrderId(); + $order = ($orderId) ? Mage::getModel('sales/order')->load($orderId) : false; + + if ($order && $order->getId() && $order->getQuoteId() == $this->_getCheckoutSession()->getQuoteId()) { + $order->cancel()->save(); + $this->_getCheckoutSession()->unsLastQuoteId()->unsLastSuccessQuoteId()->unsLastOrderId() + ->unsLastRealOrderId(); + } + + $this->_message($this->__('Mobile Express Checkout has been canceled.'), self::MESSAGE_STATUS_SUCCESS); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to cancel Mobile Express Checkout.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } + } + + /** + * Instantiate quote and checkout + * + * @throws Mage_Core_Exception + * @return null + */ + protected function _initCheckout() + { + $quote = $this->_getQuote(); + if (!$quote->hasItems() || $quote->getHasError()) { + Mage::throwException($this->__('Unable to initialize PayPal Mobile Express Checkout.')); + } + if (!$quote->validateMinimumAmount()) { + $error = Mage::getStoreConfig('sales/minimum_order/error_message'); + Mage::throwException($error); + } + $this->_getCheckoutSession()->setCartWasUpdated(false); + + $this->_checkout = Mage::getSingleton($this->_checkoutType, array( + 'config' => $this->_config, 'quote' => $quote + )); + } + + /** + * Return checkout session object + * + * @return Mage_Checkout_Model_Session + */ + protected function _getCheckoutSession() + { + return Mage::getSingleton('checkout/session'); + } + + /** + * Return checkout quote object + * + * @return Mage_Sale_Model_Quote + */ + protected function _getQuote() + { + if (!$this->_quote) { + $this->_quote = $this->_getCheckoutSession()->getQuote(); + } + return $this->_quote; + } + + /** + * Search for proper checkout token in request or session or (un)set specified one + * Combined getter/setter + * + * @throws Mage_Core_Exception + * @param string $setToken + * @return Mage_Paypal_ExpressController|string + */ + protected function _initToken($setToken = null) + { + if (null !== $setToken) { + if (false === $setToken) { + if (!$this->_getSession()->getExpressCheckoutToken()) { // security measure for avoid unset token twice + Mage::throwException($this->__('PayPal Mobile Express Checkout Token does not exist.')); + } + $this->_getSession()->unsExpressCheckoutToken(); + } else { + $this->_getSession()->setExpressCheckoutToken($setToken); + } + return $this; + } + + $setToken = $this->getRequest()->getParam('token'); + if ($setToken) { + if ($setToken !== $this->_getSession()->getExpressCheckoutToken()) { + Mage::throwException($this->__('Wrong PayPal Mobile Express Checkout Token specified.')); + } + } else { + $setToken = $this->_getSession()->getExpressCheckoutToken(); + } + return $setToken; + } + + /** + * PayPal session instance getter + * + * @return Mage_PayPal_Model_Session + */ + private function _getSession() + { + return Mage::getSingleton('paypal/session'); + } +} diff --git a/app/code/core/Mage/XmlConnect/controllers/Paypal/MepController.php b/app/code/core/Mage/XmlConnect/controllers/Paypal/MepController.php index 7b35f5e25b..9ae6d5b99e 100644 --- a/app/code/core/Mage/XmlConnect/controllers/Paypal/MepController.php +++ b/app/code/core/Mage/XmlConnect/controllers/Paypal/MepController.php @@ -50,7 +50,7 @@ class Mage_XmlConnect_Paypal_MepController extends Mage_XmlConnect_Controller_Ac /** * Make sure customer is logged in * - * @return void + * @return null */ public function preDispatch() { @@ -59,33 +59,43 @@ public function preDispatch() && !Mage::getSingleton('checkout/session')->getQuote()->isAllowedGuestCheckout() ) { $this->setFlag('', self::FLAG_NO_DISPATCH, true); - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); - return ; + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); + return; } } /** * Start MEP Checkout * - * @return void + * @return null */ public function indexAction() { try { + if (is_object(Mage::getConfig()->getNode('modules/Enterprise_GiftCardAccount'))) { + $giftcardInfoBlock = $this->getLayout()->addBlock( + 'enterprise_giftcardaccount/checkout_onepage_payment_additional', 'giftcard_info' + ); + + if (intval($giftcardInfoBlock->getAppliedGiftCardAmount())) { + $this->_message( + $this->__('Paypal MEP doesn\'t support checkout with any discount.'), + self::MESSAGE_STATUS_ERROR + ); + return; + } + } + $this->_initCheckout(); $this->_checkout->initCheckout(); - $this->_message( - $this->__('Checkout has been initialized.'), - self::MESSAGE_STATUS_SUCCESS - ); + $this->_message($this->__('Checkout has been initialized.'), self::MESSAGE_STATUS_SUCCESS); return; } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); } catch (Exception $e) { - $this->_message( - $this->__('Unable to start MEP Checkout.'), - self::MESSAGE_STATUS_ERROR - ); + $this->_message($this->__('Unable to start MEP Checkout.'), self::MESSAGE_STATUS_ERROR); Mage::logException($e); } } @@ -93,7 +103,7 @@ public function indexAction() /** * Save shipping address to current quote using onepage model * - * @return void + * @return null */ public function saveShippingAddressAction() { @@ -131,10 +141,7 @@ public function saveShippingAddressAction() $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); Mage::logException($e); } catch (Exception $e) { - $this->_message( - $this->__('Unable to save shipping address.'), - self::MESSAGE_STATUS_ERROR - ); + $this->_message($this->__('Unable to save shipping address.'), self::MESSAGE_STATUS_ERROR); Mage::logException($e); } } @@ -142,7 +149,7 @@ public function saveShippingAddressAction() /** * Get shipping methods for current quote * - * @return void + * @return null */ public function shippingMethodsAction() { @@ -153,10 +160,7 @@ public function shippingMethodsAction() } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); } catch (Exception $e) { - $this->_message( - $this->__('Unable to get shipping methods list.'), - self::MESSAGE_STATUS_ERROR - ); + $this->_message($this->__('Unable to get shipping methods list.'), self::MESSAGE_STATUS_ERROR); Mage::logException($e); } } @@ -164,7 +168,7 @@ public function shippingMethodsAction() /** * Shipping method save action * - * @return void + * @return null */ public function saveShippingMethodAction() { @@ -176,12 +180,9 @@ public function saveShippingMethodAction() try { $this->_initCheckout(); $data = $this->getRequest()->getPost('shipping_method', ''); - $this->_quote->getShippingAddress() - ->setShippingMethod($data) - ->setCollectShippingRates(true) - ->save(); - + $this->_getQuote()->getShippingAddress()->setShippingMethod($data)->setCollectShippingRates(true)->save(); $result = $this->_checkout->saveShippingMethod($data); + if (!isset($result['error'])) { /** @var $message Mage_XmlConnect_Model_Simplexml_Element */ $message = Mage::getModel('xmlconnect/simplexml_element', ''); @@ -192,15 +193,9 @@ public function saveShippingMethodAction() } else { $quoteAddress = $this->_getQuote()->getShippingAddress(); } - $taxAmount = Mage::helper('core')->currency( - $quoteAddress->getBaseTaxAmount(), - false, - false - ); - $message->addChild( - 'tax_amount', - Mage::helper('xmlconnect')->formatPriceForXml($taxAmount) - ); + $taxAmount = Mage::helper('core')->currency($quoteAddress->getBaseTaxAmount(), false, false); + $message->addChild('tax_amount', Mage::helper('xmlconnect')->formatPriceForXml($taxAmount)); + $this->_getQuote()->collectTotals()->save(); $this->getResponse()->setBody($message->asNiceXml()); } else { if (!is_array($result['message'])) { @@ -211,10 +206,7 @@ public function saveShippingMethodAction() } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); } catch (Exception $e) { - $this->_message( - $this->__('Unable to save shipping method.'), - self::MESSAGE_STATUS_ERROR - ); + $this->_message($this->__('Unable to save shipping method.'), self::MESSAGE_STATUS_ERROR); Mage::logException($e); } } @@ -222,7 +214,7 @@ public function saveShippingMethodAction() /** * Shopping cart totals * - * @return void + * @return null */ public function cartTotalsAction() { @@ -242,7 +234,7 @@ public function cartTotalsAction() /** * Submit the order * - * @return void + * @return null */ public function saveOrderAction() { @@ -263,9 +255,7 @@ public function saveOrderAction() $data = $this->getRequest()->getPost('payment', array()); if (Mage::getSingleton('customer/session')->isLoggedIn()) { - $data['payer'] = Mage::getSingleton('customer/session') - ->getCustomer() - ->getEmail(); + $data['payer'] = Mage::getSingleton('customer/session')->getCustomer()->getEmail(); } $this->_checkout->savePayment($data); @@ -304,7 +294,7 @@ public function saveOrderAction() * Instantiate quote and checkout * * @throws Mage_Core_Exception - * @return void + * @return null */ protected function _initCheckout() { diff --git a/app/code/core/Mage/XmlConnect/controllers/PbridgeController.php b/app/code/core/Mage/XmlConnect/controllers/PbridgeController.php index 398050564a..8a33ad5a1f 100755 --- a/app/code/core/Mage/XmlConnect/controllers/PbridgeController.php +++ b/app/code/core/Mage/XmlConnect/controllers/PbridgeController.php @@ -72,7 +72,7 @@ protected function _checkPbridge() * Index Action. * Forward to result action * - * @return void + * @return null */ public function indexAction() { @@ -82,7 +82,7 @@ public function indexAction() /** * Result Action * - * @return void + * @return null */ public function resultAction() { @@ -131,8 +131,6 @@ public function outputAction() EOT; } - $this->getResponse()->setBody( - html_entity_decode(Mage::helper('xmlconnect')->htmlize($body)) - ); + $this->getResponse()->setBody(html_entity_decode(Mage::helper('xmlconnect')->htmlize($body))); } } diff --git a/app/code/core/Mage/XmlConnect/controllers/ReviewController.php b/app/code/core/Mage/XmlConnect/controllers/ReviewController.php index 0a0d2f8268..0c99bdcb62 100644 --- a/app/code/core/Mage/XmlConnect/controllers/ReviewController.php +++ b/app/code/core/Mage/XmlConnect/controllers/ReviewController.php @@ -27,7 +27,9 @@ /** * XmlConnect review controller * - * @author Magento Core Team + * @category Mage + * @package Mage_Xmlconnect + * @author Magento Core Team */ class Mage_XmlConnect_ReviewController extends Mage_XmlConnect_Controller_Action { @@ -38,22 +40,17 @@ class Mage_XmlConnect_ReviewController extends Mage_XmlConnect_Controller_Action */ protected function _initProduct() { - Mage::dispatchEvent('review_controller_product_init_before', array('controller_action'=>$this)); + Mage::dispatchEvent('review_controller_product_init_before', array('controller_action' => $this)); + $productId = (int) $this->getRequest()->getParam('id'); $product = $this->_loadProduct($productId); try { - Mage::dispatchEvent( - 'review_controller_product_init', - array('product' => $product) - ); - Mage::dispatchEvent( - 'review_controller_product_init_after', - array( - 'product' => $product, - 'controller_action' => $this - ) - ); + Mage::dispatchEvent('review_controller_product_init', array('product' => $product)); + Mage::dispatchEvent('review_controller_product_init_after', array( + 'product' => $product, + 'controller_action' => $this + )); } catch (Mage_Core_Exception $e) { Mage::logException($e); return false; @@ -75,9 +72,7 @@ protected function _loadProduct($productId) return false; } - $product = Mage::getModel('catalog/product') - ->setStoreId(Mage::app()->getStore()->getId()) - ->load($productId); + $product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($productId); /** @var $product Mage_Catalog_Model_Product */ if (!$product->getId() || !$product->isVisibleInCatalog() || !$product->isVisibleInSiteVisibility()) { return false; @@ -98,9 +93,7 @@ protected function _loadProduct($productId) */ protected function _checkGuestAllowed() { - if (Mage::getSingleton('customer/session')->isLoggedIn() - || Mage::helper('review')->getIsGuestAllowToWrite() - ) { + if (Mage::getSingleton('customer/session')->isLoggedIn() || Mage::helper('review')->getIsGuestAllowToWrite()) { return true; } @@ -114,7 +107,7 @@ protected function _checkGuestAllowed() /** * Get review form * - * @return void + * @return null */ public function formAction() { @@ -122,14 +115,21 @@ public function formAction() return; } - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + $this->_message($this->__('Unable to load review form.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + } } /** * Save product review * - * @return void + * @return null */ public function saveAction() { @@ -140,39 +140,38 @@ public function saveAction() $data = $this->getRequest()->getPost(); $rating = $this->getRequest()->getPost('ratings', array()); - if (($product = $this->_initProduct()) && !empty($data)) { + $product = $this->_initProduct(); + if ($product && !empty($data)) { /** @var $review Mage_Review_Model_Review */ $review = Mage::getModel('review/review')->setData($data); + $validate = $review->validate(); - if (($validate = $review->validate()) === true) { + if ($validate === true) { try { $review->setEntityId($review->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE)) - ->setEntityPkValue($product->getId()) - ->setStatusId(Mage_Review_Model_Review::STATUS_PENDING) + ->setEntityPkValue($product->getId())->setStatusId(Mage_Review_Model_Review::STATUS_PENDING) ->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId()) ->setStoreId(Mage::app()->getStore()->getId()) - ->setStores(array(Mage::app()->getStore()->getId())) - ->save(); + ->setStores(array(Mage::app()->getStore()->getId()))->save(); foreach ($rating as $ratingId => $optionId) { - Mage::getModel('rating/rating') - ->setRatingId($ratingId) - ->setReviewId($review->getId()) + Mage::getModel('rating/rating')->setRatingId($ratingId)->setReviewId($review->getId()) ->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId()) ->addOptionVote($optionId, $product->getId()); } $review->aggregate(); $this->_message( - $this->__('Your review has been accepted for moderation.'), - self::MESSAGE_STATUS_SUCCESS + $this->__('Your review has been accepted for moderation.'), self::MESSAGE_STATUS_SUCCESS ); } catch (Exception $e) { $this->_message($this->__('Unable to post the review.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); } } else { if (is_array($validate)) { - $this->_message(implode('. ', $validate), self::MESSAGE_STATUS_ERROR); + $validate = array_map(array($this, '_trimDot'), $validate); + $this->_message(implode('. ', $validate) . '.', self::MESSAGE_STATUS_ERROR); } else { $this->_message($this->__('Unable to post the review.'), self::MESSAGE_STATUS_ERROR); } @@ -181,4 +180,15 @@ public function saveAction() $this->_message($this->__('Unable to post the review.'), self::MESSAGE_STATUS_ERROR); } } + + /** + * Trim ending dot (the ".") symbol from string + * + * @param string $text + * @return string + */ + private function _trimDot($text) + { + return trim($text, " \n\r\t."); + } } diff --git a/app/code/core/Mage/XmlConnect/controllers/WishlistController.php b/app/code/core/Mage/XmlConnect/controllers/WishlistController.php index 3037c58597..7fad737b17 100644 --- a/app/code/core/Mage/XmlConnect/controllers/WishlistController.php +++ b/app/code/core/Mage/XmlConnect/controllers/WishlistController.php @@ -36,14 +36,16 @@ class Mage_XmlConnect_WishlistController extends Mage_XmlConnect_Controller_Acti /** * Check if customer is logged in * - * @return void + * @return null */ public function preDispatch() { parent::preDispatch(); if (!$this->_getCustomerSession()->isLoggedIn()) { $this->setFlag('', self::FLAG_NO_DISPATCH, true); - $this->_message($this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR); + $this->_message( + $this->__('Customer not logged in.'), self::MESSAGE_STATUS_ERROR, array('logged_in' => '0') + ); return ; } } @@ -82,23 +84,32 @@ protected function _getWishlist() /** * Display customer wishlist * - * @return void + * @return null */ public function indexAction() { $this->_getWishlist(); - $this->loadLayout(false); - $this->renderLayout(); + try { + $this->loadLayout(false); + $this->renderLayout(); + } catch (Mage_Core_Exception $e) { + $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); + } catch (Exception $e) { + Mage::logException($e); + $this->_message( + $this->__('An error occurred while loading wishlist.'), + self::MESSAGE_STATUS_ERROR + ); + } } /** * Adding new item * - * @return void + * @return null */ public function addAction() { - $session = $this->_getCustomerSession(); $wishlist = $this->_getWishlist(); if (!$wishlist) { return; @@ -118,30 +129,39 @@ public function addAction() } try { - $item = $wishlist->addNewItem($product); + $buyRequest = new Varien_Object($this->getRequest()->getParams()); + $result = $wishlist->addNewItem($product, $buyRequest); if (strlen(trim((string)$request->getParam('description')))) { - $item->setDescription($request->getParam('description')) - ->save(); + $result->setDescription($request->getParam('description'))->save(); } $wishlist->save(); - Mage::dispatchEvent('wishlist_add_product', array('wishlist'=>$wishlist, 'product'=>$product)); + Mage::dispatchEvent('wishlist_add_product', array( + 'wishlist' => $wishlist, + 'product' => $product, + 'item' => $result + )); Mage::helper('wishlist')->calculate(); - $message = $this->__('%1$s has been added to your wishlist.', $product->getName()); - $this->_message($message, self::MESSAGE_STATUS_SUCCESS); + $this->_message( + $this->__('%1$s has been added to your wishlist.', $product->getName()), + self::MESSAGE_STATUS_SUCCESS + ); } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); } catch (Exception $e) { - $this->_message($this->__('An error occurred while adding item to wishlist.'), self::MESSAGE_STATUS_ERROR); + Mage::logException($e); + $this->_message( + $this->__('An error occurred while adding item to wishlist.'), self::MESSAGE_STATUS_ERROR + ); } } /** * Remove item * - * @return void + * @return null */ public function removeAction() { @@ -169,7 +189,7 @@ public function removeAction() /** * Clear wishlist action * - * @return void + * @return null */ public function clearAction() { @@ -185,7 +205,9 @@ public function clearAction() } catch (Mage_Core_Exception $e) { $this->_message($e->getMessage(), self::MESSAGE_STATUS_ERROR); } catch(Exception $e) { - $this->_message($this->__('An error occurred while removing items from wishlist.'), self::MESSAGE_STATUS_ERROR); + $this->_message( + $this->__('An error occurred while removing items from wishlist.'), self::MESSAGE_STATUS_ERROR + ); } Mage::helper('wishlist')->calculate(); @@ -194,7 +216,7 @@ public function clearAction() /** * Update wishlist item comments * - * @return void + * @return null */ public function updateAction() { @@ -234,7 +256,10 @@ public function updateAction() $this->_message($message, self::MESSAGE_STATUS_SUCCESS); } catch (Exception $e) { - $this->_message($this->__('Items were updated. But can\'t update wishlist.'), self::MESSAGE_STATUS_SUCCESS); + $this->_message( + $this->__('Items were updated. But can\'t update wishlist.'), + self::MESSAGE_STATUS_SUCCESS + ); } } else { $this->_message($this->__('No items were updated.'), self::MESSAGE_STATUS_ERROR); @@ -250,7 +275,7 @@ public function updateAction() * If Product has required options - item removed from wishlist and redirect * to product view page with message about needed defined required options * - * @return void + * @return null */ public function cartAction() { @@ -268,23 +293,20 @@ public function cartAction() return; } - /* @var $session Mage_Wishlist_Model_Session */ - $session = Mage::getSingleton('wishlist/session'); - $cart = Mage::getSingleton('checkout/cart'); - try { + $cart = Mage::getSingleton('checkout/cart'); $item->addToCart($cart, true); $cart->save()->getQuote()->collectTotals(); $wishlist->save(); - Mage::helper('wishlist')->calculate(); - $this->_message($this->__('Item has been added to cart.'), self::MESSAGE_STATUS_SUCCESS); + } catch (Mage_Core_Exception $e) { if ($e->getCode() == Mage_Wishlist_Model_Item::EXCEPTION_CODE_NOT_SALABLE) { $this->_message($this->__('Product(s) currently out of stock.'), self::MESSAGE_STATUS_ERROR); - } else if ($e->getCode() == Mage_Wishlist_Model_Item::EXCEPTION_CODE_HAS_REQUIRED_OPTIONS || - $e->getCode() == Mage_Wishlist_Model_Item::EXCEPTION_CODE_IS_GROUPED_PRODUCT) { + } else if ($e->getCode() == Mage_Wishlist_Model_Item::EXCEPTION_CODE_HAS_REQUIRED_OPTIONS + || $e->getCode() == Mage_Wishlist_Model_Item::EXCEPTION_CODE_IS_GROUPED_PRODUCT + ) { $item->delete(); $message = Mage::getModel('xmlconnect/simplexml_element', ''); diff --git a/app/code/core/Mage/XmlConnect/etc/config.xml b/app/code/core/Mage/XmlConnect/etc/config.xml index 42d5a5c103..339824ed87 100644 --- a/app/code/core/Mage/XmlConnect/etc/config.xml +++ b/app/code/core/Mage/XmlConnect/etc/config.xml @@ -29,6 +29,7 @@ 1.6.0.0 + 22.0 @@ -167,6 +168,13 @@ 0 paypal + + 1 + xmlconnect/payment_method_paypal_mecl + PayPal Mobile Express Checkout Library + 0 + paypal + 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/page/head.phtml b/app/design/adminhtml/default/default/template/page/head.phtml index c190c099f5..8f8b5ba647 100644 --- a/app/design/adminhtml/default/default/template/page/head.phtml +++ b/app/design/adminhtml/default/default/template/page/head.phtml @@ -1,6 +1,8 @@ +getCanLoadTinyMce()): ?> + +<?php echo htmlspecialchars(html_entity_decode($this->getTitle())) ?> - 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..7898e15828 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 @@
    • - __('Cancel URL: ') ?>
      - - getFrontendUrl('paypal/payflow/cancelPayment') ?> + __('Error URL: ') ?>
      +
      + getFrontendUrl('paypal/payflow/returnUrl') ?>
    • @@ -72,7 +72,7 @@
      __('Note:') ?>
      • - __('Do not set any fields in the Billing and Shipping Information block as editable in your Payflow accout.') ?> + __('Do not set any fields in the Billing and Shipping Information block as editable in your Payflow account.'); ?>
      • __('Do not enable AVS or CSC options. The do not work when using Payflow Link Silent Mode.') ?> @@ -81,7 +81,32 @@ __('If your Magento instance is used for multiple websites, you must configure a separate Payflow Link account for each website.') ?>
      • - __('Make sure that you configure the design settings for the Payflow Link form in your Payflow link account.') ?> + __('Please navigate to Hosted Checkout Pages - Customize menu and select Layout C.') ?> +
      • +
      + + + 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..53fefdb79f 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,21 @@ * @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/shipment/packaging/popup.phtml b/app/design/adminhtml/default/default/template/sales/order/shipment/packaging/popup.phtml index 0e064fb260..aacd90daba 100644 --- a/app/design/adminhtml/default/default/template/sales/order/shipment/packaging/popup.phtml +++ b/app/design/adminhtml/default/default/template/sales/order/shipment/packaging/popup.phtml @@ -80,6 +80,7 @@ document.observe("dom:loaded", function() {
  • - - - - - - - - - - + + + + + + + + + + + + + - + + + + + + + + + + + + + + + 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/default/template/widget/instance/js.phtml b/app/design/adminhtml/default/default/template/widget/instance/js.phtml index 7f0d09e733..fac6c64288 100644 --- a/app/design/adminhtml/default/default/template/widget/instance/js.phtml +++ b/app/design/adminhtml/default/default/template/widget/instance/js.phtml @@ -30,16 +30,16 @@ function setSettings(urlTemplate, typeElement, packageThemeElement) { templateSyntax = /(^|.|\r|\n)({{(\w+)}})/; var template = new Template(urlTemplate, templateSyntax); typeElement = $F(typeElement).replace(/\//g, "-"); - packageThemeElement = $F(packageThemeElement); - slashPosition = packageThemeElement.indexOf('/'); - if (slashPosition !== -1) { - mPackage = packageThemeElement.slice(0, slashPosition).replace(/\//g, "_"); - mTheme = packageThemeElement.slice(slashPosition+1, packageThemeElement.length).replace(/\//g, "_"); - } else { - mPackage = '' - mTheme = '' + packageThemeElement = $F(packageThemeElement).split(/\//g); + if(typeof packageThemeElement[0] == 'undefined' || typeof packageThemeElement[1] == 'undefined') { + alert('__('Undefined Design Package or Theme.'); ?>'); + return false; } - setLocation(template.evaluate({type:typeElement,mpackage:mPackage,mtheme:mTheme})); + setLocation(template.evaluate({ + 'type': typeElement, + 'package': packageThemeElement[0], + 'theme': packageThemeElement[1] + })); } function saveAndContinueEdit(){ editForm.submit($('edit_form').action+'back/edit/'); diff --git a/app/design/adminhtml/default/default/template/xmlconnect/edit/tab/design/preview/home_iphone.phtml b/app/design/adminhtml/default/default/template/xmlconnect/edit/tab/design/preview/home_iphone.phtml index edad855865..e04976a59c 100755 --- a/app/design/adminhtml/default/default/template/xmlconnect/edit/tab/design/preview/home_iphone.phtml +++ b/app/design/adminhtml/default/default/template/xmlconnect/edit/tab/design/preview/home_iphone.phtml @@ -42,11 +42,10 @@ $title9color = $previewModel->getConfigFontInfo('Title9/color'); $backgroundColor = $previewModel->getData('conf/body/backgroundColor'); $menImage = $previewModel->getPreviewImagesUrl('men.png'); $bannerImage = $previewModel->getBannerImage(); -$backgroundImage = $previewModel->getBackgroundImage(); ?>
    -
    +
    __("Carrier"); ?>
    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/catalog_msrp.xml b/app/design/frontend/base/default/layout/catalog_msrp.xml index bae705460e..4244b59a1a 100644 --- a/app/design/frontend/base/default/layout/catalog_msrp.xml +++ b/app/design/frontend/base/default/layout/catalog_msrp.xml @@ -73,6 +73,9 @@ Default layout, loads most of the pages + + + 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..10260440ff 100644 --- a/app/design/frontend/base/default/layout/paypal.xml +++ b/app/design/frontend/base/default/layout/paypal.xml @@ -134,10 +134,16 @@ Available logo types can be assigned with action="setLogoType": + + + + + + @@ -171,11 +177,12 @@ Available logo types can be assigned with action="setLogoType": - + + - + diff --git a/app/design/frontend/base/default/layout/paypaluk.xml b/app/design/frontend/base/default/layout/paypaluk.xml index 66e9b8686d..1566812990 100644 --- a/app/design/frontend/base/default/layout/paypaluk.xml +++ b/app/design/frontend/base/default/layout/paypaluk.xml @@ -122,11 +122,18 @@ + + + + + + + diff --git a/app/design/frontend/base/default/layout/xmlconnect.xml b/app/design/frontend/base/default/layout/xmlconnect.xml index f378615f7a..004d24bfc0 100644 --- a/app/design/frontend/base/default/layout/xmlconnect.xml +++ b/app/design/frontend/base/default/layout/xmlconnect.xml @@ -50,7 +50,7 @@ - + @@ -171,23 +171,28 @@ - - defaultxmlconnect/customer_order_item_renderer_default - groupedxmlconnect/customer_order_item_renderer_grouped - bundlexmlconnect/customer_order_item_renderer_bundle - downloadablexmlconnect/customer_order_item_renderer_downloadable - giftcardxmlconnect/customer_order_item_renderer_giftcard - - - + + defaultxmlconnect/customer_order_item_renderer_default + groupedxmlconnect/customer_order_item_renderer_grouped + bundlexmlconnect/customer_order_item_renderer_bundle + downloadablexmlconnect/customer_order_item_renderer_downloadable + giftcardxmlconnect/customer_order_item_renderer_giftcard + + + - - - + + + + + + + + @@ -266,6 +271,23 @@ + + + + + + defaultxmlconnect/cart_item_renderer + groupedxmlconnect/cart_item_renderer_grouped + configurablexmlconnect/cart_item_renderer_configurable + + + + + + + + + diff --git a/app/design/frontend/base/default/template/catalog/product/price_msrp_item.phtml b/app/design/frontend/base/default/template/catalog/product/price_msrp_item.phtml index fb464b2765..7937f0abad 100644 --- a/app/design/frontend/base/default/template/catalog/product/price_msrp_item.phtml +++ b/app/design/frontend/base/default/template/catalog/product/price_msrp_item.phtml @@ -42,6 +42,7 @@ $_product = $this->getProduct(); $_id = $_product->getId(); $_msrpPrice = ''; + $priceElementIdPrefix = $this->getPriceElementIdPrefix() ? $this->getPriceElementIdPrefix() : 'product-price-'; ?>
    helper('tax')->getPrice($_product, $_product->getMsrp()) ?> @@ -51,7 +52,7 @@ isShowPriceOnGesture($_product)): ?> - getIdSuffix(); ?> + getIdSuffix(); ?> getRandomString(20); ?> __('Click for price'); ?> 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/checkout/onepage/payment/methods.phtml b/app/design/frontend/base/default/template/checkout/onepage/payment/methods.phtml index 97c8063ee2..9cf2e1d693 100644 --- a/app/design/frontend/base/default/template/checkout/onepage/payment/methods.phtml +++ b/app/design/frontend/base/default/template/checkout/onepage/payment/methods.phtml @@ -32,12 +32,20 @@ */ ?>
    -getMethods() as $_method): $_code = $_method->getCode() ?> +getMethods(); + $oneMethod = count($methods) <= 1; +?> +getCode(); +?>
    - getMethods()) > 1 ): ?> + getSelectedMethodCode()==$_code): ?> checked="checked" class="radio" /> +
    @@ -53,5 +61,8 @@ //getChildChildHtml('scripts'); ?> payment.init(); + + payment.switchMethod(''); + //]]> 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/express/review.phtml b/app/design/frontend/base/default/template/paypal/express/review.phtml index 2a0ca05789..d93e650d24 100644 --- a/app/design/frontend/base/default/template/paypal/express/review.phtml +++ b/app/design/frontend/base/default/template/paypal/express/review.phtml @@ -120,8 +120,8 @@ getChildHtml('agreements'); ?>
    - - + + 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..e77f2c25f8 --- /dev/null +++ b/app/design/frontend/base/default/template/paypal/payflowlink/iframe.phtml @@ -0,0 +1,119 @@ + +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..7bc272298c --- /dev/null +++ b/app/design/frontend/base/default/template/paypal/payflowlink/redirect.phtml @@ -0,0 +1,85 @@ + + + + + + + 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') ?>  
    getContainers(); ?>
    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 @@ ?>